fontisan 0.4.47 → 0.4.49

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. checksums.yaml +4 -4
  2. data/BENCHMARKS.md +56 -0
  3. data/CHANGELOG.md +12 -0
  4. data/Cargo.lock +550 -0
  5. data/Cargo.toml +12 -0
  6. data/Gemfile +10 -0
  7. data/README.adoc +69 -0
  8. data/Rakefile +5 -1
  9. data/benchmark/baseline.json +5 -0
  10. data/benchmark/ci_gate.rb +217 -0
  11. data/benchmark/corpus/harness.rb +175 -0
  12. data/benchmark/corpus/ops.rb +150 -0
  13. data/benchmark/corpus/run.rb +182 -0
  14. data/benchmark/corpus/scan_child.rb +8 -0
  15. data/benchmark/corpus/tiers.rb +176 -0
  16. data/benchmark/tier_baseline.json +12 -0
  17. data/build_mingw32_stub.rb +15 -0
  18. data/docs/.vitepress/config.ts +2 -1
  19. data/docs/guide/engines.md +117 -0
  20. data/docs/reference-facade.md +130 -0
  21. data/ext/fontisan_cdylib/Cargo.lock +313 -0
  22. data/ext/fontisan_cdylib/Cargo.toml +18 -0
  23. data/ext/fontisan_cdylib/build.rs +22 -0
  24. data/ext/fontisan_cdylib/extconf.rb +36 -0
  25. data/ext/fontisan_cdylib/src/lib.rs +13 -0
  26. data/ext/fontisan_native/Cargo.toml +21 -0
  27. data/ext/fontisan_native/build.rs +22 -0
  28. data/ext/fontisan_native/clippy.toml +10 -0
  29. data/ext/fontisan_native/extconf.rb +59 -0
  30. data/ext/fontisan_native/src/lib.rs +478 -0
  31. data/lib/fontisan/audit/checks/cmap_check.rb +7 -0
  32. data/lib/fontisan/audit/checks/hinting_check.rb +1 -1
  33. data/lib/fontisan/audit/checks/maxp_check.rb +1 -1
  34. data/lib/fontisan/audit/checks/opentype_conformance_check.rb +5 -2
  35. data/lib/fontisan/base_collection.rb +30 -0
  36. data/lib/fontisan/byte_ops.rb +314 -0
  37. data/lib/fontisan/cli.rb +11 -5
  38. data/lib/fontisan/commands/audit_command.rb +38 -43
  39. data/lib/fontisan/commands/convert_command.rb +55 -1
  40. data/lib/fontisan/commands/instance_command.rb +75 -0
  41. data/lib/fontisan/commands/multi_format_output.rb +6 -1
  42. data/lib/fontisan/commands/subset_command.rb +43 -0
  43. data/lib/fontisan/commands/unpack_command.rb +56 -0
  44. data/lib/fontisan/converters/cff_table_builder.rb +1 -1
  45. data/lib/fontisan/converters/collection_converter.rb +13 -5
  46. data/lib/fontisan/converters/format_converter.rb +1 -1
  47. data/lib/fontisan/converters/woff2_encoder.rb +8 -6
  48. data/lib/fontisan/converters/woff_writer.rb +6 -5
  49. data/lib/fontisan/engine.rb +393 -0
  50. data/lib/fontisan/ffi/client.rb +123 -0
  51. data/lib/fontisan/ffi.rb +387 -0
  52. data/lib/fontisan/ffi_platform.rb +24 -0
  53. data/lib/fontisan/font_loader.rb +5 -1
  54. data/lib/fontisan/font_writer.rb +13 -1
  55. data/lib/fontisan/native.rb +235 -0
  56. data/lib/fontisan/output_guard.rb +40 -0
  57. data/lib/fontisan/reference/table_digests.rb +251 -0
  58. data/lib/fontisan/reference.rb +663 -0
  59. data/lib/fontisan/scan.rb +372 -0
  60. data/lib/fontisan/sfnt_directory.rb +41 -0
  61. data/lib/fontisan/sfnt_font.rb +16 -6
  62. data/lib/fontisan/subset/builder.rb +2 -1
  63. data/lib/fontisan/tables/cff/charstring.rb +16 -0
  64. data/lib/fontisan/tables/cff.rb +15 -5
  65. data/lib/fontisan/tables/cmap.rb +11 -1
  66. data/lib/fontisan/tables/gpos.rb +7 -0
  67. data/lib/fontisan/tables/gsub.rb +7 -0
  68. data/lib/fontisan/tables/layout_common.rb +172 -0
  69. data/lib/fontisan/tables/name.rb +10 -4
  70. data/lib/fontisan/utilities/brotli_wrapper.rb +39 -4
  71. data/lib/fontisan/validators/opentype_validator.rb +2 -0
  72. data/lib/fontisan/variable/instancer.rb +1 -0
  73. data/lib/fontisan/variable/static_font_builder.rb +4 -1
  74. data/lib/fontisan/variable/table_updater.rb +4 -2
  75. data/lib/fontisan/variation/instancing/axis_space.rb +1 -1
  76. data/lib/fontisan/variation/instancing/true_type_instancer.rb +14 -6
  77. data/lib/fontisan/version.rb +1 -1
  78. data/lib/fontisan/woff2/collection_decoder.rb +15 -1
  79. data/lib/fontisan/woff2/collection_encoder.rb +29 -6
  80. data/lib/fontisan/woff2/encoder_rules.rb +12 -4
  81. data/lib/fontisan/woff2/glyf_loca_reconstruct.rb +1 -1
  82. data/lib/fontisan/woff2_collection.rb +7 -5
  83. data/lib/fontisan/woff2_font.rb +12 -3
  84. data/lib/fontisan/woff_container.rb +83 -0
  85. data/lib/fontisan/woff_font.rb +24 -20
  86. data/lib/fontisan.rb +25 -1
  87. data/rakelib/bench.rake +9 -0
  88. data/rakelib/cdylib.rake +39 -0
  89. data/rakelib/corpus.rake +272 -0
  90. data/rakelib/corpus_convert.rake +43 -0
  91. data/rakelib/corpus_goldens.rake +22 -0
  92. data/rakelib/corpus_malformed.rake +20 -0
  93. data/rakelib/corpus_scan.rake +24 -0
  94. data/rakelib/java.rake +61 -0
  95. data/rakelib/native.rake +43 -0
  96. data/scripts/build-woff2.sh +57 -0
  97. data/scripts/corpus/generate_convert_goldens.rb +478 -0
  98. data/scripts/corpus/generate_goldens.rb +282 -0
  99. data/scripts/corpus/generate_malformed_goldens.rb +254 -0
  100. data/scripts/corpus/generate_scan_goldens.rb +98 -0
  101. data/scripts/tier_fallback.rb +228 -0
  102. data/scripts/tier_smoke.rb +72 -0
  103. metadata +71 -7
