Class: Fontisan::Tables::Cmap

Inherits:
Binary::BaseRecord show all
Defined in:
lib/fontisan/tables/cmap.rb

Overview

Parser for the 'cmap' (Character to Glyph Index Mapping) table

The cmap table maps character codes to glyph indices. It supports multiple encoding formats to accommodate different character sets and Unicode planes.

This implementation focuses on:

  • Format 4: Segment mapping for BMP (Basic Multilingual Plane, U+0000-U+FFFF)
  • Format 12: Segmented coverage for full Unicode support

Reference: OpenType specification, cmap table

Constant Summary collapse

PLATFORM_UNICODE =

Platform IDs

0
PLATFORM_MACINTOSH =
1
PLATFORM_MICROSOFT =
3
ENC_MS_UNICODE_BMP =

Microsoft Encoding IDs

1
ENC_MS_UNICODE_UCS4 =

Unicode BMP (UCS-2)

10

Instance Method Summary collapse

Methods inherited from Binary::BaseRecord

#raw_data, read, #valid?

Instance Method Details

#extract_subtable_data(record, data) ⇒ Object

Extract subtable data if record exists and offset is valid



123
124
125
126
127
128
# File 'lib/fontisan/tables/cmap.rb', line 123

def extract_subtable_data(record, data)
  return nil unless record
  return nil unless record[:offset] < data.length

  data[record[:offset]..]
end

#find_best_unicode_subtable(records, data) ⇒ Object

Find the best Unicode subtable from encoding records



91
92
93
94
95
96
# File 'lib/fontisan/tables/cmap.rb', line 91

def find_best_unicode_subtable(records, data)
  # Try in priority order: UCS-4, BMP, Unicode
  find_ucs4_subtable(records, data) ||
    find_bmp_subtable(records, data) ||
    find_unicode_subtable(records, data)
end

#find_bmp_subtable(records, data) ⇒ Object

Find Microsoft Unicode BMP subtable



108
109
110
111
112
113
114
# File 'lib/fontisan/tables/cmap.rb', line 108

def find_bmp_subtable(records, data)
  record = records.find do |r|
    r[:platform_id] == PLATFORM_MICROSOFT &&
      r[:encoding_id] == ENC_MS_UNICODE_BMP
  end
  extract_subtable_data(record, data)
end

#find_ucs4_subtable(records, data) ⇒ Object

Find Microsoft Unicode UCS-4 subtable (full Unicode)



99
100
101
102
103
104
105
# File 'lib/fontisan/tables/cmap.rb', line 99

def find_ucs4_subtable(records, data)
  record = records.find do |r|
    r[:platform_id] == PLATFORM_MICROSOFT &&
      r[:encoding_id] == ENC_MS_UNICODE_UCS4
  end
  extract_subtable_data(record, data)
end

#find_unicode_subtable(records, data) ⇒ Object

Find Unicode platform subtable (any encoding)



117
118
119
120
# File 'lib/fontisan/tables/cmap.rb', line 117

def find_unicode_subtable(records, data)
  record = records.find { |r| r[:platform_id] == PLATFORM_UNICODE }
  extract_subtable_data(record, data)
end

#has_bmp_coverage?Boolean

Validation helper: Check if BMP coverage exists

Checks if the Basic Multilingual Plane (U+0000-U+FFFF) has mappings

Returns:

  • (Boolean)

    True if BMP characters are mapped



307
308
309
310
311
312
313
# File 'lib/fontisan/tables/cmap.rb', line 307

def has_bmp_coverage?
  mappings = unicode_mappings
  return false if mappings.nil? || mappings.empty?

  # Check if any BMP characters (0x0000-0xFFFF) are mapped
  mappings.keys.any? { |code| code.between?(0x0000, 0xFFFF) }
end

#has_format_4_subtable?Boolean

Validation helper: Check if format 4 subtable exists

Format 4 is the minimum requirement for Unicode BMP support

Returns:

  • (Boolean)

    True if format 4 subtable is found



333
334
335
336
337
338
339
340
341
342
343
344
345
346
# File 'lib/fontisan/tables/cmap.rb', line 333

def has_format_4_subtable?
  data = to_binary_s
  records = read_encoding_records(data)

  records.any? do |record|
    subtable_data = extract_subtable_data(record, data)
    next false unless subtable_data && subtable_data.length >= 2

    format = subtable_data[0, 2].unpack1("n")
    format == 4
  end
rescue StandardError
  false
end

#has_required_characters?(*required_chars) ⇒ Boolean

Validation helper: Check if required characters are mapped

