Module: Prawn::Rtl::Bidi

Extended by:
FFI::Library
Defined in:
lib/prawn/rtl/bidi.rb

Overview

FFI BiDi wrapper for Unicode Bidirectional Algorithm support

This module provides direct FFI bindings to ICU’s ubidi functions for bidirectional text processing.

Defined Under Namespace

Classes: BiDiError

Constant Summary collapse

UBIDI_DEFAULT_LTR =

Constants from ubidi.h

0xfe
UBIDI_DEFAULT_RTL =
0xff
UBIDI_LTR =
0
UBIDI_RTL =
1
UBIDI_MIXED =
2
UBIDI_NEUTRAL =
3
UBIDI_DO_MIRRORING =

Reorder options

2
UBIDI_OUTPUT_REVERSE =
16

Class Method Summary collapse

Class Method Details

.attach_icu_function(ruby_name, icu_name, args, return_type) ⇒ Object

Helper to attach function with detected suffix



108
109
110
111
# File 'lib/prawn/rtl/bidi.rb', line 108

def self.attach_icu_function(ruby_name, icu_name, args, return_type)
  suffixed_name = "#{icu_name}#{detect_icu_suffix}"
  attach_function ruby_name, suffixed_name.to_sym, args, return_type
end

.contains_rtl?(text) ⇒ Boolean

Checks if a string contains RTL characters

Parameters:

  • text (String)

    the text to check

Returns:

  • (Boolean)

    true if the text contains RTL characters



197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
# File 'lib/prawn/rtl/bidi.rb', line 197

def self.contains_rtl?(text)
  return false if text.nil? || text.empty?

  bidi = nil
  begin
    bidi = ubidi_open
    return false if bidi.null?

    utf16_text = text.encode('UTF-16LE')
    text_length = utf16_text.bytesize / 2

    text_buffer = FFI::MemoryPointer.new(:uint16, text_length + 1)
    text_buffer.put_bytes(0, utf16_text)

    status = FFI::MemoryPointer.new(:int32)
    status.put_int32(0, 0)

    ubidi_setPara(bidi, text_buffer, text_length, UBIDI_DEFAULT_LTR, nil, status)

    return false if status.get_int32(0).positive?

    direction = ubidi_getDirection(bidi)
    [UBIDI_RTL, UBIDI_MIXED].include?(direction)
  ensure
    ubidi_close(bidi) if bidi && !bidi.null?
  end
end

.detect_icu_suffixObject

Detect ICU version suffix by checking for a known function



86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# File 'lib/prawn/rtl/bidi.rb', line 86

def self.detect_icu_suffix
  @detect_icu_suffix ||= begin
    # Try common suffixes from newer to older versions
    # Some versions use _4_2 format, others use _42 format
    suffixes = [''] + 90.downto(4).flat_map { |v| ["_#{v}", "_#{v / 10}_#{v % 10}"] }

    # Find suffix by checking if ubidi_open function exists
    suffix = suffixes.find do |s|
      # Try to find the function
      func_name = :"ubidi_open#{s}"
      ffi_libraries.any? do |lib|
        lib.find_function(func_name.to_s)
      end
    rescue StandardError
      false
    end

    suffix || ''
  end
end

.find_icu_libObject

Find ICU library files



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/prawn/rtl/bidi.rb', line 53

def self.find_icu_lib
  candidates = []
  lib_name = 'icuuc'

  search_paths.each do |path|
    Dir.glob(File.expand_path(path)).each do |dir|
      # Try versioned libraries first (newer to older)
      # ICU versions from 4.0 (2009) to potential future versions
      90.downto(4).each do |version|
        case platform
        when :osx
          candidates << File.join(dir, "lib#{lib_name}.#{version}.dylib")
          candidates << File.join(dir, "lib#{lib_name}.dylib")
        when :windows
          candidates << File.join(dir, "#{lib_name}#{version}.dll")
          candidates << File.join(dir, "#{lib_name}.dll")
        else
          candidates << File.join(dir, "lib#{lib_name}.so.#{version}")
          candidates << File.join(dir, "lib#{lib_name}.so")
        end
      end
    end
  end

  # Find the first existing library
  found = candidates.find { |path| File.exist?(path) }
  found || ["lib#{lib_name}.so", "lib#{lib_name}.dylib", "#{lib_name}.dll", lib_name]
end

.platformObject

Detect platform



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/prawn/rtl/bidi.rb', line 18

def self.platform
  os = RbConfig::CONFIG['host_os']
  case os
  when /darwin/
    :osx
  when /linux/
    :linux
  when /bsd/
    :bsd
  when /mswin|msys|mingw|cygwin|bccwin|wince|emc/
    :windows
  else
    :linux
  end
end

.reorder(text, direction: :auto) ⇒ String

Reorders text according to the Unicode Bidirectional Algorithm

Parameters:

  • text (String)

    the text to reorder

  • direction (Symbol) (defaults to: :auto)

    :ltr, :rtl, or :auto (default)

Returns:

  • (String)

    the visually reordered text



140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
# File 'lib/prawn/rtl/bidi.rb', line 140

def self.reorder(text, direction: :auto)
  return text if text.nil? || text.empty?

  # Convert direction to ubidi constant
  para_level =
    case direction
    when :ltr then UBIDI_LTR
    when :rtl then UBIDI_RTL
    else UBIDI_DEFAULT_LTR
    end

  bidi = nil
  begin
    # Open BiDi object
    bidi = ubidi_open
    raise BiDiError, 'Failed to create BiDi object' if bidi.null?

    # Convert string to UTF-16 for ICU
    utf16_text = text.encode('UTF-16LE')
    text_length = utf16_text.bytesize / 2

    # Create buffer for UTF-16 string
    text_buffer = FFI::MemoryPointer.new(:uint16, text_length + 1)
    text_buffer.put_bytes(0, utf16_text)

    # Error status
    status = FFI::MemoryPointer.new(:int32)
    status.put_int32(0, 0)

    # Set paragraph
    ubidi_setPara(bidi, text_buffer, text_length, para_level, nil, status)

    error_code = status.get_int32(0)
    raise BiDiError, "ubidi_setPara failed with error code: #{error_code}" if error_code.positive?

    # Get required size for output
    output_length = text_length * 2
    output_buffer = FFI::MemoryPointer.new(:uint16, output_length)

    # Write reordered text
    written = ubidi_writeReordered(bidi, output_buffer, output_length, UBIDI_DO_MIRRORING, status)

    error_code = status.get_int32(0)
    raise BiDiError, "ubidi_writeReordered failed with error code: #{error_code}" if error_code.positive?

    # Convert back from UTF-16 to UTF-8
    result_bytes = output_buffer.get_bytes(0, written * 2)
    result_bytes.force_encoding('UTF-16LE').encode('UTF-8')
  ensure
    ubidi_close(bidi) if bidi && !bidi.null?
  end
end

.search_pathsObject

Search paths for ICU libraries



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/prawn/rtl/bidi.rb', line 35

def self.search_paths
  @search_paths ||=
    if ENV['ICU_LIB_PATH']
      [ENV['ICU_LIB_PATH']]
    elsif FFI::Platform::IS_WINDOWS
      ENV['PATH'].split(File::PATH_SEPARATOR)
    else
      [
        '/usr/local/{lib64,lib}',
        '/usr/local/opt/icu4c/{lib64,lib}',
        '/opt/local/{lib64,lib}',
        '/opt/homebrew/{lib64,lib}',
        '/usr/{lib64,lib}'
      ] + Dir['/usr/lib/*-linux-gnu'] + Dir['/lib/*-linux-gnu']
    end
end