@@ -0,0 +1,314 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Fontisan
4
+ # Routing rules, result rebuilding and error rebuilding shared by the engine
5
+ # tiers that serve convert, extract, instance and subset
6
+ # ({Fontisan::Native}, {Fontisan::Ffi}). Included into their singleton
7
+ # classes; the methods are private to the tier.
8
+ module ByteOps
9
+ # Convert target codes of the engine (extension and C ABI alike).
10
+ TARGET_CODES = { ttf: 0, otf: 1, woff: 2, woff2: 3, ttc: 4, otc: 5 }.freeze
11
+ SINGLE_TARGETS = %i[ttf otf woff woff2].freeze
12
+ COLLECTION_TARGETS = %i[ttc otc woff2].freeze
13
+ CONVERT_OPTIONS = %i[to output timestamp quiet].freeze
14
+ SUBSET_PROFILES = %w[web pdf minimal].freeze
15
+ MAX_CODEPOINT = 0x10FFFF
16
+ # The engine's extract index is a u32; a larger one would wrap, not raise.
17
+ MAX_FONT_INDEX = 0xFFFF_FFFF
18
+
19
+ BYTE_OPERATIONS = %i[convert extract instance subset].freeze
20
+
21
+ # "<ruby class>: <message>": how the engine reports a Ruby exception it
22
+ # mirrors (the byte operations carry one class and one message, no chain).
23
+ FAILURE_MESSAGE = /\A([A-Z]\w*(?:::\w+)*): (.*)\z/m
24
+ # The engine's text for a file that is no font (convert adds a "Conversion
25
+ # failed: " prefix); Ruby's is InvalidFontError.
26
+ UNRECOGNISED_FORMAT_MESSAGE = "unrecognised font format"
27
+ # Prefix of a convert failure that wraps the engine's own message.
28
+ TRANSFORMATION_PREFIX = "Conversion failed: Transformation failed: "
29
+ # Engine messages for bad font data that Ruby raises as InvalidFontError:
30
+ # the WOFF/WOFF2 container decoders ("woff: ...", "woff2: ..."), and the
31
+ # same error as its debug text.
32
+ INVALID_FONT_MESSAGE = /\A(?:woff2?: |Error \{ class: InvalidFont, message: ")/
33
+ # The instancer's own error; convert keeps Fontisan::Error for it, as Ruby does.
34
+ TRUNCATED_TABLE_MESSAGE = "Static instancing: truncated or malformed table"
35
+ # The engine prints the error's Debug form: the message is a Rust string
36
+ # literal and a cause follows it (`, cause: None`).
37
+ DEBUG_ERROR_MESSAGE = /\AError \{ class: InvalidFont, message: "(.*?)"(?:, cause: .*)? \}\z/m
38
+ # The text InvalidAxisError builds from its axis and reason.
39
+ AXIS_MESSAGE = /\AInvalid variation axis '(.*?)': (.*)\z/m
40
+ RUST_ESCAPES = { '\\"' => '"', "\\\\" => "\\", "\\n" => "\n", "\\t" => "\t", "\\r" => "\r" }.freeze
41
+
42
+ # The engine's error kinds (fontisan-rs `ErrorKind`, `FONTISAN_KIND_*` of the
43
+ # C ABI), by number. Only the kinds that name one Ruby class are mapped: the
44
+ # others stand for several (InvalidFont: InvalidFontError and RuntimeError;
45
+ # MissingTable: MissingTableError and MissingVariationTableError; Truncated:
46
+ # EOFError and IOError; Io: every Errno), or for none (Other, Unsupported),
47
+ # and fall back to the reported class and message text.
48
+ KIND_CLASSES = {
49
+ 2 => "Fontisan::InvalidAxisError",
50
+ 3 => "Fontisan::InvalidCoordinatesError",
51
+ 6 => "Fontisan::SubsettingError",
52
+ 7 => "Fontisan::CorruptedTableError",
53
+ 9 => "ArgumentError",
54
+ }.freeze
55
+
56
+ private
57
+
58
+ # Whether the engine honours +options+ for +operation+ (one of
59
+ # {BYTE_OPERATIONS}); the first reuse point for tier routing.
60
+ def byte_options?(operation, options, path)
61
+ case operation
62
+ when :convert then convert_options?(options, path)
63
+ when :extract then extract_options?(options)
64
+ when :instance then instance_options?(options, path)
65
+ when :subset then subset_options?(options, path)
66
+ else false
67
+ end
68
+ end
69
+
70
+ # A collection: `ttcf`, or a WOFF2 whose flavor is `ttcf`.
71
+ def collection_file?(path)
72
+ head = File.binread(path, 8) or return false
73
+ head.start_with?("ttcf") || (head.start_with?("wOF2") && head.byteslice(4, 4) == "ttcf")
74
+ rescue SystemCallError
75
+ false
76
+ end
77
+
78
+ # `.otc` decision (card 2f): Ruby picks a collection's source type from
79
+ # the input path's extension (`.otc` vs anything else), and the engine
80
+ # only sees bytes and assumes `.ttc`. No hint is passed: `.otc`
81
+ # inputs stay on the Ruby tier.
82
+ def otc_hint?(path)
83
+ File.extname(path).casecmp?(".otc")
84
+ end
85
+
86
+ # Single target `to:` (no multi-format), a format pair the engine
87
+ # serves, no `coordinates:` / `preserve_hints` / compression knobs.
88
+ def convert_options?(options, path)
89
+ return false unless options.keys.all? { |key| CONVERT_OPTIONS.include?(key) }
90
+ return false unless options[:output].is_a?(String) || options[:output].respond_to?(:to_path)
91
+ return false unless timestamp_option?(options[:timestamp])
92
+
93
+ target = convert_target(options[:to]) or return false
94
+ return false unless path.is_a?(String)
95
+ return false if otc_hint?(path)
96
+
97
+ (collection_file?(path) ? COLLECTION_TARGETS : SINGLE_TARGETS).include?(target)
98
+ end
99
+
100
+ def convert_target(value)
101
+ return nil unless value.is_a?(Symbol) || value.is_a?(String)
102
+
103
+ target = value.to_s.downcase.to_sym
104
+ TARGET_CODES.key?(target) ? target : nil
105
+ end
106
+
107
+ def timestamp_option?(value)
108
+ value.nil? || value.is_a?(Integer) || value.respond_to?(:to_time)
109
+ end
110
+
111
+ def extract_options?(options)
112
+ options.keys.sort == %i[index output_dir] && options[:index].is_a?(Integer) &&
113
+ options[:index].between?(0, MAX_FONT_INDEX) && options[:output_dir].respond_to?(:to_str)
114
+ end
115
+
116
+ def instance_options?(options, path)
117
+ return false unless options.keys.all? { |key| %i[coords timestamp].include?(key) }
118
+ return false unless options[:coords].is_a?(Hash) && !path.nil? && !collection_file?(path)
119
+
120
+ options[:coords].all? { |tag, value| tag.to_s.bytesize == 4 && numeric?(value) }
121
+ end
122
+
123
+ def subset_options?(options, path)
124
+ return false unless options.keys.all? { |key| %i[unicodes text profile timestamp].include?(key) }
125
+ return false if path.nil? || collection_file?(path)
126
+ return false unless SUBSET_PROFILES.include?(options.fetch(:profile, "web"))
127
+
128
+ text = options[:text]
129
+ return false unless text.nil? || text.is_a?(String)
130
+
131
+ Array(options[:unicodes]).all? { |cp| cp.is_a?(Integer) && cp.between?(0, MAX_CODEPOINT) }
132
+ end
133
+
134
+ def numeric?(value)
135
+ Float(value)
136
+ true
137
+ rescue ArgumentError, TypeError
138
+ false
139
+ end
140
+
141
+ # The output path of a convert, after the checks the Ruby tier makes before
142
+ # it converts: the name ConvertCommand gives a single font (an output with no
143
+ # extension gets ".<format>", a ".ttf" dot file keeps its name), never the
144
+ # input file, and its directory exists. A collection is written to the path
145
+ # as given.
146
+ def convert_output(path, output, target)
147
+ output = File.path(output)
148
+ output = Commands::MultiFormatOutput.new(output, [target]).paths.first unless collection_file?(path)
149
+ OutputGuard.check!(path, output)
150
+ dir = File.dirname(output)
151
+ raise ArgumentError, "Output directory not found: #{dir}" unless File.directory?(dir)
152
+
153
+ output
154
+ end
155
+
156
+ def finish_convert(path, target, output, bytes)
157
+ write_output(output, bytes)
158
+ result = { success: true, input_path: path, output_path: output }
159
+ result.merge!(convert_formats(path, target))
160
+ result.merge(input_size: File.size(path), output_size: bytes.bytesize,
161
+ **convert_tail(path))
162
+ end
163
+
164
+ # Writes as the Ruby tier's convert does: an IO failure is a Fontisan::Error.
165
+ def write_output(output, bytes)
166
+ File.binwrite(output, bytes)
167
+ rescue SystemCallError => e
168
+ raise Fontisan::Error, "Conversion failed: Transformation failed: #{e.message}"
169
+ end
170
+
171
+ # An IO failure while extracting (unreadable input, output directory that
172
+ # cannot be made or written) is a Fontisan::Error, as UnpackCommand raises it.
173
+ def unpacking_io
174
+ yield
175
+ rescue SystemCallError => e
176
+ raise Fontisan::Error, "Unexpected error during unpacking: #{e.message}"
177
+ end
178
+
179
+ def convert_formats(path, target)
180
+ return { source_format: single_format(path), target_format: target } unless collection_file?(path)
181
+
182
+ source = File.binread(path, 4) == "wOF2" ? :woff2_collection : :ttc
183
+ { source_format: source, target_format: target == :woff2 ? :woff2_collection : target }
184
+ end
185
+
186
+ # Collections report `num_fonts`; single fonts the variation strategy
187
+ # (an fvar font is converted as an instance, the rest are preserved).
188
+ def convert_tail(path)
189
+ return { num_fonts: collection_font_count(path) } if collection_file?(path)
190
+
191
+ { variation_strategy: variable_font?(path) ? :instance : :preserve }
192
+ end
193
+
194
+ def single_format(path)
195
+ FontLoader.detect_format(path)
196
+ end
197
+
198
+ # A WOFF2 collection is counted from its directory, not decoded: the
199
+ # decode needs `brotli`, which the java platform (JRuby) does not have, and
200
+ # the engine has already served the convert.
201
+ def collection_font_count(path)
202
+ if File.binread(path, 4) == "wOF2"
203
+ return Woff2::CollectionDecoder.new(File.binread(path)).font_count
204
+ end
205
+
206
+ FontLoader.load_collection(path).num_fonts
207
+ end
208
+
209
+ def variable_font?(path)
210
+ return woff2_tags(path).include?("fvar") if File.binread(path, 4) == "wOF2"
211
+
212
+ font = FontLoader.load(path, mode: :metadata, lazy: true)
213
+ font.has_table?("fvar")
214
+ ensure
215
+ font.close if font.respond_to?(:close)
216
+ end
217
+
218
+ # Table tags from the WOFF2 table directory, which is stored uncompressed
219
+ # (no `brotli` needed, unlike loading the font).
220
+ def woff2_tags(path)
221
+ File.open(path, "rb") do |io|
222
+ header = Woff2::Woff2Header.read(io)
223
+ Woff2Font.read_table_directory_from_io(io, header).map(&:tag)
224
+ end
225
+ end
226
+
227
+ def unix_seconds(timestamp)
228
+ timestamp.respond_to?(:to_time) ? timestamp.to_time.to_i : Integer(timestamp)
229
+ end
230
+
231
+ # Raise the Ruby tier's exception: class, message and the cause chain
232
+ # (each cause is raised so that its own #cause is set).
233
+ def raise_failure(details, byte_operation: false)
234
+ class_name, message, causes, kind = details
235
+ klass, message = byte_failure(class_name, message, kind) if byte_operation
236
+ klass ||= exception_class(class_name)
237
+ raised, text = public_failure(klass, message)
238
+ # The leaked Ruby error stays as the cause, as the Ruby tier's does.
239
+ causes = [[class_name, message], *causes] unless raised == klass
240
+ cause = nil
241
+ causes.reverse_each { |name, detail| cause = build_exception(name, detail, cause) }
242
+ raise build_instance(raised, text), cause: cause
243
+ end
244
+
245
+ # An engine error that mirrors a Ruby parser leak (EOFError, NoMethodError,
246
+ # ...) is raised as the Ruby tier raises it now: InvalidFontError.
247
+ def public_failure(klass, message)
248
+ return [klass, message] unless Reference::PARSER_LEAKS.any? { |leak| klass <= leak }
249
+
250
+ [InvalidFontError, Reference.malformed_message(klass, message)]
251
+ end
252
+
253
+ # The Ruby class and message of a failed byte operation, so that a tier
254
+ # never changes what a caller can rescue or match: an engine error that
255
+ # names the Ruby exception it mirrors ("RuntimeError: ...") is unwrapped,
256
+ # and the engine's unrecognised-format error becomes the loader's. A +kind+
257
+ # that names one Ruby class decides it; message text is read only for the
258
+ # other kinds (Other and the ambiguous ones), and when no kind was reported.
259
+ def byte_failure(class_name, message, kind = nil)
260
+ kind_class = KIND_CLASSES[kind]
261
+ return [exception_class(kind_class), message] if kind_class
262
+
263
+ if class_name == "Fontisan::Error" && (match = FAILURE_MESSAGE.match(message))
264
+ class_name = match[1]
265
+ message = match[2]
266
+ end
267
+ bare = message.delete_prefix(TRANSFORMATION_PREFIX)
268
+ return [InvalidFontError, FontLoader::UNKNOWN_FORMAT_MESSAGE] if bare.delete_prefix("Conversion failed: ") == UNRECOGNISED_FORMAT_MESSAGE
269
+ return [InvalidFontError, message] if message == TRUNCATED_TABLE_MESSAGE
270
+ return [InvalidFontError, unwrap_debug_message(bare)] if class_name == "Fontisan::Error" && INVALID_FONT_MESSAGE.match?(bare)
271
+
272
+ [exception_class(class_name), message]
273
+ end
274
+
275
+ # The message inside the engine's Debug text for an InvalidFont error, with
276
+ # the Rust string escapes undone; any other text is returned as it is.
277
+ def unwrap_debug_message(text)
278
+ match = DEBUG_ERROR_MESSAGE.match(text) or return text
279
+
280
+ match[1].gsub(/\\[\\"ntr]/) { |escape| RUST_ESCAPES.fetch(escape) }
281
+ end
282
+
283
+ # `klass.new(message)`, or the keyword form some Fontisan errors use
284
+ # (`message:` for MissingVariationTableError; `axis:` and `reason:` for
285
+ # InvalidAxisError, split out of its own text); never a failed constructor.
286
+ def build_instance(klass, message)
287
+ klass.new(message)
288
+ rescue ArgumentError
289
+ build_keyword_instance(klass, message)
290
+ end
291
+
292
+ def build_keyword_instance(klass, message)
293
+ axis = AXIS_MESSAGE.match(message) if klass <= InvalidAxisError
294
+ return klass.new(axis: axis[1], reason: axis[2]) if axis
295
+
296
+ klass.new(message: message)
297
+ rescue ArgumentError
298
+ Fontisan::Error.new(message)
299
+ end
300
+
301
+ def build_exception(name, text, cause)
302
+ raise build_instance(exception_class(name), text), cause: cause
303
+ rescue Exception => e # rubocop:disable Lint/RescueException
304
+ e
305
+ end
306
+
307
+ def exception_class(name)
308
+ klass = Object.const_get(name)
309
+ klass.is_a?(Class) && klass <= Exception ? klass : Fontisan::Error
310
+ rescue NameError
311
+ Fontisan::Error
312
+ end
313
+ end
314
+ end
data/lib/fontisan/cli.rb CHANGED
@@ -12,6 +12,12 @@ module Fontisan
12
12
  # @example Run the info command
13
13
  # Fontisan::Cli.start(['info', 'font.ttf'])
14
14
  class Cli < Thor
15
+ # A Thor::Error (unknown command, missing --output) must fail the process:
16
+ # without this Thor exits 0 and prints a deprecation warning.
17
+ def self.exit_on_failure?
18
+ true
19
+ end
20
+
15
21
  class_option :format, type: :string, default: "text",
16
22
  desc: "Output format (text, yaml, json)",
17
23
  aliases: "-f"
@@ -226,7 +232,7 @@ module Fontisan
226
232
  # @param font_file [String] Path to the font file
227
233
  def subset(font_file)
228
234
  command = Commands::SubsetCommand.new(font_file, options)
229
- result = command.run
235
+ result = command.run_routed
230
236
 
231
237
  unless options[:quiet]
232
238
  puts "Subset font created:"
@@ -422,7 +428,7 @@ module Fontisan
422
428
  convert_options[:options] = conv_options if conv_options
423
429
 
424
430
  command = Commands::ConvertCommand.new(font_file, convert_options)
425
- command.run
431
+ command.run_routed
426
432
  rescue Errno::ENOENT, Error => e
427
433
  handle_error(e)
428
434
  end
@@ -443,7 +449,7 @@ module Fontisan
443
449
  option :opsz, type: :numeric,
444
450
  desc: "Optical size axis value"
445
451
  option :named_instance, type: :string,
446
- desc: "Use named instance (e.g., 'Bold', 'Light')",
452
+ desc: "Use named instance by fvar index (e.g., 0, 1; see --list-instances)",
447
453
  aliases: "-n"
448
454
  option :list_instances, type: :boolean, default: false,
449
455
  desc: "List available named instances",
@@ -463,7 +469,7 @@ module Fontisan
463
469
  # fontisan instance variable.ttf --wght=700 --output=bold.ttf
464
470
  #
465
471
  # @example Use named instance
466
- # fontisan instance variable.ttf --named-instance="Bold" --output=bold.ttf
472
+ # fontisan instance variable.ttf --named-instance=0 --output=bold.ttf
467
473
  #
468
474
  # @example Instance with format conversion
469
475
  # fontisan instance variable.ttf --wght=700 --to=woff2 --output=bold.woff2
@@ -668,7 +674,7 @@ module Fontisan
668
674
  # fontisan unpack family.ttc --output-dir extracted/ --prefix "NotoSans"
669
675
  def unpack(font_file)
670
676
  command = Commands::UnpackCommand.new(font_file, options)
671
- result = command.run
677
+ result = command.run_routed
672
678
 
673
679
  unless options[:quiet]
674
680
  puts "Collection unpacked successfully:"
@@ -103,9 +103,9 @@ module Fontisan
103
103
  # ------------------------------------------------------------------
104
104
 
105
105
  def populate_identity(report, face)
106
- return unless face.has_table?(Constants::NAME_TAG)
106
+ name_table = readable_table(face, Constants::NAME_TAG)
107
+ return unless name_table
107
108
 
108
- name_table = face.table(Constants::NAME_TAG)
109
109
  report.family_name = name_table.english_name(Tables::Name::FAMILY)
110
110
  report.subfamily_name = name_table.english_name(Tables::Name::SUBFAMILY)
111
111
  report.full_name = name_table.english_name(Tables::Name::FULL_NAME)
@@ -113,9 +113,17 @@ module Fontisan
113
113
  name_table.english_name(Tables::Name::POSTSCRIPT_NAME)
114
114
  report.version = name_table.english_name(Tables::Name::VERSION)
115
115
 
116
- return unless face.has_table?(Constants::HEAD_TAG)
116
+ head = readable_table(face, Constants::HEAD_TAG)
117
+ report.font_revision = head.font_revision if head
118
+ end
117
119
 
118
- report.font_revision = face.table(Constants::HEAD_TAG).font_revision
120
+ # A table listed in the directory whose data cannot be read (offset or
121
+ # length outside the file) comes back from `face.table` as nil. The
122
+ # audit reports on what is readable, so such a table is treated as
123
+ # absent: its section stays empty instead of raising NoMethodError on
124
+ # nil. The native tier does the same.
125
+ def readable_table(face, tag)
126
+ face.has_table?(tag) ? face.table(tag) : nil
119
127
  end
120
128
 
121
129
  # ------------------------------------------------------------------
@@ -126,13 +134,15 @@ module Fontisan
126
134
  report.is_variable = false
127
135
  report.italic = false
128
136
  report.bold = false
129
- populate_os2_style(report, face) if face.has_table?(Constants::OS2_TAG)
130
- populate_head_style(report, face) if face.has_table?(Constants::HEAD_TAG)
131
- populate_fvar_style(report, face) if face.has_table?(Constants::FVAR_TAG)
137
+ populate_os2_style(report, face)
138
+ populate_head_style(report, face)
139
+ populate_fvar_style(report, face)
132
140
  end
133
141
 
134
142
  def populate_os2_style(report, face)
135
- os2 = face.table(Constants::OS2_TAG)
143
+ os2 = readable_table(face, Constants::OS2_TAG)
144
+ return unless os2
145
+
136
146
  report.weight_class = os2.us_weight_class
137
147
  report.width_class = os2.us_width_class
138
148
  report.italic = os2.fs_selection && (os2.fs_selection & 0x01).positive?
@@ -141,7 +151,9 @@ module Fontisan
141
151
  end
142
152
 
143
153
  def populate_head_style(report, face)
144
- head = face.table(Constants::HEAD_TAG)
154
+ head = readable_table(face, Constants::HEAD_TAG)
155
+ return unless head
156
+
145
157
  mac_style = head.mac_style || 0
146
158
  # head macStyle overrides OS/2 fsSelection only when OS/2 didn't set it
147
159
  report.italic = true if (mac_style & 0x02).positive?
@@ -149,8 +161,10 @@ module Fontisan
149
161
  end
150
162
 
151
163
  def populate_fvar_style(report, face)
164
+ fvar = readable_table(face, Constants::FVAR_TAG)
165
+ return unless fvar
166
+
152
167
  report.is_variable = true
153
- fvar = face.table(Constants::FVAR_TAG)
154
168
  report.axes = fvar.axes.map do |axis|
155
169
  Models::AuditAxis.new(
156
170
  tag: axis.axis_tag,
@@ -173,8 +187,8 @@ module Fontisan
173
187
  # ------------------------------------------------------------------
174
188
 
175
189
  def populate_coverage(report, face)
176
- if face.has_table?(Constants::CMAP_TAG)
177
- cmap = face.table(Constants::CMAP_TAG)
190
+ cmap = readable_table(face, Constants::CMAP_TAG)
191
+ if cmap
178
192
  mappings = cmap.unicode_mappings || {}
179
193
  report.total_codepoints = mappings.size
180
194
  report.cmap_subtables = cmap.subtable_formats
@@ -208,48 +222,29 @@ module Fontisan
208
222
  # OpenType layout (GSUB/GPOS)
209
223
  # ------------------------------------------------------------------
210
224
 
225
+ # GSUB and GPOS are each read once through the budgeted
226
+ # `script_features`, which serves both the scripts and their features.
211
227
  def populate_layout(report, face)
212
- report.opentype_scripts = collect_scripts(face)
213
- report.features = collect_features(face)
214
- end
215
-
216
- def collect_scripts(face)
217
228
  scripts = Set.new
218
- %w[GSUB GPOS].each do |tag|
219
- next unless face.has_table?(tag)
220
-
221
- table = face.table(tag)
222
- scripts.merge(table.scripts) if table
223
- end
224
- scripts.sort
225
- end
226
-
227
- def collect_features(face)
228
229
  features = Set.new
229
230
  %w[GSUB GPOS].each do |tag|
230
231
  next unless face.has_table?(tag)
231
232
 
232
233
  table = face.table(tag)
233
- features.merge(collect_features_from_table(table)) if table
234
- end
235
- features.sort
236
- end
234
+ next unless table
237
235
 
238
- def collect_features_from_table(layout_table)
239
- scripts = begin
240
- layout_table.scripts
241
- rescue StandardError
242
- []
236
+ scripts.merge(table.scripts)
237
+ table.script_features.each_value { |tags| features.merge(tags) }
243
238
  end
244
- scripts.flat_map { |script| features_for_script(layout_table, script) }
245
- rescue StandardError
246
- []
239
+ report.opentype_scripts = printable_tags(scripts.sort)
240
+ report.features = printable_tags(features.sort)
247
241
  end
248
242
 
249
- def features_for_script(layout_table, script)
250
- layout_table.features(script_tag: script)
251
- rescue StandardError
252
- []
243
+ # Layout tags come from BinData as ASCII-8BIT. A damaged table can yield
244
+ # bytes that are not UTF-8, which the JSON generator rejects. Each
245
+ # invalid byte becomes U+FFFD, as the native tier's lossy decode does.
246
+ def printable_tags(tags)
247
+ tags.map { |tag| tag.dup.force_encoding(Encoding::UTF_8).scrub }
253
248
  end
254
249
 
255
250
  # ------------------------------------------------------------------
@@ -64,10 +64,13 @@ module Fontisan
64
64
  # @option options [Boolean] :preserve_variation Preserve variation data (default: auto)
65
65
  # @option options [Boolean] :preserve_hints Preserve rendering hints (default: false)
66
66
  # @option options [String] :target_format Target outline format for collections: 'preserve' (default), 'ttf', or 'otf'
67
+ # @option options [Integer] :timestamp Fixed head.modified (Unix seconds)
68
+ # for WOFF2 output; nil (default) stamps the current time
67
69
  # @option options [Boolean] :no_validate Skip output validation
68
70
  # @option options [Boolean] :verbose Verbose output
69
71
  # @option options [ConversionOptions] :options ConversionOptions object
70
72
  def initialize(font_path, options = {})
73
+ check_sfnt_directory!(font_path)
71
74
  super(font_path, options)
72
75
 
73
76
  # Convert string keys to symbols for Thor compatibility. All command
@@ -113,6 +116,7 @@ module Fontisan
113
116
  # @raise [Error] If conversion fails
114
117
  def run
115
118
  validate_options!
119
+ Array(@output_paths || @output_path).each { |out| OutputGuard.check!(font_path, out) }
116
120
 
117
121
  if collection_file?
118
122
  if multi_format?
@@ -127,15 +131,64 @@ module Fontisan
127
131
  else
128
132
  convert_single_font(@target_formats.first, @output_paths.first)
129
133
  end
130
- rescue ArgumentError
134
+ rescue ArgumentError, OutputGuard::Refused
131
135
  # Let ArgumentError propagate for validation errors
132
136
  raise
133
137
  rescue StandardError => e
134
138
  raise Error, "Conversion failed: #{e.message}"
135
139
  end
136
140
 
141
+ # Execute through the engine selection (the CLI entry): a tier other than
142
+ # Ruby serves the plain single-target conversions it supports, anything
143
+ # else (several targets, instance coordinates, ConversionOptions, hints,
144
+ # collection target format, compression knobs, a font index) runs {#run}
145
+ # on the Ruby tier. A routed conversion prints the same summary lines
146
+ # (minus the variation note) unless +quiet+.
147
+ #
148
+ # @return [Hash] same as {#run} for a single target
149
+ def run_routed
150
+ validate_options!
151
+ gate = routed_options
152
+ return run unless gate && Engine.resolve(:convert, font_path.to_s, gate) != :ruby
153
+
154
+ result = Reference.convert(font_path, **gate)
155
+ print_routed_summary(result) unless @options[:quiet]
156
+ result
157
+ end
158
+
137
159
  private
138
160
 
161
+ # A plain sfnt whose table directory the engine tiers reject fails with
162
+ # their error, before the loader can raise its own (fontist/fontisan#159).
163
+ def check_sfnt_directory!(path)
164
+ path = path.to_path if path.respond_to?(:to_path)
165
+ return unless path.is_a?(String) && File.file?(path)
166
+ return unless %i[ttf otf].include?(FontLoader.detect_format(path))
167
+
168
+ SfntDirectory.check!(File.binread(path))
169
+ rescue SfntDirectory::Malformed => e
170
+ raise Error, "Conversion failed: #{e.message}"
171
+ end
172
+
173
+ # Reference.convert keywords when the call is a plain conversion; else nil.
174
+ def routed_options
175
+ return nil if multi_format? || @coordinates || @instance_index || @conv_options
176
+ return nil if @preserve_hints || !@preserve_variation.nil? || @collection_target_format != "preserve"
177
+ return nil if @options.fetch(:font_index, 0).to_i != 0
178
+ return nil if Converters::FormatConverter.all_strategy_option_names.any? { |name| @options.key?(name) }
179
+ return nil unless @output_path.is_a?(String)
180
+
181
+ { to: @target_formats.first, output: @output_path }
182
+ end
183
+
184
+ def print_routed_summary(result)
185
+ puts "Converting #{File.basename(font_path)} to #{result[:target_format]}..."
186
+ puts "Conversion complete!"
187
+ puts " Input: #{font_path} (#{format_size(result[:input_size])})"
188
+ puts " Output: #{result[:output_path]} (#{format_size(result[:output_size])})"
189
+ puts " Format: #{result[:source_format]} → #{result[:target_format]}"
190
+ end
191
+
139
192
  # @return [Boolean] true when more than one target format was given
140
193
  def multi_format?
141
194
  @target_formats.size > 1
@@ -268,6 +321,7 @@ module Fontisan
268
321
  output: @output_path,
269
322
  target_format: @collection_target_format,
270
323
  verbose: @options[:verbose],
324
+ timestamp: @options[:timestamp],
271
325
  options: @conv_options, # Pass ConversionOptions
272
326
  },
273
327
  )