diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 3d1ef77494..34e0bcd6f3 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -12,9 +12,10 @@ author, source and license. Library code and original assets are under the repos | `crates/cms/profiles/photocraft-coated-cmyk.icc` | PhotoCraft contributors; generated by `craft_cms::synth::coated_cmyk` | [PhotoCraft `crates/cms`](https://github.com/storytold/photocraft/tree/b3222ee8e7e6bcb4799c37f904c595f20f9baf5e/crates/cms) | CC0-1.0 | | `crates/cms/profiles/craft-coated-fogra39.icc` | craft-libs contributors; generated by `crates/cms/tests/fogra39.rs` from the FOGRA39 data below | this repository | CC0-1.0 | | `crates/ppt-binary/tests/fixtures/old-talk.pps` | DeckCraft contributors; a one-slide PowerPoint 97-2003 show built from records by `crates/ppt-binary/src/tests.rs` (`the_pps_fixture_is_a_built_presentation`, with `CRAFT_WRITE_PPT_FIXTURE=1`); no PowerPoint involved | [storytold/deckcraft#1137](https://github.com/storytold/deckcraft/pull/1137) | CC0-1.0 | -| `crates/font-store/index/sources.json` (unmodified) | craft-font-index contributors | [aiongg/craft-font-index@5a9a7f8](https://github.com/aiongg/craft-font-index/tree/5a9a7f8038c8f3e2e1583a79c92a816e8e71b34f) | Apache-2.0 | -| `crates/font-store/index/indexes/google-fonts.json.gz` (unmodified) | craft-font-index contributors; generated from the METADATA.pb files of [google/fonts](https://github.com/google/fonts) at `45e3d5269e4a17d823f6d84470bc084dc5ae46f6` | [aiongg/craft-font-index@5a9a7f8](https://github.com/aiongg/craft-font-index/tree/5a9a7f8038c8f3e2e1583a79c92a816e8e71b34f) | Apache-2.0 | -| `crates/font-store/index/indexes/noto.json.gz` (unmodified) | craft-font-index contributors; generated from [notofonts/notofonts.github.io](https://github.com/notofonts/notofonts.github.io) at `93fac8abebe6c7fed0c5b7d2456d8fa484fa146c` and [noto-cjk](https://github.com/notofonts/noto-cjk) releases | [aiongg/craft-font-index@5a9a7f8](https://github.com/aiongg/craft-font-index/tree/5a9a7f8038c8f3e2e1583a79c92a816e8e71b34f) | Apache-2.0 | +| `crates/font-store/index/sources.json` (unmodified) | craft-font-index contributors | [aiongg/craft-font-index@995ef20](https://github.com/aiongg/craft-font-index/tree/995ef2000a0159d70da245e22cfa0797a0756ae8) | Apache-2.0 | +| `crates/font-store/index/indexes/google-fonts.json.gz` (unmodified) | craft-font-index contributors; generated from the METADATA.pb files of [google/fonts](https://github.com/google/fonts) at `45e3d5269e4a17d823f6d84470bc084dc5ae46f6` | [aiongg/craft-font-index@995ef20](https://github.com/aiongg/craft-font-index/tree/995ef2000a0159d70da245e22cfa0797a0756ae8) | Apache-2.0 | +| `crates/font-store/index/indexes/noto.json.gz` (unmodified) | craft-font-index contributors; generated from [notofonts/notofonts.github.io](https://github.com/notofonts/notofonts.github.io) at `93fac8abebe6c7fed0c5b7d2456d8fa484fa146c` and [noto-cjk](https://github.com/notofonts/noto-cjk) releases | [aiongg/craft-font-index@995ef20](https://github.com/aiongg/craft-font-index/tree/995ef2000a0159d70da245e22cfa0797a0756ae8) | Apache-2.0 | +| `crates/font-manager/tests/data/preview-vectors.json` (sample sentences) | Google Fonts `lang/` contributors; texts from the Universal Declaration of Human Rights via Eric Muller's UDHR in Unicode (translations' own terms not checked); the Iroha poem is public domain | [google/fonts `lang/`](https://github.com/google/fonts/tree/45e3d5269e4a17d823f6d84470bc084dc5ae46f6/lang) at `45e3d52` | Apache-2.0 | | `crates/cms/tests/data/FOGRA39.txt` (unmodified) | Fogra | [Fogra characterisation data](https://fogra.org/en/downloads/work-tools/characterisation-data), `FOGRA39_to_FOGRA60_v2.zip` | Fogra terms: free use and redistribution, unmodified, with Fogra identified as the source; "FOGRA39" identifies the reference data only and implies no certification, approval or endorsement by Fogra (full text in [NOTICE](NOTICE)) | | `vendor/linesweeper/tests/regression/`, `vendor/linesweeper/proptest-regressions/`, the `.snap` files under `vendor/linesweeper/src/` and the path data in `vendor/linesweeper/benches/painted_dreams.rs` (all unmodified; hashes in `vendor/linesweeper/SOURCE.json`) | As published in the package, whose manifest names Joe Neeman as author and records no other source | [linesweeper 0.5.0](https://crates.io/crates/linesweeper/0.5.0) | MIT OR Apache-2.0 (the package's `license` field) | | `crates/i18n/data/collation.postcard` | Unicode, Inc. (ICU 78.1 collation data, CLDR 48.2.1); generated by `crates/i18n/data/generate-collation.sh` | [ICU](https://github.com/unicode-org/icu/releases/tag/release-78.1rc) | Unicode-3.0 | @@ -189,3 +190,13 @@ Retained XFDF source contributors (move-aware blame): Brandon Thomas, Marco Arnu `crates/media-source/src/y4m.rs` adapts the in-house [FilmCraft Y4mSource at 3f137a7e](https://github.com/storytold/filmcraft/blob/3f137a7ed420cac79b32145f5243b7f98b31f71c/crates/codecs/src/y4m.rs), MIT OR Apache-2.0. Original playback by Lloyd Nicholson ([FilmCraft #1303](https://github.com/storytold/filmcraft/pull/1303)); shared-parser integration by Dylan M. Taylor ([FilmCraft #4862](https://github.com/storytold/filmcraft/pull/4862)). The adaptation changes source/frame types and declines payloads above the shared media allocation ceiling before playback. The parser and its previous header-safety work remain in `craft-y4m` ([craft-libs #933](https://github.com/storytold/craft-libs/pull/933)). `crates/media-source/tests/it/y4m.rs` contains original repository-authored synthetic test data under MIT OR Apache-2.0: literal YUV samples and a sparse reader that reports only the length of an oversized frame. It does not use external media or decoder output. + +## Material graph runtime + +`crates/material-graph` moves the graph text format, parser, evaluator, pixel-program compiler, and tests from +[TextureCraft's SPP importer at 22a37c29](https://github.com/vangel76/texturecraft/tree/22a37c29e98d8e6fc8c5e611e22f0ab95b83243d/crates/graph) +(MIT OR Apache-2.0). [xilefenko introduced this runtime in TextureCraft](https://github.com/vangel76/texturecraft/commit/af862722be61bd7050ac782ec57a5e8938a5b017), +adapting code from [PiJellyPin's MaterialCraft](https://github.com/PiJellyPin/MaterialCraft). See the crate's +`NOTICE` for the original attribution. This extraction retains vangel76's subsequent evaluator and GPU work. +The format reference and tests are from the same TextureCraft source. The tests' numerical rule tables document +their provenance in their headers. diff --git a/Cargo.lock b/Cargo.lock index 27b9e695a6..b1573a89b8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1846,6 +1846,7 @@ dependencies = [ "craft-lottie", "craft-macho", "craft-markdown", + "craft-material-graph", "craft-materialx", "craft-math", "craft-mcmat", @@ -2754,7 +2755,9 @@ dependencies = [ "epaint_default_fonts", "log", "serde", - "skrifa 0.44.0", + "serde_json", + "skrifa 0.47.0", + "wuff", ] [[package]] @@ -3229,6 +3232,14 @@ dependencies = [ "craft-wordmodel", ] +[[package]] +name = "craft-material-graph" +version = "0.1.0" +dependencies = [ + "libm", + "rayon", +] + [[package]] name = "craft-materialx" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 9e861a40bd..2f081aca2e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -170,6 +170,7 @@ craft-math = { path = "crates/math" } craft-media = { path = "crates/media", default-features = false } craft-media-source = { path = "crates/media-source" } craft-materialx = { path = "crates/materialx" } +craft-material-graph = { path = "crates/material-graph" } craft-media-testkit = { path = "crates/media-testkit" } craft-midi = { path = "crates/midi" } craft-sf2 = { path = "crates/sf2" } diff --git a/crates/aaf/src/aaf.rs b/crates/aaf/src/aaf.rs index 7ea67f4ec1..f7a061ccb3 100644 --- a/crates/aaf/src/aaf.rs +++ b/crates/aaf/src/aaf.rs @@ -37,6 +37,7 @@ //! name), `FilmCraft Frame Size` and `FilmCraft Audio Sample Rate` (on the composition). mod ids; +pub mod linked_audio; pub mod properties; mod read; pub(crate) mod store; diff --git a/crates/aaf/src/aaf/linked_audio.rs b/crates/aaf/src/aaf/linked_audio.rs new file mode 100644 index 0000000000..cf291d69dc --- /dev/null +++ b/crates/aaf/src/aaf/linked_audio.rs @@ -0,0 +1,121 @@ +//! WAV/PCM FileDescriptor metadata, without loading a SourceMob or touching its locators. + +use super::ids::{cls, pid}; + +/// The two audio descriptor classes commonly attached to an external WAV source. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum DescriptorKind { + Wave, + Pcm, +} + +impl DescriptorKind { + /// Classify a compound-file storage's CLSID in AAF on-disk AUID byte order + /// (little-endian GUID fields, not RFC 4122/network order). + pub fn from_auid_le(class: [u8; 16]) -> Option { + match class { + cls::WAVE_DESCRIPTOR => Some(Self::Wave), + cls::PCM_DESCRIPTOR => Some(Self::Pcm), + _ => None, + } + } +} + +/// One property from an already framed and caller-validated object. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum DescriptorProperty<'a> { + Missing, + OtherForm, + Data(&'a [u8]), +} + +/// Why a descriptor field is unavailable. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum DescriptorFieldError { + Missing, + OtherForm, + Truncated, +} + +/// A lazy descriptor view over a caller's property store. This neither opens +/// the media file nor determines whether the AAF source is external. +pub struct AudioFileDescriptor { + kind: DescriptorKind, + property: F, +} + +impl<'a, F: Fn(u16) -> DescriptorProperty<'a>> AudioFileDescriptor { + /// Supply the property view for this class; the descriptor chooses AAF property IDs. + pub fn new(kind: DescriptorKind, property: F) -> Self { + Self { kind, property } + } + + /// `FileDescriptor::SampleRate` as the signed numerator and denominator on + /// the wire. The caller's rational policy (including zero) is not applied. + pub fn sample_rate(&self) -> Result<(i32, i32), DescriptorFieldError> { + let [a, b, c, d, e, f, g, h] = self.bytes(pid::SAMPLE_RATE)?; + Ok((i32::from_le_bytes([a, b, c, d]), i32::from_le_bytes([e, f, g, h]))) + } + + /// `FileDescriptor::Length` in sample-rate units, before validating clip ranges. + pub fn length(&self) -> Result { + self.bytes(pid::FILE_LENGTH).map(i64::from_le_bytes) + } + + /// `SoundDescriptor::Channels` for a PCM descriptor. A WAVEDescriptor has + /// no such declared count here; an absent PCM field is also left to the caller. + pub fn pcm_channels(&self) -> Result, DescriptorFieldError> { + if self.kind == DescriptorKind::Wave { + return Ok(None); + } + match self.bytes(pid::CHANNELS) { + Ok(bytes) => Ok(Some(u32::from_le_bytes(bytes))), + Err(DescriptorFieldError::Missing) => Ok(None), + Err(err) => Err(err), + } + } + + fn bytes(&self, pid: u16) -> Result<[u8; N], DescriptorFieldError> { + match (self.property)(pid) { + DescriptorProperty::Data(data) => data.first_chunk().copied().ok_or(DescriptorFieldError::Truncated), + DescriptorProperty::Missing => Err(DescriptorFieldError::Missing), + DescriptorProperty::OtherForm => Err(DescriptorFieldError::OtherForm), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn descriptor_class_and_little_endian_fields_are_typed() { + assert_eq!(DescriptorKind::from_auid_le([1, 1, 1, 13, 1, 1, 0, 0x48, 6, 14, 43, 52, 2, 6, 1, 1]), Some(DescriptorKind::Pcm)); + assert_eq!(DescriptorKind::from_auid_le(cls::WAVE_DESCRIPTOR), Some(DescriptorKind::Wave)); + assert_eq!(DescriptorKind::from_auid_le(cls::CDCI_DESCRIPTOR), None); + let file = AudioFileDescriptor::new(DescriptorKind::Pcm, |tag| match tag { + pid::SAMPLE_RATE => DescriptorProperty::Data(&[0x80, 0xbb, 0, 0, 1, 0, 0, 0]), + pid::FILE_LENGTH => DescriptorProperty::Data(&[2, 1, 0, 0, 0, 0, 0, 0, 99]), + pid::CHANNELS => DescriptorProperty::Data(&[2, 0, 0, 0]), + _ => DescriptorProperty::Missing, + }); + assert_eq!(file.sample_rate(), Ok((48000, 1))); + assert_eq!(file.length(), Ok(258)); + assert_eq!(file.pcm_channels(), Ok(Some(2))); + } + + #[test] + fn descriptor_fields_are_lazy_and_distinguish_missing_form_and_short_data() { + let wave = AudioFileDescriptor::new(DescriptorKind::Wave, |tag| match tag { + pid::SAMPLE_RATE => DescriptorProperty::OtherForm, + pid::FILE_LENGTH => DescriptorProperty::Data(&[0; 7]), + _ => panic!("unexpected field read"), + }); + assert_eq!(wave.pcm_channels(), Ok(None)); + assert_eq!(wave.sample_rate(), Err(DescriptorFieldError::OtherForm)); + assert_eq!(wave.length(), Err(DescriptorFieldError::Truncated)); + let pcm = AudioFileDescriptor::new(DescriptorKind::Pcm, |_| DescriptorProperty::Missing); + assert_eq!(pcm.pcm_channels(), Ok(None)); + assert_eq!(pcm.sample_rate(), Err(DescriptorFieldError::Missing)); + } +} diff --git a/crates/android-res/src/arsc.rs b/crates/android-res/src/arsc.rs index 79a029625c..5ef10798ee 100644 --- a/crates/android-res/src/arsc.rs +++ b/crates/android-res/src/arsc.rs @@ -3,7 +3,7 @@ //! orientation, SDK level…). Simple and complex (bag) entries, sparse and 16-bit offset tables. use crate::Error; -use crate::axml::{ResValue, StringPool, chunk}; +use crate::axml::{MAX_RETAINED_VALUE_BYTES, ResValue, StringPool, ValueBudget, chunk, report_partial_string_pool}; use crate::bytes::Reader; use serde::Serialize; @@ -21,14 +21,18 @@ const MAX_BAG: usize = 4096; pub struct Limits { /// Most entries decoded across all types and configurations. pub max_entries: usize, + /// Most bytes retained in formatted simple-entry and bag values. + pub max_value_bytes: usize, } impl Default for Limits { fn default() -> Self { - Limits { max_entries: 2_000_000 } + Limits { max_entries: 2_000_000, max_value_bytes: MAX_RETAINED_VALUE_BYTES } } } +const VALUE_BUDGET_WARNING: &str = "resource value budget reached; remaining values were omitted"; + #[derive(Debug, Clone, PartialEq, Serialize)] pub struct TypeInfo { pub id: u8, @@ -300,30 +304,32 @@ pub fn parse(data: &[u8], limits: Limits) -> Result { let r = Reader::new(data); let mut table = Table::default(); let mut global = StringPool::default(); + let mut value_budget = ValueBudget::new(limits.max_value_bytes); let mut pos = h; while pos < size { let Some((ct, _ch, cs)) = chunk(&r, pos) else { + table.truncated = true; table.warnings.push(format!("unreadable chunk at offset {pos}")); break; }; match ct { crate::axml::RES_STRING_POOL => match StringPool::parse(data, pos) { Ok(p) => { - if p.strings.len() < p.declared { - table.truncated = true; - table.warnings.push(format!("global string pool was capped at {} of {} strings", p.strings.len(), p.declared)); - } + report_partial_string_pool(&p, "global string pool", &mut table.truncated, &mut table.warnings); table.global_strings = p.declared; global = p; } - Err(e) => table.warnings.push(format!("global string pool: {e}")), + Err(e) => { + table.truncated = true; + table.warnings.push(format!("global string pool: {e}")); + } }, RES_PACKAGE => { if table.packages.len() >= MAX_PACKAGES { table.truncated = true; table.warnings.push("too many packages; the rest were skipped".into()); } else { - parse_package(data, pos, cs, &global, &mut table, limits); + parse_package(data, pos, cs, &global, &mut table, limits, &mut value_budget); } } _ => {} @@ -336,14 +342,16 @@ pub fn parse(data: &[u8], limits: Limits) -> Result { Ok(table) } -fn parse_package(data: &[u8], pos: usize, cs: usize, global: &StringPool, table: &mut Table, limits: Limits) { +fn parse_package(data: &[u8], pos: usize, cs: usize, global: &StringPool, table: &mut Table, limits: Limits, value_budget: &mut ValueBudget) { let Some(data) = pos.checked_add(cs).and_then(|end| data.get(..end)) else { + table.truncated = true; table.warnings.push("package runs past its resource table".into()); return; }; let r = Reader::new(data); let hsize = usize::from(r.u16_le(pos + 2).unwrap_or(0)); if hsize < 284 { + table.truncated = true; table.warnings.push(format!("package at offset {pos}: incomplete header")); return; } @@ -365,22 +373,17 @@ fn parse_package(data: &[u8], pos: usize, cs: usize, global: &StringPool, table: return StringPool::default(); } let Some(start) = pos.checked_add(offset).filter(|&start| offset >= hsize && start < end) else { + table.truncated = true; table.warnings.push(format!("package {name}: {label} string pool is outside its payload")); return StringPool::default(); }; match StringPool::parse(data, start) { Ok(pool) => { - if pool.strings.len() < pool.declared { - table.truncated = true; - table.warnings.push(format!( - "package {name}: {label} string pool was capped at {} of {} strings", - pool.strings.len(), - pool.declared - )); - } + report_partial_string_pool(&pool, &format!("package {name}: {label} string pool"), &mut table.truncated, &mut table.warnings); pool } Err(error) => { + table.truncated = true; table.warnings.push(format!("package {name}: {label} string pool: {error}")); StringPool::default() } @@ -393,12 +396,14 @@ fn parse_package(data: &[u8], pos: usize, cs: usize, global: &StringPool, table: let mut c = pos.saturating_add(hsize.max(8)); while c < end { let Some((ct, ch, sz)) = chunk(&r, c) else { + table.truncated = true; table.warnings.push(format!("package {name}: unreadable chunk at offset {c}")); break; }; // Each child was checked against its package; reads within it must also stop before // the next sibling, including fixed-width library records and bag headers. let Some(child) = data.get(..c.saturating_add(sz)) else { + table.truncated = true; table.warnings.push(format!("package {name}: child chunk runs past its package")); break; }; @@ -437,7 +442,7 @@ fn parse_package(data: &[u8], pos: usize, cs: usize, global: &StringPool, table: } } } - parse_type(&r, c, (ch, sz), (cfg, locale), &p, tid, global, table, limits); + parse_type(&r, c, (ch, sz), (cfg, locale), &p, tid, global, table, limits, value_budget); } (RES_TYPE_SPEC | RES_TYPE, None) if ch >= 16 => { table.truncated = true; @@ -449,6 +454,9 @@ fn parse_package(data: &[u8], pos: usize, cs: usize, global: &StringPool, table: if n > available { table.warnings.push(format!("package {name}: library records run past their chunk")); } + if n > available.min(256) { + table.truncated = true; + } for i in 0..n.min(256).min(available) { let e = c + ch + i * 260; if let Some(lid) = r.u32_le(e) { @@ -457,6 +465,7 @@ fn parse_package(data: &[u8], pos: usize, cs: usize, global: &StringPool, table: } } (RES_TYPE_SPEC | RES_TYPE | RES_LIBRARY, _) => { + table.truncated = true; table.warnings.push(format!("package {name}: incomplete chunk header at offset {c}")); } _ => {} @@ -480,6 +489,7 @@ fn parse_type( global: &StringPool, table: &mut Table, limits: Limits, + value_budget: &mut ValueBudget, ) { let tid = r.u8(c + 8).unwrap_or(0); let flags = r.u8(c + 9).unwrap_or(0); @@ -493,10 +503,12 @@ fn parse_type( let mut slots: Vec<(u32, usize)> = Vec::new(); let table_bytes = if sparse || off16 { count.saturating_mul(if sparse { 4 } else { 2 }) } else { count.saturating_mul(4) }; if c.saturating_add(ch).saturating_add(table_bytes) > end { + table.truncated = true; table.warnings.push(format!("{tname} ({cfg}): entry table runs past its chunk")); return; } if count != 0 && (entries_start < ch.saturating_add(table_bytes) || entries_start > sz) { + table.truncated = true; table.warnings.push(format!("{tname} ({cfg}): invalid entry data start")); return; } @@ -517,15 +529,16 @@ fn parse_type( } } } + let mut skipped = 0usize; for (idx, o) in slots { if table.entries.len() >= limits.max_entries { table.truncated = true; - return; + break; } - let Some(e) = c.checked_add(entries_start).and_then(|x| x.checked_add(o)) else { continue }; - if e.saturating_add(8) > end { + let Some(e) = c.checked_add(entries_start).and_then(|x| x.checked_add(o)).filter(|e| e.saturating_add(8) <= end) else { + skipped += 1; continue; - } + }; let esize = usize::from(r.u16_le(e).unwrap_or(0)); let eflags = r.u16_le(e + 2).unwrap_or(0); let id = (p.id << 24) | (u32::from(type_id) << 16) | (idx & 0xffff); @@ -546,7 +559,7 @@ fn parse_type( // Compact entry: key index in the size field, type in the high byte of flags. entry.key = p.keys.get(u32::from(r.u16_le(e).unwrap_or(0))).unwrap_or("").to_string(); let v = ResValue { data_type: (eflags >> 8) as u8, data: r.u32_le(e + 4).unwrap_or(0) }; - entry.value = Some(v.format(global)); + entry.value = value_budget.take(v.format(global), &mut table.truncated, &mut table.warnings, VALUE_BUDGET_WARNING); entry.value_type = Some(v.type_name()); entry.raw = Some(v); } else { @@ -579,21 +592,30 @@ fn parse_type( } let name = r.u32_le(m).unwrap_or(0); let v = ResValue { data_type: r.u8(m + 7).unwrap_or(0), data: r.u32_le(m + 8).unwrap_or(0) }; - entry.bag.push(BagItem { name: format!("@{name:#010x}"), value: v.format(global), value_type: v.type_name() }); + let value = + value_budget.take(v.format(global), &mut table.truncated, &mut table.warnings, VALUE_BUDGET_WARNING).unwrap_or_default(); + entry.bag.push(BagItem { name: format!("@{name:#010x}"), value, value_type: v.type_name() }); m += 12; } } else { let v_at = e.saturating_add(esize.max(8)); if v_at.saturating_add(8) <= end { let v = ResValue { data_type: r.u8(v_at + 3).unwrap_or(0), data: r.u32_le(v_at + 4).unwrap_or(0) }; - entry.value = Some(v.format(global)); + entry.value = value_budget.take(v.format(global), &mut table.truncated, &mut table.warnings, VALUE_BUDGET_WARNING); entry.value_type = Some(v.type_name()); entry.raw = Some(v); + } else { + table.truncated = true; + table.warnings.push(format!("{tname} ({cfg}): incomplete value")); } } } table.entries.push(entry); } + if skipped > 0 { + table.truncated = true; + table.warnings.push(format!("{tname} ({cfg}): {skipped} entries run past their chunk")); + } } impl Table { @@ -642,6 +664,30 @@ mod tests { assert_eq!(style.config, "night-xhdpi-v21"); } + #[test] + fn skipped_type_chunks_and_entries_mark_the_table_partial() { + let bytes = fx::resources_arsc(); + // The French type chunk: RES_TYPE, an 84-byte header, and "fr" in its configuration. + let fr = (0..bytes.len() - 30).find(|&i| bytes[i..i + 4] == [0x01, 0x02, 84, 0] && &bytes[i + 28..i + 30] == b"fr").unwrap(); + let corrupt = |at: usize, value: u32| { + let mut b = bytes.clone(); + b[at..at + 4].copy_from_slice(&value.to_le_bytes()); + parse(&b, Limits::default()).unwrap() + }; + for (what, t) in [ + ("entry table past its chunk", corrupt(fr + 12, 1000)), + ("invalid entry data start", corrupt(fr + 16, 0xffff)), + ("an entry past its chunk", corrupt(fr + 84, 0x1000)), + // The second entry's header fits, but its value runs past the chunk. + ("a value past its chunk", corrupt(fr + 88, 24)), + ] { + let french = t.entries.iter().filter(|e| e.locale == "fr" && e.value.is_some()).count(); + assert!(french < 2, "{what}: the corruption should lose a French value"); + assert!(t.truncated, "{what}: lost content must mark the table partial"); + assert!(!t.warnings.is_empty(), "{what}: lost content must be reported"); + } + } + #[test] fn distinct_locale_scripts_and_variants_keep_separate_keys() { let mut cfg = [0u8; 64]; @@ -674,4 +720,162 @@ mod tests { assert_eq!(q, "es-rMX-land"); assert_eq!(l, "es-rMX"); } + + fn le_u16(v: &mut Vec, x: u16) { + v.extend_from_slice(&x.to_le_bytes()); + } + + fn le_u32(v: &mut Vec, x: u32) { + v.extend_from_slice(&x.to_le_bytes()); + } + + fn type_spec(id: u8, entries: u32) -> Vec { + let mut c = Vec::new(); + le_u16(&mut c, 0x0202); + le_u16(&mut c, 16); + le_u32(&mut c, 16 + 4 * entries); + c.push(id); + c.push(0); + le_u16(&mut c, 0); + le_u32(&mut c, entries); + for _ in 0..entries { + le_u32(&mut c, 0); + } + c + } + + fn type_chunk(id: u8, entries: &[Vec]) -> Vec { + let mut cfg = vec![0u8; 64]; + cfg[0] = 64; + let header = 20 + cfg.len(); + let start = header + 4 * entries.len(); + let mut body = Vec::new(); + let mut offs = Vec::new(); + for e in entries { + offs.push(body.len() as u32); + body.extend_from_slice(e); + } + let mut c = Vec::new(); + le_u16(&mut c, 0x0201); + le_u16(&mut c, header as u16); + le_u32(&mut c, (start + body.len()) as u32); + c.push(id); + c.push(0); + le_u16(&mut c, 0); + le_u32(&mut c, entries.len() as u32); + le_u32(&mut c, start as u32); + c.extend_from_slice(&cfg); + for o in offs { + le_u32(&mut c, o); + } + c.extend(body); + c + } + + fn table_with_entries(pool: &[&str], type_name: &str, keys: &[&str], entries: &[Vec]) -> Vec { + let global = fx::string_pool(pool, true); + let types = fx::string_pool(&[type_name], false); + let key_pool = fx::string_pool(keys, false); + let mut chunks = type_spec(1, entries.len() as u32); + chunks.extend(type_chunk(1, entries)); + let header = 288usize; + let mut pkg = Vec::new(); + le_u16(&mut pkg, 0x0200); + le_u16(&mut pkg, header as u16); + le_u32(&mut pkg, (header + types.len() + key_pool.len() + chunks.len()) as u32); + le_u32(&mut pkg, 0x7f); + pkg.extend(vec![0u8; 256]); + le_u32(&mut pkg, header as u32); + le_u32(&mut pkg, 1); + le_u32(&mut pkg, (header + types.len()) as u32); + le_u32(&mut pkg, keys.len() as u32); + le_u32(&mut pkg, 0); + pkg.extend(types); + pkg.extend(key_pool); + pkg.extend(chunks); + let mut out = Vec::new(); + le_u16(&mut out, 0x0002); + le_u16(&mut out, 12); + le_u32(&mut out, (12 + global.len() + pkg.len()) as u32); + le_u32(&mut out, 1); + out.extend(global); + out.extend(pkg); + out + } + + fn simple_string_entry(key: u32, pool_index: u32) -> Vec { + let mut e = Vec::new(); + le_u16(&mut e, 8); + le_u16(&mut e, 0); + le_u32(&mut e, key); + le_u16(&mut e, 8); + e.push(0); + e.push(0x03); + le_u32(&mut e, pool_index); + e + } + + fn compact_string_entry(key: u16, pool_index: u32) -> Vec { + let mut e = Vec::new(); + le_u16(&mut e, key); + le_u16(&mut e, 0x0308); + le_u32(&mut e, pool_index); + e + } + + fn bag_string_entry(key: u32, pool_indices: &[u32]) -> Vec { + let mut e = Vec::new(); + le_u16(&mut e, 16); + le_u16(&mut e, 1); + le_u32(&mut e, key); + le_u32(&mut e, 0); + le_u32(&mut e, pool_indices.len() as u32); + for (i, idx) in pool_indices.iter().enumerate() { + le_u32(&mut e, 0x0101_0000 + i as u32); + le_u16(&mut e, 8); + e.push(0); + e.push(0x03); + le_u32(&mut e, *idx); + } + e + } + + #[test] + fn value_budget_omits_long_copies_and_keeps_a_later_short_value() { + let long = "x".repeat(16); + let tight = Limits { max_value_bytes: 20, ..Limits::default() }; + let keys = ["a", "b", "c"]; + + let simple = + table_with_entries(&[&long, "ok"], "string", &keys, &[simple_string_entry(0, 0), simple_string_entry(1, 0), simple_string_entry(2, 1)]); + let complete = parse(&simple, Limits::default()).unwrap(); + assert!(!complete.truncated, "{:?}", complete.warnings); + assert_eq!(complete.entries.iter().map(|e| e.value.as_deref()).collect::>(), [Some(long.as_str()), Some(long.as_str()), Some("ok")]); + + let partial = parse(&simple, tight).unwrap(); + assert!(partial.truncated); + assert!(partial.warnings.iter().any(|w| w.contains("value budget")), "{:?}", partial.warnings); + assert_eq!(partial.entries.iter().map(|e| e.value.as_deref()).collect::>(), [Some(long.as_str()), None, Some("ok")]); + + let compact = table_with_entries( + &[&long, "ok"], + "string", + &keys, + &[compact_string_entry(0, 0), compact_string_entry(1, 0), compact_string_entry(2, 1)], + ); + let partial = parse(&compact, tight).unwrap(); + assert!(partial.truncated); + assert!(partial.warnings.iter().any(|w| w.contains("value budget")), "{:?}", partial.warnings); + assert_eq!(partial.entries.iter().map(|e| e.value.as_deref()).collect::>(), [Some(long.as_str()), None, Some("ok")]); + + let bag = table_with_entries(&[&long, "ok"], "style", &["theme"], &[bag_string_entry(0, &[0, 0, 1])]); + let complete = parse(&bag, Limits::default()).unwrap(); + assert!(!complete.truncated, "{:?}", complete.warnings); + assert_eq!(complete.entries[0].bag.iter().map(|i| i.value.as_str()).collect::>(), [long.as_str(), long.as_str(), "ok"]); + + let partial = parse(&bag, tight).unwrap(); + assert!(partial.truncated); + assert!(partial.warnings.iter().any(|w| w.contains("value budget")), "{:?}", partial.warnings); + assert_eq!(partial.entries[0].bag.iter().map(|i| i.value.as_str()).collect::>(), [long.as_str(), "", "ok"]); + } } diff --git a/crates/android-res/src/axml.rs b/crates/android-res/src/axml.rs index 3aea1f7ffc..3525e0434c 100644 --- a/crates/android-res/src/axml.rs +++ b/crates/android-res/src/axml.rs @@ -20,8 +20,10 @@ const XML_RESOURCE_MAP: u16 = 0x0180; const MAX_STRINGS: usize = 1_000_000; /// Longest string kept (characters). const MAX_STRING: usize = 64 * 1024; +/// Default budget for copied resource and XML values, and the base string-pool byte cap. +pub(crate) const MAX_RETAINED_VALUE_BYTES: usize = 64 << 20; /// Base budget for decoded string bytes; larger chunks allow at most three times their size. -const BASE_POOL_BYTES: usize = 64 << 20; +const BASE_POOL_BYTES: usize = MAX_RETAINED_VALUE_BYTES; /// Most extra UTF-8 length candidates examined across one string pool. const MAX_RECOVERY_PROBES: usize = 65_536; /// Most XML nodes decoded. @@ -54,6 +56,8 @@ pub struct StringPool { pub utf8: bool, /// Strings the pool declared (may exceed `strings.len()` when capped). pub declared: usize, + /// Entries left empty because the UTF-8 recovery probe budget ran out. + pub recovery_omitted: usize, } impl StringPool { @@ -104,12 +108,13 @@ impl StringPool { let strings_reader = Reader::new(string_bytes); let mut strings = Vec::with_capacity(count.min(MAX_STRINGS).min(65_536)); let mut bytes_left = BASE_POOL_BYTES.max(size.saturating_mul(3)); + let mut recovery_omitted = 0; for i in 0..count.min(MAX_STRINGS) { let at = r.u32_le(hdr + i * 4).ok_or_else(|| Error::Truncated("string offsets".into()))? as usize; let s = if at >= string_bytes.len() { None } else if utf8 { - utf8_string(&strings_reader, at, string_bytes.len(), recovery_left) + utf8_string(&strings_reader, at, string_bytes.len(), recovery_left, &mut recovery_omitted) } else { utf16_string(&strings_reader, at, string_bytes.len()) }; @@ -120,7 +125,7 @@ impl StringPool { bytes_left -= s.len(); strings.push(s); } - Ok(StringPool { strings, utf8, declared: count }) + Ok(StringPool { strings, utf8, declared: count, recovery_omitted }) } } @@ -134,7 +139,7 @@ fn utf8_len(r: &Reader<'_>, at: usize) -> Option<(usize, usize)> { } } -fn utf8_string(r: &Reader<'_>, at: usize, end: usize, recovery_left: &mut usize) -> Option { +fn utf8_string(r: &Reader<'_>, at: usize, end: usize, recovery_left: &mut usize, recovery_omitted: &mut usize) -> Option { let (_chars, n1) = utf8_len(r, at)?; let (mut bytes, n2) = utf8_len(r, at.checked_add(n1)?)?; let start = at.checked_add(n1 + n2)?; @@ -146,7 +151,11 @@ fn utf8_string(r: &Reader<'_>, at: usize, end: usize, recovery_left: &mut usize) } // The declared candidate costs one read per entry, already bounded by MAX_STRINGS. if bytes >= 0x8000 { - *recovery_left = recovery_left.checked_sub(1)?; + if *recovery_left == 0 { + *recovery_omitted += 1; + return None; + } + *recovery_left -= 1; } if r.u8(terminator)? == 0 { break; @@ -173,6 +182,56 @@ fn utf16_string(r: &Reader<'_>, at: usize, end: usize) -> Option { Some(String::from_utf16_lossy(&units)) } +/// Record that a string pool was capped or omitted recovery entries. +pub(crate) fn report_partial_string_pool(pool: &StringPool, prefix: &str, truncated: &mut bool, warnings: &mut Vec) { + if pool.strings.len() < pool.declared { + *truncated = true; + warnings.push(format!("{prefix} was capped at {} of {} strings", pool.strings.len(), pool.declared)); + } + if pool.recovery_omitted > 0 { + *truncated = true; + warnings.push(format!("{prefix} omitted {} strings after the UTF-8 recovery budget was exhausted", pool.recovery_omitted)); + } +} + +/// Charge `value` against a retained-byte budget. When it does not fit, report truncation once +/// and return `None`, so a later shorter value can still be kept. +pub(crate) fn retain_value( + left: &mut usize, + value: String, + truncated: &mut bool, + warned: &mut bool, + warnings: &mut Vec, + warning: &str, +) -> Option { + if value.len() > *left { + if !*warned { + warnings.push(warning.to_string()); + *warned = true; + } + *truncated = true; + None + } else { + *left -= value.len(); + Some(value) + } +} + +pub(crate) struct ValueBudget { + left: usize, + warned: bool, +} + +impl ValueBudget { + pub(crate) fn new(max_bytes: usize) -> Self { + Self { left: max_bytes, warned: false } + } + + pub(crate) fn take(&mut self, value: String, truncated: &mut bool, warnings: &mut Vec, warning: &str) -> Option { + retain_value(&mut self.left, value, truncated, &mut self.warned, warnings, warning) + } +} + /// A typed value (`Res_value`): data type and 32-bit data. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] pub struct ResValue { @@ -313,10 +372,10 @@ pub fn framework_attr(id: u32) -> Option<&'static str> { /// Decode a binary XML file. pub fn parse(data: &[u8]) -> Result { - parse_with_limits(data, MAX_NODES, MAX_DEPTH) + parse_with_limits(data, MAX_NODES, MAX_DEPTH, MAX_RETAINED_VALUE_BYTES) } -fn parse_with_limits(data: &[u8], max_nodes: usize, max_depth: usize) -> Result { +fn parse_with_limits(data: &[u8], max_nodes: usize, max_depth: usize, max_value_bytes: usize) -> Result { let r = Reader::new(data); let (t, h, size) = chunk(&r, 0).ok_or_else(|| Error::Truncated("binary XML header".into()))?; if t != RES_XML { @@ -329,6 +388,7 @@ fn parse_with_limits(data: &[u8], max_nodes: usize, max_depth: usize) -> Result< let mut pos = h; let mut depth = 0usize; let mut ns_stack: Vec<(String, String)> = Vec::new(); + let mut value_budget = ValueBudget::new(max_value_bytes); while pos < size { let Some((ct, ch, cs)) = chunk(&r, pos) else { doc.truncated = true; @@ -354,10 +414,7 @@ fn parse_with_limits(data: &[u8], max_nodes: usize, max_depth: usize) -> Result< match ct { RES_STRING_POOL => match StringPool::parse(data, pos) { Ok(p) => { - if p.strings.len() < p.declared { - doc.truncated = true; - doc.warnings.push(format!("string pool was capped at {} of {} strings", p.strings.len(), p.declared)); - } + report_partial_string_pool(&p, "string pool", &mut doc.truncated, &mut doc.warnings); doc.pool = p; } Err(e) => doc.warnings.push(format!("string pool: {e}")), @@ -431,6 +488,9 @@ fn parse_with_limits(data: &[u8], max_nodes: usize, max_depth: usize) -> Result< } else { raw.format(&doc.pool) }; + let value = value_budget + .take(value, &mut doc.truncated, &mut doc.warnings, "XML value budget reached; remaining values were omitted") + .unwrap_or_default(); attributes.push(Attribute { namespace: ans, name: aname, @@ -450,6 +510,9 @@ fn parse_with_limits(data: &[u8], max_nodes: usize, max_depth: usize) -> Result< } XML_CDATA => { let text = r.u32_le(pos + ch).and_then(|i| doc.pool.get(i)).unwrap_or("").to_string(); + let text = value_budget + .take(text, &mut doc.truncated, &mut doc.warnings, "XML value budget reached; remaining values were omitted") + .unwrap_or_default(); doc.nodes.push(Node::Text { depth, text }); } _ => {} @@ -639,6 +702,7 @@ mod tests { assert_eq!(parsed.get(1), parsed.get(0)); assert_eq!(parsed.get(2), Some("")); assert_eq!(parsed.get(3), Some("ok")); + assert_eq!(parsed.recovery_omitted, 1); } #[test] @@ -655,6 +719,7 @@ mod tests { assert_eq!(parsed.get(1).map(str::len), Some(0x8000)); assert_eq!(parsed.get(2), Some("")); assert_eq!(parsed.get(3), Some("ok")); + assert_eq!(parsed.recovery_omitted, 1); } #[test] @@ -670,6 +735,7 @@ mod tests { assert_eq!(left, remaining); assert_eq!(parsed.get(0).map(str::len), Some(length)); assert_eq!(parsed.get(1), Some("ok")); + assert_eq!(parsed.recovery_omitted, usize::from(length == 0)); } } @@ -681,10 +747,10 @@ mod tests { assert_eq!(left, 7); assert_eq!(parsed.get(0), Some("")); assert_eq!(parsed.get(1), Some("ok")); + assert_eq!(parsed.recovery_omitted, 0); } - #[test] - fn default_pool_budget_stops_repeated_recovery_before_later_long_strings() { + fn utf8_recovery_exhausted_pool() -> (Vec, usize) { let mut strings = vec![b'x'; 2 * 0x8000 + 16]; strings[..4].copy_from_slice(&[0x80, 0, 0x80, 0]); let long = append_legacy_ascii(&mut strings, 0x8000); @@ -694,13 +760,78 @@ mod tests { let repeated = MAX_RECOVERY_PROBES / 3 + 1; let mut offsets = vec![0; repeated]; offsets.extend([long, short]); - let data = pool_with_offsets(&offsets, &strings); + (pool_with_offsets(&offsets, &strings), repeated) + } + + #[test] + fn default_pool_budget_stops_repeated_recovery_before_later_long_strings() { + let (data, repeated) = utf8_recovery_exhausted_pool(); let parsed = StringPool::parse(&data, 0).unwrap(); assert_eq!(parsed.declared, repeated + 2); assert_eq!(parsed.strings.len(), repeated + 2); assert!(parsed.strings[..repeated].iter().all(String::is_empty)); assert_eq!(parsed.get(repeated as u32), Some("")); assert_eq!(parsed.get((repeated + 1) as u32), Some("ok")); + assert!(parsed.recovery_omitted > 0); + } + + #[test] + fn xml_and_resource_tables_disclose_recovery_omissions() { + let (pool, repeated) = utf8_recovery_exhausted_pool(); + let short_index = (repeated + 1) as u32; + { + let doc = parse(&pool_container(RES_XML, 8, &pool)).unwrap(); + assert!(doc.truncated); + assert!(doc.warnings.iter().any(|w| w.contains("string pool") && w.contains("UTF-8 recovery budget"))); + assert_eq!(doc.pool.get(short_index), Some("ok")); + assert!(doc.pool.recovery_omitted > 0); + } + let table = crate::arsc::parse(&pool_container(2, 12, &pool), crate::arsc::Limits::default()).unwrap(); + assert!(table.truncated); + assert!(table.warnings.iter().any(|w| w.contains("global string pool") && w.contains("UTF-8 recovery budget"))); + for (field, label) in [(268, "type"), (276, "key")] { + let mut package = pool_container(0x0200, 288, &pool); + package[8..12].copy_from_slice(&0x7fu32.to_le_bytes()); + package[field..field + 4].copy_from_slice(&288u32.to_le_bytes()); + let table = crate::arsc::parse(&pool_container(2, 12, &package), crate::arsc::Limits::default()).unwrap(); + assert!(table.truncated, "{label}"); + assert!( + table.warnings.iter().any(|w| w.contains(&format!("{label} string pool")) && w.contains("UTF-8 recovery budget")), + "{label}: {:?}", + table.warnings + ); + } + } + + #[test] + fn xml_value_budget_omits_long_copies_and_keeps_a_later_short_value() { + let long = "x".repeat(16); + let attrs = vec![ + fx::AxAttr { name: "a", res_id: None, val: fx::AxVal::Str(&long) }, + fx::AxAttr { name: "b", res_id: None, val: fx::AxVal::Str(&long) }, + fx::AxAttr { name: "c", res_id: None, val: fx::AxVal::Str("ok") }, + ]; + let bytes = fx::axml(&[fx::AxNode::Start("root", attrs), fx::AxNode::End("root")]); + let complete = parse(&bytes).unwrap(); + assert!(!complete.truncated); + let Node::Start { attributes, .. } = complete.nodes.iter().find(|n| matches!(n, Node::Start { name, .. } if name == "root")).unwrap() else { + panic!("expected the root start"); + }; + assert_eq!( + attributes.iter().map(|a| (a.name.as_str(), a.value.as_str())).collect::>(), + [("a", long.as_str()), ("b", long.as_str()), ("c", "ok")] + ); + + let partial = parse_with_limits(&bytes, MAX_NODES, MAX_DEPTH, 20).unwrap(); + assert!(partial.truncated); + assert!(partial.warnings.iter().any(|w| w.contains("value budget"))); + let Node::Start { attributes, .. } = partial.nodes.iter().find(|n| matches!(n, Node::Start { name, .. } if name == "root")).unwrap() else { + panic!("expected the root start"); + }; + assert_eq!( + attributes.iter().map(|a| (a.name.as_str(), a.value.as_str())).collect::>(), + [("a", long.as_str()), ("b", ""), ("c", "ok")] + ); } fn chunk_at(data: &[u8], kind: u16) -> usize { @@ -757,11 +888,11 @@ mod tests { #[test] fn dropping_a_close_event_marks_the_document_partial() { let bytes = fx::axml(&[fx::AxNode::Start("root", vec![]), fx::AxNode::End("root")]); - let complete = parse_with_limits(&bytes, 3, 1).unwrap(); + let complete = parse_with_limits(&bytes, 3, 1, MAX_RETAINED_VALUE_BYTES).unwrap(); assert!(!complete.truncated); assert!(matches!(complete.nodes.last(), Some(Node::End { depth: 0, .. }))); - let partial = parse_with_limits(&bytes, 2, 1).unwrap(); + let partial = parse_with_limits(&bytes, 2, 1, MAX_RETAINED_VALUE_BYTES).unwrap(); assert!(partial.truncated); assert_eq!(partial.nodes, complete.nodes[..2]); } @@ -770,19 +901,19 @@ mod tests { fn nesting_limit_keeps_an_exact_prefix_instead_of_saturating_depth() { let bytes = fx::axml(&[fx::AxNode::Start("root", vec![]), fx::AxNode::Start("child", vec![]), fx::AxNode::End("child"), fx::AxNode::End("root")]); - let complete = parse_with_limits(&bytes, 5, 2).unwrap(); + let complete = parse_with_limits(&bytes, 5, 2, MAX_RETAINED_VALUE_BYTES).unwrap(); assert!(!complete.truncated); assert!(matches!(complete.nodes[3], Node::End { depth: 1, .. })); assert!(matches!(complete.nodes[4], Node::End { depth: 0, .. })); - let partial = parse_with_limits(&bytes, 5, 1).unwrap(); + let partial = parse_with_limits(&bytes, 5, 1, MAX_RETAINED_VALUE_BYTES).unwrap(); assert!(partial.truncated); assert_eq!(partial.nodes, complete.nodes[..2]); } #[test] fn values_format() { - let p = StringPool { strings: vec!["x".into()], utf8: false, declared: 1 }; + let p = StringPool { strings: vec!["x".into()], utf8: false, declared: 1, recovery_omitted: 0 }; assert_eq!(ResValue { data_type: 0x05, data: (16 << 8) | 1 }.format(&p), "16dp"); assert_eq!(ResValue { data_type: 0x12, data: 0xffff_ffff }.format(&p), "true"); assert_eq!(ResValue { data_type: 0x1c, data: 0xff00_ff00 }.format(&p), "#ff00ff00"); diff --git a/crates/craft/Cargo.toml b/crates/craft/Cargo.toml index 5d93b4ee60..3cae59522b 100644 --- a/crates/craft/Cargo.toml +++ b/crates/craft/Cargo.toml @@ -109,6 +109,7 @@ craft-kra = { workspace = true, optional = true } craft-latex = { workspace = true, optional = true } craft-lottie = { workspace = true, optional = true } craft-markdown = { workspace = true, optional = true } +craft-material-graph = { workspace = true, optional = true } craft-materialx = { workspace = true, optional = true } craft-math = { workspace = true, optional = true } craft-mesh = { workspace = true, optional = true } @@ -609,6 +610,8 @@ macho-serde = ["macho", "craft-macho/serde"] markdown = ["dep:craft-markdown"] +material-graph = ["dep:craft-material-graph"] + materialx = ["dep:craft-materialx"] math = ["dep:craft-math"] diff --git a/crates/craft/src/lib.rs b/crates/craft/src/lib.rs index 5eba7a44d9..caeb7d5267 100644 --- a/crates/craft/src/lib.rs +++ b/crates/craft/src/lib.rs @@ -221,6 +221,8 @@ pub use craft_lottie as lottie; pub use craft_macho as macho; #[cfg(feature = "markdown")] pub use craft_markdown as markdown; +#[cfg(feature = "material-graph")] +pub use craft_material_graph as material_graph; #[cfg(feature = "materialx")] pub use craft_materialx as materialx; #[cfg(feature = "math")] diff --git a/crates/develop/src/camera_raw/mod.rs b/crates/develop/src/camera_raw/mod.rs index 0119fa1a08..feaff7b4fb 100644 --- a/crates/develop/src/camera_raw/mod.rs +++ b/crates/develop/src/camera_raw/mod.rs @@ -67,10 +67,10 @@ mod whites_blacks; pub use local_tone::{LocalTone, ToneKind, TonePass}; pub use per_pixel::{ - CURVE_LUT, Grade, Grain, PerPixel, Vignette, VignetteStyle, WB_STEPS, WhitesBlacks, WhitesBlacksModel, per_pixel, spatial, white_black_points, - whites_blacks_model, + CURVE_LUT, Grade, Grain, PerPixel, Vignette, VignetteStyle, WB_STEPS, WhitesBlacks, WhitesBlacksModel, per_pixel, spatial, spatial_tone, + white_black_points, whites_blacks_model, }; -pub use spatial::{Clarity, Dehaze, Texture}; +pub use spatial::{Clarity, Dehaze, Detail, Texture}; /// How the pixels encode light: the sRGB curve (gamma 0) or a pure power law (ProPhoto's 1.8, /// Adobe RGB's 2.2). The tone controls work on light, so the document's own curve decodes it. @@ -243,6 +243,7 @@ fn box_mean(v: &[f32], w: usize, h: usize, r: usize) -> Vec { } /// Approximate Gaussian (three box passes). +#[cfg(test)] fn gauss(v: &[f32], w: usize, h: usize, sigma: f32) -> Vec { box_means(v, w, h, &spatial::gauss_radii(sigma)) } @@ -484,7 +485,6 @@ pub fn develop(px: &mut [[f32; 4]], w: usize, h: usize, p: &CameraRaw, inputs: & if px.is_empty() || p.is_identity() { return; } - let ps = inputs.pixel_scale.clamp(0.01, 1.0); // 1. White balance + exposure in linear light. if let Some(g) = per_pixel::gains(p) { par_rows(px, w, 1, |_, row| { @@ -629,8 +629,8 @@ pub fn develop(px: &mut [[f32; 4]], w: usize, h: usize, p: &CameraRaw, inputs: & }); } // 8. Detail. - if p.noise_luminance > 0.0 || p.noise_color > 0.0 || p.sharpen_amount > 0.0 { - detail(px, w, h, p, ps); + if let Some(d) = Detail::new(p, inputs) { + detail(px, w, h, &d); } // 9. Effects. if p.vignette_amount != 0.0 { @@ -843,54 +843,41 @@ fn sharpening_detail(detail: f32) -> f32 { detail / 100.0 } -fn detail(px: &mut [[f32; 4]], w: usize, h: usize, p: &CameraRaw, ps: f32) { - // The controls' documented 0..=100 range: raw values drive the filter radii below. - let [nl, nld, nc, ncd] = [p.noise_luminance, p.noise_luminance_detail, p.noise_color, p.noise_color_detail].map(|v| v.clamp(0.0, 100.0)); +fn detail(px: &mut [[f32; 4]], w: usize, h: usize, d: &Detail) { // Work in Y + chroma (BT.709 luma, B−Y, R−Y). let mut y: Vec = px.iter().map(|q| luma([q[0], q[1], q[2]])).collect(); let mut cb: Vec = px.iter().zip(&y).map(|(q, l)| q[2] - l).collect(); let mut cr: Vec = px.iter().zip(&y).map(|(q, l)| q[0] - l).collect(); - if nl > 0.0 { - let n = nl / 100.0; - let r = ((1.0 + 3.0 * n) * ps).round().max(1.0) as usize; - let smooth = guided(&y, &y, w, h, r, (n * 0.06).powi(2) + 1e-6); - let keep = nld / 100.0 * 0.5; + if let Some(n) = &d.luminance { + let smooth = guided(&y, &y, w, h, n.radius, n.eps); for i in 0..w * h { - y[i] = smooth[i] + (y[i] - smooth[i]) * keep; + y[i] = smooth[i] + (y[i] - smooth[i]) * n.keep; } } - if nc > 0.0 { - let sigma = (nc / 100.0 * 6.0 * ps).max(0.3); - let (bcb, bcr) = (gauss(&cb, w, h, sigma), gauss(&cr, w, h, sigma)); - let keep = ncd / 100.0 * 0.3; + if let Some(c) = &d.color { + let (bcb, bcr) = (box_means(&cb, w, h, &c.radii), box_means(&cr, w, h, &c.radii)); for i in 0..w * h { - cb[i] = bcb[i] + (cb[i] - bcb[i]) * keep; - cr[i] = bcr[i] + (cr[i] - bcr[i]) * keep; + cb[i] = bcb[i] + (cb[i] - bcb[i]) * c.keep; + cr[i] = bcr[i] + (cr[i] - bcr[i]) * c.keep; } } - if p.sharpen_amount > 0.0 { - let sigma = (p.sharpen_radius.clamp(0.5, 3.0) * ps).max(0.3); - let blur = gauss(&y, w, h, sigma); + if let Some(s) = &d.sharpen { + let blur = box_means(&y, w, h, &s.radii); // Masking: an edge mask from the gradient of a smoothed luminance. - let mask: Option> = (p.sharpen_masking > 0.0).then(|| { - let s = gauss(&y, w, h, 1.0 * ps.max(0.5)); - let t = p.sharpen_masking / 100.0 * 0.08; + let mask: Option> = s.mask.as_ref().map(|(radii, [e0, e1])| { + let s = box_means(&y, w, h, radii); util::par_map(w * h, |i| { let (x, yy) = (i % w, i / w); let gx = s[yy * w + (x + 1).min(w - 1)] - s[yy * w + x.saturating_sub(1)]; let gy = s[(yy + 1).min(h - 1) * w + x] - s[yy.saturating_sub(1) * w + x]; - smoothstep(t * 0.5, t + 1e-4, gx.hypot(gy)) + smoothstep(*e0, *e1, gx.hypot(gy)) }) }); - let amt = p.sharpen_amount / 100.0 * 1.2; - let det = sharpening_detail(p.sharpen_detail); for i in 0..w * h { - let hp = y[i] - blur[i]; // Low Detail damps large (halo-producing) differences. - let limit = 0.03 + det * 0.3; - let hp = hp.clamp(-limit, limit) * (0.5 + 0.5 * det); + let hp = (y[i] - blur[i]).clamp(-s.limit, s.limit) * s.scale; let m = mask.as_ref().map_or(1.0, |m| m[i]); - y[i] += amt * hp * m; + y[i] += s.amount * hp * m; } } for i in 0..w * h { @@ -1204,6 +1191,23 @@ mod tests { assert!(per_pixel(&cr! { exposure: 0.5}, 2, 2, false, None).is_some()); } + #[test] + fn detail_reaches_the_per_pixel_stages_after_measured_whites_and_blacks() { + // Detail runs after Whites and Blacks, so another implementation can take its parameters + // and still measure the points on the per-pixel image. + let sharpened = cr! { sharpen_amount: 60.0, noise_luminance: 30.0, whites: 20.0}; + let stages = per_pixel(&sharpened, 8, 8, false, Some((0.05, 0.9))).expect("Detail alone stays on the per-pixel stages"); + assert_eq!(stages.detail, Detail::new(&sharpened, &DevelopInputs::default())); + assert!(stages.detail.is_some() && stages.whites_blacks.is_some() && stages.measure_whites_blacks.is_none()); + let px = vec![[0.4f32, 0.5, 0.6, 1.0]; 64]; + assert!(white_black_points(&px, 8, 8, &sharpened, &DevelopInputs::default()).is_some()); + // A stage before Whites and Blacks still leaves the measuring to whatever runs it. + let clarified = cr!(sharpened.clone() => clarity: 30.0); + assert!(white_black_points(&px, 8, 8, &clarified, &DevelopInputs::default()).is_none()); + assert!(per_pixel(&clarified, 8, 8, false, None).is_some_and(|s| s.measure_whites_blacks.is_some())); + assert!(spatial(&sharpened) && !spatial_tone(&sharpened) && spatial_tone(&clarified)); + } + #[test] fn calibration_turns_primaries_keeps_neutrals_and_tints_shadows() { let w = calibration_weights(0.0); diff --git a/crates/develop/src/camera_raw/per_pixel.rs b/crates/develop/src/camera_raw/per_pixel.rs index 9273036bce..d4b1eacd15 100644 --- a/crates/develop/src/camera_raw/per_pixel.rs +++ b/crates/develop/src/camera_raw/per_pixel.rs @@ -1,11 +1,11 @@ //! Develop's stages resolved for one image: every constant and table the per-pixel ones use, so //! another implementation of them (the GPU preview, `photocraft_gpu::CameraRawDevelop`) runs the //! same maths. [`develop`](super::develop) builds its own constants with the same functions. -//! The spatial stages other than Detail come as their parameters: Dehaze, Clarity and Texture -//! (see [`spatial`](super::spatial)), Shadows and Highlights as a [`LocalTone`]. +//! The spatial stages come as their parameters: Dehaze, Clarity, Texture and Detail (see +//! [`spatial`](super::spatial)), Shadows and Highlights as a [`LocalTone`]. use super::local_tone::{LocalTone, WORK_SIDE}; -use super::spatial::{Clarity, Dehaze, Texture}; +use super::spatial::{Clarity, Dehaze, Detail, Texture}; use super::types::VignetteStyle as StoredStyle; use super::{ CameraRaw, DevelopInputs, Encoding, Wheel, calibration_neutral, curve_lut, grade_neutral, hsl_neutral, hsv_to_rgb, is_linear, luma, @@ -177,7 +177,7 @@ pub struct PerPixel { /// 3b. Whites and Blacks, in the document's encoding. pub whites_blacks: Option, /// 3b. Whites and Blacks to measure the image's points for (the sliders, −100 … 100), when a - /// spatial stage is set: the points then depend on its output, so whatever runs it + /// spatial stage before them is set (any but Detail): the points then depend on its output, so whatever runs it /// measures them and picks the curves from [`whites_blacks_model`]. `whites_blacks` is /// then `None`. pub measure_whites_blacks: Option<[f32; 2]>, @@ -193,6 +193,8 @@ pub struct PerPixel { pub hsl: Option<[[f32; 8]; 3]>, /// 7. Color Grading. pub grade: Option, + /// 8. Detail: noise reduction and sharpening. + pub detail: Option, /// 9. Vignette. pub vignette: Option, /// 9. Grain. @@ -204,20 +206,22 @@ pub struct PerPixel { /// Whether developing needs a stage that reads neighbouring pixels: Dehaze, Shadows and /// Highlights, Texture, Clarity, sharpening or noise reduction. pub fn spatial(p: &CameraRaw) -> bool { - p.dehaze != 0.0 || [p.highlights, p.shadows, p.texture, p.clarity].iter().any(|v| *v != 0.0) || detail_on(p) + spatial_tone(p) || p.sharpen_amount > 0.0 || p.noise_luminance > 0.0 || p.noise_color > 0.0 } -/// Whether developing needs Detail: sharpening or noise reduction. -fn detail_on(p: &CameraRaw) -> bool { - p.sharpen_amount > 0.0 || p.noise_luminance > 0.0 || p.noise_color > 0.0 +/// Whether a stage before Whites and Blacks reads neighbouring pixels: Dehaze, Shadows and +/// Highlights, Texture or Clarity (all of [`spatial`] but Detail). The image's points then +/// depend on its output. +pub fn spatial_tone(p: &CameraRaw) -> bool { + p.dehaze != 0.0 || [p.highlights, p.shadows, p.texture, p.clarity].iter().any(|v| *v != 0.0) } /// The image's black and white points that Whites and Blacks adapt to, for `px` (`w × h`, /// display-encoded) developed per pixel with `p`: what [`develop`](super::develop) measures /// after white balance and Contrast. `None` when Whites and Blacks are 0 or `p` needs a -/// spatial stage. +/// spatial stage before them ([`spatial_tone`]; Detail comes after). pub fn white_black_points(px: &[[f32; 4]], w: usize, h: usize, p: &CameraRaw, inputs: &DevelopInputs) -> Option<(f32, f32)> { - if (p.whites == 0.0 && p.blacks == 0.0) || spatial(p) || px.len() != w.saturating_mul(h) { + if (p.whites == 0.0 && p.blacks == 0.0) || spatial_tone(p) || px.len() != w.saturating_mul(h) { return None; } let enc = Encoding::of(inputs.encoding_gamma); @@ -228,14 +232,14 @@ pub fn white_black_points(px: &[[f32; 4]], w: usize, h: usize, p: &CameraRaw, in })) } -/// Develop's stages for settings without Detail or Calibration, on a `w × h` image; `points` are -/// the image's [`white_black_points`]. `None` when `p` needs Detail or Calibration (these stages -/// run neither), Shadows or Highlights on a frame wider than the filter's working copy (the +/// Develop's stages for settings without Calibration, on a `w × h` image; `points` are the image's +/// [`white_black_points`]. `None` when `p` needs Calibration (these stages don't run it), Shadows +/// or Highlights on a frame wider than the filter's working copy (the /// develop then filters a reduced copy) or only 2 pixels on its short side, or Whites or Blacks /// without a spatial stage and without `points`. The points themselves leave Calibration out, so a /// caller may cache them across Calibration changes. pub fn per_pixel(p: &CameraRaw, inputs: &DevelopInputs, w: usize, h: usize, float: bool, points: Option<(f32, f32)>) -> Option { - if detail_on(p) || !calibration_neutral(p) { + if !calibration_neutral(p) { return None; } // The develop leaves frames under 2 pixels on a side alone. @@ -277,6 +281,7 @@ pub fn per_pixel(p: &CameraRaw, inputs: &DevelopInputs, w: usize, h: usize, floa point: [pts(&p.point_curve), pts(&p.point_curve_red), pts(&p.point_curve_green), pts(&p.point_curve_blue)], hsl: (!hsl_neutral(p)).then_some([p.hsl_hue, p.hsl_sat, p.hsl_lum]), grade: (!grade_neutral(p)).then(|| Grade::new(p)), + detail: Detail::new(p, inputs), vignette: (p.vignette_amount != 0.0).then(|| Vignette::new(w, h, p)), grain: (p.grain_amount > 0.0).then(|| Grain::new(p, inputs)), clamp: !float && !identity, diff --git a/crates/develop/src/camera_raw/spatial.rs b/crates/develop/src/camera_raw/spatial.rs index a7b17347f0..a74ea7a059 100644 --- a/crates/develop/src/camera_raw/spatial.rs +++ b/crates/develop/src/camera_raw/spatial.rs @@ -1,6 +1,6 @@ #![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used, clippy::panic))] -//! Dehaze, Clarity and Texture resolved for one frame: the sizes, radii and constants their +//! Dehaze, Clarity, Texture and Detail resolved for one frame: the sizes, radii and constants their //! filters use, so another implementation of them (the GPU preview, //! `photocraft_gpu::CameraRawDevelop`) runs the same filters. [`develop`](super::develop) builds //! its own from the same constructors. @@ -13,6 +13,9 @@ //! J. Sun, *Fast Guided Filter*, arXiv 2015), weighted toward the midtones. //! - **Texture** raises its difference from a Gaussian blur (three box passes), limited to //! ±[`TEXTURE_LIMIT`]. +//! - **Detail** works on BT.709 luminance and two chroma planes: a guided filter of the luminance +//! by itself for luminance noise, a Gaussian of the chroma for colour noise, then an unsharp +//! mask of the luminance, optionally weighted by its smoothed gradient. use super::{CameraRaw, DevelopInputs}; @@ -144,6 +147,80 @@ impl Texture { } } +/// Detail (noise reduction, then sharpening) on BT.709 luminance Y and the chroma B − Y, R − Y, +/// resolved for one frame. Each part is `None` when it is off. +#[derive(Clone, Debug, PartialEq)] +pub struct Detail { + pub luminance: Option, + pub color: Option, + pub sharpen: Option, +} + +/// Luminance noise reduction: a guided filter of Y by itself, with some of the detail kept. +#[derive(Clone, Debug, PartialEq)] +pub struct LuminanceNoise { + /// The guided filter's radius. + pub radius: usize, + /// Its regularisation. + pub eps: f32, + /// The share of Y's difference from the filter that stays. + pub keep: f32, +} + +/// Colour noise reduction: a Gaussian of both chroma planes, with some of the detail kept. +#[derive(Clone, Debug, PartialEq)] +pub struct ColorNoise { + /// The Gaussian's box radii, in order. + pub radii: Vec, + /// The share of the chroma's difference from the blur that stays. + pub keep: f32, +} + +/// Sharpening: Y plus `amount` times its difference from a Gaussian (after noise reduction), +/// clamped to ±`limit` and scaled by `scale`, optionally weighted by an edge mask. +#[derive(Clone, Debug, PartialEq)] +pub struct Sharpen { + /// The Gaussian's box radii, in order. + pub radii: Vec, + pub amount: f32, + pub limit: f32, + pub scale: f32, + /// Masking: the box radii of another Gaussian of Y, and the smoothstep edges its gradient's + /// length is weighed between. + pub mask: Option<(Vec, [f32; 2])>, +} + +impl Detail { + /// Detail for `p` at the job's pixel scale; `None` when sharpening and both noise reductions + /// are off. + pub fn new(p: &CameraRaw, inputs: &DevelopInputs) -> Option { + let ps = inputs.pixel_scale.clamp(0.01, 1.0); + // The controls' documented 0..=100 range: raw values drive the filter radii below. + let [nl, nld, nc, ncd] = [p.noise_luminance, p.noise_luminance_detail, p.noise_color, p.noise_color_detail].map(|v| v.clamp(0.0, 100.0)); + let luminance = (nl > 0.0).then(|| { + let n = nl / 100.0; + LuminanceNoise { radius: ((1.0 + 3.0 * n) * ps).round().max(1.0) as usize, eps: (n * 0.06).powi(2) + 1e-6, keep: nld / 100.0 * 0.5 } + }); + let color = (nc > 0.0).then(|| ColorNoise { radii: gauss_radii((nc / 100.0 * 6.0 * ps).max(0.3)), keep: ncd / 100.0 * 0.3 }); + let sharpen = (p.sharpen_amount > 0.0).then(|| { + let det = super::sharpening_detail(p.sharpen_detail); + // Masking: an edge mask from the gradient of a smoothed luminance. + let mask = (p.sharpen_masking > 0.0).then(|| { + let t = p.sharpen_masking / 100.0 * 0.08; + (gauss_radii(1.0 * ps.max(0.5)), [t * 0.5, t + 1e-4]) + }); + Sharpen { + radii: gauss_radii((p.sharpen_radius.clamp(0.5, 3.0) * ps).max(0.3)), + amount: p.sharpen_amount / 100.0 * 1.2, + limit: 0.03 + det * 0.3, + scale: 0.5 + 0.5 * det, + mask, + } + }); + (luminance.is_some() || color.is_some() || sharpen.is_some()).then_some(Detail { luminance, color, sharpen }) + } +} + /// The box radii of develop's Gaussian of `sigma`: none below 0.3. pub(crate) fn gauss_radii(sigma: f32) -> Vec { if sigma < 0.3 { @@ -189,6 +266,31 @@ mod tests { ); } + #[test] + fn detail_parts_follow_their_sliders_and_shrink_on_a_proxy() { + let full = DevelopInputs::default(); + let scale = |pixel_scale| DevelopInputs { pixel_scale, ..full }; + assert!(Detail::new(&CameraRaw::default(), &full).is_none()); + // Each part is on only when its own slider is. + let parts = |p: &CameraRaw| Detail::new(p, &full).map(|d| (d.luminance.is_some(), d.color.is_some(), d.sharpen.is_some())); + assert_eq!(parts(&cr! { noise_luminance: 40.0}), Some((true, false, false))); + assert_eq!(parts(&cr! { noise_color: 40.0}), Some((false, true, false))); + assert_eq!(parts(&cr! { sharpen_amount: 40.0}), Some((false, false, true))); + let masked = |m| Detail::new(&cr! { sharpen_amount: 40.0, sharpen_masking: m}, &full).and_then(|d| d.sharpen).map(|s| s.mask.is_some()); + assert_eq!((masked(0.0), masked(50.0)), (Some(false), Some(true))); + // Out-of-range noise sliders act as their ends. + assert_eq!(Detail::new(&cr! { noise_luminance: 1e30}, &full), Detail::new(&cr! { noise_luminance: 100.0}, &full)); + // On the dialog's proxy the filters are no wider than at full size. + let p = cr! { noise_luminance: 80.0, noise_color: 80.0, sharpen_amount: 80.0, sharpen_radius: 3.0, sharpen_masking: 50.0}; + let (big, small) = (Detail::new(&p, &full).unwrap(), Detail::new(&p, &scale(0.143)).unwrap()); + let reach = |r: &[usize]| r.iter().sum::(); + let (bl, sl) = (big.luminance.unwrap(), small.luminance.unwrap()); + assert!(sl.radius < bl.radius); + assert!(reach(&small.color.unwrap().radii) < reach(&big.color.unwrap().radii)); + let (bs, ss) = (big.sharpen.unwrap(), small.sharpen.unwrap()); + assert!(reach(&ss.radii) < reach(&bs.radii) && reach(&ss.mask.unwrap().0) <= reach(&bs.mask.unwrap().0)); + } + #[test] fn dehaze_cells_average_blocks_after_white_balance_and_refuse_a_wrong_size() { let d = Dehaze::new(&cr! { dehaze: 10.0}, 3, 1).unwrap(); diff --git a/crates/develop/src/sensor/mod.rs b/crates/develop/src/sensor/mod.rs index f7f20ab0aa..4174ecbdd0 100644 --- a/crates/develop/src/sensor/mod.rs +++ b/crates/develop/src/sensor/mod.rs @@ -168,7 +168,7 @@ impl RawDevelopExt for RawImage { fn develop_balanced_masked(&self, method: Method, wb: [f32; 3], clip: f32) -> Result<(Rgb32f, Option>)> { let n = self.normalized()?; - let mask = clip_mask(self, &n, method, clip); + let mask = raw_clip_mask(self, &n, method, clip); Ok((develop_full(self, n, method, Some(wb)), mask)) } @@ -253,17 +253,34 @@ fn scale_mosaic(n: &mut Normalized, method: Method, gains: [f32; 3]) -> bool { true } -fn clip_mask(raw: &RawImage, n: &Normalized, method: Method, clip: f32) -> Option> { +fn raw_clip_mask(raw: &RawImage, n: &Normalized, method: Method, clip: f32) -> Option> { + let crop = raw.develop_crop(n.width, n.height); + if !raw.opcodes.list3.is_empty() || stretched_height(crop.height, raw.pixel_aspect) != crop.height { + return None; + } + clip_mask(n, crop, method, clip) +} + +/// The [`highlight::reconstruct_masked`] mask for the output of [`demosaic()`] with `method` on the single-plane CFA +/// mosaic `n`, cropped to `crop` (one entry per pixel of `crop`, row-major). `n` holds sensor values normalised so +/// that 1.0 is white and before white balance; samples at or above `clip` count as clipped. Use it when the mosaic +/// is demosaicked by the caller (for example white-balanced first) rather than through [`RawDevelopExt`]. +/// `None` when nothing is clipped, `n` is not a single-plane RGB CFA mosaic, `crop` does not fit inside it, or `clip` +/// is not a positive finite level. +pub fn clip_mask(n: &Normalized, crop: Rect, method: Method, clip: f32) -> Option> { use highlight::{CLIPPED_BITS, FROM_CLIPPED_BITS}; // This radius covers samples read directly by the directional interpolators. Estimates // that build on interpolated green can depend on samples farther away. const REACH: usize = 2; - let cfa = n.cfa.as_ref().filter(|_| n.cpp == 1)?; + let cfa = n.cfa.as_ref().filter(|c| n.cpp == 1 && cfa_valid(c) && c.pattern.iter().all(|&p| p <= 2))?; let (w, h) = (n.width, n.height); - let crop = raw.develop_crop(w, h); - if !clip.is_finite() || clip <= 0.0 || !raw.opcodes.list3.is_empty() || stretched_height(crop.height, raw.pixel_aspect) != crop.height { + let fits = crop.width > 0 + && crop.height > 0 + && crop.x.checked_add(crop.width).is_some_and(|r| r <= w) + && crop.y.checked_add(crop.height).is_some_and(|b| b <= h); + if !clip.is_finite() || clip <= 0.0 || !fits || w.checked_mul(h) != Some(n.data.len()) { return None; } let is_clipped = |v: &f32| *v >= clip; diff --git a/crates/develop/tests/it/balanced.rs b/crates/develop/tests/it/balanced.rs index 4c85843041..bf7b6bbcaf 100644 --- a/crates/develop/tests/it/balanced.rs +++ b/crates/develop/tests/it/balanced.rs @@ -1,7 +1,7 @@ //! Original synthetic RAW scenes from storytold/lightcraft#1463, generated in these tests. use craft_develop::raster::Rgb32f; -use craft_develop::sensor::{Method, RawDevelopExt, highlight}; +use craft_develop::sensor::{self, Method, RawDevelopExt, highlight}; use craft_raw::opcodes::{Opcode, OpcodeLists}; use craft_raw::{BlackLevel, Cfa, ColorData, Orientation, RawData, RawFormat, RawImage, Rect}; @@ -355,6 +355,30 @@ fn the_clip_mask_marks_the_colours_interpolated_from_clipped_samples() { assert!(raw.develop_balanced_masked(Method::Ahd, DAYLIGHT, CLIP).unwrap().1.is_none()); } +#[test] +fn a_caller_demosaicking_its_own_mosaic_gets_the_same_clip_mask() { + let (w, h) = (40usize, 30usize); + let light = photograph(w, h, |x, y| if (x - 18.0).powi(2) + (y - 14.0).powi(2) < 49.0 { 6.0 } else { 0.4 }); + let mut cases = layouts(); + cases.push(("RGGB bilinear".into(), Cfa::bayer("RGGB").unwrap(), Method::Bilinear)); + for (name, cfa, method) in cases { + let mut raw = raw_of(w, h, &cfa, DAYLIGHT, |x, y| [light[y * w + x]; 3]); + raw.crop = Rect::new(2, 1, 33, 27); + let (_, expected) = raw.develop_balanced_masked(method, DAYLIGHT, CLIP).unwrap(); + let n = raw.normalized().unwrap(); + let crop = raw.develop_crop(n.width, n.height); + assert_eq!(sensor::clip_mask(&n, crop, method, CLIP), expected, "{name}"); + assert!(expected.is_some(), "{name}: clipped samples"); + let outside = Rect::new(crop.x + 1, crop.y, n.width - crop.x, crop.height); + assert!(sensor::clip_mask(&n, outside, method, CLIP).is_none(), "{name}: a crop past the mosaic"); + let mut four_colour = n.clone(); + four_colour.cfa.as_mut().unwrap().pattern[0] = 3; + assert!(sensor::clip_mask(&four_colour, crop, method, CLIP).is_none(), "{name}: a colour index past blue"); + let huge = sensor::Normalized { width: usize::MAX, height: 2, data: Vec::new(), ..n.clone() }; + assert!(sensor::clip_mask(&huge, Rect::new(0, 0, 1, 1), method, CLIP).is_none(), "{name}: dimensions past usize"); + } +} + #[test] fn ppg_clip_mask_marks_same_colour_dependencies() { let cfa = Cfa::bayer("RGGB").unwrap(); diff --git a/crates/font-manager/Cargo.toml b/crates/font-manager/Cargo.toml index e3fd1e6770..1374378fab 100644 --- a/crates/font-manager/Cargo.toml +++ b/crates/font-manager/Cargo.toml @@ -46,7 +46,9 @@ craft-theme = { workspace = true, optional = true } serde = { workspace = true, optional = true } log = { version = "0.4", optional = true } # Variation axes and named instances of a face (`axes`), on every feature set. -skrifa = { version = "0.44", default-features = false, features = ["std"] } +skrifa = { version = "0.47", default-features = false, features = ["std"] } +# Decodes the preview service's WOFF2 subsets; pure Rust. Brotli only: WOFF 1 isn't served. +wuff = { version = "0.2.9", default-features = false, features = ["brotli"] } [build-dependencies] # The Arabic sample story's face, from the craft fonts set when `CRAFT_FONTS_DIR` names one. @@ -54,6 +56,8 @@ craft-fonts-build = { workspace = true } [dev-dependencies] craft-font-manager = { path = ".", features = ["suite"] } +# The shared preview test vectors. +serde_json = { workspace = true } [[test]] name = "it" diff --git a/crates/font-manager/src/lib.rs b/crates/font-manager/src/lib.rs index f3bb0d1ace..9ee20f5948 100644 --- a/crates/font-manager/src/lib.rs +++ b/crates/font-manager/src/lib.rs @@ -17,6 +17,7 @@ pub mod filter; pub mod index; pub mod installed; +pub mod remote; pub mod store; pub mod axes; diff --git a/crates/font-manager/src/panel/samples.rs b/crates/font-manager/src/panel/samples.rs index f0523150e6..763d8e5a27 100644 --- a/crates/font-manager/src/panel/samples.rs +++ b/crates/font-manager/src/panel/samples.rs @@ -1,5 +1,9 @@ -//! Sample text: a sentence in the language the catalogue is filtered by, or in a family's own -//! script when it has no Latin, so a sample never comes out as boxes. +//! Sample text: a family's own sentence from the index (its script's, by `sample_script`), the +//! one the preview service's sample subsets hold; a sentence in the language the catalogue is +//! filtered by; and built-in sentences by script for families the index has no sample for. + +use crate::index::{Family, Index}; +use crate::panel::app::list_file; /// The English pangram, the sample for Latin. pub const PANGRAM: &str = "The quick brown fox jumps over the lazy dog"; @@ -81,6 +85,12 @@ pub fn for_script(script: &str) -> Option<&'static str> { } } +/// The sample of the face the list shows for `family`, from the index: the sentence of the +/// face's `sample_script` (else the family's), or the face's own text. +pub fn of_family<'a>(index: &'a Index, family: &'a Family) -> Option<&'a str> { + list_file(family).and_then(|file| index.sample_text(family, file)) +} + /// The sample for a family with `scripts`: the pangram when it has Latin, else a sentence in the /// first of its scripts there is one for. pub fn for_scripts<'a>(scripts: impl IntoIterator) -> &'static str { diff --git a/crates/font-manager/src/remote.rs b/crates/font-manager/src/remote.rs new file mode 100644 index 0000000000..f8f1479305 --- /dev/null +++ b/crates/font-manager/src/remote.rs @@ -0,0 +1,683 @@ +//! The font preview service's client: subset URLs, a pool that fetches and decodes them, and a +//! disk cache. +//! +//! The service serves a small subset of one font file per preview, addressed by the upstream +//! file's sha256: the face's default sample, printable ASCII, or a set of codepoints, at the +//! instance the list shows or with every axis kept. Responses never change, so the cache never +//! revalidates. With the service at `https://fonts.example.com`, the list's sample of a face is +//! `https://fonts.example.com/v1/faces//list/sample-.woff2`. +//! +//! [`Previews`] requests nothing unless a preview service is set and previews are enabled +//! ([`Installer::preview_service`], [`Installer::previews_enabled`]). Previews are on by default; +//! a user setting turns them off. There is no prompt, and the install consent +//! ([`Installer::downloads_allowed`]) is not consulted: previews are fetched whether or not +//! installs are allowed. With previews off nothing goes to the network, but previews already in +//! the disk cache are still used. Without a service the panel keeps its whole-family previews. + +use std::collections::{BTreeMap, BTreeSet, HashMap}; +use std::fmt::Write as _; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::mpsc::{Receiver, Sender, channel}; +use std::sync::{Arc, Condvar, Mutex, MutexGuard}; +use std::time::{Duration, SystemTime}; + +use craft_font_store::{Cancel, Client, FetchError, Timeouts, is_font, sha256_hex}; + +use crate::store::Installer; + +/// The most codepoints one request may name; the service rejects more. +pub const MAX_CODEPOINTS: usize = 256; + +/// The largest response accepted. Subsets are a few KB; a `var` subset of CJK text is the largest. +pub const MAX_PREVIEW_BYTES: u64 = 8 << 20; + +/// The disk cache's size. +pub const CACHE_LIMIT: u64 = 50 << 20; + +/// Requests at a time. +pub const WORKERS: usize = 8; + +/// A set of codepoints, as a subset request names them. +#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] +pub struct Codepoints(BTreeSet); + +impl Codepoints { + /// The characters of `text` without C0 and C1 controls and DEL, which no font draws. + pub fn from_text(text: &str) -> Codepoints { + text.chars().collect() + } + + pub fn len(&self) -> usize { + self.0.len() + } + + pub fn is_empty(&self) -> bool { + self.0.is_empty() + } + + pub fn contains(&self, c: char) -> bool { + self.0.contains(&c) + } + + /// In ascending order. + pub fn iter(&self) -> impl Iterator + '_ { + self.0.iter().copied() + } + + /// Keeps the codepoints `keep` accepts, such as those a face covers. + pub fn retain(&mut self, mut keep: impl FnMut(char) -> bool) { + self.0.retain(|&c| keep(c)); + } + + /// The canonical form the service accepts, and so the cache key: ascending lowercase hex + /// without leading zeros, a run of two or more as `first-last`, joined by commas + /// (`20,41-5a,e9`). Empty for the empty set. + pub fn encode(&self) -> String { + let mut out = String::new(); + let mut rest = self.0.iter().map(|&c| c as u32).peekable(); + while let Some(first) = rest.next() { + let mut last = first; + while rest.peek() == Some(&(last + 1)) { + last += 1; + rest.next(); + } + if !out.is_empty() { + out.push(','); + } + let _ = if last == first { write!(out, "{first:x}") } else { write!(out, "{first:x}-{last:x}") }; + } + out + } +} + +impl FromIterator for Codepoints { + /// Without C0 and C1 controls and DEL. + fn from_iter>(chars: I) -> Codepoints { + Codepoints(chars.into_iter().filter(|&c| !matches!(c as u32, 0..0x20 | 0x7f..=0x9f)).collect()) + } +} + +/// Which instance of a face a subset is drawn at. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Instance { + /// What the list shows: the "Regular" named instance of a variable face, else its default, + /// pinned to a static font. + List, + /// Every axis kept, for the detail view's styles and sliders. + Var, +} + +impl Instance { + fn as_str(self) -> &'static str { + match self { + Instance::List => "list", + Instance::Var => "var", + } + } +} + +/// The first 12 lowercase hex digits of the sha256 of a sample text (UTF-8, as the index has +/// it), which names the sample subset for that text. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct SampleHash(String); + +impl SampleHash { + pub fn of(text: &str) -> SampleHash { + SampleHash(sha256_hex(text.as_bytes())[..12].to_string()) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +/// Which characters a subset holds. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub enum Subset { + /// The face's default sample (its script's sentence from the index) and the family name. + /// The hash names the text the client has; the service answers 404 for any other. + Sample(SampleHash), + /// Printable ASCII, U+0020 to U+007E, for faces that cover Latin. + Ascii, + /// These codepoints, for typed text the static subsets don't cover. + Codepoints(Codepoints), +} + +/// One subset of one face: a request, a cache entry and the key results come back under. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct PreviewKey { + sha256: String, + instance: Instance, + subset: Subset, +} + +impl PreviewKey { + /// The subset of the font file with this sha256 (as the index has it). `None` for a sha256 + /// that isn't 64 hex digits, and for codepoints that are empty or more than + /// [`MAX_CODEPOINTS`]. + pub fn new(sha256: &str, instance: Instance, subset: Subset) -> Option { + if sha256.len() != 64 || !sha256.bytes().all(|b| b.is_ascii_hexdigit()) { + return None; + } + if let Subset::Codepoints(c) = &subset + && (c.is_empty() || c.len() > MAX_CODEPOINTS) + { + return None; + } + Some(PreviewKey { sha256: sha256.to_ascii_lowercase(), instance, subset }) + } + + pub fn sha256(&self) -> &str { + &self.sha256 + } + + pub fn instance(&self) -> Instance { + self.instance + } + + pub fn subset(&self) -> &Subset { + &self.subset + } + + /// The path below the service's base URL: `v1/faces///sample-.woff2`, + /// `.../ascii.woff2` or `.../u/.woff2`. + pub fn path(&self) -> String { + let what = match &self.subset { + Subset::Sample(h) => format!("sample-{}", h.as_str()), + Subset::Ascii => "ascii".to_string(), + Subset::Codepoints(c) => format!("u/{}", c.encode()), + }; + format!("v1/faces/{}/{}/{what}.woff2", self.sha256, self.instance.as_str()) + } + + /// The URL at the service whose base URL is `service`. + pub fn url(&self, service: &str) -> String { + format!("{}/{}", service.trim_end_matches('/'), self.path()) + } +} + +/// Why a preview didn't load. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum PreviewError { + /// The user turned previews off, and the subset isn't cached. + PreviewsOff, + /// No preview service is set. + NoService, + /// The request failed: the network, an HTTP status (503 while the service is busy), the + /// size limit. + Failed(String), + /// The service has no such subset (HTTP 404): for a sample, its text isn't the client's. + NotFound, + /// The response isn't a WOFF2 font with outlines. + NotAFont, +} + +impl std::fmt::Display for PreviewError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + PreviewError::PreviewsOff => f.write_str("font previews are turned off"), + PreviewError::NoService => f.write_str("no preview service is set"), + PreviewError::Failed(e) => f.write_str(e), + PreviewError::NotFound => f.write_str("the service has no such preview"), + PreviewError::NotAFont => f.write_str("the preview is not a font, or a damaged one"), + } + } +} + +impl std::error::Error for PreviewError {} + +/// A finished request. +#[derive(Debug)] +pub struct Preview { + pub key: PreviewKey, + /// The decoded font file (TrueType or OpenType), ready to register. + pub font: Result, PreviewError>, +} + +/// How the pool downloads: craft-font-store's [`Client`], or a stand-in in tests. +pub trait Fetch: Send + Sync { + /// GETs `url`, built from the preview-service setting, at most `max` bytes, stopping soon after `cancel` is set. + fn get(&self, url: &str, max: u64, cancel: &Cancel) -> Result, FetchError>; +} + +impl Fetch for Client { + fn get(&self, url: &str, max: u64, cancel: &Cancel) -> Result, FetchError> { + Client::get_from_service(self, url, max, cancel, &mut |_| {}) + } +} + +/// Subsets as the service sent them (WOFF2), one file per key, named by the sha256 of the key's +/// path. The least recently used go once the folder holds more than its limit. Several apps can +/// share the folder: a file another one removed is a miss. +pub struct DiskCache { + dir: PathBuf, + limit: u64, + /// Read from the folder on first use. + entries: Mutex>, +} + +#[derive(Default)] +struct Entries { + /// File name to its size and last use. + files: HashMap, + /// Last use to file name, oldest first. + order: BTreeMap, + total: u64, + tick: u64, +} + +impl Entries { + fn touch(&mut self, name: &str, size: u64) { + self.tick += 1; + if let Some((old_size, old_tick)) = self.files.insert(name.to_string(), (size, self.tick)) { + self.order.remove(&old_tick); + self.total = self.total.saturating_sub(old_size); + } + self.order.insert(self.tick, name.to_string()); + self.total = self.total.saturating_add(size); + } + + fn forget(&mut self, name: &str) { + if let Some((size, tick)) = self.files.remove(name) { + self.order.remove(&tick); + self.total = self.total.saturating_sub(size); + } + } + + /// Removes the oldest files, except `keep`, until the rest fit in `limit`. + fn evict(&mut self, dir: &Path, limit: u64, keep: Option<&str>) { + while self.total > limit { + let Some(name) = self.order.values().find(|n| Some(n.as_str()) != keep).cloned() else { break }; + let _ = std::fs::remove_file(dir.join(&name)); + self.forget(&name); + } + } +} + +/// A temporary file older than this belongs to a write that never finished. +const STALE_TEMP: Duration = Duration::from_secs(600); + +impl DiskCache { + /// A cache in `dir` (created on the first write) of at most `limit` bytes. + pub fn new(dir: impl Into, limit: u64) -> DiskCache { + DiskCache { dir: dir.into(), limit, entries: Mutex::new(None) } + } + + pub fn dir(&self) -> &Path { + &self.dir + } + + /// The bytes cached for `path` ([`PreviewKey::path`]), marking them as just used. + pub fn get(&self, path: &str) -> Option> { + let name = file_name(path); + let file = self.dir.join(&name); + let bytes = std::fs::metadata(&file).ok().filter(|m| m.len() <= MAX_PREVIEW_BYTES).and_then(|_| std::fs::read(&file).ok()); + match bytes { + Some(bytes) => { + self.with(|e| e.touch(&name, bytes.len() as u64)); + // The modification time keeps the order for the next session. + let _ = std::fs::File::options().write(true).open(&file).and_then(|f| f.set_modified(SystemTime::now())); + Some(bytes) + } + None => { + self.with(|e| e.forget(&name)); + None + } + } + } + + /// Whether `path` is cached, without marking it used. Asks the folder, which another app + /// sharing it may have added to since it was read. + pub fn contains(&self, path: &str) -> bool { + std::fs::metadata(self.dir.join(file_name(path))).is_ok_and(|m| m.is_file()) + } + + /// Caches `bytes` for `path`, then removes the least recently used past the limit. Bytes + /// larger than the whole limit aren't cached. + pub fn put(&self, path: &str, bytes: &[u8]) { + let size = bytes.len() as u64; + if size > self.limit { + return; + } + let name = file_name(path); + if std::fs::create_dir_all(&self.dir).is_err() { + return; + } + // A reader never sees half a file: write beside it, then rename. + static N: AtomicU64 = AtomicU64::new(0); + let temp = self.dir.join(format!(".tmp-{}-{}", std::process::id(), N.fetch_add(1, Ordering::Relaxed))); + if std::fs::write(&temp, bytes).and_then(|()| std::fs::rename(&temp, self.dir.join(&name))).is_err() { + let _ = std::fs::remove_file(&temp); + return; + } + self.with(|e| { + e.touch(&name, size); + e.evict(&self.dir, self.limit, Some(&name)); + }); + } + + /// Removes the entry for `path`, as when it doesn't decode. + pub fn remove(&self, path: &str) { + let name = file_name(path); + let _ = std::fs::remove_file(self.dir.join(&name)); + self.with(|e| e.forget(&name)); + } + + /// Bytes held. + pub fn size(&self) -> u64 { + self.with(|e| e.total) + } + + fn with(&self, f: impl FnOnce(&mut Entries) -> R) -> R { + let mut guard = self.entries.lock().unwrap_or_else(|e| e.into_inner()); + f(guard.get_or_insert_with(|| self.scan())) + } + + /// The files in the folder, oldest modification first; drops stale temporary files and + /// whatever no longer fits. + fn scan(&self) -> Entries { + let mut found = Vec::new(); + for entry in std::fs::read_dir(&self.dir).into_iter().flatten().flatten() { + let name = entry.file_name().to_string_lossy().into_owned(); + let Ok(meta) = entry.metadata() else { continue }; + let modified = meta.modified().unwrap_or(SystemTime::UNIX_EPOCH); + if name.starts_with(".tmp-") { + if modified.elapsed().is_ok_and(|age| age > STALE_TEMP) { + let _ = std::fs::remove_file(entry.path()); + } + } else if meta.is_file() && is_entry_name(&name) { + found.push((modified, name, meta.len())); + } + } + found.sort(); + let mut entries = Entries::default(); + for (_, name, size) in found { + entries.touch(&name, size); + } + entries.evict(&self.dir, self.limit, None); + entries + } +} + +fn file_name(path: &str) -> String { + format!("{}.woff2", sha256_hex(path.as_bytes())) +} + +fn is_entry_name(name: &str) -> bool { + name.strip_suffix(".woff2").is_some_and(|h| h.len() == 64 && h.bytes().all(|b| b.is_ascii_hexdigit())) +} + +type Wake = Arc; + +/// Fetches subsets on [`WORKERS`] threads of its own, separate from the panel's jobs, highest +/// priority first. Results wait in [`Previews::poll`]; a cancelled request delivers nothing. +/// +/// Each request reads the disk cache first. Only on a miss, and only while previews are enabled +/// and a service is set, does it go to the network; the response is decoded, checked and cached. +/// Without a service, requests come back as [`PreviewError::NoService`] at once and nothing is +/// read or fetched. +pub struct Previews { + installer: Arc, + fetcher: Arc, + cache: Option>, + wake: Option, + workers: usize, + shared: Arc, + tx: Sender, + rx: Receiver, +} + +struct Shared { + state: Mutex, + ready: Condvar, +} + +#[derive(Default)] +struct State { + /// Waiting: priority and order of arrival. + queued: HashMap, + /// Being fetched: the job's id and its cancel flag. + running: HashMap, + next: u64, + started: bool, + stop: bool, +} + +impl State { + /// The highest priority, then the oldest. + fn take_next(&mut self) -> Option { + let key = self.queued.iter().max_by_key(|(_, (priority, seq))| (*priority, std::cmp::Reverse(*seq))).map(|(k, _)| k.clone())?; + self.queued.remove(&key); + Some(key) + } + + fn is_running(&self, key: &PreviewKey) -> bool { + self.running.get(key).is_some_and(|(_, c)| !c.is_cancelled()) + } +} + +impl Previews { + /// A pool fetching with the installer's client ([`Installer::http_client`]) given short timeouts + /// (10 s to connect, 15 s to respond, 30 s overall; the down state stays shared), else with its + /// own craft-font-store [`Client`]. A network failure of the service pauses its requests for a + /// minute, for every user of the same client (installs too). It caches in the store's + /// [`Installer::preview_cache`] folder, up to [`CACHE_LIMIT`]. It starts its threads on the + /// first request. + pub fn new(installer: Arc) -> Previews { + let timeouts = Timeouts { connect: Duration::from_secs(10), response: Duration::from_secs(15), overall: Duration::from_secs(30) }; + let client = installer.http_client().map_or_else(|| Client::new(timeouts), |c| c.with_timeouts(timeouts)); + let cache = installer.preview_cache().map(|dir| Arc::new(DiskCache::new(dir, CACHE_LIMIT))); + let (tx, rx) = channel(); + Previews { + installer, + fetcher: Arc::new(client), + cache, + wake: None, + workers: WORKERS, + shared: Arc::new(Shared { state: Mutex::new(State::default()), ready: Condvar::new() }), + tx, + rx, + } + } + + /// Fetches through `fetcher` instead. + pub fn with_fetcher(mut self, fetcher: Arc) -> Previews { + self.fetcher = fetcher; + self + } + + /// Caches in `cache`, or with `None` not at all. + pub fn with_cache(mut self, cache: Option) -> Previews { + self.cache = cache.map(Arc::new); + self + } + + /// Runs `workers` requests at a time (at least one) instead of [`WORKERS`]. + pub fn with_workers(mut self, workers: usize) -> Previews { + self.workers = workers.max(1); + self + } + + /// Calls `wake` from a worker thread after each result, such as egui's `request_repaint`. + pub fn on_ready(mut self, wake: impl Fn() + Send + Sync + 'static) -> Previews { + self.wake = Some(Arc::new(wake)); + self + } + + /// Whether a preview service is set and previews are enabled. It reads the store's settings, so callers ask when the + /// panel opens or its settings change, not every frame. + pub fn available(&self) -> bool { + self.installer.preview_service().is_some() && self.installer.previews_enabled() + } + + /// The disk cache, if there is one. + pub fn cache(&self) -> Option<&DiskCache> { + self.cache.as_deref() + } + + /// Queues `key` at `priority` (higher first; the same priority in the order asked). A key + /// already queued takes the new priority; one being fetched is left alone. + pub fn request(&self, key: PreviewKey, priority: u32) { + let mut state = self.lock(); + if state.is_running(&key) { + return; + } + if !state.started { + state.started = true; + self.start(); + } + let seq = state.next; + state.next += 1; + let entry = state.queued.entry(key).or_insert((priority, seq)); + entry.0 = priority; + drop(state); + self.shared.ready.notify_one(); + } + + /// Drops `key` from the queue, or stops fetching it. Nothing is delivered for it, unless it + /// finished before the call. + pub fn cancel(&self, key: &PreviewKey) { + self.retain(|k| k != key); + } + + /// Cancels every queued and running request `keep` rejects, such as rows that scrolled out + /// of the window. + pub fn retain(&self, mut keep: impl FnMut(&PreviewKey) -> bool) { + let mut state = self.lock(); + state.queued.retain(|k, _| keep(k)); + for (key, (_, cancel)) in &state.running { + if !keep(key) { + cancel.cancel(); + } + } + } + + /// Whether `key` is queued or being fetched. + pub fn is_pending(&self, key: &PreviewKey) -> bool { + let state = self.lock(); + state.queued.contains_key(key) || state.is_running(key) + } + + /// Requests queued or being fetched. + pub fn pending(&self) -> usize { + let state = self.lock(); + state.queued.len() + state.running.values().filter(|(_, c)| !c.is_cancelled()).count() + } + + /// The results since the last call. + pub fn poll(&self) -> Vec { + self.rx.try_iter().collect() + } + + fn lock(&self) -> MutexGuard<'_, State> { + self.shared.state.lock().unwrap_or_else(|e| e.into_inner()) + } + + fn start(&self) { + for i in 0..self.workers { + let worker = Worker { + installer: Arc::clone(&self.installer), + fetcher: Arc::clone(&self.fetcher), + cache: self.cache.clone(), + wake: self.wake.clone(), + shared: Arc::clone(&self.shared), + tx: self.tx.clone(), + }; + // A pool short of threads still works, more slowly; with none, requests stay queued. + let _ = std::thread::Builder::new().name(format!("font-previews-{i}")).spawn(move || worker.run()); + } + } +} + +impl Drop for Previews { + fn drop(&mut self) { + let mut state = self.lock(); + state.stop = true; + state.queued.clear(); + for (_, cancel) in state.running.values() { + cancel.cancel(); + } + drop(state); + self.shared.ready.notify_all(); + } +} + +struct Worker { + installer: Arc, + fetcher: Arc, + cache: Option>, + wake: Option, + shared: Arc, + tx: Sender, +} + +impl Worker { + fn run(self) { + while let Some((key, id, cancel)) = self.next() { + let font = self.load(&key, &cancel); + let mut state = self.shared.state.lock().unwrap_or_else(|e| e.into_inner()); + if state.running.get(&key).is_some_and(|(i, _)| *i == id) { + state.running.remove(&key); + } + if cancel.is_cancelled() { + continue; + } + // Sent under the lock, so a cancel that returned has either dropped it or comes after. + let _ = self.tx.send(Preview { key, font }); + drop(state); + if let Some(wake) = &self.wake { + wake(); + } + } + } + + /// Waits for a request; `None` once the pool is dropped. + fn next(&self) -> Option<(PreviewKey, u64, Cancel)> { + let mut state = self.shared.state.lock().unwrap_or_else(|e| e.into_inner()); + loop { + if state.stop { + return None; + } + if let Some(key) = state.take_next() { + let id = state.next; + state.next += 1; + let cancel = Cancel::new(); + state.running.insert(key.clone(), (id, cancel.clone())); + return Some((key, id, cancel)); + } + state = self.shared.ready.wait(state).unwrap_or_else(|e| e.into_inner()); + } + } + + fn load(&self, key: &PreviewKey, cancel: &Cancel) -> Result, PreviewError> { + let Some(service) = self.installer.preview_service() else { return Err(PreviewError::NoService) }; + let path = key.path(); + if let Some(cache) = &self.cache + && let Some(bytes) = cache.get(&path) + { + match decode(&bytes) { + Ok(font) => return Ok(font), + Err(_) => cache.remove(&path), + } + } + if !self.installer.previews_enabled() { + return Err(PreviewError::PreviewsOff); + } + let bytes = self.fetcher.get(&key.url(&service), MAX_PREVIEW_BYTES, cancel).map_err(|e| match e { + FetchError::Failed(m) if m == "HTTP 404" => PreviewError::NotFound, + e => PreviewError::Failed(e.to_string()), + })?; + let font = decode(&bytes)?; + if let Some(cache) = &self.cache { + cache.put(&path, &bytes); + } + Ok(font) + } +} + +/// The font file inside a WOFF2 response, when it parses and has outlines. +fn decode(woff2: &[u8]) -> Result, PreviewError> { + let font = wuff::decompress_woff2(woff2).map_err(|_| PreviewError::NotAFont)?; + if is_font(&font) { Ok(font) } else { Err(PreviewError::NotAFont) } +} diff --git a/crates/font-manager/src/store.rs b/crates/font-manager/src/store.rs index ca76c2da0a..4f49aa307d 100644 --- a/crates/font-manager/src/store.rs +++ b/crates/font-manager/src/store.rs @@ -13,9 +13,9 @@ use std::sync::{Condvar, Mutex}; #[cfg(not(target_arch = "wasm32"))] use craft_font_catalog::Catalog; -pub use craft_font_store::UserSource; #[cfg(not(target_arch = "wasm32"))] use craft_font_store::{Cancel, Client, Face, FontStore, Network, PINNED_INDEX, verify_font}; +pub use craft_font_store::{LegalText, PREVIEW_SERVICE_ENV, PreviewServiceSource, UserSource}; use crate::index::{Family, Index}; @@ -147,6 +147,56 @@ pub trait Installer: Send + Sync { fn remove_user_source(&self, _url: &str) -> Result<(), StoreError> { Err(StoreError(NO_FOLDER.into())) } + + /// The preview service's base URL, if one is set: [`craft_font_store::PREVIEW_SERVICE_ENV`], else the font + /// store's `preview_service` setting, else the host's default + /// ([`SuiteStore::with_default_preview_service`]). Installs try it as a mirror first. + fn preview_service(&self) -> Option { + None + } + + /// Where [`Installer::preview_service`] comes from: the environment variable (the setting + /// can't change it), the saved setting, the host's default + /// ([`PreviewServiceSource::Default`]), or nowhere. + fn preview_service_source(&self) -> PreviewServiceSource { + PreviewServiceSource::None + } + + /// The store's HTTP client, if it has one. [`Previews`](crate::remote::Previews) fetches + /// with it, so a preview service that installs found unreachable is skipped by previews too, + /// and the reverse. + fn http_client(&self) -> Option { + None + } + + /// Whether previews may be fetched from the preview service: the user's setting, on by + /// default. + fn previews_enabled(&self) -> bool { + true + } + + /// Turns previews on or off, as the user's own action. + fn set_previews_enabled(&self, _enabled: bool) -> Result<(), StoreError> { + Err(StoreError(NO_FOLDER.into())) + } + + /// Sets or clears the preview service (https, or http for a loopback host), as the user's own + /// action. + fn set_preview_service(&self, _url: Option<&str>) -> Result<(), StoreError> { + Err(StoreError(NO_FOLDER.into())) + } + + /// The folder [`crate::remote::Previews`] caches preview subsets in; none keeps them only + /// for as long as the caller holds them. + fn preview_cache(&self) -> Option { + None + } + + /// The text of `family`'s licence or NOTICE file: the installed copy, else downloaded when + /// downloads are allowed. `None` when the family has no such file. + fn legal_text(&self, _index: &Index, _family: &Family, _which: LegalText) -> Result, StoreError> { + Err(StoreError(NO_FOLDER.into())) + } } const NO_FOLDER: &str = "there is no folder for the font store"; @@ -155,7 +205,6 @@ const NO_FOLDER: &str = "there is no folder for the font store"; /// craft-font-store's store, in the user's font store folder. pub struct SuiteStore { store: FontStore, - client: Client, } #[cfg(not(target_arch = "wasm32"))] @@ -163,7 +212,25 @@ impl SuiteStore { /// The store the catalog's environment names, rescanning `catalog` after each change. pub fn for_user(catalog: Arc) -> Option { let store = FontStore::for_user(catalog.env())?.with_catalog(catalog); - Some(SuiteStore { store, client: Client::default() }) + Some(SuiteStore { store }) + } + + /// Uses `url` as the preview service while neither [`PREVIEW_SERVICE_ENV`] nor the user's + /// setting names one; see [`FontStore::with_default_preview_service`]. Never saved. + pub fn with_default_preview_service(self, url: &str) -> SuiteStore { + SuiteStore { store: self.store.with_default_preview_service(url) } + } + + /// Uses `network` for "Allow font downloads" while the user hasn't chosen; see + /// [`FontStore::with_default_network`]. Never saved. + pub fn with_default_network(self, network: Network) -> SuiteStore { + SuiteStore { store: self.store.with_default_network(network) } + } + + /// The store's HTTP client. Clones share the preview service's down state with installs; + /// [`Previews::new`](crate::remote::Previews::new) takes it through [`Installer::http_client`]. + pub fn client(&self) -> Client { + self.store.client() } /// The store's source and name for the family holding `files`, which can differ from the @@ -222,7 +289,7 @@ impl Installer for SuiteStore { let mut reasons = Vec::new(); for url in index.file_urls(family, file) { let mut on_bytes = |n: u64| progress(Progress { done: before.saturating_add(n), total }); - match self.client.get(&url, file.size, &cancel, &mut on_bytes) { + match self.store.client().get(&url, file.size, &cancel, &mut on_bytes) { Ok(bytes) => match verify_font(file, &bytes) { Ok(()) => { out.push(Downloaded { path: file.path.clone(), bytes }); @@ -261,6 +328,38 @@ impl Installer for SuiteStore { fn remove_user_source(&self, url: &str) -> Result<(), StoreError> { self.store.remove_user_source(url).map_err(err) } + + fn preview_service(&self) -> Option { + self.store.preview_service() + } + + fn preview_service_source(&self) -> PreviewServiceSource { + self.store.preview_service_source() + } + + fn http_client(&self) -> Option { + Some(self.store.client()) + } + + fn set_preview_service(&self, url: Option<&str>) -> Result<(), StoreError> { + self.store.set_preview_service(url).map_err(err) + } + + fn preview_cache(&self) -> Option { + Some(self.store.previews_dir()) + } + + fn previews_enabled(&self) -> bool { + self.store.previews_enabled() + } + + fn set_previews_enabled(&self, enabled: bool) -> Result<(), StoreError> { + self.store.set_previews_enabled(enabled).map_err(err) + } + + fn legal_text(&self, index: &Index, family: &Family, which: LegalText) -> Result, StoreError> { + self.store.legal_text(index, family, which, &Cancel::new()).map_err(err) + } } /// The store when the system names no folder for it (no home folder): nothing installs. diff --git a/crates/font-manager/src/store/fake.rs b/crates/font-manager/src/store/fake.rs index eb7019499b..a72870ad57 100644 --- a/crates/font-manager/src/store/fake.rs +++ b/crates/font-manager/src/store/fake.rs @@ -4,6 +4,7 @@ use super::{ AtomicBool, Condvar, Downloaded, Family, HashMap, Index, Installer, Mutex, Ordering, Path, PathBuf, Progress, RemoveRequest, StoreError, UserSource, err, }; +use super::{LegalText, PreviewServiceSource}; /// What a [`FakeStore`] was asked to do. #[derive(Clone, Debug, PartialEq, Eq)] @@ -35,6 +36,8 @@ pub struct FakeStore { /// Index files user sources "download", by URL. served_indexes: HashMap>, user: Mutex>, + preview_service: Mutex>, + previews: Mutex, /// User sources downloaded so far, and those whose file changed since. fetched: Mutex>, changed: Mutex>, @@ -55,6 +58,8 @@ impl FakeStore { builtin: None, served_indexes: HashMap::new(), user: Mutex::new(Vec::new()), + preview_service: Mutex::new(None), + previews: Mutex::new(true), fetched: Mutex::new(Vec::new()), changed: Mutex::new(Vec::new()), held: (Mutex::new(false), Condvar::new()), @@ -265,4 +270,45 @@ impl Installer for FakeStore { self.user.lock().map_err(err)?.retain(|s| s.url != url); Ok(()) } + + fn preview_service(&self) -> Option { + self.preview_service.lock().ok()?.clone() + } + + fn preview_service_source(&self) -> PreviewServiceSource { + if self.preview_service().is_some() { PreviewServiceSource::Saved } else { PreviewServiceSource::None } + } + + fn previews_enabled(&self) -> bool { + self.previews.lock().map_or(true, |p| *p) + } + + fn set_previews_enabled(&self, enabled: bool) -> Result<(), StoreError> { + *self.previews.lock().map_err(err)? = enabled; + Ok(()) + } + + fn set_preview_service(&self, url: Option<&str>) -> Result<(), StoreError> { + let url = url.map(craft_font_store::check_preview_service).transpose().map_err(err)?; + *self.preview_service.lock().map_err(err)? = url; + Ok(()) + } + + fn preview_cache(&self) -> Option { + Some(self.dir.join("previews")) + } + + /// Served from the file table by the index path, like a font. + fn legal_text(&self, _: &Index, family: &Family, which: LegalText) -> Result, StoreError> { + let path = match which { + LegalText::License => family.license_file.as_ref().map(|f| f.path.as_str()).or(family.license_path.as_deref()), + LegalText::Notice => family.notice_file.as_ref().map(|f| f.path.as_str()), + }; + let Some(path) = path else { return Ok(None) }; + if !self.downloads_allowed() { + return Err(StoreError("downloading fonts is turned off".into())); + } + let bytes = self.files.get(path).ok_or_else(|| StoreError(format!("{path} isn't available")))?; + Ok(Some(String::from_utf8_lossy(bytes).into_owned())) + } } diff --git a/crates/font-manager/tests/data/Tiny-glyf.woff2 b/crates/font-manager/tests/data/Tiny-glyf.woff2 new file mode 100644 index 0000000000..f44e1433df Binary files /dev/null and b/crates/font-manager/tests/data/Tiny-glyf.woff2 differ diff --git a/crates/font-manager/tests/data/preview-vectors.json b/crates/font-manager/tests/data/preview-vectors.json new file mode 100644 index 0000000000..e9c78938d9 --- /dev/null +++ b/crates/font-manager/tests/data/preview-vectors.json @@ -0,0 +1,105 @@ +{ + "about": "Shared test vectors for font-preview-service (server, B2) and craft-font-manager's preview client (C3). Both must produce exactly these strings.", + "rules": { + "codepoints": "The codepoints of the text, minus C0 controls (< U+0020), C1 controls and DEL (U+007F-009F) and surrogates; deduplicated and sorted. Written as lowercase hex without leading zeros; a run of two or more consecutive codepoints is written first-last; items joined by commas. The empty set is the empty string. At most 256 codepoints.", + "closure": "Server only: the codepoints above, plus the NFKD decomposition of each kept character, plus U+0020, U+200C, U+200D and U+25CC. Applied before subsetting; not part of the URL." + }, + "vectors": [ + { + "text": "Whereas recognition of the inherent dignity", + "codepoints": "20,57,61,63-69,6e-6f,72-74,79", + "closure": "20,57,61,63-69,6e-6f,72-74,79,200c-200d,25cc" + }, + { + "text": "ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz", + "codepoints": "20,41-5a,61-7a", + "closure": "20,41-5a,61-7a,200c-200d,25cc" + }, + { + "text": "0123456789 & ? ! @ # % ( ) [ ] { } $ € £ ¥", + "codepoints": "20-21,23-26,28-29,30-39,3f-40,5b,5d,7b,7d,a3,a5,20ac", + "closure": "20-21,23-26,28-29,30-39,3f-40,5b,5d,7b,7d,a3,a5,200c-200d,20ac,25cc" + }, + { + "text": "aab", + "codepoints": "61-62", + "closure": "20,61-62,200c-200d,25cc" + }, + { + "text": "ab", + "codepoints": "61-62", + "closure": "20,61-62,200c-200d,25cc" + }, + { + "text": "abc", + "codepoints": "61-63", + "closure": "20,61-63,200c-200d,25cc" + }, + { + "text": "Line one\nLine two\t!", + "codepoints": "20-21,4c,65,69,6e-6f,74,77", + "closure": "20-21,4c,65,69,6e-6f,74,77,200c-200d,25cc" + }, + { + "text": "โดยที่การไม่นำพาและการหมิ่นในคุณค่าของสิทธิมนุษยชน", + "codepoints": "e01-e02,e04,e07,e0a,e13-e14,e17-e19,e1e,e21-e23,e25,e29-e2b,e2d,e30,e32-e35,e38,e41-e44,e48", + "closure": "20,e01-e02,e04,e07,e0a,e13-e14,e17-e19,e1e,e21-e23,e25,e29-e2b,e2d,e30,e32-e35,e38,e41-e44,e48,e4d,200c-200d,25cc" + }, + { + "text": "ສະບາຍດີ ນຳ", + "codepoints": "20,e8d,e94,e99-e9a,eaa,eb0,eb2-eb3,eb5", + "closure": "20,e8d,e94,e99-e9a,eaa,eb0,eb2-eb3,eb5,ecd,200c-200d,25cc" + }, + { + "text": "चूंकि मानव परिवार के सभी सदस्यों", + "codepoints": "20,902,915,91a,926,928,92a,92d-930,935,938,93e-940,942,947,94b,94d", + "closure": "20,902,915,91a,926,928,92a,92d-930,935,938,93e-940,942,947,94b,94d,200c-200d,25cc" + }, + { + "text": "لمّا كان الاعتراف بالكرامة", + "codepoints": "20,627-62a,631,639,641,643-646,651", + "closure": "20,627-62a,631,639,641,643-646,651,200c-200d,25cc" + }, + { + "text": "人類社会のすべての構成員", + "codepoints": "3059,3066,306e,3079,4eba,4f1a,54e1,6210,69cb,793e,985e", + "closure": "20,200c-200d,25cc,3059,3066,306e,3078-3079,3099,4eba,4f1a,54e1,6210,69cb,793e,985e" + }, + { + "text": "Œuvre fine ²", + "codepoints": "20,65,6e,72,75-76,b2,152,fb01", + "closure": "20,32,65-66,69,6e,72,75-76,b2,152,200c-200d,25cc,fb01" + }, + { + "text": "😀 👍🏽", + "codepoints": "20,1f3fd,1f44d,1f600", + "closure": "20,200c-200d,25cc,1f3fd,1f44d,1f600" + }, + { + "text": "", + "codepoints": "", + "closure": "20,200c-200d,25cc" + } + ], + "sample_hash": { + "rule": "The {h} of /v1/faces/{sha256}/{inst}/sample-{h}.woff2: the first 12 lowercase hex characters of the sha256 of the face's sample text exactly as the index gives it (the file's sample_text, else samples[file.sample_script ?? family.sample_script].text), as UTF-8 bytes, with no normalisation and newlines kept. The subset itself also covers the family name; h covers only the sample text. A request whose h is not the face's current one gets 404; the client then falls back to u/{codepoints}.", + "vectors": [ + { + "text": "Whereas recognition of the inherent dignity", + "h": "a79fe905fc38" + }, + { + "text": "โดยที่การไม่นำพาและการหมิ่นในคุณค่าของสิทธิมนุษยชน", + "h": "ea9257b96f35" + }, + { + "text": "𐊪𐊾𐊠𐊽𐊾𐊲𐊸𐊫𐊷𐋉𐋃𐊷𐊲𐊷𐊲𐊰𐊫𐋇𐊫𐊰𐊪𐊫𐊣\n𐊪𐊾𐊠𐊽𐊾𐊲𐊸𐊫𐊷𐋉𐋃𐊷𐊲𐊷𐊲𐊰𐊫𐋇𐊫𐊰𐊪𐊫𐊣", + "h": "259046b056a5" + }, + { + "text": "Hello", + "h": "185f8db32271" + } + ] + } +} \ No newline at end of file diff --git a/crates/font-manager/tests/remote.rs b/crates/font-manager/tests/remote.rs new file mode 100644 index 0000000000..c3633e56c4 --- /dev/null +++ b/crates/font-manager/tests/remote.rs @@ -0,0 +1,349 @@ +//! The preview service client against the shared test vectors and a local fake service. +//! +//! `data/Tiny-glyf.woff2` is `crates/fonts-build/tests/fixture/subset/Tiny-glyf.ttf` compressed +//! with fontTools 4.67.0: `fonttools ttLib.woff2 compress -o Tiny-glyf.woff2 Tiny-glyf.ttf`. +//! `data/preview-vectors.json` is shared with the preview service, unchanged, so the client's +//! URLs and the service's cache keys can't drift. + +use std::collections::HashMap; +use std::io::{Read, Write}; +use std::net::{TcpListener, TcpStream}; +use std::path::PathBuf; +use std::sync::{Arc, Condvar, Mutex}; +use std::time::{Duration, Instant}; + +use craft_font_manager::craft_font_catalog::Os; +use craft_font_manager::remote::{Codepoints, DiskCache, Instance, MAX_CODEPOINTS, Preview, PreviewError, PreviewKey, Previews, SampleHash, Subset}; +use craft_font_manager::store::{FakeStore, Installer, SuiteStore}; +use craft_font_manager::{Catalog, FontEnv}; +use craft_font_store::{Client, is_font}; + +const WOFF2: &[u8] = include_bytes!("data/Tiny-glyf.woff2"); + +fn sha(n: u8) -> String { + format!("{n:02x}").repeat(32) +} + +fn temp(name: &str) -> PathBuf { + let dir = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("remote").join(name); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +#[test] +fn canonical_codepoints_match_the_shared_vectors() { + let vectors: serde_json::Value = serde_json::from_str(include_str!("data/preview-vectors.json")).unwrap(); + let vectors = vectors["vectors"].as_array().unwrap(); + assert!(vectors.len() > 10); + for v in vectors { + let text = v["text"].as_str().unwrap(); + let expected = v["codepoints"].as_str().unwrap(); + let codepoints = Codepoints::from_text(text); + assert_eq!(codepoints.encode(), expected, "{text:?}"); + let key = PreviewKey::new(&sha(0xab), Instance::List, Subset::Codepoints(codepoints)); + match key { + Some(key) => assert_eq!(key.path(), format!("v1/faces/{}/list/u/{expected}.woff2", sha(0xab))), + None => assert_eq!(expected, "", "only the empty set has no URL"), + } + } +} + +#[test] +fn subset_urls() { + let key = |inst, subset| PreviewKey::new(&sha(0x0a), inst, subset).map(|k| k.url("https://fonts.example.com/")); + let base = format!("https://fonts.example.com/v1/faces/{}", sha(0x0a)); + assert_eq!(key(Instance::List, Subset::Sample(SampleHash::of("Hello"))), Some(format!("{base}/list/sample-185f8db32271.woff2"))); + assert_eq!(key(Instance::List, Subset::Ascii), Some(format!("{base}/list/ascii.woff2"))); + assert_eq!(key(Instance::Var, Subset::Sample(SampleHash::of("Hello"))), Some(format!("{base}/var/sample-185f8db32271.woff2"))); + assert_eq!(key(Instance::Var, Subset::Codepoints(Codepoints::from_text("ab"))), Some(format!("{base}/var/u/61-62.woff2"))); + + let upper = PreviewKey::new(&"AB".repeat(32), Instance::List, Subset::Sample(SampleHash::of("Hello"))).unwrap(); + assert_eq!(upper.sha256(), "ab".repeat(32)); + assert!(PreviewKey::new("../../etc", Instance::List, Subset::Sample(SampleHash::of("Hello"))).is_none()); + assert!(PreviewKey::new(&"g".repeat(64), Instance::List, Subset::Sample(SampleHash::of("Hello"))).is_none()); + let many: Codepoints = ('\u{4e00}'..).take(MAX_CODEPOINTS + 1).collect(); + assert!(PreviewKey::new(&sha(1), Instance::List, Subset::Codepoints(many.clone())).is_none()); + let mut fits = many; + fits.retain(|c| c != '\u{4e00}'); + assert!(PreviewKey::new(&sha(1), Instance::List, Subset::Codepoints(fits)).is_some()); +} + +#[test] +fn disk_cache_drops_the_least_recently_used() { + let dir = temp("cache"); + let cache = DiskCache::new(&dir, 300); + let bytes = |b: u8| vec![b; 100]; + cache.put("a", &bytes(1)); + cache.put("b", &bytes(2)); + cache.put("c", &bytes(3)); + assert_eq!(cache.get("a"), Some(bytes(1))); + cache.put("d", &bytes(4)); + assert!(!cache.contains("b"), "b was used least recently"); + assert!(cache.contains("a") && cache.contains("c") && cache.contains("d")); + assert_eq!(cache.size(), 300); + assert_eq!(cache.get("b"), None); + + // Larger than the whole cache: not kept, and nothing else goes for it. + cache.put("e", &vec![5; 301]); + assert!(!cache.contains("e") && cache.contains("a")); + + // Another session reads the same entries, and a smaller limit trims them at once. + std::fs::write(dir.join(".tmp-1-1"), b"half").unwrap(); + let files = || std::fs::read_dir(&dir).unwrap().filter(|e| e.as_ref().unwrap().file_name().to_string_lossy().ends_with(".woff2")).count(); + assert_eq!(files(), 3); + let again = DiskCache::new(&dir, 300); + assert_eq!(again.size(), 300); + assert_eq!(again.get("d"), Some(bytes(4))); + let smaller = DiskCache::new(&dir, 200); + assert_eq!(smaller.size(), 200); + assert_eq!(files(), 2); + // A file another session cached after this one read the folder. + smaller.put("f", &bytes(6)); + assert!(again.contains("f")); + let _ = std::fs::remove_dir_all(dir); +} + +/// What the fake service answers for a path. +#[derive(Clone)] +enum Reply { + Ok(Vec), + /// Waits for [`Service::release`], then answers with the fixture. + Held, +} + +/// A local HTTP server standing in for the preview service. +struct Service { + base: String, + routes: Arc>>, + log: Arc>>, + gate: Arc<(Mutex, Condvar)>, +} + +impl Service { + fn start() -> Service { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let base = format!("http://{}", listener.local_addr().unwrap()); + let service = Service { base, routes: Arc::default(), log: Arc::default(), gate: Arc::default() }; + let (routes, log, gate) = (service.routes.clone(), service.log.clone(), service.gate.clone()); + std::thread::spawn(move || { + for stream in listener.incoming() { + let Ok(stream) = stream else { continue }; + let (routes, log, gate) = (routes.clone(), log.clone(), gate.clone()); + std::thread::spawn(move || answer(stream, &routes, &log, &gate)); + } + }); + service + } + + fn serve(&self, key: &PreviewKey, reply: Reply) { + self.routes.lock().unwrap().insert(format!("/{}", key.path()), reply); + } + + fn requests(&self) -> Vec { + self.log.lock().unwrap().clone() + } + + fn release(&self) { + *self.gate.0.lock().unwrap() = true; + self.gate.1.notify_all(); + } +} + +fn answer(mut s: TcpStream, routes: &Mutex>, log: &Mutex>, gate: &(Mutex, Condvar)) { + let mut head = Vec::new(); + let mut b = [0u8; 1]; + while !head.ends_with(b"\r\n\r\n") { + match s.read(&mut b) { + Ok(1) => head.push(b[0]), + _ => return, + } + } + let path = String::from_utf8_lossy(&head).split_whitespace().nth(1).unwrap_or("/").to_string(); + log.lock().unwrap().push(path.clone()); + let reply = routes.lock().unwrap().get(&path).cloned(); + let body = match reply { + Some(Reply::Ok(body)) => body, + Some(Reply::Held) => { + let mut open = gate.0.lock().unwrap(); + while !*open { + open = gate.1.wait(open).unwrap(); + } + WOFF2.to_vec() + } + None => { + let _ = write!(s, "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"); + return; + } + }; + let _ = write!(s, "HTTP/1.1 200 OK\r\nContent-Type: font/woff2\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len()); + let _ = s.write_all(&body); +} + +/// The results until `n` have come, or two seconds. +fn wait_for(previews: &Previews, n: usize) -> Vec { + let deadline = Instant::now() + Duration::from_secs(2); + let mut out = Vec::new(); + while out.len() < n && Instant::now() < deadline { + out.extend(previews.poll()); + std::thread::sleep(Duration::from_millis(5)); + } + out +} + +fn wait_until(mut done: impl FnMut() -> bool) { + let deadline = Instant::now() + Duration::from_secs(2); + while !done() && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(5)); + } +} + +#[test] +fn previews_come_from_the_service_then_the_cache_and_only_with_consent() { + let service = Service::start(); + let dir = temp("service"); + let store = Arc::new(FakeStore::new(&dir, HashMap::new())); + let sample = PreviewKey::new(&sha(1), Instance::List, Subset::Sample(SampleHash::of("Hello"))).unwrap(); + let broken = PreviewKey::new(&sha(2), Instance::List, Subset::Sample(SampleHash::of("Hello"))).unwrap(); + service.serve(&sample, Reply::Ok(WOFF2.to_vec())); + service.serve(&broken, Reply::Ok(b"wOF2 but not really".to_vec())); + let previews = Previews::new(store.clone()); + + // No service: nothing happens. + assert!(!previews.available()); + previews.request(sample.clone(), 1); + let got = wait_for(&previews, 1); + assert_eq!(got.first().map(|p| p.font.clone().unwrap_err()), Some(PreviewError::NoService)); + + // A service, but previews off: no request. + store.set_preview_service(Some(&service.base)).unwrap(); + store.set_previews_enabled(false).unwrap(); + assert!(!previews.available()); + previews.request(sample.clone(), 1); + let got = wait_for(&previews, 1); + assert_eq!(got.first().map(|p| p.font.clone().unwrap_err()), Some(PreviewError::PreviewsOff)); + assert!(service.requests().is_empty()); + + // Previews on (the default), installs not allowed: decoded, checked and cached anyway. + store.set_previews_enabled(true).unwrap(); + assert!(previews.available() && !store.downloads_allowed()); + previews.request(sample.clone(), 1); + previews.request(broken.clone(), 1); + let got = wait_for(&previews, 2); + let font = |key: &PreviewKey| got.iter().find(|p| &p.key == key).map(|p| p.font.clone()); + assert!(font(&sample).unwrap().is_ok_and(|f| is_font(&f))); + assert_eq!(font(&broken), Some(Err(PreviewError::NotAFont))); + assert_eq!(service.requests().len(), 2); + let cache = previews.cache().unwrap(); + assert!(cache.dir().starts_with(&dir) && cache.contains(&sample.path()) && !cache.contains(&broken.path())); + + // A new session reads the disk cache, even with previews off. + store.set_previews_enabled(false).unwrap(); + let later = Previews::new(store.clone()); + later.request(sample.clone(), 1); + assert!(wait_for(&later, 1).first().is_some_and(|p| p.font.as_ref().is_ok_and(|f| is_font(f)))); + assert_eq!(service.requests().len(), 2); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn the_suite_store_and_its_previews_share_the_service_down_state() { + let root = temp("suite"); + let env = FontEnv { os: Os::Unix, root: root.clone(), font_store: Some(root.join("store")), ..FontEnv::default() }; + let store = SuiteStore::for_user(Arc::new(Catalog::new(env).with_font_service(false))).unwrap(); + let client = store.http_client().unwrap(); + let svc = "https://fonts.example.com"; + assert!(!client.service_is_down(svc) && !store.client().service_is_down(svc)); + client.mark_service_down(svc); + assert!(store.client().service_is_down(svc)); + // The pool's client has its own timeouts and the same down state. + let pool_client = client.with_timeouts(craft_font_store::Timeouts::default()); + assert!(pool_client.service_is_down(svc)); + let _ = std::fs::remove_dir_all(root); +} + +#[test] +fn a_service_marked_down_gets_no_requests() { + let service = Service::start(); + let dir = temp("down"); + let store = Arc::new(FakeStore::new(&dir, HashMap::new())); + store.set_preview_service(Some(&service.base)).unwrap(); + store.allow_downloads(true).unwrap(); + let key = PreviewKey::new(&sha(1), Instance::List, Subset::Sample(SampleHash::of("Hello"))).unwrap(); + service.serve(&key, Reply::Ok(WOFF2.to_vec())); + // The client is shared with, say, the store's installs, which found the service unreachable. + let client = Client::default(); + client.mark_service_down(&service.base); + let previews = Previews::new(store.clone()).with_fetcher(Arc::new(client)); + previews.request(key, 1); + let got = wait_for(&previews, 1); + assert!(matches!(got.first().map(|p| p.font.clone()), Some(Err(PreviewError::Failed(_))))); + assert!(service.requests().is_empty()); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn highest_priority_first_and_cancelled_requests_deliver_nothing() { + let service = Service::start(); + let dir = temp("cancel"); + let store = Arc::new(FakeStore::new(&dir, HashMap::new())); + store.allow_downloads(true).unwrap(); + store.set_preview_service(Some(&service.base)).unwrap(); + let keys: Vec = (1..=4).map(|n| PreviewKey::new(&sha(n), Instance::List, Subset::Sample(SampleHash::of("Hello"))).unwrap()).collect(); + let [held, low, high, dropped] = [&keys[0], &keys[1], &keys[2], &keys[3]]; + service.serve(held, Reply::Held); + for key in [low, high, dropped] { + service.serve(key, Reply::Ok(WOFF2.to_vec())); + } + let previews = Previews::new(store.clone()).with_cache(None).with_workers(1); + + previews.request(held.clone(), 9); + wait_until(|| !service.requests().is_empty()); + previews.request(low.clone(), 1); + previews.request(dropped.clone(), 1); + previews.request(high.clone(), 5); + assert_eq!(previews.pending(), 4); + previews.cancel(dropped); + assert!(!previews.is_pending(dropped)); + // The running request stops while the service still sends nothing. + previews.cancel(held); + + let got = wait_for(&previews, 2); + assert_eq!(got.iter().map(|p| &p.key).collect::>(), [high, low]); + let path = |k: &PreviewKey| format!("/{}", k.path()); + assert_eq!(service.requests(), [path(held), path(high), path(low)]); + std::thread::sleep(Duration::from_millis(100)); + assert!(previews.poll().is_empty()); + assert_eq!(previews.pending(), 0); + service.release(); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn sample_hash_is_the_sha256_prefix_of_the_exact_text() { + let vectors: serde_json::Value = serde_json::from_str(include_str!("data/preview-vectors.json")).unwrap(); + let vectors = vectors["sample_hash"]["vectors"].as_array().unwrap(); + assert!(vectors.len() >= 4); + for v in vectors { + let text = v["text"].as_str().unwrap(); + assert_eq!(SampleHash::of(text).as_str(), v["h"].as_str().unwrap(), "{text:?}"); + } + assert_ne!(SampleHash::of("Hello\n"), SampleHash::of("Hello")); + let a = PreviewKey::new(&sha(1), Instance::List, Subset::Sample(SampleHash::of("a"))).unwrap(); + let b = PreviewKey::new(&sha(1), Instance::List, Subset::Sample(SampleHash::of("b"))).unwrap(); + assert_ne!(a.path(), b.path(), "the disk cache key names the text"); +} + +#[test] +fn a_404_comes_back_as_not_found() { + let service = Service::start(); + let dir = temp("notfound"); + let store = Arc::new(FakeStore::new(&dir, HashMap::new())); + store.set_preview_service(Some(&service.base)).unwrap(); + let key = PreviewKey::new(&sha(1), Instance::List, Subset::Sample(SampleHash::of("Hello"))).unwrap(); + let previews = Previews::new(store.clone()); + previews.request(key, 1); + let got = wait_for(&previews, 1); + assert_eq!(got.first().map(|p| p.font.clone().unwrap_err()), Some(PreviewError::NotFound)); + let _ = std::fs::remove_dir_all(dir); +} diff --git a/crates/font-store/README.md b/crates/font-store/README.md index d54b0a9232..c0e4aed347 100644 --- a/crates/font-store/README.md +++ b/crates/font-store/README.md @@ -25,10 +25,13 @@ A source the user adds is an index file at an https URL (`.json` or `.json.gz`). | Rule | How | |---|---| -| Off until the user turns it on | `FontStore::network()` is `Network::Off` until `enable_network()`. The setting is `settings.json` in the store folder, so it holds for every app. | +| Off until the user turns it on | `FontStore::network()` is `Network::Off` until `enable_network()`. The setting is `settings.json` in the store folder, so it holds for every app. A host may give its own default for a user who hasn't chosen (`FontStore::with_default_network`); it is never saved, and the user's `enable_network()` or `disable_network()` beats it. A `settings.json` that exists but can't be read, is too large or doesn't parse reads as `Network::Off`, whatever the host's default, and the next saved setting starts from that. | | Only the user turns it on | `FontStore::for_user` is for the app's own interface; call `enable_network()` from a setting or from the user's Install click. `FontStore::for_agent` (MCP, CLI, scripting) gets `Error::NotAllowed`. An agent can install while the user has the network on. | | No requests at startup | Nothing in the crate makes a request on its own. Only `fetch_indexes` and the installs do, and they return `Error::NetworkOff` without one while the network is off. | -| One HTTP client | `Client`: ureq with rustls and the webpki roots, HTTPS only, no cookies, `User-Agent: craft-font-store/`. Timeouts: 15 s to connect, 30 s to the response headers, 10 minutes per file. | +| Optional preview service | Off unless set: craft-libs has no default address. `CRAFT_FONT_PREVIEW_URL`, else the `preview_service` field of `settings.json` (`FontStore::set_preview_service`, user only, `Error::NotAllowed` for an agent), else the host's default (`FontStore::with_default_preview_service`), which is never saved, so clearing the setting brings it back and other apps sharing the store don't see it. `FontStore::preview_service()` returns the one in effect and `preview_service_source()` says whether it is `Env`, `Saved`, `Default` or `None`; the variable's name is `PREVIEW_SERVICE_ENV`. A `settings.json` that exists but can't be read or parsed means no saved service and no host default. Installs and `legal_text` try the service's mirror only for curated families (the built-in sources, `Family::is_curated`), so the hashes of files from sources the user added are never sent to it. https only; http is accepted only for the addresses `127.0.0.1` and `::1`, never for a host name, which a resolver can point off the machine. A trailing slash is dropped. Example: `CRAFT_FONT_PREVIEW_URL=https://fonts.example.com`. | +| Previews setting | `previews` in `settings.json`, on by default: `FontStore::previews_enabled()`, `set_previews_enabled(bool)` (user only, `Error::NotAllowed` for an agent). The app fetches previews from a set service only while it is on; installs ignore it. | +| Mirror first | With a service set, an install requests `/v1/files/` for each font file and `/v1/licences/` for a licence (when the index gives its sha256) before the index's URLs. The size and sha256 checks are the same, and a response that fails them moves on to the next URL. | +| One HTTP client | `Client`: ureq with rustls and the webpki roots, HTTPS only (plain http only to `127.0.0.1` or `::1`, following no redirects, for a preview service run locally), no cookies, `User-Agent: craft-font-store/`. Timeouts: 15 s to connect, 30 s to the response headers, 10 minutes per file. | A file's URLs come from its source's URL templates, best first. Both built-in sources use `https://cdn.jsdelivr.net/gh/{repo}@{ref}/{path}`, then `https://raw.githubusercontent.com/{repo}/{ref}/{path}`. The store tries the next URL after any failure: a network error, an HTTP error (jsDelivr answers 403 for files over 20 MB, such as the Noto Serif CJK fonts), or bytes that don't verify. @@ -52,6 +55,10 @@ Reading checks every entry: the version (a major version other than 1 is refused | `index.sources()`, `index.source_of(family)` | Each source's name, homepage, curated flag, commit, and families left out with why. | | `family.source`, `family.is_curated()` | The family's source ID, and whether that source is curated. | | `index.file_urls(family, file)`, `index.license_urls(family)` | The URLs to try, best first. | +| `family.tags`, `family.copyright`, `family.reserved_names`, `family.notice_file`, `family.upstream` | Format 1.2: design traits, the copyright notice, the Reserved Font Names (a client that modifies a font renames it when there are any), an Apache family's `NOTICE` file and where the family is developed. Absent in a 1.1 index: empty or `None`. | +| `file.instances`, `file.list_instance` | Format 1.2: a variable font's named instances, and the position of the one a font list shows (`None`: the default instance). | +| `index.samples()`, `index.sample(script)` | Format 1.2: the default preview text of each script. When sources have one for the same script, the first source's wins. | +| `index.sample_text(family, file)` | The file's preview text: its own `sample_text`, else the sample of its `sample_script`, else of the family's `sample_script`. | ## Exact matches only @@ -93,6 +100,7 @@ When every file has passed, the store takes `.lock`, moves the files into the fa settings.json the network setting and the sources the user added manifest.json what is installed indexes/ the last indexes fetched: sources.json, .json.gz, user- +previews/ preview subsets (WOFF2) craft-font-manager caches, at most 50 MB / the font files and the licence language-packs/ installed Language packs, one folder per locale language-packs.json which Language packs are installed diff --git a/crates/font-store/index/indexes/google-fonts.json.gz b/crates/font-store/index/indexes/google-fonts.json.gz index 9d4b924065..f4989d4e3f 100644 Binary files a/crates/font-store/index/indexes/google-fonts.json.gz and b/crates/font-store/index/indexes/google-fonts.json.gz differ diff --git a/crates/font-store/index/indexes/noto.json.gz b/crates/font-store/index/indexes/noto.json.gz index bb40f47542..3a3d3c23b4 100644 Binary files a/crates/font-store/index/indexes/noto.json.gz and b/crates/font-store/index/indexes/noto.json.gz differ diff --git a/crates/font-store/index/sources.json b/crates/font-store/index/sources.json index e124d132d4..fa9ed6aa36 100644 --- a/crates/font-store/index/sources.json +++ b/crates/font-store/index/sources.json @@ -1,4 +1,4 @@ -{"schema":1,"version":"1.1","indexes":[ -{"source":"google/fonts","name":"Google Fonts","curated":true,"path":"indexes/google-fonts.json","size":4724581,"sha256":"72ea418e43785d572e73350ad08e9e6601a5a12f93315805f92bd3e092618a63","gz_path":"indexes/google-fonts.json.gz","gz_size":596893,"gz_sha256":"62d1d5645417a691e4710f6d1b895f925284ea9c804de268a97432bd67e9c1f6","commit":"45e3d5269e4a17d823f6d84470bc084dc5ae46f6","families":2040,"files":3781}, -{"source":"notofonts","name":"Noto","curated":true,"path":"indexes/noto.json","size":117706,"sha256":"8243d697c407776ec4fb19fa892c089279a4a528eb4e04cd970ac6ec14ce142a","gz_path":"indexes/noto.json.gz","gz_size":18192,"gz_sha256":"0d467fb79bcd3afe10350ed3caba2ff57af02aedbc413292e06bc78c02994999","commit":"93fac8abebe6c7fed0c5b7d2456d8fa484fa146c","families":30,"files":130} +{"schema":1,"version":"1.2","indexes":[ +{"source":"google/fonts","name":"Google Fonts","curated":true,"path":"indexes/google-fonts.json","size":5672345,"sha256":"89ec33d9c7644963f24c9d749787af85c347b94c3586a5f3a5bd22fe6ae6f8eb","gz_path":"indexes/google-fonts.json.gz","gz_size":721528,"gz_sha256":"85e0678cd48f381e858e6728fd93d865e0f502caa12cec4354e954a27bec82f2","commit":"45e3d5269e4a17d823f6d84470bc084dc5ae46f6","families":2040,"files":3781}, +{"source":"notofonts","name":"Noto","curated":true,"path":"indexes/noto.json","size":123691,"sha256":"3c9a615d287f9a4e5a745ce94748dd10dbbcf4eb75370e98456e47534629da55","gz_path":"indexes/noto.json.gz","gz_size":19722,"gz_sha256":"0ffe5e43faa4a3d8218faf3bb97145493760ec74c5779f973f0812fd98b05fcb","commit":"93fac8abebe6c7fed0c5b7d2456d8fa484fa146c","families":30,"files":130} ]} diff --git a/crates/font-store/src/http.rs b/crates/font-store/src/http.rs index 3c6d007bde..f264dac2c0 100644 --- a/crates/font-store/src/http.rs +++ b/crates/font-store/src/http.rs @@ -1,11 +1,13 @@ //! The one HTTP client: blocking HTTPS GET through ureq with rustls, timeouts, a size cap, -//! progress and cancellation. +//! progress and cancellation. Plain http only to a loopback host, and only when the caller opts +//! in for a preview service run locally. +use std::collections::HashMap; use std::io::Read; -use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::mpsc::{self, RecvTimeoutError}; -use std::time::Duration; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; /// Cancels a download from another thread. Clones share the flag. #[derive(Clone, Debug, Default)] @@ -47,6 +49,14 @@ impl Default for Timeouts { } } +impl FetchError { + /// Whether the server couldn't be reached or didn't answer in time, as opposed to answering + /// with an HTTP status or too much data. + pub fn is_network(&self) -> bool { + matches!(self, FetchError::Failed(m) if !m.starts_with("HTTP ")) + } +} + /// Why a request failed. #[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)] pub enum FetchError { @@ -64,13 +74,34 @@ pub enum FetchError { Failed(String), } +/// How long a preview service that failed on the network is skipped. +pub const SERVICE_BACKOFF: Duration = Duration::from_secs(60); + +/// `scheme://host:port` of `url`, lowercased. +fn service_origin(url: &str) -> String { + let (scheme, rest) = url.split_once("://").unwrap_or(("", url)); + let authority = rest.split(['/', '?', '#']).next().unwrap_or_default(); + format!("{}://{}", scheme.to_ascii_lowercase(), authority.to_ascii_lowercase()) +} + +fn now_millis() -> u64 { + SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_millis() as u64) +} + /// The User-Agent every request sends: the crate and its version, nothing about the user. pub const USER_AGENT: &str = concat!("craft-font-store/", env!("CARGO_PKG_VERSION")); -/// The HTTP client. HTTPS only; no cookies, no credentials. +/// The HTTP client. HTTPS only, except [`Client::get_from_service`], which also speaks plain +/// http to `127.0.0.1` or `::1`; no cookies, no credentials. #[derive(Clone)] pub struct Client { agent: ureq::Agent, + /// For `http://` to a loopback host. It follows no redirects, so it never leaves the machine. + loopback: ureq::Agent, + /// The origins of preview services that failed on the network, each with when it may be + /// tried again. Clones share it. + service_down: Arc>>, + https_only: bool, /// URL prefixes the tests serve from a local server. #[cfg(test)] pub(crate) rewrite: Vec<(String, String)>, @@ -95,17 +126,26 @@ impl Client { } fn build(t: Timeouts, https_only: bool) -> Self { - let config = ureq::Agent::config_builder() - .https_only(https_only) - .user_agent(USER_AGENT) - .timeout_connect(Some(t.connect)) - .timeout_recv_response(Some(t.response)) - .timeout_global(Some(t.overall)) - .max_redirects(3) - .http_status_as_error(true) - .build(); + let agent = |https_only: bool, redirects: u32| { + let builder = ureq::Agent::config_builder(); + // A loopback request never goes through an environment proxy. + let builder = if https_only || redirects > 0 { builder } else { builder.proxy(None) }; + let config = builder + .https_only(https_only) + .user_agent(USER_AGENT) + .timeout_connect(Some(t.connect)) + .timeout_recv_response(Some(t.response)) + .timeout_global(Some(t.overall)) + .max_redirects(redirects) + .http_status_as_error(true) + .build(); + ureq::Agent::new_with_config(config) + }; Self { - agent: ureq::Agent::new_with_config(config), + agent: agent(https_only, 3), + loopback: agent(false, 0), + service_down: Arc::new(Mutex::new(HashMap::new())), + https_only, #[cfg(test)] rewrite: Vec::new(), } @@ -117,6 +157,18 @@ impl Client { Self::build(t, false) } + /// A client with other timeouts that shares this one's preview-service down state, so a + /// pool with short timeouts (previews) and the installs agree on which service is down. + pub fn with_timeouts(&self, timeouts: Timeouts) -> Client { + let fresh = Self::build(timeouts, self.https_only); + Client { + service_down: Arc::clone(&self.service_down), + #[cfg(test)] + rewrite: self.rewrite.clone(), + ..fresh + } + } + /// Plain `http://` to a local test server, with `https://` prefixes mapped onto it. #[cfg(test)] pub(crate) fn for_tests(t: Timeouts, rewrite: Vec<(String, String)>) -> Self { @@ -136,12 +188,52 @@ impl Client { /// GETs `url`, at most `max` bytes, calling `on_bytes` with the bytes read so far. The /// request runs on a helper thread, so `cancel` stops it even while the server sends nothing. pub fn get(&self, url: &str, max: u64, cancel: &Cancel, on_bytes: &mut dyn FnMut(u64)) -> Result, FetchError> { + self.request(url, max, cancel, on_bytes, false) + } + + /// [`Client::get`] for a URL built from the validated preview-service setting: plain `http://` + /// to a loopback host is allowed, without following redirects. Never call it with a URL from + /// an index or a user source. + /// + /// After a network failure (no connection, a timeout; not an HTTP status) that service (its + /// scheme, host and port) counts as down for [`SERVICE_BACKOFF`]: calls in that time fail at once, so a service that is off + /// doesn't make every request wait out the timeouts. Clones of the client share this. + pub fn get_from_service(&self, url: &str, max: u64, cancel: &Cancel, on_bytes: &mut dyn FnMut(u64)) -> Result, FetchError> { + if self.service_is_down(url) { + return Err(FetchError::Failed("the preview service is down".into())); + } + let got = self.request(url, max, cancel, on_bytes, true); + if got.as_ref().is_err_and(FetchError::is_network) { + self.mark_service_down(url); + } + got + } + + /// Whether a network failure of the preview service at `service` (its URL or any URL on it) + /// is recent enough to skip it. Another service is not down. + pub fn service_is_down(&self, service: &str) -> bool { + let down = self.service_down.lock().unwrap_or_else(|e| e.into_inner()); + down.get(&service_origin(service)).is_some_and(|until| now_millis() < *until) + } + + /// Marks the preview service at `service` as down for [`SERVICE_BACKOFF`]. + pub fn mark_service_down(&self, service: &str) { + let until = now_millis() + SERVICE_BACKOFF.as_millis() as u64; + let mut down = self.service_down.lock().unwrap_or_else(|e| e.into_inner()); + let now = now_millis(); + down.retain(|_, until| now < *until); + down.insert(service_origin(service), until); + } + + fn request(&self, url: &str, max: u64, cancel: &Cancel, on_bytes: &mut dyn FnMut(u64), allow_loopback_http: bool) -> Result, FetchError> { if cancel.is_cancelled() { return Err(FetchError::Cancelled); } let stop = Arc::new(AtomicBool::new(false)); let (tx, rx) = mpsc::channel(); - let (agent, url, flag) = (self.agent.clone(), self.url(url), Arc::clone(&stop)); + let url = self.url(url); + let agent = if allow_loopback_http && is_loopback_http(&url) { self.loopback.clone() } else { self.agent.clone() }; + let flag = Arc::clone(&stop); std::thread::Builder::new() .name("font-store-fetch".into()) .spawn(move || { @@ -168,6 +260,20 @@ impl Client { } } +/// Whether `url` is `http://` to `127.0.0.1` or `[::1]`. +pub(crate) fn is_loopback_http(url: &str) -> bool { + let Some(rest) = url.get(..7).filter(|s| s.eq_ignore_ascii_case("http://")).and_then(|_| url.get(7..)) else { return false }; + let authority = rest.split(['/', '?', '#']).next().unwrap_or_default(); + if authority.contains('@') { + return false; + } + let host = match authority.strip_prefix('[') { + Some(v6) => v6.split(']').next().unwrap_or_default(), + None => authority.split(':').next().unwrap_or_default(), + }; + matches!(host.to_ascii_lowercase().as_str(), "127.0.0.1" | "::1") +} + enum Msg { Bytes(u64), Done(Result, FetchError>), diff --git a/crates/font-store/src/index.rs b/crates/font-store/src/index.rs index 5a082d26f1..07bea9fd7d 100644 --- a/crates/font-store/src/index.rs +++ b/crates/font-store/src/index.rs @@ -76,6 +76,29 @@ pub struct Script { pub name: String, } +/// A script's default preview text. +#[derive(Clone, Debug, PartialEq, Deserialize)] +pub struct Sample { + /// The text: a sentence for `udhr`, the poem for `iroha`, characters for `exemplar`. + pub text: String, + /// Where it comes from: `udhr`, `iroha` or `exemplar`. + #[serde(default)] + pub method: String, + /// The gflanguages ID of the text's language. + #[serde(default)] + pub language: String, +} + +/// A named instance of a variable font. +#[derive(Clone, Debug, PartialEq, Deserialize)] +pub struct Instance { + /// The instance's subfamily name (`Bold`). + pub name: String, + /// The user coordinate of each axis, by axis tag. + #[serde(default)] + pub coordinates: BTreeMap, +} + /// A variation axis of a font file. #[derive(Clone, Debug, PartialEq, Deserialize)] pub struct Axis { @@ -110,6 +133,19 @@ pub struct FontFile { /// PostScript names: the face's and, for a variable font, each named instance's. #[serde(default)] pub postscript: Vec, + /// Format 1.2: a variable font's named instances, in font order; empty for a static font. + #[serde(default)] + pub instances: Vec, + /// Format 1.2: the instance a font list shows, as a position in `instances`; none when the + /// list shows the default instance. + #[serde(default)] + pub list_instance: Option, + /// Format 1.2: the file's own preview script, when not the family's `sample_script`. + #[serde(default)] + pub sample_script: Option, + /// Format 1.2: the file's own preview text, when no script sample fits it. + #[serde(default)] + pub sample_text: Option, /// The repository holding the file, when not the family's. #[serde(default)] pub repo: Option, @@ -216,6 +252,25 @@ pub struct Family { /// The licence file, with its size and sha256. #[serde(default)] pub license_file: Option, + /// Format 1.2: design traits, sorted, from the index's tag vocabulary. + #[serde(default)] + pub tags: Vec, + /// Format 1.2: the script whose sample previews the family. + #[serde(default)] + pub sample_script: Option, + /// Format 1.2: the copyright notice. + #[serde(default)] + pub copyright: Option, + /// Format 1.2: the Reserved Font Names the OFL notice declares. A client that modifies a font + /// must rename it when this isn't empty. + #[serde(default)] + pub reserved_names: Vec, + /// Format 1.2: an Apache family's `NOTICE` file, located like the licence file. + #[serde(default)] + pub notice_file: Option, + /// Format 1.2: where the family is developed. + #[serde(default)] + pub upstream: Option, /// The repository holding the files, when not the source's. #[serde(default)] pub repo: Option, @@ -399,7 +454,7 @@ pub struct SourceProblem { pub error: String, } -pub(crate) type Part = (FontSource, Vec, Vec