fontisan 0.4.48 → 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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 1acd9a7fdcd6fc469e7d8ca2614a8e5e036248e31fa297d1056f151b2796ab27
4
- data.tar.gz: 6c9593f9cce03a5aba93dedf68a1c3606e25bf7f2deb5991443f048cb51c753e
3
+ metadata.gz: 51430e15cca3521c48311a779b13b499ff76052567fd9c87631bb840caffad5c
4
+ data.tar.gz: 5cbdd5fce36d23df906380ae8cd8e0d79182deaf85522d8b9dc9d767a73b0ff4
5
5
  SHA512:
6
- metadata.gz: 5db866166488d311c45a6fc0265ba3da422d28717469bc5303a06028dc2c50038d84d953d850303e967d55c59cbc1f3113a1ce364a9b0b2eab3be3f40e94845d
7
- data.tar.gz: bf0cecbde3bc1ebc7312ada4fafc112e8e6e905fe682a1f33ee46645cf8e54eadcad15c768d1a5b22212cd1ddc9b9928795e7bf94c044b0e528bf517920277ae
6
+ metadata.gz: f153bd0244883e0d0aa9cf7ba6ddd2e1e3ec279139846fdab239ad496de3bfda91a2e5f61fb19f7f7d3e437e92e61cf0d41c26f11c0b7597474914edd4942fe4
7
+ data.tar.gz: 954c26b260c3253a8e54f66f4c3a58980dbb5a0a1fd227eb4972acf464c4fc1560e811903ff70d742518f55bbd1d85218e07fd63dd306742cdffaa9bb5b2ea87
data/CHANGELOG.md CHANGED
@@ -9,10 +9,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
9
9
 
10
10
  ### Changed
11
11
 