Checks for essential characters like space (U+0020)

Parameters:

  • required_chars (Array<Integer>)

    Character codes that must be present

Returns:

  • (Boolean)

    True if all required characters are mapped



321
322
323
324
325
326
# File 'lib/fontisan/tables/cmap.rb', line 321

def has_required_characters?(*required_chars)
  mappings = unicode_mappings
  return false if mappings.nil?

  required_chars.all? { |code| mappings.key?(code) }
end

#has_subtables?Boolean

Validation helper: Check if at least one subtable exists

Returns:

  • (Boolean)

    True if num_tables > 0



291
292
293
# File 'lib/fontisan/tables/cmap.rb', line 291

def has_subtables?
  num_tables&.positive?
end

#has_unicode_mapping?Boolean

Validation helper: Check if Unicode mapping exists

Returns:

  • (Boolean)

    True if Unicode mappings are present



298
299
300
# File 'lib/fontisan/tables/cmap.rb', line 298

def has_unicode_mapping?
  !unicode_mappings.nil? && !unicode_mappings.empty?
end

#map_character_range(start_char, end_char, start_glyph, mappings) ⇒ Object

Map a range of characters to glyphs



272
273
274
275
276
277
# File 'lib/fontisan/tables/cmap.rb', line 272

def map_character_range(start_char, end_char, start_glyph, mappings)
  (start_char..end_char).each do |code|
    glyph_index = start_glyph + (code - start_char)
    mappings[code] = glyph_index if glyph_index != 0
  end
end

#parse_format_12(data, mappings) ⇒ Object

Parse Format 12 subtable (segmented coverage) Format 12 supports full Unicode range



231
232
233
234
235
236
237
# File 'lib/fontisan/tables/cmap.rb', line 231

def parse_format_12(data, mappings)
  header = parse_format_12_header(data)
  return unless header

  parse_format_12_groups(data, header[:num_groups], header[:length],
                         mappings)
end

#parse_format_12_groups(data, num_groups, length, mappings) ⇒ Object

Parse Format 12 sequential map groups



255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
# File 'lib/fontisan/tables/cmap.rb', line 255

def parse_format_12_groups(data, num_groups, length, mappings)
  offset = 16
  num_groups.times do
    break if offset + 12 > length

    start_char_code = data[offset, 4].unpack1("N")
    end_char_code = data[offset + 4, 4].unpack1("N")
    start_glyph_id = data[offset + 8, 4].unpack1("N")

    map_character_range(start_char_code, end_char_code, start_glyph_id,
                        mappings)

    offset += 12
  end
end

#parse_format_12_header(data) ⇒ Object

Parse Format 12 header



240
241
242
243
244
245
246
247
248
249
250
251
252
# File 'lib/fontisan/tables/cmap.rb', line 240

def parse_format_12_header(data)
  return nil if data.length < 16

  format = data[0, 2].unpack1("n")
  return nil unless format == 12

  length = data[4, 4].unpack1("N")
  return nil if length > data.length

  num_groups = data[12, 4].unpack1("N")

  { length: length, num_groups: num_groups }
end

#parse_format_4(data, mappings) ⇒ Object

Parse Format 4 subtable (segment mapping to delta values) Format 4 is the most common format for BMP Unicode fonts rubocop:disable Metrics/MethodLength rubocop:disable Metrics/CyclomaticComplexity rubocop:disable Metrics/PerceivedComplexity



135
136
137
138
139
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
192
193
194
195
196
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
224
# File 'lib/fontisan/tables/cmap.rb', line 135

def parse_format_4(data, mappings)
  return if data.length < 14

  # Format 4 header
  format = data[0, 2].unpack1("n")
  return unless format == 4

  length = data[2, 2].unpack1("n")
  return if length > data.length

  seg_count_x2 = data[6, 2].unpack1("n")
  seg_count = seg_count_x2 / 2

  # Arrays start at offset 14
  offset = 14

  # Read endCode array
  end_codes = []
  seg_count.times do
    break if offset + 2 > length

    end_codes << data[offset, 2].unpack1("n")
    offset += 2
  end

  # Skip reservedPad (2 bytes)
  offset += 2

  # Read startCode array
  start_codes = []
  seg_count.times do
    break if offset + 2 > length

    start_codes << data[offset, 2].unpack1("n")
    offset += 2
  end

  # Read idDelta array
  id_deltas = []
  seg_count.times do
    break if offset + 2 > length

    id_deltas << data[offset, 2].unpack1("n")
    offset += 2
  end

  # Read idRangeOffset array
  id_range_offsets = []
  id_range_offset_pos = offset
  seg_count.times do
    break if offset + 2 > length

    id_range_offsets << data[offset, 2].unpack1("n")
    offset += 2
  end

  # Process each segment
  seg_count.times do |i|
    start_code = start_codes[i]
    end_code = end_codes[i]
    id_delta = id_deltas[i]
    id_range_offset = id_range_offsets[i]

    # Skip the final segment (0xFFFF)
    next if start_code == 0xFFFF

    if id_range_offset.zero?
      # Use idDelta directly
      (start_code..end_code).each do |code|
        glyph_index = (code + id_delta) & 0xFFFF
        mappings[code] = glyph_index if glyph_index != 0
      end
    else
      # Use glyphIdArray
      (start_code..end_code).each do |code|
        # Calculate position in glyphIdArray
        array_offset = id_range_offset_pos + (i * 2) + id_range_offset
        array_offset += (code - start_code) * 2

        next if array_offset + 2 > length

        glyph_index = data[array_offset, 2].unpack1("n")
        next if glyph_index.zero?

        glyph_index = (glyph_index + id_delta) & 0xFFFF
        mappings[code] = glyph_index if glyph_index != 0
      end
    end
  end
end

#parse_mappingsObject

Parse all encoding records and extract Unicode mappings



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/fontisan/tables/cmap.rb', line 38

def parse_mappings
  mappings = {}

  # Get the full binary data
  data = to_binary_s

  # Read encoding records
  records = read_encoding_records(data)

  # Try to find the best Unicode subtable
  # Prefer Microsoft Unicode UCS-4 (format 12), then Unicode BMP (format 4)
  subtable_data = find_best_unicode_subtable(records, data)

  return mappings unless subtable_data

  # Parse the subtable based on its format
  format = subtable_data[0, 2].unpack1("n")

  case format
  when 4
    parse_format_4(subtable_data, mappings)
  when 12
    parse_format_12(subtable_data, mappings)
  end

  mappings
end

#read_encoding_records(data) ⇒ Object

Read encoding records from the beginning of the table



67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/fontisan/tables/cmap.rb', line 67

def read_encoding_records(data)
  records = []
  offset = 4 # Skip version and numTables

  num_tables.times do
    break if offset + 8 > data.length

    platform_id = data[offset, 2].unpack1("n")
    encoding_id = data[offset + 2, 2].unpack1("n")
    subtable_offset = data[offset + 4, 4].unpack1("N")

    records << {
      platform_id: platform_id,
      encoding_id: encoding_id,
      offset: subtable_offset,
    }

    offset += 8
  end

  records
end

#subtable_formatsArray<Integer>

Distinct subtable formats present in this cmap, sorted ascending.

Each encoding record's subtable begins with a uint16 format tag. Returns the unique set of those formats across all records. Useful for audit reports that need to record which cmap subtables contributed to the Unicode mappings.

Returns:

  • (Array<Integer>)

    sorted unique format numbers



356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
# File 'lib/fontisan/tables/cmap.rb', line 356

def subtable_formats
  data = to_binary_s
  records = read_encoding_records(data)

  formats = records.filter_map do |record|
    subtable_data = extract_subtable_data(record, data)
    next nil unless subtable_data && subtable_data.length >= 2

    subtable_data[0, 2].unpack1("n")
  end

  formats.uniq.sort
rescue StandardError
  []
end

#unicode_mappingsObject

Parse encoding records and subtables



33
34
35
# File 'lib/fontisan/tables/cmap.rb', line 33

def unicode_mappings
  @unicode_mappings ||= parse_mappings
end

#valid_glyph_indices?(max_glyph_id) ⇒ Boolean

Validation helper: Check if glyph indices are within bounds

Parameters:

  • max_glyph_id (Integer)

    Maximum valid glyph ID from maxp table

Returns:

  • (Boolean)

    True if all mapped glyph IDs are valid



376
377
378
379
380
381
382
383
# File 'lib/fontisan/tables/cmap.rb', line 376

def valid_glyph_indices?(max_glyph_id)
  mappings = unicode_mappings
  return true if mappings.nil? || mappings.empty?

  mappings.values.all? do |glyph_id|
    glyph_id >= 0 && glyph_id < max_glyph_id
  end
end

#valid_version?Boolean

Validation helper: Check if version is valid

cmap version should be 0

Returns:

  • (Boolean)

    True if version is 0



284
285
286
# File 'lib/fontisan/tables/cmap.rb', line 284

def valid_version?
  version.zero?
end