12
- - The default engine is now `FONTISAN_ENGINE=auto`: installs with a native tier
13
- serve the path-based `Fontisan::Reference` operations from it (native, then
14
- ffi), and installs without one fall back to Ruby with no toolchain needed.
15
- Set `FONTISAN_ENGINE=ruby` to opt out. Engine: fontisan-rs at git rev
12
+ - `FONTISAN_ENGINE=auto` (the default) resolves to the Ruby tier until the
13
+ phase-3 gates pass (fontisan#160); `FONTISAN_ENGINE=native` or `ffi` still
14
+ select the Rust tiers explicitly. The native-preferring order is kept as
15
+ `Engine::NATIVE_PREFERRED_ORDER` for the later flip. Engine: fontisan-rs at git rev
16
16
  `daffb3f45b67517e924a3e5d0e113a2ecbde9959` (crate version 0.0.0, not yet on
17
17
  crates.io), bundled as the magnus extension and the C-ABI shared library.
18
18
  Platform gems: `x86_64-linux`, `x86_64-linux-musl`, `arm64-darwin`,
data/Cargo.lock CHANGED
@@ -185,7 +185,7 @@ dependencies = [
185
185
  [[package]]
186
186
  name = "fontisan"
187
187
  version = "0.0.0"
188
- source = "git+https://github.com/fontist/fontisan-rs?rev=daffb3f45b67517e924a3e5d0e113a2ecbde9959#daffb3f45b67517e924a3e5d0e113a2ecbde9959"
188
+ source = "git+https://github.com/fontist/fontisan-rs?rev=f45057a12e15ba9f2c02526cd8ca0603c80edaf9#f45057a12e15ba9f2c02526cd8ca0603c80edaf9"
189
189
  dependencies = [
190
190
  "brotli",
191
191
  "brotli-decompressor",
@@ -252,9 +252,9 @@ dependencies = [
252
252
 
253
253
  [[package]]
254
254
  name = "magnus"
255
- version = "0.8.4"
255
+ version = "0.9.4"
256
256
  source = "registry+https://github.com/rust-lang/crates.io-index"
257
- checksum = "e76237a607e1dea288dd0ef0c6c8f49037df2152d14bb52b3542c46522d9e6fc"
257
+ checksum = "3c5f2dd2017d172e2fde9969a35f10f1374a4dd79b37a17f1847f83201883de7"
258
258
  dependencies = [
259
259
  "magnus-macros",
260
260
  "rb-sys",
@@ -264,9 +264,9 @@ dependencies = [
264
264
 
265
265
  [[package]]
266
266
  name = "magnus-macros"
267
- version = "0.8.0"
267
+ version = "0.9.1"
268
268
  source = "registry+https://github.com/rust-lang/crates.io-index"
269
- checksum = "47607461fd8e1513cb4f2076c197d8092d921a1ea75bd08af97398f593751892"
269
+ checksum = "9dafde2eeb66f090e0f326112323eb8324b12cb32b5d1210e541d3df6b0ce77e"
270
270
  dependencies = [
271
271
  "proc-macro2",
272
272
  "quote",
data/README.adoc CHANGED
@@ -60,11 +60,10 @@ operations from three tiers: `native` (a precompiled Rust extension), `ffi` (the
60
60
  bundled Rust shared library, loaded through the `ffi` gem) and `ruby` (the pure
61
61
  Ruby implementation, always present).
62
62
 
63
- The default is `auto`: the first available tier wins, in the order
64
- `native`, `ffi`, `ruby`. An operation a tier cannot serve goes to the next one.
65
- Installed from the source gem on a machine with no Rust toolchain and no
66
- bundled library, `auto` serves everything from `ruby`, with no warning and
67
- no error.
63
+ The default is `auto`, which currently serves everything from `ruby`: the Rust
64
+ tiers are used only when selected with `FONTISAN_ENGINE=native` or `ffi`, until
65
+ the native tier's release gates pass (see fontist/fontisan#160). After that,
66
+ `auto` will pick the first available tier in the order `native`, `ffi`, `ruby`.
68
67
 
69
68
  [cols="1,3"]
70
69
  |===
@@ -85,6 +84,24 @@ unset, empty, `0`, `false`, `no` and `off` leave it off; any other value raises
85
84
  an operation. See link:docs/guide/engines.md[Engines] for tiers, platforms and
86
85
  troubleshooting.
87
86
 
87
+ === Python face
88
+
89
+ https://github.com/fontist/fontisan-python[fontisan-python] is the Python face
90
+ of fontisan. It is a setuptools package that rides the same Rust cdylib the
91
+ `ffi` tier loads, shipped as per-platform package data and bound with
92
+ `ctypes`. It is not a second engine and adds no new FFI surface.
93
+
94
+ It binds the batch audit and table-read operations. Anything the C ABI does not
95
+ expose returns an explicit `unsupported` result rather than a guess.
96
+
97
+ Its results are held to the same parity contract as the other faces: they are
98
+ compared against the Ruby-tier goldens in `corpus/` (see
99
+ link:https://github.com/fontist/fontisan/issues/166[fontist/fontisan#166]).
100
+
101
+ NOTE: The package name on PyPI and the Python version floor are not settled,
102
+ and nothing is published yet. Treat the package as unreleased until the
103
+ maintainers say otherwise.
104
+
88
105
  == Installation
89
106
 
90
107
  Add this line to your application's Gemfile:
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "rubygems/package"
4
+
5
+ # Builds the lib-only x64-mingw32 platform stub (the parsanol-ruby
6
+ # release protocol). The newest x64-mingw32 Ruby is 3.0, outside the
7
+ # cross-gem ABI set (3.2+), so a native gem cannot exist for that
8
+ # platform; the stub carries the pure-Ruby engine so the platform
9
+ # matrix on RubyGems is complete for resolvers and installs build
10
+ # nothing.
11
+ spec = Gem::Specification.load("fontisan.gemspec")
12
+ spec.platform = Gem::Platform.new("x64-mingw32")
13
+ spec.extensions = []
14
+ spec.files = spec.files.reject { |f| f.start_with?("ext/") }
15
+ Gem::Package.build(spec)
@@ -31,7 +31,7 @@ Set `FONTISAN_ENGINE` before the process starts. Unset or empty means `auto`:
31
31
  | `ruby` | Use the Ruby tier only. |
32
32
  | `native` | Use the native tier. |
33
33
  | `ffi` | Use the ffi tier. |
34
- | `auto` | The default. Use the first tier that is available and supports the operation, in the order native, ffi, ruby. |
34
+ | `auto` | The default. Currently serves everything from ruby; the Rust tiers are used only when selected explicitly, until the phase-3 gates pass (fontisan#160). After that, the first available tier in the order native, ffi, ruby. |
35
35
 
36
36
  ```sh
37
37
  FONTISAN_ENGINE=native FONTISAN_ENGINE_STRICT=1 fontisan convert MyFont.ttf --to woff2 --output out.woff2
@@ -126,7 +126,7 @@ dependencies = [
126
126
  [[package]]
127
127
  name = "fontisan"
128
128
  version = "0.0.0"
129
- source = "git+https://github.com/fontist/fontisan-rs?rev=daffb3f45b67517e924a3e5d0e113a2ecbde9959#daffb3f45b67517e924a3e5d0e113a2ecbde9959"
129
+ source = "git+https://github.com/fontist/fontisan-rs?rev=f45057a12e15ba9f2c02526cd8ca0603c80edaf9#f45057a12e15ba9f2c02526cd8ca0603c80edaf9"
130
130
  dependencies = [
131
131
  "brotli",
132
132
  "brotli-decompressor",
@@ -15,4 +15,4 @@ crate-type = ["cdylib"]
15
15
  [dependencies]
16
16
  # TEMPORARY (decision D3: the crate is not on crates.io yet). Replace with
17
17
  # `fontisan = { version = "=<release>", features = ["ffi"] }` once published.
18
- fontisan = { git = "https://github.com/fontist/fontisan-rs", rev = "daffb3f45b67517e924a3e5d0e113a2ecbde9959", features = ["ffi"] }
18
+ fontisan = { git = "https://github.com/fontist/fontisan-rs", rev = "f45057a12e15ba9f2c02526cd8ca0603c80edaf9", features = ["ffi"] }
@@ -13,8 +13,8 @@ crate-type = ["cdylib"]
13
13
  # TEMPORARY (decision D3: the crate is not on crates.io yet). Replace with
14
14
  # `fontisan = "=<version>"` once published. The rev must be a commit on
15
15
  # fontist/fontisan-rs; keep it equal to the rev in ext/fontisan_cdylib/Cargo.toml.
16
- fontisan = { git = "https://github.com/fontist/fontisan-rs", rev = "daffb3f45b67517e924a3e5d0e113a2ecbde9959" }
17
- magnus = "=0.8.4"
16
+ fontisan = { git = "https://github.com/fontist/fontisan-rs", rev = "f45057a12e15ba9f2c02526cd8ca0603c80edaf9" }
17
+ magnus = "=0.9.4"
18
18
  rb-sys = { version = "=0.9.130", default-features = false }
19
19
 
20
20
  [lints.rust]
@@ -9,13 +9,14 @@
9
9
  //! section touches Ruby: inputs are copied into owned Rust values first and
10
10
  //! the result is plain Rust data until the GVL is back.
11
11
  //! * A failure is raised as `Fontisan::Native::Failure` carrying the engine's
12
- //! `[class, message, [[cause class, cause message], ...]]`; the Ruby side
12
+ //! `[class, message, [[cause class, cause message], ...], error kind]`; the Ruby side
13
13
  //! rebuilds the Ruby tier's exception class and cause chain from it. A Rust
14
14
  //! panic is caught inside the released section and raised as
15
15
  //! `Fontisan::Native::Panic`.
16
16
  use fontisan::audit;
17
17
  use fontisan::convert::{self, Target};
18
18
  use fontisan::json::Json;
19
+ use fontisan::ErrorKind;
19
20
  use fontisan::read;
20
21
  use fontisan::scan::{self, RowStatus};
21
22
  use fontisan::sfnt::{self, Format, LoadingMode, Options};
@@ -36,6 +37,8 @@ enum Fail {
36
37
  class: String,
37
38
  message: String,
38
39
  causes: Vec<(String, String)>,
40
+ /// `ErrorKind` code (the C ABI's `FONTISAN_KIND_*`); the Ruby side maps by it.
41
+ kind: i32,
39
42
  },
40
43
  Panic(String),
41
44
  }
@@ -46,6 +49,7 @@ impl Fail {
46
49
  class: class.to_string(),
47
50
  message: message.into(),
48
51
  causes: Vec::new(),
52
+ kind: ErrorKind::from_class(class).code(),
49
53
  }
50
54
  }
51
55
 
@@ -75,10 +79,13 @@ impl Fail {
75
79
  .collect(),
76
80
  _ => Vec::new(),
77
81
  };
82
+ let class = text("class");
83
+ let kind = ErrorKind::from_class(&class).code();
78
84
  Self::Engine {
79
- class: text("class"),
85
+ class,
80
86
  message: text("message"),
81
87
  causes,
88
+ kind,
82
89
  }
83
90
  }
84
91
  }
@@ -150,6 +157,7 @@ fn raise(ruby: &Ruby, fail: Fail) -> Error {
150
157
  class,
151
158
  message,
152
159
  causes,
160
+ kind,
153
161
  } => {
154
162
  let klass: magnus::ExceptionClass = native.const_get("Failure")?;
155
163
  let exc: Value = klass.funcall("new", (message.as_str(),))?;
@@ -160,10 +168,11 @@ fn raise(ruby: &Ruby, fail: Fail) -> Error {
160
168
  pair.push(ruby.str_new(m))?;
161
169
  causes_rb.push(pair)?;
162
170
  }
163
- let details = ruby.ary_new_capa(3);
171
+ let details = ruby.ary_new_capa(4);
164
172
  details.push(ruby.str_new(&class))?;
165
173
  details.push(ruby.str_new(&message))?;
166
174
  details.push(causes_rb)?;
175
+ details.push(kind)?;
167
176
  exc.funcall::<_, _, Value>("instance_variable_set", ("@details", details))?;
168
177
  let exception = magnus::Exception::from_value(exc)
169
178
  .ok_or_else(|| Error::new(ruby.exception_runtime_error(), "bad failure"))?;
@@ -310,7 +319,7 @@ fn native_audit_dir_rows(ruby: &Ruby, dir: String, validate: bool) -> Result<RAr
310
319
  }
311
320
 
312
321
  /// Whether the engine reads the file itself: false for a file that is gone, a
313
- /// directory, dfont and Type 1 (the Ruby tier serves those).
322
+ /// directory, dfont, Type 1 and anything that is not a font (the Ruby tier serves those).
314
323
  fn native_supports_file(ruby: &Ruby, path: String) -> Result<bool, Error> {
315
324
  finish(
316
325
  ruby,
@@ -323,10 +332,16 @@ fn native_supports_file(ruby: &Ruby, path: String) -> Result<bool, Error> {
323
332
  if file.take(256).read_to_end(&mut head).is_err() {
324
333
  return Ok(false);
325
334
  }
326
- Ok(!matches!(
327
- sfnt::detect_format(&head),
328
- Some(Format::Dfont | Format::Pfa | Format::Pfb)
329
- ))
335
+ // Not a font at all (random bytes, a zero-filled or empty file): the
336
+ // Ruby tier raises the canonical InvalidFontError, and the engine never
337
+ // slurps a huge non-font into memory. A `ttcf` file whose directory lies
338
+ // past the 256-byte head is a font the engine reads itself.
339
+ let unknown = sfnt::detect_format(&head).is_none() && !head.starts_with(b"ttcf");
340
+ Ok(!unknown
341
+ && !matches!(
342
+ sfnt::detect_format(&head),
343
+ Some(Format::Dfont | Format::Pfa | Format::Pfb)
344
+ ))
330
345
  }),
331
346
  )
332
347
  }
@@ -13,14 +13,45 @@ module Fontisan
13
13
  CONVERT_OPTIONS = %i[to output timestamp quiet].freeze
14
14
  SUBSET_PROFILES = %w[web pdf minimal].freeze
15
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
16
18
 
17
19
  BYTE_OPERATIONS = %i[convert extract instance subset].freeze
18
20
 
19
21
  # "<ruby class>: <message>": how the engine reports a Ruby exception it
20
22
  # mirrors (the byte operations carry one class and one message, no chain).
21
23
  FAILURE_MESSAGE = /\A([A-Z]\w*(?:::\w+)*): (.*)\z/m
22
- # The engine's text for a file that is no font; Ruby's is InvalidFontError.
23
- UNRECOGNISED_FORMAT_MESSAGE = "Conversion failed: unrecognised font format"
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
24
55
 
25
56
  private
26
57
 
@@ -79,7 +110,7 @@ module Fontisan
79
110
 
80
111
  def extract_options?(options)
81
112
  options.keys.sort == %i[index output_dir] && options[:index].is_a?(Integer) &&
82
- !options[:index].negative? && options[:output_dir].respond_to?(:to_str)
113
+ options[:index].between?(0, MAX_FONT_INDEX) && options[:output_dir].respond_to?(:to_str)
83
114
  end
84
115
 
85
116
  def instance_options?(options, path)
@@ -107,14 +138,44 @@ module Fontisan
107
138
  false
108
139
  end
109
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
+
110
156
  def finish_convert(path, target, output, bytes)
111
- File.binwrite(output, bytes)
157
+ write_output(output, bytes)
112
158
  result = { success: true, input_path: path, output_path: output }
113
159
  result.merge!(convert_formats(path, target))
114
160
  result.merge(input_size: File.size(path), output_size: bytes.bytesize,
115
161
  **convert_tail(path))
116
162
  end
117
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
+
118
179
  def convert_formats(path, target)
119
180
  return { source_format: single_format(path), target_format: target } unless collection_file?(path)
120
181
 
@@ -170,37 +231,71 @@ module Fontisan
170
231
  # Raise the Ruby tier's exception: class, message and the cause chain
171
232
  # (each cause is raised so that its own #cause is set).
172
233
  def raise_failure(details, byte_operation: false)
173
- class_name, message, causes = details
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
174
240
  cause = nil
175
- causes.reverse_each { |name, text| cause = build_exception(name, text, cause) }
176
- klass, message = byte_failure(class_name, message) if byte_operation
177
- raise build_instance(klass || exception_class(class_name), message), cause: cause
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)]
178
251
  end
179
252
 
180
253
  # The Ruby class and message of a failed byte operation, so that a tier
181
254
  # never changes what a caller can rescue or match: an engine error that
182
255
  # names the Ruby exception it mirrors ("RuntimeError: ...") is unwrapped,
183
- # and the engine's unrecognised-format error becomes the loader's.
184
- def byte_failure(class_name, message)
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
+
185
263
  if class_name == "Fontisan::Error" && (match = FAILURE_MESSAGE.match(message))
186
264
  class_name = match[1]
187
265
  message = match[2]
188
266
  end
189
- return [InvalidFontError, FontLoader::UNKNOWN_FORMAT_MESSAGE] if message == UNRECOGNISED_FORMAT_MESSAGE
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)
190
271
 
191
272
  [exception_class(class_name), message]
192
273
  end
193
274
 
194
- # `klass.new(message)`, or the `message:` keyword form some Fontisan
195
- # errors use (MissingVariationTableError); never a failed constructor.
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.
196
286
  def build_instance(klass, message)
197
287
  klass.new(message)
198
288
  rescue ArgumentError
199
- begin
200
- klass.new(message: message)
201
- rescue ArgumentError
202
- Fontisan::Error.new(message)
203
- end
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)
204
299
  end
205
300
 
206
301
  def build_exception(name, text, cause)
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"
@@ -116,6 +116,7 @@ module Fontisan
116
116
  # @raise [Error] If conversion fails
117
117
  def run
118
118
  validate_options!
119
+ Array(@output_paths || @output_path).each { |out| OutputGuard.check!(font_path, out) }
119
120
 
120
121
  if collection_file?
121
122
  if multi_format?
@@ -130,7 +131,7 @@ module Fontisan
130
131
  else
131
132
  convert_single_font(@target_formats.first, @output_paths.first)
132
133
  end
133
- rescue ArgumentError
134
+ rescue ArgumentError, OutputGuard::Refused
134
135
  # Let ArgumentError propagate for validation errors
135
136
  raise
136
137
  rescue StandardError => e
@@ -51,8 +51,13 @@ module Fontisan
51
51
  @target_formats.map { |fmt| "#{@base_path}.#{fmt}" }
52
52
  end
53
53
 
54
+ # A dot file whose whole name is the extension (".ttf") has one: appending
55
+ # the format would write ".ttf.ttf".
54
56
  def has_extension?
55
- !File.extname(@base_path).strip.downcase.empty?
57
+ name = File.basename(@base_path)
58
+ return true if name.length > 1 && name.start_with?(".") && name.count(".") == 1
59
+
60
+ !File.extname(name).strip.downcase.empty?
56
61
  end
57
62
  end
58
63
  end
@@ -6,8 +6,10 @@ module Fontisan
6
6
  # FONTISAN_ENGINE=ruby|native|ffi|auto (default auto)
7
7
  # FONTISAN_ENGINE_STRICT=1 (no fallback)
8
8
  #
9
- # `auto` resolves native, then ffi, then ruby: the first tier that is
10
- # available and supports the operation wins. A forced tier that is unavailable
9
+ # `auto` resolves to the Ruby tier until the phase-3 gates pass
10
+ # (fontisan#160); only an explicit native or ffi selection uses the Rust
11
+ # tiers. The post-gate order (native, ffi, ruby) is
12
+ # {NATIVE_PREFERRED_ORDER}. A forced tier that is unavailable
11
13
  # falls back to Ruby silently, or raises {TierUnavailable} at setup when
12
14
  # strict. An operation (or a path, e.g. dfont) a tier cannot serve always goes to
13
15
  # Ruby, strict or not. FONTISAN_MODE and FONTISAN_LAZY are not read here.
@@ -27,11 +29,16 @@ module Fontisan
27
29
  SELECTIONS = %w[ruby native ffi auto].freeze
28
30
  STRICT_ON = %w[1 true yes on].freeze
29
31
  STRICT_OFF = ["", "0", "false", "no", "off"].freeze
30
- AUTO_ORDER = %i[native ffi ruby].freeze
32
+ # The order `auto` will use once the phase-3 gates pass (fontisan#160).
33
+ # Until then `auto` resolves to ruby only; the 2d flip is replacing
34
+ # AUTO_ORDER with this constant.
35
+ NATIVE_PREFERRED_ORDER = %i[native ffi ruby].freeze
36
+ AUTO_ORDER = %i[ruby].freeze
31
37
  OPS = %i[read outline_hashes audit audit_dir scan convert extract
32
38
  instance glyph_ids subset].freeze
33
39
  REPLACEABLE_TIERS = %i[native ffi].freeze
34
40
  TIER_CONTRACT = %i[available? supports? call].freeze
41
+ FACE_ENTRY = "fontisan/ruby"
35
42
  ROW_RECORDER = :fontisan_engine_rows
36
43
  IN_OPERATION = :fontisan_engine_in_operation
37
44
 
@@ -68,6 +75,7 @@ module Fontisan
68
75
 
69
76
  @mutex = Mutex.new
70
77
  @tiers = nil
78
+ @registered_tiers = {}.freeze
71
79
  @served = {}
72
80
  @counters = nil
73
81
  @availability = {}
@@ -174,7 +182,7 @@ module Fontisan
174
182
  record(:ruby, operation, nil)
175
183
  end
176
184
 
177
- # Forget probes, counters, served state and registered tiers.
185
+ # Forget probes, counters, served state and temporary tier overrides.
178
186
  def reset!
179
187
  @mutex.synchronize do
180
188
  @served = {}
@@ -182,14 +190,28 @@ module Fontisan
182
190
  @availability = {}
183
191
  @tiers = @tiers.slice(:ruby) if @tiers
184
192
  end
185
- Native.reset!
186
- Ffi.reset!
193
+ @registered_tiers.each_value do |tier|
194
+ tier.reset! if tier.respond_to?(:reset!)
195
+ end
196
+ end
197
+
198
+ # Register a provider independently of Reference's lazy installation.
199
+ # Providers survive reset!; reset! on a provider is optional.
200
+ def register_tier(name, mod)
201
+ validate_registration!(name, mod)
202
+ @mutex.synchronize do
203
+ @registered_tiers = @registered_tiers.merge(name.to_sym => mod).freeze
204
+ @availability.delete(name.to_sym)
205
+ end
187
206
  end
188
207
 
189
- # Register a tier object (tests, or the extension itself). A bad
208
+ # Override a tier object until reset! (tests, or the extension itself). A bad
190
209
  # registration raises here, at setup, never as a silent fallback later.
191
210
  def register(name, tier)
211
+ return register_tier(name, tier) if @loading_face
212
+
192
213
  validate_registration!(name, tier)
214
+ Fontisan::Reference unless @tiers
193
215
  @mutex.synchronize do
194
216
  @tiers = @tiers.merge(name.to_sym => tier).freeze
195
217
  @availability.delete(name.to_sym)
@@ -268,7 +290,7 @@ module Fontisan
268
290
  def tier_object(name)
269
291
  case name
270
292
  when :ruby then @tiers.fetch(:ruby)
271
- else @tiers[name] || { native: Native, ffi: Ffi }.fetch(name)
293
+ else @tiers[name] || @registered_tiers[name]
272
294
  end
273
295
  end
274
296
 
@@ -282,11 +304,29 @@ module Fontisan
282
304
 
283
305
  # Any failure while probing is "not available"; never an exception.
284
306
  def probe(name)
307
+ load_face if REPLACEABLE_TIERS.include?(name) && !@tiers.key?(name)
285
308
  tier_object(name).available? || false
286
309
  rescue StandardError, ScriptError
287
310
  false
288
311
  end
289
312
 
313
+ # The optional face registers its own providers through register. Keep
314
+ # those registrations across resets, just like the bundled providers.
315
+ def load_face
316
+ return if @face_loaded
317
+
318
+ begin
319
+ @loading_face = true
320
+ require FACE_ENTRY
321
+ @face_loaded = true
322
+ rescue LoadError
323
+ # Bundled providers remain usable until they move to the face gem.
324
+ nil
325
+ ensure
326
+ @loading_face = false
327
+ end
328
+ end
329
+
290
330
  # A tier may also vet the call's keyword options (`supports_options?`).
291
331
  def supports?(name, operation, path, options = nil)
292
332
  tier = tier_object(name)
@@ -346,5 +386,8 @@ module Fontisan
346
386
  Thread.current[ROW_RECORDER] = previous
347
387
  end
348
388
  end
389
+
390
+ register_tier(:native, Native)
391
+ register_tier(:ffi, Ffi)
349
392
  end
350
393
  end
@@ -17,7 +17,7 @@ module Fontisan
17
17
  UNSUPPORTED = 10
18
18
 
19
19
  # The result block of one call; its pointers die with {#close}.
20
- Reply = Struct.new(:status, :payload, :message)
20
+ Reply = Struct.new(:status, :payload, :message, :kind)
21
21
 
22
22
  class Header < FFI::Struct
23
23
  layout :magic, :uint32, :abi_version, :uint32, :struct_size, :uint32,
@@ -35,7 +35,8 @@ module Fontisan
35
35
 
36
36
  class Result < FFI::Struct
37
37
  layout :header, Header, :status, :int32, :error, ErrorRow,
38
- :payload, :pointer, :payload_len, :size_t
38
+ :payload, :pointer, :payload_len, :size_t,
39
+ :error_kind, :int32, :reserved, :int32
39
40
  end
40
41
 
41
42
  # Loads +path+ and binds its symbols.
@@ -106,7 +107,8 @@ module Fontisan
106
107
  result = Result.new(pointer)
107
108
  Reply.new(result[:status], bytes(result[:payload], result[:payload_len]),
108
109
  bytes(result[:error][:message], result[:error][:message_len])
109
- .force_encoding(Encoding::UTF_8))
110
+ .force_encoding(Encoding::UTF_8),
111
+ result[:error_kind])
110
112
  ensure
111
113
  @binding.fontisan_result_free(pointer) unless pointer.null?
112
114
  end
data/lib/fontisan/ffi.rb CHANGED
@@ -83,7 +83,11 @@ module Fontisan
83
83
  # Options the engine honours; anything else is served by Ruby. The
84
84
  # read-side operations check their own options and fall back inside.
85
85
  def supports_options?(operation, options, path = nil)
86
- return byte_options?(operation, options, path) if ByteOps::BYTE_OPERATIONS.include?(operation)
86
+ if ByteOps::BYTE_OPERATIONS.include?(operation)
87
+ return false unless byte_options?(operation, options, path)
88
+
89
+ return operation != :instance || fixed_coordinates?(options[:coords])
90
+ end
87
91
 
88
92
  OPERATIONS.include?(operation)
89
93
  end
@@ -99,6 +103,18 @@ module Fontisan
99
103
 
100
104
  attr_reader :client
101
105
 
106
+ # The instance request carries each coordinate as a signed 16.16 Fixed.
107
+ # A value that is not finite, does not fit, or is not an exact multiple
108
+ # of 1/65536 would be rounded or wrapped (1e9 became -13824.0), so the
109
+ # engine would build a different font than the Ruby and native tiers;
110
+ # those requests go to Ruby.
111
+ def fixed_coordinates?(coords)
112
+ coords.each_value.all? do |value|
113
+ scaled = Float(value) * FIXED_ONE
114
+ scaled.finite? && scaled.abs < 2**31 && scaled == scaled.round
115
+ end
116
+ end
117
+
102
118
  def probe
103
119
  require "fontisan/ffi/client"
104
120
  path = library_path or return false
@@ -125,8 +141,11 @@ module Fontisan
125
141
  bundled && File.file?(bundled) ? bundled : File.expand_path("ffi/#{file}", __dir__)
126
142
  end
127
143
 
144
+ # dfont, Type 1 and anything that is not a font (the native tier hands
145
+ # those to Ruby too, so auto never lands them on this tier).
128
146
  def ruby_only?(path)
129
- RUBY_ONLY_FORMATS.include?(FontLoader.detect_format(path))
147
+ format = FontLoader.detect_format(path)
148
+ format.nil? || RUBY_ONLY_FORMATS.include?(format)
130
149
  rescue StandardError
131
150
  false
132
151
  end
@@ -135,6 +154,7 @@ module Fontisan
135
154
  def serve_convert(path, output:, timestamp: nil, **options)
136
155
  path = File.path(path)
137
156
  target = convert_target(options.fetch(:to))
157
+ output = convert_output(path, output, target)
138
158
  stamp = timestamp ? unix_seconds(timestamp) : Time.now.to_i
139
159
  prefix = [ByteOps::TARGET_CODES.fetch(target), 0, stamp].pack("NNq>")
140
160
  bytes = byte_op(OP_CONVERT, prefix + File.binread(path))
@@ -143,11 +163,13 @@ module Fontisan
143
163
 
144
164
  # Same file layout as UnpackCommand: <output_dir>/<basename>.
145
165
  def serve_extract(path, index:, output_dir:)
146
- payload = byte_op(OP_EXTRACT, [index, 0, 0, 0].pack("NNNN") + File.binread(File.path(path)))
166
+ payload = byte_op(OP_EXTRACT, [index, 0, 0, 0].pack("NNNN") + unpacking_io { File.binread(File.path(path)) })
147
167
  length = payload.unpack1("N")
148
168
  name = payload.byteslice(4, length).force_encoding(Encoding::UTF_8)
149
- FileUtils.mkdir_p(output_dir)
150
- File.join(output_dir, name).tap { |out| File.binwrite(out, payload.byteslice(4 + length..)) }
169
+ unpacking_io do
170
+ FileUtils.mkdir_p(output_dir)
171
+ File.join(output_dir, name).tap { |out| File.binwrite(out, payload.byteslice(4 + length..)) }
172
+ end
151
173
  end
152
174
 
153
175
  def serve_instance(path, coords:, timestamp: nil)
@@ -198,15 +220,27 @@ module Fontisan
198
220
  end
199
221
 
200
222
  def raise_byte_failure(reply)
201
- match = ByteOps::FAILURE_MESSAGE.match(reply.message)
202
- if reply.status == CONVERT_FAILED && match
203
- klass, message = byte_failure(match[1], match[2])
204
- raise build_instance(klass, message)
223
+ if reply.status == CONVERT_FAILED
224
+ class_name, message = reported_failure(reply)
225
+ if class_name
226
+ klass, message = public_failure(*byte_failure(class_name, message, reply.kind))
227
+ raise build_instance(klass, message)
228
+ end
205
229
  end
206
230
 
207
231
  raise Fontisan::Error, "fontisan ffi status #{reply.status}: #{reply.message}"
208
232
  end
209
233
 
234
+ # The class name and message of a failed byte operation: the engine's
235
+ # "<class>: <message>" text, or the bare text under a kind that names its
236
+ # class (byte_failure then takes the class from the kind).
237
+ def reported_failure(reply)
238
+ match = ByteOps::FAILURE_MESSAGE.match(reply.message)
239
+ return [match[1], match[2]] if match
240
+
241
+ [Fontisan::Error.name, reply.message] if ByteOps::KIND_CLASSES.key?(reply.kind)
242
+ end
243
+
210
244
  def serve_read(path, mode: :metadata, lazy: true)
211
245
  return ruby(:read, path, mode: mode, lazy: lazy) unless %i[metadata full].include?(mode)
212
246
 
@@ -222,16 +256,23 @@ module Fontisan
222
256
  return ruby(:audit, path, validate: validate) unless [true, false, nil].include?(validate)
223
257
 
224
258
  path = reference_path(path)
225
- input = [File.basename(path).bytesize].pack("N") + File.basename(path).b + File.binread(path)
259
+ input = [File.basename(path).bytesize].pack("N") + File.basename(path).b + load_font_bytes(path)
226
260
  reply = client.call(OP_AUDIT, input, validate ? FLAG_VALIDATE : 0)
227
261
  return ruby(:audit, path, validate: validate) if reply.status == Client::UNSUPPORTED
228
262
 
229
263
  rows(reply)
230
264
  end
231
265
 
266
+ # An unreadable file is a Fontisan::Error, as the Ruby loader raises it.
267
+ def load_font_bytes(path)
268
+ File.binread(path)
269
+ rescue SystemCallError => e
270
+ raise Fontisan::Error, "Failed to load font: #{e.message}"
271
+ end
272
+
232
273
  def serve_scan(paths)
233
274
  Array(paths).flat_map do |path|
234
- reply = client.call(OP_SCAN, File.path(path))
275
+ reply = client.call(OP_SCAN, Reference.__send__(:path_arg, path, must_exist: false))
235
276
  result = reply.status == Client::OK ? decode(reply.payload) : nil
236
277
  result = nil if result&.any? { |row| row["status"] == "unsupported" }
237
278
  # "status" is the engine's routing marker; Reference rows have none.
@@ -308,8 +349,11 @@ module Fontisan
308
349
 
309
350
  # Raise the reported error as its Ruby class, message and cause chain.
310
351
  def raise_reported(report)
311
- raise_chain([report.slice("class", "message"),
312
- *Array(report["causes"])])
352
+ head = report.slice("class", "message")
353
+ klass, message = public_failure(exception_class(head["class"]), head["message"])
354
+ chain = [head, *Array(report["causes"])]
355
+ chain.unshift({ "class" => klass.name, "message" => message }) if klass == InvalidFontError && head["class"] != klass.name
356
+ raise_chain(chain)
313
357
  end
314
358
 
315
359
  def raise_chain(infos)
@@ -26,7 +26,7 @@ module Fontisan
26
26
  # engine pin in ext/*/Cargo.toml, which each build embeds. ABI_VERSION does
27
27
  # not move on a repin, so this is what keeps a stale binary from serving old
28
28
  # behaviour. A repin seds it with the Cargo files (repin-push162.sh).
29
- ENGINE_REV = "daffb3f45b67517e924a3e5d0e113a2ecbde9959"
29
+ ENGINE_REV = "f45057a12e15ba9f2c02526cd8ca0603c80edaf9"
30
30
 
31
31
  # Operations served natively. Convert, extract, instance and subset are
32
32
  # path-based only (card 2f): the object-based entry points
@@ -35,7 +35,8 @@ module Fontisan
35
35
  OPERATIONS = %i[read audit audit_dir scan convert extract instance subset].freeze
36
36
 
37
37
  # Raised by the extension for an engine failure; `details` is
38
- # `[class name, message, [[cause class, cause message], ...]]`.
38
+ # `[class name, message, [[cause class, cause message], ...], error kind]`;
39
+ # the kind is the engine's `ErrorKind` number (see {ByteOps::KIND_CLASSES}).
39
40
  class Failure < StandardError
40
41
  attr_reader :details
41
42
  end
@@ -149,7 +150,7 @@ module Fontisan
149
150
  def read_options?(options)
150
151
  return false unless options.keys.all? { |key| %i[mode lazy].include?(key) }
151
152
 
152
- %w[metadata full].include?(options.fetch(:mode, :metadata).to_s) &&
153
+ %i[metadata full].include?(options.fetch(:mode, :metadata)) &&
153
154
  [true, false].include?(options.fetch(:lazy, true))
154
155
  end
155
156
 
@@ -158,6 +159,7 @@ module Fontisan
158
159
  def convert(path, output:, timestamp: nil, **options)
159
160
  path = File.path(path)
160
161
  target = convert_target(options.fetch(:to))
162
+ output = convert_output(path, output, target)
161
163
  bytes = native_convert(path, ByteOps::TARGET_CODES.fetch(target), timestamp ? unix_seconds(timestamp) : Time.now.to_i)
162
164
  finish_convert(path, target, File.path(output), bytes)
163
165
  end
@@ -165,8 +167,10 @@ module Fontisan
165
167
  # Same file layout as UnpackCommand: <output_dir>/<basename>.
166
168
  def extract(path, index:, output_dir:)
167
169
  name, bytes = native_extract(File.path(path), index)
168
- FileUtils.mkdir_p(output_dir)
169
- File.join(output_dir, name).tap { |out| File.binwrite(out, bytes) }
170
+ unpacking_io do
171
+ FileUtils.mkdir_p(output_dir)
172
+ File.join(output_dir, name).tap { |out| File.binwrite(out, bytes) }
173
+ end
170
174
  end
171
175
 
172
176
  def instance(path, coords:, timestamp: nil)
@@ -184,7 +188,7 @@ module Fontisan
184
188
  end
185
189
 
186
190
  def read(path, mode: :metadata, lazy: true)
187
- native_read(File.path(path), mode.to_s == "metadata", lazy)
191
+ native_read(File.path(path), mode == :metadata, lazy)
188
192
  end
189
193
 
190
194
  def audit(path, validate: false)
@@ -0,0 +1,40 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Fontisan
4
+ # Refuses to write a conversion over the font it reads.
5
+ #
6
+ # The output is compared with the input after symlinks and `..` are resolved
7
+ # (a symlink to the input, or `dir/../input`, is the input). Every engine tier
8
+ # calls this before it converts, so none of them overwrites its own input.
9
+ module OutputGuard
10
+ # The output path is the input file.
11
+ class Refused < Error; end
12
+
13
+ module_function
14
+
15
+ # @param input [String, #to_path] the font being read
16
+ # @param output [String, #to_path] where the result would be written
17
+ # @raise [Refused] when both name the same file
18
+ # @return [void]
19
+ def check!(input, output)
20
+ source = resolve(File.path(input))
21
+ return if source.nil?
22
+ return unless resolve(File.path(output)) == source
23
+
24
+ raise Refused, "Output path #{File.path(output).inspect} is the input file " \
25
+ "#{File.path(input).inspect}; refusing to overwrite it"
26
+ end
27
+
28
+ # The real path of +path+; for a file that does not exist yet, the real
29
+ # directory plus the file name. nil when neither can be resolved.
30
+ def resolve(path)
31
+ File.realpath(path)
32
+ rescue SystemCallError
33
+ begin
34
+ File.join(File.realpath(File.dirname(path)), File.basename(path))
35
+ rescue SystemCallError
36
+ nil
37
+ end
38
+ end
39
+ end
40
+ end
@@ -50,9 +50,23 @@ module Fontisan
50
50
  is_fixed_pitch min_mem_type42 max_mem_type42 min_mem_type1
51
51
  max_mem_type1].freeze
52
52
 
53
+ # Ruby errors a malformed font can provoke inside the parsers and builders.
54
+ # They are not part of any contract; {.malformed_font} turns them into
55
+ # Fontisan::InvalidFontError. A bare RuntimeError is deliberately absent:
56
+ # the loaders raise "Invalid <Type> file: ..." and the specs and goldens
57
+ # pin that class. EOFError is absent too: the corpus goldens (read, audit,
58
+ # scan of the truncated fonts) pin it as the reference behaviour.
59
+ PARSER_LEAKS = [NoMethodError, IndexError, RangeError, TypeError, ZeroDivisionError].freeze
60
+
53
61
  autoload :TableDigests, "fontisan/reference/table_digests"
54
62
 
55
63
  class << self
64
+ # The InvalidFontError text for a leaked parser error, shared with the
65
+ # engine tiers that mirror the Ruby classes the engine reports.
66
+ def malformed_message(klass, message)
67
+ "Malformed font data (#{klass}): #{message}"
68
+ end
69
+
56
70
  # Read the structure of every face in a font file.
57
71
  #
58
72
  # @param path [String]
@@ -61,18 +75,20 @@ module Fontisan
61
75
  # @return [Array<Hash>] one Hash per face (see docs for the schema)
62
76
  def read(path, mode: :metadata, lazy: true)
63
77
  path = path_arg(path)
64
- sha = Digest::SHA256.file(path).hexdigest
65
- format = FontLoader.detect_format(path)&.to_s
66
- count = face_count(path)
67
- faces = Array.new(count) do |index|
68
- font = FontLoader.load(path, font_index: index, mode: mode, lazy: lazy)
69
- begin
70
- read_face(font, index, sha, format, mode, lazy)
71
- ensure
72
- font.close if font.respond_to?(:close)
78
+ malformed_font do
79
+ sha = Digest::SHA256.file(path).hexdigest
80
+ format = FontLoader.detect_format(path)&.to_s
81
+ count = face_count(path)
82
+ faces = Array.new(count) do |index|
83
+ font = FontLoader.load(path, font_index: index, mode: mode, lazy: lazy)
84
+ begin
85
+ read_face(font, index, sha, format, mode, lazy)
86
+ ensure
87
+ font.close if font.respond_to?(:close)
88
+ end
73
89
  end
90
+ normalize(faces)
74
91
  end
75
- normalize(faces)
76
92
  end
77
93
 
78
94
  # Per-glyph outline hashes of one face (full mode).
@@ -85,12 +101,14 @@ module Fontisan
85
101
  # @return [Hash] `{"kind"=>"glyf"|"cff"|nil, "hashes"=>[hex, ...]}`
86
102
  def outline_hashes(path, index: 0)
87
103
  path = path_arg(path)
88
- font = FontLoader.load(path, font_index: index, mode: :full,
89
- lazy: true)
90
- begin
91
- normalize(outline_data(font))
92
- ensure
93
- font.close if font.respond_to?(:close)
104
+ malformed_font do
105
+ font = FontLoader.load(path, font_index: index, mode: :full,
106
+ lazy: true)
107
+ begin
108
+ normalize(outline_data(font))
109
+ ensure
110
+ font.close if font.respond_to?(:close)
111
+ end
94
112
  end
95
113
  end
96
114
 
@@ -102,9 +120,11 @@ module Fontisan
102
120
  # @return [Array<Hash>] one canonical report per face
103
121
  def audit(path, validate: false)
104
122
  path = path_arg(path)
105
- result = Commands::AuditCommand.new(
106
- path, validate: validate || false, include_codepoints: false
107
- ).run
123
+ result = malformed_font do
124
+ Commands::AuditCommand.new(
125
+ path, validate: validate || false, include_codepoints: false
126
+ ).run
127
+ end
108
128
  normalize(Array(result).map { |report| audit_hash(report) })
109
129
  end
110
130
 
@@ -199,9 +219,11 @@ module Fontisan
199
219
  # @return [String] binary font bytes
200
220
  def instance(path, coords:, timestamp: nil)
201
221
  _ = timestamp
202
- font = FontLoader.load(path_arg(path), mode: :full, lazy: false)
222
+ path = path_arg(path)
223
+ check_sfnt_directory(path)
224
+ font = malformed_font { FontLoader.load(path, mode: :full, lazy: false) }
203
225
  values = coords.to_h { |tag, value| [tag.to_s, Float(value)] }
204
- Variable::Instancer.new(font).instance(values)
226
+ malformed_font { Variable::Instancer.new(font).instance(values) }
205
227
  end
206
228
 
207
229
  # Glyph ids kept by a subset request (fontist's `glyph_ids`).
@@ -213,9 +235,9 @@ module Fontisan
213
235
  # <basename>"
214
236
  def glyph_ids(path, unicodes: nil, text: nil)
215
237
  path = path_arg(path)
216
- font = FontLoader.load(path, mode: :full, lazy: false)
238
+ font = malformed_font { FontLoader.load(path, mode: :full, lazy: false) }
217
239
  codepoints = Array(unicodes).map(&:to_i) + text.to_s.codepoints
218
- gids_for(font, codepoints, File.basename(path))
240
+ malformed_font { gids_for(font, codepoints, File.basename(path)) }
219
241
  end
220
242
 
221
243
  # Subset a font to the glyphs of the given characters.
@@ -227,11 +249,13 @@ module Fontisan
227
249
  def subset(path, unicodes: nil, text: nil, profile: "web", timestamp: nil)
228
250
  _ = timestamp
229
251
  path = path_arg(path)
230
- font = FontLoader.load(path, mode: :full, lazy: false)
252
+ font = malformed_font { FontLoader.load(path, mode: :full, lazy: false) }
231
253
  codepoints = Array(unicodes).map(&:to_i) + text.to_s.codepoints
232
- gids = gids_for(font, codepoints, File.basename(path))
233
254
  options = Subset::Options.new(profile: profile)
234
- Subset::Builder.new(font, gids, options).build
255
+ malformed_font do
256
+ gids = gids_for(font, codepoints, File.basename(path))
257
+ Subset::Builder.new(font, gids, options).build
258
+ end
235
259
  end
236
260
 
237
261
  # Canonical JSON text of a read-type result: sorted keys, two-space
@@ -257,6 +281,26 @@ module Fontisan
257
281
 
258
282
  private
259
283
 
284
+ # Run a parse or build step of a font that may be malformed. A Ruby
285
+ # internal error (see PARSER_LEAKS) becomes Fontisan::InvalidFontError, the
286
+ # class every tier raises for bad font data; the original is the cause.
287
+ def malformed_font
288
+ yield
289
+ rescue *PARSER_LEAKS => e
290
+ raise InvalidFontError, malformed_message(e.class, e.message)
291
+ end
292
+
293
+ # A plain sfnt whose table directory runs past the end of the file fails
294
+ # as convert does (the engine tiers' own check, fontist/fontisan#159),
295
+ # not with whatever the loader or the instancer would trip over.
296
+ def check_sfnt_directory(path)
297
+ return unless File.file?(path) && %i[ttf otf].include?(FontLoader.detect_format(path))
298
+
299
+ SfntDirectory.check!(File.binread(path))
300
+ rescue SfntDirectory::Malformed => e
301
+ raise Error, "Conversion failed: #{e.message}"
302
+ end
303
+
260
304
  def path_arg(path, must_exist: true)
261
305
  unless path.is_a?(String) || path.respond_to?(:to_path)
262
306
  raise TypeError,
@@ -62,7 +62,7 @@ module Fontisan
62
62
  value = requested.transform_keys(&:to_s)[axis.tag]
63
63
  value = axis.default if value.nil?
64
64
  value = Float(value)
65
- unless value.between?(axis.minimum, axis.maximum)
65
+ unless value.finite? && value.between?(axis.minimum, axis.maximum)
66
66
  raise InvalidCoordinatesError.new(
67
67
  axis: axis.tag, value: value, range: [axis.minimum, axis.maximum],
68
68
  )
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Fontisan
4
- VERSION = "0.4.48"
4
+ VERSION = "0.4.49"
5
5
  end
data/lib/fontisan.rb CHANGED
@@ -135,6 +135,7 @@ module Fontisan
135
135
  autoload :Woff2Collection, "fontisan/woff2_collection"
136
136
  autoload :Woff2Font, "fontisan/woff2_font"
137
137
  autoload :SfntDirectory, "fontisan/sfnt_directory"
138
+ autoload :OutputGuard, "fontisan/output_guard"
138
139
  autoload :WoffContainer, "fontisan/woff_container"
139
140
  autoload :WoffFont, "fontisan/woff_font"
140
141
 
@@ -2,7 +2,7 @@
2
2
 
3
3
  # Tier fallback checks with strict mode OFF (fontist/fontisan#156 card 3a).
4
4
  #
5
- # ruby scripts/tier_fallback.rb TIERS [CORPUS_ROOT [SCENARIO]]
5
+ # ruby scripts/tier_fallback.rb TIERS [CORPUS_ROOT [SCENARIO]] [--gem GEM_NAME]
6
6
  #
7
7
  # TIERS is the comma list of non-Ruby tiers this platform is expected to have
8
8
  # (native,ffi | ffi | none). Without SCENARIO it runs every scenario below, each
@@ -17,8 +17,8 @@
17
17
  # ffi_abi_mismatch
18
18
  # mixed dfont and Type 1 rows are served by ruby, the
19
19
  # rest by the forced tier
20
- # auto_all, auto_no_native, `auto` resolves native, then ffi with native
21
- # auto_none removed, then ruby with both removed
20
+ # auto_all, auto_no_native, `auto` resolves to the first Engine::AUTO_ORDER tier
21
+ # auto_none still present (ruby until the #160 gates flip it)
22
22
  #
23
23
  # A scenario about a tier the platform lacks is skipped. Run it against an
24
24
  # INSTALLED gem on the CI matrix (outside the checkout), or locally with
@@ -33,15 +33,23 @@ SCENARIOS = %w[no_native no_ffi native_missing_symbol native_abi_mismatch
33
33
  ffi_missing_symbol ffi_abi_mismatch mixed
34
34
  auto_all auto_no_native auto_none].freeze
35
35
 
36
- usage = "usage: tier_fallback.rb native,ffi|ffi|none [corpus root [scenario]]"
37
- tiers = ARGV.fetch(0) { abort usage }.split(",") - ["none"]
38
- root = File.expand_path(ARGV.fetch(1, File.join(__dir__, "..", "corpus")))
39
- scenario = ARGV[2]
36
+ usage = "usage: tier_fallback.rb native,ffi|ffi|none [corpus root [scenario]] [--gem GEM_NAME]"
37
+ arguments = ARGV.dup
38
+ gem_option = arguments.index("--gem")
39
+ gem_name = "fontisan"
40
+ if gem_option
41
+ gem_name = arguments.fetch(gem_option + 1) { abort usage }
42
+ arguments.slice!(gem_option, 2)
43
+ end
44
+ tiers = arguments.fetch(0) { abort usage }.split(",") - ["none"]
45
+ root = File.expand_path(arguments.fetch(1, File.join(__dir__, "..", "corpus")))
46
+ scenario = arguments[2]
40
47
  abort "unknown tiers #{tiers.inspect}" unless (tiers - %w[native ffi]).empty?
41
48
 
42
49
  unless scenario
43
50
  results = SCENARIOS.to_h do |name|
44
- [name, system(RbConfig.ruby, __FILE__, tiers.join(",").then { |t| t.empty? ? "none" : t }, root, name)]
51
+ [name, system(RbConfig.ruby, __FILE__, tiers.join(",").then { |t| t.empty? ? "none" : t }, root, name,
52
+ "--gem", gem_name)]
45
53
  end
46
54
  failed = results.reject { |_, ok| ok }.keys
47
55
  puts failed.empty? ? "all #{SCENARIOS.size} fallback scenarios hold" : "FAILED: #{failed.join(', ')}"
@@ -74,6 +82,7 @@ end
74
82
 
75
83
  ENV["FONTISAN_ENGINE"] = "auto"
76
84
  ENV.delete("FONTISAN_ENGINE_STRICT")
85
+ gem gem_name
77
86
  case scenario
78
87
  when "no_native", "auto_no_native", "auto_none" then Object.prepend(Sabotage::BlockNative)
79
88
  end
@@ -177,11 +186,12 @@ begin
177
186
  Fontisan::Engine.reset!
178
187
  # dfont and PFB must be ruby's. Ruby's detect_format does not recognise a
179
188
  # PFA (nil), so the tier may take it; its error row equals the golden either way.
189
+ # Anything detect_format cannot name (empty or garbage bytes) is Ruby's too.
180
190
  scan_corpus.call(lambda { |path|
181
191
  case File.extname(path).downcase
182
192
  when ".dfont", ".pfb" then ["ruby"]
183
193
  when ".pfa" then ["ruby", tier]
184
- else [tier]
194
+ else Fontisan::FontLoader.detect_format(path).nil? ? ["ruby"] : [tier]
185
195
  end
186
196
  })
187
197
  end
@@ -203,9 +213,8 @@ begin
203
213
  when "auto_all", "auto_no_native", "auto_none"
204
214
  ENV["FONTISAN_ENGINE"] = "auto"
205
215
  Fontisan::Engine.reset!
206
- want = { "auto_all" => tiers.first || "ruby",
207
- "auto_no_native" => tiers.include?("ffi") ? "ffi" : "ruby",
208
- "auto_none" => "ruby" }.fetch(scenario)
216
+ present = { "auto_all" => tiers, "auto_no_native" => tiers - ["native"], "auto_none" => [] }.fetch(scenario)
217
+ want = Fontisan::Engine::AUTO_ORDER.map(&:to_s).find { |t| t == "ruby" || present.include?(t) }
209
218
  problems << "auto resolved #{resolved.call}, expected #{want}" unless resolved.call == want
210
219
  served = scan_corpus.call(->(path) { [want, *("ruby" if HANDED_TO_RUBY.include?(File.extname(path).downcase))] })
211
220
  problems << "no #{want} row served" if served[want].zero?
@@ -5,9 +5,10 @@
5
5
  # ruby scripts/tier_smoke.rb EXPECTED_TIER [CORPUS_ROOT]
6
6
  #
7
7
  # Run it against an INSTALLED fontisan gem (never the checkout's lib/). It scans
8
- # every `ci`-tier corpus font through Fontisan::Engine under the default engine (FONTISAN_ENGINE unset = auto),
8
+ # every `ci`-tier corpus font through Fontisan::Engine with FONTISAN_ENGINE=EXPECTED_TIER (strict off),
9
9
  # then checks that
10
- # * the tier auto resolves to is EXPECTED_TIER (native, ffi or ruby);
10
+ # * auto resolves to the first tier of Engine::AUTO_ORDER this gem has (ruby until the
11
+ # phase-3 gates flip it, fontist/fontisan#160);
11
12
  # * every row equals the committed scan golden (minus the served_by key);
12
13
  # * served_by is EXPECTED_TIER, except for files the engine hands to Ruby
13
14
  # (dfont, Type 1), which may say ruby; with EXPECTED_TIER=ruby nothing else.
@@ -18,7 +19,7 @@ expected = ARGV.fetch(0) { abort "usage: tier_smoke.rb native|ffi|ruby [corpus r
18
19
  root = File.expand_path(ARGV.fetch(1, File.join(__dir__, "..", "corpus")))
19
20
  abort "unknown tier #{expected.inspect}" unless %w[native ffi ruby].include?(expected)
20
21
 
21
- ENV.delete("FONTISAN_ENGINE") # the default (auto) is what is under test
22
+ ENV["FONTISAN_ENGINE"] = expected # the bundled tier is what is under test
22
23
  ENV.delete("FONTISAN_ENGINE_STRICT")
23
24
  require "fontisan"
24
25
  Fontisan::Reference # autoloading it installs the engine gates
@@ -44,20 +45,27 @@ entries.each do |entry|
44
45
  problems << "#{entry['id']}: rows differ from golden" unless JSON.parse(JSON.generate(actual)) == golden
45
46
 
46
47
  allowed = [expected]
47
- allowed << "ruby" if expected != "ruby" && HANDED_TO_RUBY.include?(File.extname(path).downcase)
48
+ handed = HANDED_TO_RUBY.include?(File.extname(path).downcase) || Fontisan::FontLoader.detect_format(path).nil?
49
+ allowed << "ruby" if expected != "ruby" && handed
48
50
  rows.each do |row|
49
51
  problems << "#{entry['id']}: served_by #{row['served_by']}, expected #{allowed.join('|')}" unless allowed.include?(row["served_by"])
50
52
  end
51
53
  end
52
54
 
53
- resolved = Fontisan::Engine.resolve(:scan, File.join(root, "fonts", "fonttools-test-ttf", "TestTTF.ttf")).to_s
54
- problems << "auto resolves scan to #{resolved}, expected #{expected}" unless resolved == expected
55
+ ttf = File.join(root, "fonts", "fonttools-test-ttf", "TestTTF.ttf")
56
+ resolved = Fontisan::Engine.resolve(:scan, ttf).to_s
57
+ problems << "#{expected} resolves scan to #{resolved}" unless resolved == expected
58
+ ENV["FONTISAN_ENGINE"] = "auto"
59
+ Fontisan::Engine.reset!
60
+ auto_want = Fontisan::Engine::AUTO_ORDER.find { |t| t == :ruby || t.to_s == expected }.to_s
61
+ auto = Fontisan::Engine.resolve(:scan, ttf).to_s
62
+ problems << "auto resolves scan to #{auto}, expected #{auto_want}" unless auto == auto_want
55
63
  problems << "no #{expected} row served" if served[expected].zero?
56
64
 
57
65
  puts "fontisan #{Fontisan::VERSION} from #{lib_dir}"
58
66
  puts "ruby #{RUBY_VERSION} #{RUBY_PLATFORM}; fonts scanned: #{entries.size}; served_by: #{served.inspect}"
59
67
  if problems.empty?
60
- puts "OK: auto resolved to #{resolved}; rows equal the goldens"
68
+ puts "OK: #{expected} served the corpus, auto resolved to #{auto}; rows equal the goldens"
61
69
  else
62
70
  warn problems
63
71
  exit 1
metadata CHANGED
@@ -1,14 +1,13 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: fontisan
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.4.48
4
+ version: 0.4.49
5
5
  platform: ruby
6
6
  authors:
7
7
  - Ribose Inc.
8
- autorequire:
9
8
  bindir: exe
10
9
  cert_chain: []
11
- date: 2026-11-11 00:00:00.000000000 Z
10
+ date: 1980-01-02 00:00:00.000000000 Z
12
11
  dependencies:
13
12
  - !ruby/object:Gem::Dependency
14
13
  name: base64
@@ -208,6 +207,7 @@ files:
208
207
  - benchmark/corpus/tiers.rb
209
208
  - benchmark/tier_baseline.json
210
209
  - benchmark/variation_quick_bench.rb
210
+ - build_mingw32_stub.rb
211
211
  - docs/.gitignore
212
212
  - docs/.vitepress/config.ts
213
213
  - docs/.vitepress/theme/components/ApiMethod.vue
@@ -537,6 +537,7 @@ files:
537
537
  - lib/fontisan/optimizers/subroutine_generator.rb
538
538
  - lib/fontisan/optimizers/subroutine_optimizer.rb
539
539
  - lib/fontisan/outline_extractor.rb
540
+ - lib/fontisan/output_guard.rb
540
541
  - lib/fontisan/parsers.rb
541
542
  - lib/fontisan/parsers/dfont_parser.rb
542
543
  - lib/fontisan/parsers/tag.rb
@@ -940,7 +941,6 @@ metadata:
940
941
  source_code_uri: https://github.com/fontist/fontisan
941
942
  changelog_uri: https://github.com/fontist/fontisan/blob/main/CHANGELOG.md
942
943
  rubygems_mfa_required: 'true'
943
- post_install_message:
944
944
  rdoc_options: []
945
945
  require_paths:
946
946
  - lib
@@ -955,8 +955,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
955
955
  - !ruby/object:Gem::Version
956
956
  version: '0'
957
957
  requirements: []
958
- rubygems_version: 3.5.22
959
- signing_key:
958
+ rubygems_version: 3.6.9
960
959
  specification_version: 4
961
960
  summary: Font analysis tools and utilities for OpenType fonts
962
961
  test_files: []