From 65ce3263165b60b88a107df812ebeb74ecf3bf09 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 18 Nov 2026 16:15:24 -0500 Subject: [PATCH] pdf-shell-w10: net change of 3 commits - pdf-shell-w10: written from its sheet - pdf-shell-w10: repair 1 - pdf-shell-w10: review fixes (review-1) --- crates/ui-egui/src/bidi.rs | 275 +------ crates/ui-egui/src/fonts.rs | 176 +++++ crates/ui-egui/src/i18n.rs | 41 +- crates/ui-egui/src/platform/motion.rs | 346 --------- crates/ui-egui/src/platform/motion/tests.rs | 449 ----------- crates/ui-egui/src/platform/system_fonts.rs | 729 ------------------ .../src/platform/system_fonts/fontconfig.rs | 329 -------- crates/ui-egui/src/platform/ui_scale.rs | 53 +- crates/ui-egui/src/theme.rs | 542 ------------- crates/ui-egui/src/theme/tests.rs | 303 -------- 10 files changed, 206 insertions(+), 3037 deletions(-) create mode 100644 crates/ui-egui/src/fonts.rs delete mode 100644 crates/ui-egui/src/platform/motion.rs delete mode 100644 crates/ui-egui/src/platform/motion/tests.rs delete mode 100644 crates/ui-egui/src/platform/system_fonts.rs delete mode 100644 crates/ui-egui/src/platform/system_fonts/fontconfig.rs delete mode 100644 crates/ui-egui/src/theme.rs delete mode 100644 crates/ui-egui/src/theme/tests.rs diff --git a/crates/ui-egui/src/bidi.rs b/crates/ui-egui/src/bidi.rs index e08c6b9df1..c2df4be3eb 100644 --- a/crates/ui-egui/src/bidi.rs +++ b/crates/ui-egui/src/bidi.rs @@ -1,83 +1,12 @@ -//! Wrapping right-to-left text into logical lines, and test-only display-order helpers. +//! Wrapping right-to-left text into logical lines. //! //! egui 0.37's epaint shapes text with the Unicode bidirectional algorithm (UAX #9), so //! production code passes it logical (typing-order) text: [`wrap`] breaks a comment into logical -//! lines and lets epaint reorder each one. [`visual`], [`visual_auto`] and [`display_rtl`] are -//! kept for the tests that prove the old preordering is gone; they must not be used for painting -//! with egui 0.37, where they would reverse mixed-direction text a second time. +//! lines and lets epaint reorder each one. -#[cfg(test)] -use std::borrow::Cow; use std::ops::Range; use unicode_bidi::BidiInfo; -#[cfg(test)] -use unicode_bidi::{Level, ParagraphInfo}; - -/// `text` rearranged for an egui call that lays out one line. Text without right-to-left -/// characters comes back borrowed and unchanged. -/// -/// The base direction is left to right, as the interface is: a file name keeps its extension -/// at the end, the way the window title shows it. Use it for painting only; accessibility -/// labels and anything stored keep the logical text. -#[cfg(test)] -pub fn visual(text: &str) -> Cow<'_, str> { - if !text.chars().any(is_rtl_script) { - return Cow::Borrowed(text); - } - let mut out = String::with_capacity(text.len()); - push_visual(&mut out, text, Level::ltr()); - Cow::Owned(out) -} - -/// `text` in display order for the paragraph direction `base`, appended to `out`. -#[cfg(test)] -fn push_visual(out: &mut String, text: &str, base: Level) { - let info = BidiInfo::new(text, Some(base)); - for para in &info.paragraphs { - push_line(out, text, &info, para, para.range.clone()); - } -} - -/// The `line` of paragraph `para` (a non-empty byte range of `text`) in display order, as egui -/// needs it, appended to `out`. -#[cfg(test)] -fn push_line(out: &mut String, text: &str, info: &BidiInfo<'_>, para: &ParagraphInfo, line: Range) { - let (levels, runs) = info.visual_runs(para, line); - // First the true display order, every character left to right as it appears on screen. - let mut shown = String::with_capacity(text.len()); - for run in runs { - let rtl = levels.get(run.start).is_some_and(Level::is_rtl); - // Runs lie on character boundaries; a missing slice is skipped, never a panic. - let Some(piece) = text.get(run) else { continue }; - let chars = piece.chars().filter(|c| !is_bidi_control(*c)); - if rtl { - shown.extend(chars.rev().map(mirrored)); - } else { - shown.extend(chars); - } - } - push_for_shaper(out, &shown); -} - -/// `shown` (in screen order) as egui must get it: egui hands each stretch of right-to-left -/// script to the shaper as one run, which lays it out right to left (and joins its letters), so -/// each such stretch goes back to logical order. What lies between them (spaces, punctuation, -/// Latin) is drawn by the Latin face left to right and stays as it is. The stretches include -/// Persian and Arabic-Indic digits: Arabic script to the shaper, though they read left to right. -#[cfg(test)] -fn push_for_shaper(out: &mut String, shown: &str) { - let mut stretch: Vec = Vec::new(); - for c in shown.chars() { - if is_rtl_script(c) || is_joiner(c) { - stretch.push(c); - } else { - out.extend(stretch.drain(..).rev()); - out.push(c); - } - } - out.extend(stretch.drain(..).rev()); -} /// One line of wrapped text (see [`wrap`]). #[derive(Clone, Debug, PartialEq, Eq)] @@ -88,41 +17,11 @@ pub struct Line { pub rtl: bool, } -/// Whether `text` holds any right-to-left script, so [`wrap`] or [`visual_auto`] is needed. +/// Whether `text` holds any right-to-left script, so [`wrap`] is needed. pub fn has_rtl(text: &str) -> bool { text.chars().any(is_rtl_script) } -/// The paragraph direction for translated interface text: explicitly right to left for Arabic, -/// Kurdish and Persian, and `TextDirection::Auto` otherwise. A label whose first strong character is -/// Latin or a `{placeholder}` must not fall back to a left-to-right paragraph in an RTL locale. -pub fn ui_direction() -> egui::epaint::text::TextDirection { - if crate::i18n::current().rtl() { egui::epaint::text::TextDirection::RightToLeft } else { egui::epaint::text::TextDirection::Auto } -} - -/// Lay out one line of translated interface text with the locale's explicit base direction. -pub fn layout_ui(ui: &egui::Ui, text: impl Into, font: egui::FontId, color: egui::Color32) -> std::sync::Arc { - layout_one_line(ui, text, font, color, ui_direction()) -} - -/// Lay out one line of file or path text left to right, so an Arabic file name keeps `.pdf` at -/// its visual end exactly as a Latin one does. The text stays logical for accessibility. -pub fn layout_ltr(ui: &egui::Ui, text: impl Into, font: egui::FontId, color: egui::Color32) -> std::sync::Arc { - layout_one_line(ui, text, font, color, egui::epaint::text::TextDirection::LeftToRight) -} - -fn layout_one_line( - ui: &egui::Ui, - text: impl Into, - font: egui::FontId, - color: egui::Color32, - direction: egui::epaint::text::TextDirection, -) -> std::sync::Arc { - let mut job = egui::text::LayoutJob::simple_singleline(text.into(), font, color); - job.direction = direction; - ui.painter().layout_job(job) -} - /// Multi-line text with right-to-left script (a comment in Persian, Arabic, Hebrew), broken /// into logical-order lines that `fits` accepts (it measures a line in logical order). /// @@ -149,22 +48,6 @@ pub fn wrap(text: &str, mut fits: impl FnMut(&str) -> bool) -> Vec { lines } -/// One line of `text` in display order, its direction from its first strong character (an -/// author's name). Text without right-to-left characters comes back borrowed and unchanged. -/// -/// Only the bidi unit tests use this now: interface labels keep logical text and let the egui -/// fork reorder, so no production call site preorders a label. -#[cfg(test)] -pub fn visual_auto(text: &str) -> Cow<'_, str> { - if !has_rtl(text) { - return Cow::Borrowed(text); - } - let base = BidiInfo::new(text, None).paragraphs.first().map_or(Level::ltr(), |para| para.level); - let mut out = String::with_capacity(text.len()); - push_visual(&mut out, text, base); - Cow::Owned(out) -} - /// The byte ranges of the lines `range` of `text` breaks into: as many words as `fits` accepts /// per line, a word too wide for any line split between characters. Always at least one line. fn break_lines(text: &str, range: Range, fits: &mut impl FnMut(&str) -> bool) -> Vec> { @@ -234,163 +117,11 @@ fn is_paragraph_separator(c: char) -> bool { matches!(c, '\n' | '\r' | '\u{1C}'..='\u{1E}' | '\u{85}' | '\u{2029}') } -/// A label of a right-to-left interface language, in logical order, rearranged for egui: each -/// line reads right to left, with Latin words and numbers inside it left to right. -/// -/// - `{name}` placeholders stay whole and unmirrored, so [`crate::i18n::fmt`] still fills them. -/// What it inserts is drawn left to right at that place. -/// - Spaces and separator dots at either end stay at that end: the code appends to a label on -/// its right (`"Issued by: "` + a name), as the interface is still laid out left to right. -/// - A short caption's closing colon stays on the right too, next to the widget it captions. -/// -/// Text without right-to-left characters comes back unchanged. Like [`visual`], this is for -/// painting one line; a label egui wraps breaks at the wrong end. Kept for the tests that prove -/// the old preordering is gone; production catalogs stay logical. -#[cfg(test)] -pub fn display_rtl(text: &str) -> String { - if !text.chars().any(is_rtl_script) { - return text.to_owned(); - } - let mut out = String::with_capacity(text.len()); - for (i, line) in text.split('\n').enumerate() { - if i > 0 { - out.push('\n'); - } - push_rtl_line(&mut out, line); - } - out -} - -/// The most words a caption may have for its closing colon to stay on the right. -#[cfg(test)] -const CAPTION_WORDS: usize = 3; -/// First of the private-use characters that stand for placeholders while a line is reordered. -/// They are strong left-to-right, like the names they replace. -#[cfg(test)] -const PLACEHOLDER_BASE: u32 = 0xE000; -/// Placeholders protected per line; a line with more keeps the rest as plain text. -#[cfg(test)] -const MAX_PLACEHOLDERS: usize = 64; - -#[cfg(test)] -fn push_rtl_line(out: &mut String, line: &str) { - let edge = |c: char| c.is_whitespace() || c == '·'; - let core = line.trim_start_matches(edge); - let lead = line.get(..line.len().saturating_sub(core.len())).unwrap_or_default(); - let trimmed = core.trim_end_matches(edge); - let tail = core.get(trimmed.len()..).unwrap_or_default(); - let mut core = trimmed; - let mut colon = ""; - if let Some(caption) = core.strip_suffix(':') - && caption.split_whitespace().count() <= CAPTION_WORDS - { - core = caption; - colon = ":"; - } - // A line that already uses the stand-in characters is reordered with its placeholders as text. - let reserved = core.chars().any(|c| (PLACEHOLDER_BASE..PLACEHOLDER_BASE.saturating_add(MAX_PLACEHOLDERS as u32)).contains(&u32::from(c))); - let (masked, names) = if reserved { (core.to_owned(), Vec::new()) } else { mask_placeholders(core) }; - let mut visual = String::with_capacity(masked.len()); - push_visual(&mut visual, &masked, Level::rtl()); - out.push_str(lead); - for c in visual.chars() { - let index = u32::from(c).checked_sub(PLACEHOLDER_BASE).and_then(|i| usize::try_from(i).ok()); - match index.and_then(|i| names.get(i)) { - Some(name) => out.push_str(name), - None => out.push(c), - } - } - out.push_str(colon); - out.push_str(tail); -} - -/// `text` with each `{name}` placeholder and each keyboard shortcut (`⇧⌘+`) replaced by one -/// stand-in character, and what they replaced, in order. A shortcut's symbols have no direction -/// of their own, so left alone they would be drawn in reverse. -#[cfg(test)] -fn mask_placeholders(text: &str) -> (String, Vec<&str>) { - let mut masked = String::with_capacity(text.len()); - let mut names: Vec<&str> = Vec::new(); - let mut rest = text; - while names.len() < MAX_PLACEHOLDERS - && let Some((start, end)) = next_atom(rest) - { - let (Some(before), Some(atom), Some(after)) = (rest.get(..start), rest.get(start..end), rest.get(end..)) else { break }; - // `names.len()` is below MAX_PLACEHOLDERS, so the sum is a private-use scalar. - let Some(stand_in) = u32::try_from(names.len()).ok().and_then(|i| char::from_u32(PLACEHOLDER_BASE.saturating_add(i))) else { break }; - masked.push_str(before); - masked.push(stand_in); - names.push(atom); - rest = after; - } - masked.push_str(rest); - (masked, names) -} - -/// The byte range of the first placeholder or keyboard shortcut in `text`. -#[cfg(test)] -fn next_atom(text: &str) -> Option<(usize, usize)> { - let placeholder = text.find('{').and_then(|open| { - let len = text.get(open..)?.find('}')?; - Some((open, open.saturating_add(len).saturating_add(1))) - }); - let shortcut = text.find(is_modifier_key).map(|at| { - // The shortcut is the stretch around the symbol up to a space, a bracket or script text. - let outside = |c: char| c.is_whitespace() || is_rtl_script(c) || matches!(c, '(' | ')' | '[' | ']' | '{' | '}'); - let start = text - .get(..at) - .and_then(|before| before.rfind(outside).and_then(|i| before.get(i..)?.chars().next().map(|c| i.saturating_add(c.len_utf8())))) - .unwrap_or(0); - let end = text.get(at..).and_then(|after| after.find(outside)).map_or(text.len(), |i| at.saturating_add(i)); - (start, end) - }); - match (placeholder, shortcut) { - (Some(p), Some(s)) => Some(if s.0 < p.0 { s } else { p }), - (p, s) => p.or(s), - } -} - -/// The modifier-key symbols of keyboard shortcuts: ⌘ ⇧ ⌥ ⌃. -#[cfg(test)] -fn is_modifier_key(c: char) -> bool { - matches!(c, '\u{2318}' | '\u{21E7}' | '\u{2325}' | '\u{2303}') -} - /// Characters of the right-to-left scripts' blocks: letters, marks and the scripts' own /// punctuation, all drawn by the script's face. fn is_rtl_script(c: char) -> bool { matches!(u32::from(c), 0x0590..=0x08FF | 0xFB1D..=0xFDFF | 0xFE70..=0xFEFC | 0x1_0800..=0x1_0FFF | 0x1_E800..=0x1_EFFF) } -/// The zero-width (non-)joiners inside a word (Persian `می‌روم`): egui shapes them with the -/// letter before them. -#[cfg(test)] -fn is_joiner(c: char) -> bool { - matches!(c, '\u{200C}' | '\u{200D}') -} - -/// Direction marks, embeddings, overrides and isolates: they steer the reordering and are not drawn. -#[cfg(test)] -fn is_bidi_control(c: char) -> bool { - matches!(c, '\u{061C}' | '\u{200E}' | '\u{200F}' | '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}') -} - -#[cfg(test)] -fn mirrored(c: char) -> char { - match c { - '(' => ')', - ')' => '(', - '[' => ']', - ']' => '[', - '{' => '}', - '}' => '{', - '<' => '>', - '>' => '<', - '«' => '»', - '»' => '«', - other => other, - } -} - #[cfg(test)] mod tests; diff --git a/crates/ui-egui/src/fonts.rs b/crates/ui-egui/src/fonts.rs new file mode 100644 index 0000000000..31fabf1edf --- /dev/null +++ b/crates/ui-egui/src/fonts.rs @@ -0,0 +1,176 @@ +//! The interface fonts: PdfCraft's own faces and the craft-fonts input, handed to the framework's +//! font stack, which orders the scripts, installs the faces and loads installed system fonts on +//! demand. + +use std::sync::{Arc, LazyLock}; + +use craft::ui::fonts::{CjkRows, Family, FontRef, I18nScripts, NoCandidates, SEMIBOLD, SystemCandidates, UiFonts}; +use egui::epaint::text::{FallbackAlign, FontData, FontTweak, HintingTarget, SmoothHinting}; + +use crate::i18n::{LANGUAGES, Lang}; + +/// The family of the medium-weight interface face. +const MEDIUM: &str = "medium"; + +/// Maps a language to the scripts it is written in, from craft-i18n's table. +static SCRIPTS: I18nScripts = I18nScripts; + +/// The platform whose font rules apply; a parameter so a test can compare them. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum FontPolicyPlatform { + Windows, + Other, +} + +fn current_platform() -> FontPolicyPlatform { + if cfg!(target_os = "windows") { FontPolicyPlatform::Windows } else { FontPolicyPlatform::Other } +} + +/// The tweak of the app's own face `name`: on Windows JetBrains Mono renders without symmetric +/// smoothing, which keeps its vertical stems sharp at low pixel densities. +fn primary_tweak(platform: FontPolicyPlatform, name: &str) -> FontTweak { + let mut tweak = FontTweak::default(); + if platform == FontPolicyPlatform::Windows && name == "JetBrainsMono" { + tweak.hinting_target = HintingTarget::Smooth(SmoothHinting { symmetric_rendering: false, ..SmoothHinting::default() }); + } + tweak +} + +/// `data` with its glyphs placed on the row's baseline (#1676). epaint otherwise centres a +/// fallback face's line box on the primary's, so a face with different metrics sits higher or +/// lower than the Latin beside it. `FallbackAlign::Baseline` positions every face's glyphs from +/// the primary face's ascent. + +pub fn on_interface_baseline(mut data: FontData) -> FontData { + data.tweak.fallback_align = FallbackAlign::Baseline; + data +} + +fn own_face(platform: FontPolicyPlatform, name: &str, bytes: &'static [u8]) -> FontData { + FontData::from_static(bytes).tweak(primary_tweak(platform, name)) +} + +/// The interface font stack for `lang`: Inter and JetBrains Mono first, then the craft-fonts faces +/// (none without `CRAFT_FONTS_DIR`) and installed system fonts on demand, unless +/// `PDFCRAFT_SYSTEM_FONTS=0`. Install it with [`UiFonts::install`] when the language changes. +pub fn ui_fonts(lang: Lang) -> UiFonts<'static> { + let platform = current_platform(); + let proportional = FontRef::proportional(); + let monospace = FontRef::monospace(); + let codes: Vec<&str> = LANGUAGES.iter().map(|l| l.code).collect(); + let system_fonts_off = std::env::var_os("PDFCRAFT_SYSTEM_FONTS").is_some_and(|v| v == "0"); + let fonts = UiFonts::new(&SCRIPTS) + .app_face("Inter", own_face(platform, "Inter", pdfcraft_fonts::INTER_REGULAR), &[proportional.clone(), monospace.clone()]) + .app_face("JetBrainsMono", own_face(platform, "JetBrainsMono", JETBRAINS_MONO), &[monospace.clone()]) + .app_face("Inter-Medium", own_face(platform, "Inter-Medium", INTER_MEDIUM), &[FontRef::named(MEDIUM)]) + .app_face("Inter-SemiBold", own_face(platform, "Inter-SemiBold", INTER_SEMIBOLD), &[FontRef::named(SEMIBOLD)]) + .family(Family::named(MEDIUM).weight(500)) + .family(Family::named(SEMIBOLD).weight(600)) + // PLAN: assumed `pdfcraft_fonts::CRAFT_FONTS: &[craft::ui::fonts::EmbeddedFace]` (pdf-shell-w1 contract head). + .craft_faces(pdfcraft_fonts::CRAFT_FONTS) + .languages(&codes) + .ui_language(lang.code()) + .cjk_rows(CjkRows::Grow); + let fonts = match os_locale() { + Some(locale) => fonts.os_locale(&locale), + None => fonts, + }; + if system_fonts_off { fonts.on_demand(Arc::new(NoCandidates)) } else { fonts.on_demand(Arc::new(SystemCandidates)) } +} + +const INTER_MEDIUM: &[u8] = include_bytes!("../../../assets/fonts/Inter-Medium.ttf"); +const INTER_SEMIBOLD: &[u8] = include_bytes!("../../../assets/fonts/Inter-SemiBold.ttf"); +const JETBRAINS_MONO: &[u8] = include_bytes!("../../../assets/fonts/JetBrainsMono-Regular.ttf"); + +/// The OS locale tag, which orders the regional Han faces when the interface language has none. +#[cfg(not(target_arch = "wasm32"))] +fn os_locale() -> Option { + static LOCALE: LazyLock> = + LazyLock::new(|| ["LC_ALL", "LC_MESSAGES", "LANG"].into_iter().find_map(|name| std::env::var(name).ok().filter(|v| !v.is_empty()))); + LOCALE.clone() +} + +#[cfg(target_arch = "wasm32")] +fn os_locale() -> Option { + None +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use egui::epaint::text::{FontDefinitions, Fonts, TextOptions}; + use egui::{Color32, FontFamily, FontId}; + + use super::*; + + fn layout(defs: FontDefinitions, family: FontFamily, size: f32, ppp: f32, text: &str) -> Vec<(char, f32, f32)> { + let mut fonts = Fonts::new(TextOptions::default(), defs); + let galley = fonts.with_pixels_per_point(ppp).layout_no_wrap(text.to_owned(), FontId::new(size, family), Color32::WHITE); + galley.rows.iter().flat_map(|row| row.glyphs.iter().map(|g| (g.chr, g.pos.x, g.pos.y))).collect() + } + + fn baselines(fallback: FontData, size: f32, text: &str) -> Vec { + let mut defs = FontDefinitions::empty(); + defs.font_data.insert("Inter".to_owned(), Arc::new(FontData::from_static(pdfcraft_fonts::INTER_REGULAR))); + defs.font_data.insert("fallback".to_owned(), Arc::new(fallback)); + defs.families.insert(FontFamily::Proportional, vec!["Inter".to_owned(), "fallback".to_owned()]); + layout(defs, FontFamily::Proportional, size, 1.0, text).into_iter().map(|(_, _, y)| y).collect() + } + + fn mono_fonts(platform: FontPolicyPlatform) -> FontDefinitions { + let mut defs = FontDefinitions::empty(); + defs.font_data.insert("JetBrainsMono".to_owned(), Arc::new(own_face(platform, "JetBrainsMono", JETBRAINS_MONO))); + defs.families.insert(FontFamily::Monospace, vec!["JetBrainsMono".to_owned()]); + defs + } + + #[test] + fn fallback_faces_share_the_interface_baseline() { + // Dancing Script's metrics differ from Inter's the way a Chinese face's do (by 0.044 em), + // and it has letters Inter doesn't (DŽ), which egui then takes from it. + let dancing: &'static [u8] = include_bytes!("../../../assets/fonts/DancingScript.ttf"); + let size = 100.0; + // As egui lays it out by itself, DŽ sits ~4 pt off H's baseline: the bug (#1676). + let raw = baselines(FontData::from_static(dancing), size, "HDŽ"); + assert!((raw[1] - raw[0]).abs() > 3.0, "the test fonts must differ: {raw:?}"); + let aligned = baselines(on_interface_baseline(FontData::from_static(dancing)), size, "HDŽ"); + assert!((aligned[1] - aligned[0]).abs() <= 1.0, "{aligned:?}"); + assert_eq!(on_interface_baseline(FontData::from_static(dancing)).tweak.fallback_align, FallbackAlign::Baseline); + } + + #[test] + fn windows_hinting_changes_only_the_jetbrains_symmetric_rendering_field() { + for name in ["Inter", "Inter-Medium", "Inter-SemiBold", "JetBrainsMono"] { + assert_eq!(primary_tweak(FontPolicyPlatform::Other, name), FontTweak::default(), "non-Windows {name}"); + let windows = primary_tweak(FontPolicyPlatform::Windows, name); + if name == "JetBrainsMono" { + assert_eq!( + windows, + FontTweak { + hinting_target: HintingTarget::Smooth(SmoothHinting { symmetric_rendering: false, ..SmoothHinting::default() }), + ..FontTweak::default() + } + ); + } else { + assert_eq!(windows, FontTweak::default(), "Windows {name}"); + } + } + } + + #[test] + #[ignore = "measurement probe against egui's rasteriser; run with --ignored when retuning the hinting"] + fn windows_hinting_improves_low_dpi_mono_raster_without_changing_layout_or_coverage() { + // The raster sharpness itself is a visual measure; what must hold is that the layout the + // hinting leaves alone is identical, whatever the density. + for ppp in [1.0, 1.25, 1.5, 2.0] { + for size in [11.0, 13.0, 16.0] { + for text in ["fn main() { 0Oo1lI }", "Ünïcode ѝ", "0123456789 {}[]()"] { + let a = layout(mono_fonts(FontPolicyPlatform::Other), FontFamily::Monospace, size, ppp, text); + let b = layout(mono_fonts(FontPolicyPlatform::Windows), FontFamily::Monospace, size, ppp, text); + assert_eq!(a, b, "{size} pt, {ppp} ppp, {text:?}"); + } + } + } + } +} diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index f53af95355..7d5f5e8901 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -34,7 +34,7 @@ use std::cell::Cell; use std::collections::HashSet; -use std::sync::{LazyLock, OnceLock}; +use std::sync::{Arc, LazyLock, OnceLock}; use craft_i18n::I18n; @@ -42,15 +42,20 @@ include!(concat!(env!("OUT_DIR"), "/craft_i18n.rs")); /// The embedded catalogs, offering exactly the languages in [`LANGUAGES`]. Built on first use; a /// locale is parsed on its first lookup. -static I18N: LazyLock = LazyLock::new(|| { +static I18N: LazyLock> = LazyLock::new(|| { let offered: Vec<&str> = LANGUAGES.iter().map(|l| l.code).collect(); let (i18n, problems) = I18n::new(CRAFT_I18N, &offered); for problem in problems { log::warn!("interface catalogs: {problem}"); } - i18n + Arc::new(i18n) }); +/// The embedded catalogs, shared with the framework's host. +pub fn shared() -> Arc { + Arc::clone(&I18N) +} + /// The `language` preference value that follows the system locale. pub const AUTO: &str = "auto"; @@ -186,7 +191,7 @@ impl Lang { pub const EN: Lang = Lang { lang: craft_i18n::Lang::EN, catalogs: None }; fn i18n(self) -> &'static I18n { - self.catalogs.unwrap_or_else(|| LazyLock::force(&I18N)) + self.catalogs.unwrap_or_else(|| &**LazyLock::force(&I18N)) } fn info(self) -> Option<&'static LangInfo> { @@ -593,31 +598,9 @@ fn same_shape(translated: &str, english: &str) -> bool { } /// Fill `{name}` placeholders in one pass. Unknown placeholders are left as written, and inserted -/// values are never read as templates again, so a file name containing `{n}` stays intact. Unlike -/// the crate's `fmt` it adds no bidi isolates: the egui fork orders each run for display. -pub fn fmt(template: &str, args: &[(&str, &str)]) -> String { - let mut out = String::with_capacity(template.len()); - let mut rest = template; - while let Some((before, after_open)) = rest.split_once('{') { - out.push_str(before); - let Some((name, after_close)) = after_open.split_once('}') else { - out.push('{'); - out.push_str(after_open); - return out; - }; - match args.iter().find(|(key, _)| *key == name) { - Some((_, value)) => out.push_str(value), - None => { - out.push('{'); - out.push_str(name); - out.push('}'); - } - } - rest = after_close; - } - out.push_str(rest); - out -} +/// values are never read as templates again. It adds no bidi isolates: the text path orders each +/// run for display. +pub use craft_i18n::fmt_plain as fmt; /// A generated history label (the action part of "Undo …") in the current language. Captured /// values (file and field names) are inserted as they are; unknown labels are looked up whole. diff --git a/crates/ui-egui/src/platform/motion.rs b/crates/ui-egui/src/platform/motion.rs deleted file mode 100644 index 79878de20b..0000000000 --- a/crates/ui-egui/src/platform/motion.rs +++ /dev/null @@ -1,346 +0,0 @@ -//! Animation effects, and the system's request to do without them. -//! -//! Windows' Settings ▸ Accessibility ▸ Visual effects ▸ Animation effects, turned off, asks -//! apps not to animate (other systems have a Reduce motion switch for it). The desktop app -//! reads the setting ([`MotionSource`]), and Preferences ▸ Animation effects -//! ([`AnimationEffects`]) follows it unless the user chose On or Off there. With animation -//! effects off, nothing in the window eases: -//! -//! - A wheel notch scrolls its whole distance in the frame it arrives. egui spreads a notch -//! over about a quarter of a second and has no switch for that, so each frame's wheel input -//! is read again here, the way egui reads it but for the easing ([`WheelReader`]), and handed -//! to egui's scroll areas in place of its own. -//! - ⌘/Ctrl-wheel zooms by a notch's whole step at once: egui makes its zoom factor from the -//! same eased wheel motion. Views read [`zoom_delta`] instead of egui's. -//! - Scrolling to a place (a row revealed by the keys, the Hand tool's drag) takes no time. -//! - egui's other animations (menus fading in, sections opening) take no time: its style's -//! animation time is zero, which the app's own fades and sweeps ask about too ([`animated`]). -//! -//! How far anything scrolls or zooms doesn't change, only how long it takes. - -use egui::style::ScrollAnimation; -use egui::{Event, Modifiers, MouseWheelSource, MouseWheelUnit, TouchPhase, Vec2, vec2}; - -/// Preferences ▸ Animation effects: whether anything in the window is animated, the wheel's -/// scrolling and zooming included. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "lowercase")] -pub enum AnimationEffects { - /// Animated unless the system asks for no animations ([`Motion::reduced`]). - #[default] - System, - On, - Off, -} - -impl AnimationEffects { - pub const ALL: [Self; 3] = [Self::System, Self::On, Self::Off]; - - pub fn label(self) -> &'static str { - match self { - Self::System => "Use system setting", - Self::On => "On", - Self::Off => "Off", - } - } - - /// The name in saved settings and on the control channel. - pub fn name(self) -> &'static str { - match self { - Self::System => "system", - Self::On => "on", - Self::Off => "off", - } - } - - pub fn parse(value: &str) -> Option { - Self::ALL.into_iter().find(|choice| choice.name().eq_ignore_ascii_case(value)) - } - - /// Whether the window animates, given whether the system asks for no animations. - pub fn animates(self, system_reduced: bool) -> bool { - match self { - Self::System => !system_reduced, - Self::On => true, - Self::Off => false, - } - } -} - -/// Asks the system whether it wants no animations; `None` when it can't say, which leaves the -/// last answer standing. Asked from the UI thread every [`ASK_EVERY`] seconds while the window -/// is in use, so it must answer at once. -pub type MotionSource = Box Option>; - -/// Seconds between two questions to [`MotionSource`]. Changing the setting takes longer than -/// this away from the window, so the first frame back already follows it. -const ASK_EVERY: f64 = 2.0; - -/// What the system says about animations, and what it takes to stop egui's. -pub struct Motion { - /// The system asks for no animations. The desktop app's [`Self::source`] sets it; false - /// elsewhere, so tests and screenshots don't depend on the machine. - pub reduced: bool, - /// How to ask the system (the desktop app sets it). - pub source: Option, - /// egui time of the last question. - asked_at: f64, - /// egui's own animation time and scroll animation, kept while they are changed here. - egui_times: Option<(f32, ScrollAnimation)>, - wheel: WheelReader, - /// This frame's wheel motion, read on its first pass and reused on later passes. - /// - /// egui empties `RawInput` between the passes of a multi-pass frame, so reading the wheel - /// again in a later pass sees nothing. Only the first pass is handed the motion (a scroll - /// area keeps the offset it moved to, a view keeps the zoom it set); later passes are handed - /// no scroll and a unit zoom, explicitly. - frame: Option<(u64, WheelMotion)>, -} - -impl Default for Motion { - /// Start motion handling with animations enabled and no desktop preference sampled yet. - fn default() -> Self { - Self { reduced: false, source: None, asked_at: f64::NEG_INFINITY, egui_times: None, wheel: WheelReader::default(), frame: None } - } -} - -impl Motion { - /// Call once at the start of every pass, before any ui reads the wheel or draws. - pub(crate) fn begin_pass(&mut self, ctx: &egui::Context, effects: AnimationEffects) { - let now = ctx.input(|i| i.time); - // `>=` is false for a NaN time, which then never asks. - if now - self.asked_at >= ASK_EVERY - && let Some(source) = &self.source - { - self.asked_at = now; - if let Some(reduced) = source() { - self.reduced = reduced; - } - } - let animate = effects.animates(self.reduced); - self.sync_style(ctx, animate); - if crate::canvas::wheel_reset::reset_this_pass(ctx) { - // The document's hidden cancel resets egui before fresh input. Its app reader - // must forget the same older gesture modifiers before reading those events. - self.wheel = WheelReader::default(); - } - let options = ctx.options(|o| o.input_options); - // One frame may run several passes (`request_discard`). Only the first pass has this - // frame's events, and only it may hand the wheel on: a scroll area applies the delta to - // its persisted offset, and a view multiplies the zoom into its persisted zoom, so - // replaying either would apply it twice. egui also rebuilds `smooth_scroll_delta` and - // its zoom factor from its retained wheel state every pass, so later passes must be - // given zero scroll and a unit zoom explicitly. A missing zoom entry would not do: it - // would fall back to egui's rebuilt factor. - let frame = ctx.cumulative_frame_nr(); - let first_pass = match self.frame { - Some((read_in, _)) => read_in != frame, - None => true, - }; - let motion = match self.frame { - Some((read_in, motion)) if read_in == frame => motion, - _ => { - let motion = ctx.input(|i| self.wheel.read(&i.events, i.time, i.viewport_rect().height(), &options)); - self.frame = Some((frame, motion)); - let modifiers = self.wheel.modifiers.clone(); - ctx.data_mut(|d| d.insert_temp(gesture_id(), (frame, modifiers))); - motion - } - }; - if animate { - // egui eases the wheel itself. The reader still follows each touch gesture, as - // egui does, for the modifiers [`gesture_wheel_events`] hands the document. - return; - } - let (scroll, zoom) = if first_pass { (motion.scroll, motion.zoom) } else { (Vec2::ZERO, 1.0) }; - ctx.input_mut(|i| i.smooth_scroll_delta = scroll); - let pass = ctx.cumulative_pass_nr(); - ctx.data_mut(|d| d.insert_temp(zoom_id(), (pass, zoom))); - // Existing kinetic scrolling remains owned by egui; gating wheel input does not - // suppress a scroll area's per-pass advancement of retained velocity. - } - - /// egui's animations, and its scrolling to a place, take no time unless the window is to - /// `animate`; then both get back the times egui had. - fn sync_style(&mut self, ctx: &egui::Context, animate: bool) { - if animate && self.egui_times.is_none() { - return; - } - // Checked every pass, so a style replaced since can't bring the animations back. - let style = ctx.global_style(); - let egui_times = *self.egui_times.get_or_insert((style.animation_time, style.scroll_animation)); - let wanted = if animate { egui_times } else { (0.0, ScrollAnimation::none()) }; - if (style.animation_time, style.scroll_animation) != wanted { - ctx.all_styles_mut(|s| (s.animation_time, s.scroll_animation) = wanted); - } - if animate { - self.egui_times = None; - } - } -} - -/// Whether the window animates this pass. The app's own fades and sweeps, which have their own -/// durations, ask this; egui's animations stop by themselves ([`Motion::begin_pass`]). -pub(crate) fn animated(ctx: &egui::Context) -> bool { - ctx.global_style().animation_time > 0.0 -} - -/// Return the stable egui id holding the last wheel-zoom input state. -fn zoom_id() -> egui::Id { - egui::Id::unique("pdfcraft-motion-wheel-zoom") -} - -/// This pass's zoom factor from a pinch or ⌘/Ctrl with the wheel (1.0 for none): egui's -/// `zoom_delta`, without the easing while animation effects are off. -pub(crate) fn zoom_delta(ctx: &egui::Context) -> f32 { - let read: Option<(u64, f32)> = ctx.data(|d| d.get_temp(zoom_id())); - let pass = ctx.cumulative_pass_nr(); - ctx.input(|i| match read { - // Only what [`Motion::begin_pass`] read in this very pass: a factor left from an earlier - // one would zoom again every frame. Fingers on a touch screen are measured, never eased. - Some((at, zoom)) if at == pass && i.multi_touch().is_none() => zoom, - _ => i.zoom_delta(), - }) -} - -/// Return the stable egui id holding the modifiers of this frame's wheel events. -fn gesture_id() -> egui::Id { - egui::Id::unique("pdfcraft-motion-wheel-gesture") -} - -/// This pass's wheel events, each with the modifiers it acts with: a touch gesture keeps -/// ⌘/Ctrl or Shift from its `Start` until its `End`, as egui and [`WheelReader`] read it. A view -/// that reads the raw wheel then scrolls none of a gesture that egui or [`zoom_delta`] zooms, -/// after the keys are let go too. The events keep their own modifiers when -/// [`Motion::begin_pass`] did not read this frame's wheel. -pub(crate) fn gesture_wheel_events(ctx: &egui::Context) -> Vec { - let read: Option<(u64, Vec)> = ctx.data(|d| d.get_temp(gesture_id())); - let frame = ctx.cumulative_frame_nr(); - let mut events: Vec = ctx.input(|i| i.events.iter().filter(|e| matches!(e, Event::MouseWheel { .. })).cloned().collect()); - if let Some((at, held)) = read - && at == frame - // A later pass of the frame has no events left; only the pass that was read matches. - && events.len() == held.len() - { - for (event, held) in events.iter_mut().zip(held) { - if let Event::MouseWheel { modifiers, .. } = event { - *modifiers = held; - } - } - } - events -} - -/// One pass's wheel input. -#[derive(Clone, Copy, Debug, PartialEq)] -struct WheelMotion { - /// Points to scroll by, as `InputState::smooth_scroll_delta` gives them (positive moves the - /// content right and down). - scroll: Vec2, - /// The zoom factor from pinch events and ⌘/Ctrl with the wheel. - zoom: f32, -} - -/// Reads wheel events as egui's `WheelState` does (egui 0.36, `input_state/wheel_state.rs`): -/// the same units, modifiers and touch phases, but every step lands whole in its own pass, -/// where egui keeps part of a coarse one for later passes. Compare the two when updating egui; -/// `tests::reading_at_once_goes_as_far_as_egui_eases` fails if they come apart. -#[derive(Default)] -struct WheelReader { - /// The modifiers of the touch gesture in progress (`TouchPhase::Start` to `End`). They hold - /// for the whole gesture, as in egui: its momentum arrives after the keys are let go. - touch: Option, - /// The time of the last wheel event and what drove it. A touch whose `End` never arrives - /// (some mouse wheels on Wayland send `Start` alone) ends after egui's timeout. - last: Option<(f64, MouseWheelSource)>, - /// The modifiers each wheel event of the last [`Self::read`] acted with, in order. - modifiers: Vec, -} - -/// egui's `SCROLL_ACTION_TIMEOUT`: seconds without a wheel event that end a touch. -const TOUCH_TIMEOUT: f64 = 0.150; - -/// egui's `RESTING_FINGER_TIMEOUT`: the same for a touch driven by fingers on a trackpad. -const RESTING_FINGER_TIMEOUT: f64 = 1.0; - -impl WheelReader { - /// `time` is the pass's input time; `page_height` is what one `MouseWheelUnit::Page` - /// scrolls: the window's height in points. - fn read(&mut self, events: &[Event], time: f64, page_height: f32, options: &egui::InputOptions) -> WheelMotion { - let mut delta = Vec2::ZERO; - let mut zoom = 1.0_f32; - let mut modifiers = self.touch.unwrap_or_default(); - self.modifiers.clear(); - for event in events { - if let Event::MouseWheel { source, .. } = event { - if let Some((at, last_source)) = self.last { - let timeout = if last_source == MouseWheelSource::Trackpad { RESTING_FINGER_TIMEOUT } else { TOUCH_TIMEOUT }; - // `>` is false for a NaN time, which then keeps the touch, as egui does. - if time - at > timeout { - self.touch = None; - } - } - self.last = Some((time, *source)); - } - match event { - Event::MouseWheel { unit, delta: step, phase, modifiers: latest, .. } => match phase { - TouchPhase::Start => { - self.touch = Some(*latest); - modifiers = *latest; - self.modifiers.push(modifiers); - } - TouchPhase::Move => { - modifiers = match &mut self.touch { - Some(held) => { - *held |= *latest; - *held - } - None => *latest, - }; - self.modifiers.push(modifiers); - let mut step = match unit { - MouseWheelUnit::Point => *step, - MouseWheelUnit::Line => options.line_scroll_speed * *step, - MouseWheelUnit::Page => page_height * *step, - }; - let horizontal = modifiers.matches_any(options.horizontal_scroll_modifier); - let vertical = modifiers.matches_any(options.vertical_scroll_modifier); - if horizontal && !vertical { - step = vec2(step.x + step.y, 0.0); - } - if !horizontal && vertical { - step = vec2(0.0, step.x + step.y); - } - // The system's numbers: one that isn't finite would end up in a scroll offset. - if step.x.is_finite() && step.y.is_finite() { - delta += step; - } - } - // egui drops what the gesture moved earlier in the pass it ends in. - TouchPhase::End | TouchPhase::Cancel => { - // The end belongs to the gesture: it carries the gesture's modifiers. - self.modifiers.push(self.touch.unwrap_or(*latest)); - self.touch = None; - modifiers = Modifiers::NONE; - delta = Vec2::ZERO; - } - }, - Event::Zoom(factor) => zoom *= *factor, - _ => {} - } - } - // A pass is all zoom or all scroll, by the modifiers it ends with, as in egui. - let mut scroll = delta; - if modifiers.matches_any(options.zoom_modifier) { - zoom *= (options.scroll_zoom_speed * (delta.x + delta.y)).exp(); - scroll = Vec2::ZERO; - } - if !(zoom.is_finite() && zoom > 0.0) { - zoom = 1.0; - } - WheelMotion { scroll, zoom } - } -} - -#[cfg(test)] -mod tests; diff --git a/crates/ui-egui/src/platform/motion/tests.rs b/crates/ui-egui/src/platform/motion/tests.rs deleted file mode 100644 index 4ccb3c0230..0000000000 --- a/crates/ui-egui/src/platform/motion/tests.rs +++ /dev/null @@ -1,449 +0,0 @@ -use super::*; -use std::cell::Cell; -use std::rc::Rc; - -fn wheel(unit: MouseWheelUnit, delta: Vec2, phase: TouchPhase, modifiers: Modifiers) -> Event { - Event::MouseWheel { unit, delta, phase, modifiers, source: egui::MouseWheelSource::Unknown } -} - -fn notch(dy: f32, modifiers: Modifiers) -> Event { - wheel(MouseWheelUnit::Line, vec2(0.0, dy), TouchPhase::Move, modifiers) -} - -fn read(events: &[Event]) -> WheelMotion { - WheelReader::default().read(events, 0.0, 600.0, &egui::InputOptions::default()) -} - -#[test] -fn a_step_is_read_whole_in_its_units() { - let line = egui::InputOptions::default().line_scroll_speed; - assert_eq!(read(&[notch(-1.0, Modifiers::NONE)]), WheelMotion { scroll: vec2(0.0, -line), zoom: 1.0 }); - assert_eq!(read(&[notch(-1.0, Modifiers::NONE), notch(-2.0, Modifiers::NONE)]).scroll, vec2(0.0, -3.0 * line), "steps of one pass add up"); - let points = wheel(MouseWheelUnit::Point, vec2(3.0, -250.0), TouchPhase::Move, Modifiers::NONE); - assert_eq!(read(&[points]).scroll, vec2(3.0, -250.0)); - let page = wheel(MouseWheelUnit::Page, vec2(0.0, -1.0), TouchPhase::Move, Modifiers::NONE); - assert_eq!(read(&[page]).scroll, vec2(0.0, -600.0)); - assert_eq!(read(&[]), WheelMotion { scroll: Vec2::ZERO, zoom: 1.0 }, "and nothing is left for a later pass"); -} - -#[test] -fn modifiers_turn_the_wheel_sideways_or_into_zoom() { - let line = egui::InputOptions::default().line_scroll_speed; - assert_eq!(read(&[notch(-1.0, Modifiers::SHIFT)]).scroll, vec2(-line, 0.0)); - let sideways = wheel(MouseWheelUnit::Point, vec2(-30.0, 0.0), TouchPhase::Move, Modifiers::ALT); - assert_eq!(read(&[sideways]).scroll, vec2(0.0, -30.0)); - let zoomed = read(&[notch(1.0, Modifiers::COMMAND)]); - assert_eq!(zoomed.scroll, Vec2::ZERO, "a zooming wheel doesn't scroll"); - let step = (egui::InputOptions::default().scroll_zoom_speed * line).exp(); - assert!((zoomed.zoom - step).abs() < 1e-6, "{zoomed:?}"); - assert!((read(&[notch(-1.0, Modifiers::COMMAND)]).zoom - 1.0 / step).abs() < 1e-6); - assert!((read(&[Event::Zoom(1.5), Event::Zoom(2.0)]).zoom - 3.0).abs() < 1e-6, "pinch events multiply"); -} - -#[test] -fn a_touch_gesture_keeps_its_modifiers_and_ends_clean() { - let mut reader = WheelReader::default(); - let options = egui::InputOptions::default(); - let point = |dy: f32, phase, modifiers| wheel(MouseWheelUnit::Point, vec2(0.0, dy), phase, modifiers); - // ⌘ held as the fingers land, let go before the momentum: still zooming. - let began = - reader.read(&[point(0.0, TouchPhase::Start, Modifiers::COMMAND), point(20.0, TouchPhase::Move, Modifiers::COMMAND)], 0.0, 600.0, &options); - assert!(began.zoom > 1.0 && began.scroll == Vec2::ZERO, "{began:?}"); - let momentum = reader.read(&[point(20.0, TouchPhase::Move, Modifiers::NONE)], 0.0, 600.0, &options); - assert!(momentum.zoom > 1.0 && momentum.scroll == Vec2::ZERO, "{momentum:?}"); - assert_eq!(reader.modifiers, vec![Modifiers::COMMAND], "the momentum acts with the gesture's modifiers"); - // The pass it ends in moves nothing, and the next gesture starts without the modifier. - let ended = reader.read(&[point(20.0, TouchPhase::Move, Modifiers::NONE), point(0.0, TouchPhase::End, Modifiers::NONE)], 0.0, 600.0, &options); - assert_eq!(ended, WheelMotion { scroll: Vec2::ZERO, zoom: 1.0 }); - assert_eq!(reader.read(&[point(-20.0, TouchPhase::Move, Modifiers::NONE)], 0.0, 600.0, &options).scroll, vec2(0.0, -20.0)); -} - -/// A touch whose `End` never arrives (some mouse wheels on Wayland) ends after egui's timeout, -/// so its modifiers don't latch onto later scrolling. -#[test] -fn a_touch_without_an_end_lets_its_modifiers_go_after_a_pause() { - let options = egui::InputOptions::default(); - for (source, pause) in [(egui::MouseWheelSource::Unknown, 0.2), (egui::MouseWheelSource::Trackpad, 1.1)] { - let mut reader = WheelReader::default(); - let point = |dy: f32, phase, modifiers| Event::MouseWheel { unit: MouseWheelUnit::Point, delta: vec2(0.0, dy), phase, modifiers, source }; - reader.read(&[point(0.0, TouchPhase::Start, Modifiers::COMMAND), point(20.0, TouchPhase::Move, Modifiers::COMMAND)], 1.0, 600.0, &options); - let soon = reader.read(&[point(20.0, TouchPhase::Move, Modifiers::NONE)], 1.1, 600.0, &options); - assert!(soon.zoom > 1.0 && soon.scroll == Vec2::ZERO, "{source:?}: still the same touch: {soon:?}"); - let later = reader.read(&[point(-20.0, TouchPhase::Move, Modifiers::NONE)], 1.1 + pause, 600.0, &options); - assert_eq!(later, WheelMotion { scroll: vec2(0.0, -20.0), zoom: 1.0 }, "{source:?}"); - assert_eq!(reader.modifiers, vec![Modifiers::NONE], "{source:?}"); - } -} - -#[test] -fn numbers_that_are_not_finite_move_nothing() { - for bad in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] { - let scrolled = read(&[notch(bad, Modifiers::NONE), notch(-1.0, Modifiers::NONE)]); - assert!(scrolled.scroll.x.is_finite() && scrolled.scroll.y.is_finite(), "{bad}: {scrolled:?}"); - assert_eq!(read(&[notch(bad, Modifiers::COMMAND)]).zoom, 1.0, "{bad}"); - assert_eq!(read(&[Event::Zoom(bad)]).zoom, 1.0, "{bad}"); - } - assert_eq!(read(&[Event::Zoom(0.0)]).zoom, 1.0); - assert_eq!(read(&[Event::Zoom(-2.0)]).zoom, 1.0); - // Too far to be a factor at all. - assert_eq!(read(&[notch(1.0e9, Modifiers::COMMAND)]).zoom, 1.0); -} - -/// One pass of a bare egui context, a sixtieth of a second after the last. -fn pass(ctx: &egui::Context, time: &mut f64, events: Vec, mut seen: impl FnMut(&egui::Context)) { - *time += 1.0 / 60.0; - let raw = egui::RawInput { time: Some(*time), events, ..Default::default() }; - // A bare context's first frame uploads the font atlas; nothing paints it here. - ctx.run_ui(raw, |ui| seen(ui.ctx())).textures_delta.clear(); -} - -/// The reader must stay egui's own reading minus the easing: over the passes egui takes to -/// ease a step, it hands out as much scroll (and as much zoom) as the reader does at once. -#[test] -fn reading_at_once_goes_as_far_as_egui_eases() { - let options = egui::InputOptions::default(); - for (modifiers, unit, step) in [ - (Modifiers::NONE, MouseWheelUnit::Line, vec2(0.0, -3.0)), - (Modifiers::NONE, MouseWheelUnit::Point, vec2(40.0, -250.0)), - (Modifiers::SHIFT, MouseWheelUnit::Line, vec2(0.0, 2.0)), - (Modifiers::COMMAND, MouseWheelUnit::Line, vec2(0.0, 1.0)), - (Modifiers::COMMAND, MouseWheelUnit::Point, vec2(0.0, -90.0)), - ] { - let event = wheel(unit, step, TouchPhase::Move, modifiers); - let ctx = egui::Context::default(); - let (mut time, mut scrolled, mut zoomed, mut first) = (0.0, Vec2::ZERO, 1.0_f32, None); - let mut events = vec![event.clone()]; - for _ in 0..120 { - pass(&ctx, &mut time, std::mem::take(&mut events), |ctx| { - let (scroll, zoom) = ctx.input(|i| (i.smooth_scroll_delta, i.zoom_delta())); - first.get_or_insert((scroll, zoom)); - scrolled += scroll; - zoomed *= zoom; - }); - } - let page_height = ctx.input(|i| i.viewport_rect().height()); - let at_once = WheelReader::default().read(&[event], 0.0, page_height, &options); - assert!((scrolled - at_once.scroll).length() < 0.01, "{modifiers:?} {unit:?}: egui scrolled {scrolled:?}, read {:?}", at_once.scroll); - assert!((zoomed / at_once.zoom - 1.0).abs() < 1e-3, "{modifiers:?} {unit:?}: egui zoomed {zoomed}, read {}", at_once.zoom); - // What makes the reader necessary: egui's first pass holds part of the step back. - let first = first.expect("passes ran"); - assert!( - first != (at_once.scroll, at_once.zoom), - "{modifiers:?} {unit:?}: egui no longer eases this step ({first:?}); the reader may not be needed" - ); - } -} - -#[test] -fn reduced_motion_hands_egui_the_whole_step_and_stops_its_animations() { - let ctx = egui::Context::default(); - let mut motion = Motion { reduced: true, ..Default::default() }; - let line = egui::InputOptions::default().line_scroll_speed; - let mut time = 0.0; - let mut seen = Vec::new(); - let mut events = vec![notch(-1.0, Modifiers::NONE)]; - for _ in 0..30 { - pass(&ctx, &mut time, std::mem::take(&mut events), |ctx| { - motion.begin_pass(ctx, AnimationEffects::System); - seen.push(ctx.input(|i| i.smooth_scroll_delta)); - }); - } - assert_eq!(seen.first(), Some(&vec2(0.0, -line)), "the whole notch in the pass it arrives"); - assert!(seen.iter().skip(1).all(|d| *d == Vec2::ZERO), "and none of egui's easing after it: {seen:?}"); - let style = ctx.global_style(); - assert_eq!((style.animation_time, style.scroll_animation), (0.0, egui::style::ScrollAnimation::none())); - for theme in [egui::Theme::Light, egui::Theme::Dark] { - assert_eq!(ctx.style_of(theme).animation_time, 0.0, "{theme:?}"); - } - - // ⌘/Ctrl with the wheel: the whole zoom step at once, then nothing. - let step = (egui::InputOptions::default().scroll_zoom_speed * line).exp(); - let mut zooms = Vec::new(); - let mut events = vec![notch(1.0, Modifiers::COMMAND)]; - for _ in 0..30 { - pass(&ctx, &mut time, std::mem::take(&mut events), |ctx| { - motion.begin_pass(ctx, AnimationEffects::System); - zooms.push(zoom_delta(ctx)); - }); - } - assert!((zooms[0] - step).abs() < 1e-6, "{zooms:?}"); - assert!(zooms.iter().skip(1).all(|z| *z == 1.0), "{zooms:?}"); - - // Animations allowed again: egui's own values and its own times. - motion.reduced = false; - let mut eased = Vec::new(); - let mut events = vec![notch(1.0, Modifiers::COMMAND)]; - for _ in 0..3 { - pass(&ctx, &mut time, std::mem::take(&mut events), |ctx| { - motion.begin_pass(ctx, AnimationEffects::System); - eased.push((zoom_delta(ctx), ctx.input(|i| i.zoom_delta()))); - }); - } - assert!(eased.iter().all(|(ours, eguis)| ours == eguis), "{eased:?}"); - assert!(eased[0].0 > 1.0 && eased[0].0 < step, "egui eases the step: {eased:?}"); - let (style, default) = (ctx.global_style(), egui::Style::default()); - assert_eq!((style.animation_time, style.scroll_animation), (default.animation_time, default.scroll_animation)); -} - -#[test] -fn consumed_document_gesture_does_not_keep_shift_for_another_scroll_area() { - let ctx = egui::Context::default(); - let mut motion = Motion::default(); - let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(300.0, 300.0)); - let pointer = Event::PointerMoved(screen.center()); - let raw = egui::RawInput { - screen_rect: Some(screen), - time: Some(0.1), - events: vec![ - pointer.clone(), - wheel(MouseWheelUnit::Point, Vec2::ZERO, TouchPhase::Start, Modifiers::SHIFT), - wheel(MouseWheelUnit::Point, vec2(0.0, -30.0), TouchPhase::Move, Modifiers::SHIFT), - ], - ..Default::default() - }; - ctx.run_ui(raw, |ui| { - motion.begin_pass(ui.ctx(), AnimationEffects::Off); - assert_eq!(ui.input(|input| input.smooth_scroll_delta), vec2(-30.0, 0.0)); - // The document owns the raw gesture and schedules its hidden-wheel reset. - crate::canvas::wheel_reset::consumed(ui.ctx()); - ui.input_mut(|input| input.smooth_scroll_delta = Vec2::ZERO); - }) - .drop_without_applying_deltas(); - - let fresh = wheel(MouseWheelUnit::Point, vec2(0.0, -18.0), TouchPhase::Move, Modifiers::NONE); - let events = vec![pointer, fresh]; - let raw = egui::RawInput { screen_rect: Some(screen), time: Some(0.1 + 1.0 / 60.0), events: events.clone(), ..Default::default() }; - let mut offset = Vec2::ZERO; - ctx.run_ui(raw, |ui| { - // The real plugin already cleared egui's old gesture and hid its own Cancel. - let eguis = ui.input(|input| input.smooth_scroll_delta); - assert_eq!(eguis.x, 0.0); - assert!(eguis.y < 0.0); - assert_eq!(ui.input(|input| input.events.clone()), events); - motion.begin_pass(ui.ctx(), AnimationEffects::Off); - assert_eq!(ui.input(|input| input.smooth_scroll_delta), vec2(0.0, -18.0), "fresh motion follows the released modifier"); - let out = - egui::ScrollArea::both().id_salt("motion-after-document").scroll_offset(vec2(200.0, 200.0)).auto_shrink([false, false]).show(ui, |ui| { - ui.set_min_size(vec2(1000.0, 3000.0)); - }); - offset = out.state.clamped_offset(); - }) - .drop_without_applying_deltas(); - assert_eq!(offset, vec2(200.0, 218.0), "the other area receives the complete fresh vertical step"); -} - -#[test] -fn the_preference_overrides_the_system_for_every_animation() { - use AnimationEffects::{Off, On, System}; - assert_eq!(AnimationEffects::default(), System, "the system's setting is followed unless the user chooses"); - for choice in AnimationEffects::ALL { - assert_eq!(AnimationEffects::parse(choice.name()), Some(choice)); - } - assert_eq!((AnimationEffects::parse("OFF"), AnimationEffects::parse("smooth")), (Some(Off), None)); - let (line, egui_default) = (egui::InputOptions::default().line_scroll_speed, egui::Style::default()); - let egui_times = (egui_default.animation_time, egui_default.scroll_animation); - // The system's answer, the choice, and whether the window then animates. - for (reduced, effects, animates) in - [(false, System, true), (true, System, false), (false, On, true), (true, On, true), (false, Off, false), (true, Off, false)] - { - assert_eq!(effects.animates(reduced), animates, "{effects:?}, system reduced: {reduced}"); - let ctx = egui::Context::default(); - let mut motion = Motion { reduced, ..Default::default() }; - let (mut time, mut first) = (0.0, None); - pass(&ctx, &mut time, vec![notch(-1.0, Modifiers::NONE)], |ctx| { - motion.begin_pass(ctx, effects); - first = Some((ctx.input(|i| i.smooth_scroll_delta), animated(ctx))); - }); - // The wheel, egui's animations and the app's own fades all go the same way. - let whole_notch = first.map(|(scroll, _)| scroll) == Some(vec2(0.0, -line)); - assert_eq!( - (whole_notch, first.map(|(_, animated)| animated)), - (!animates, Some(animates)), - "{effects:?}, system reduced: {reduced}: {first:?}" - ); - let style = ctx.global_style(); - let times = if animates { egui_times } else { (0.0, ScrollAnimation::none()) }; - assert_eq!((style.animation_time, style.scroll_animation), times, "{effects:?}, system reduced: {reduced}"); - } - // A choice made while running applies from the next pass, and choosing back undoes it. - let ctx = egui::Context::default(); - let mut motion = Motion::default(); - let mut time = 0.0; - for (effects, times) in [(Off, (0.0, ScrollAnimation::none())), (System, egui_times), (Off, (0.0, ScrollAnimation::none())), (On, egui_times)] { - pass(&ctx, &mut time, Vec::new(), |ctx| motion.begin_pass(ctx, effects)); - let style = ctx.global_style(); - assert_eq!((style.animation_time, style.scroll_animation), times, "{effects:?}"); - } -} - -/// The chrome's hover wash has a duration of its own (`theme::Press`): it eases in with -/// animation effects on and is simply there with them off. -#[test] -fn the_hover_wash_eases_only_with_animation_effects_on() { - for (effects, eased) in [(AnimationEffects::On, true), (AnimationEffects::Off, false)] { - let ctx = egui::Context::default(); - let mut motion = Motion::default(); - let (mut time, mut hover) = (0.0, Vec::new()); - for _ in 0..12 { - time += 1.0 / 60.0; - let raw = egui::RawInput { time: Some(time), events: vec![Event::PointerMoved(egui::pos2(20.0, 20.0))], ..Default::default() }; - ctx.run_ui(raw, |ui| { - motion.begin_pass(ui.ctx(), effects); - let (_, response) = ui.allocate_exact_size(vec2(100.0, 40.0), egui::Sense::click()); - hover.push(crate::theme::Press::track(ui, &response).hover); - }) - .textures_delta - .clear(); - } - // The first frame the pointer is found over the control. - let first = hover.iter().copied().find(|amount| *amount > 0.0).expect("the pointer is over the control"); - assert_eq!(first < 1.0, eased, "{effects:?}: {hover:?}"); - assert_eq!(hover.last(), Some(&1.0), "{effects:?}: the wash is whole in the end either way: {hover:?}"); - } -} - -#[test] -fn a_zoom_read_in_an_earlier_pass_is_never_used_again() { - let ctx = egui::Context::default(); - let mut motion = Motion { reduced: true, ..Default::default() }; - let mut time = 0.0; - pass(&ctx, &mut time, vec![notch(1.0, Modifiers::COMMAND)], |ctx| { - motion.begin_pass(ctx, AnimationEffects::System); - assert!(zoom_delta(ctx) > 1.0); - }); - // A pass that didn't begin here (a host that draws without `logic`): egui's own answer. - pass(&ctx, &mut time, Vec::new(), |ctx| { - let eguis = ctx.input(|i| i.zoom_delta()); - assert_eq!(zoom_delta(ctx), eguis); - }); -} - -/// With animation effects off, a real scroll area moves by one wheel step whether the frame -/// runs one pass or two (a `request_discard` from a sizing pass): the scroll area already -/// applied and stored the step in the first pass, so a later pass must not apply it again, -/// and must not replay the frame's raw wheel events either. -#[test] -fn two_pass_scroll_area_applies_one_wheel_step_like_a_single_pass() { - fn run(two_passes: bool) -> (Vec, Vec) { - let ctx = egui::Context::default(); - let mut motion = Motion { reduced: true, ..Default::default() }; - let mut offsets = Vec::new(); - let mut wheel_events = Vec::new(); - let raw = egui::RawInput { - time: Some(0.1), - screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(300.0, 300.0))), - events: vec![egui::Event::PointerMoved(egui::pos2(50.0, 50.0)), notch(-1.0, Modifiers::NONE)], - ..Default::default() - }; - let output = ctx.run_ui(raw, |ui| { - motion.begin_pass(ui.ctx(), AnimationEffects::System); - wheel_events.push(ui.input(|i| i.events.iter().filter(|e| matches!(e, egui::Event::MouseWheel { .. })).count())); - // Taller than the 300-point viewport, so one step stays far from the scroll - // limit and a doubled step could not be hidden by clamping. - let out = egui::ScrollArea::vertical().id_salt("motion-two-pass-scroll").auto_shrink([false, false]).show(ui, |ui| { - ui.set_min_size(egui::vec2(100.0, 3000.0)); - }); - offsets.push(out.state.unclamped_offset()); - if two_passes && ui.ctx().current_pass_index() == 0 { - ui.ctx().request_discard("motion two-pass scroll regression"); - } - }); - output.drop_without_applying_deltas(); - (offsets, wheel_events) - } - - let (single, single_events) = run(false); - let (two, two_events) = run(true); - - assert_eq!(single.len(), 1, "one frame, one pass"); - assert_eq!(two.len(), 2, "the frame really ran two passes"); - assert_eq!(single_events, vec![1], "one wheel event reaches the first pass"); - assert_eq!(two_events, vec![1, 0], "raw wheel events are not replayed in the later pass"); - - let step = single[0].y; - assert!(step > 0.0, "the wheel step scrolled: {single:?}"); - assert!((two[0].y - step).abs() < 0.01, "the first pass applies the whole step: single={step}, two-pass={two:?}"); - assert!((two[1].y - step).abs() < 0.01, "the presented pass must not apply the same step again: single={step}, two-pass={two:?}"); -} - -/// With animation effects off, ctrl/⌘-wheel and pinch zoom reach a view's persisted zoom -/// once, whether the frame runs one pass or two (a `request_discard` from a sizing pass): -/// multiplying an accumulator by each pass's factor gives the single step either way. A -/// later pass gets a unit factor explicitly, and a frame with no wheel input resets to it. -#[test] -fn two_pass_zoom_applies_one_step_like_a_single_pass() { - /// One frame's `zoom_delta` readings, one per pass. - fn frame(ctx: &egui::Context, motion: &mut Motion, time: f64, events: Vec, two_passes: bool) -> Vec { - let raw = egui::RawInput { - time: Some(time), - screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(300.0, 300.0))), - events, - ..Default::default() - }; - let mut zooms = Vec::new(); - let output = ctx.run_ui(raw, |ui| { - motion.begin_pass(ui.ctx(), AnimationEffects::System); - zooms.push(zoom_delta(ui.ctx())); - if two_passes && ui.ctx().current_pass_index() == 0 { - ui.ctx().request_discard("motion two-pass zoom regression"); - } - }); - output.drop_without_applying_deltas(); - zooms - } - - let line = egui::InputOptions::default().line_scroll_speed; - let ctrl_step = (egui::InputOptions::default().scroll_zoom_speed * line).exp(); - for (name, events, step) in [("ctrl-wheel", vec![notch(1.0, Modifiers::COMMAND)], ctrl_step), ("pinch", vec![Event::Zoom(1.5)], 1.5)] { - assert!((step - 1.0).abs() > 0.01, "{name}: the factor is nontrivial: {step}"); - let single = { - let ctx = egui::Context::default(); - let mut motion = Motion { reduced: true, ..Default::default() }; - frame(&ctx, &mut motion, 0.1, events.clone(), false) - }; - let ctx = egui::Context::default(); - let mut motion = Motion { reduced: true, ..Default::default() }; - let two = frame(&ctx, &mut motion, 0.1, events, true); - assert_eq!(single.len(), 1, "{name}: one frame, one pass: {single:?}"); - assert_eq!(two.len(), 2, "{name}: the frame really ran two passes: {two:?}"); - let product = |zooms: &[f32]| zooms.iter().product::(); - assert!((product(&single) - step).abs() < 1e-5, "{name}: one pass applies the step: {single:?}"); - assert!((product(&two) - step).abs() < 1e-5, "{name}: two passes apply it once: {two:?}"); - assert!((two[1] - 1.0).abs() < 1e-6, "{name}: a later pass zooms by nothing: {two:?}"); - // The next frame's wheel reading starts over; the two-pass frame's factor is gone. - let after = frame(&ctx, &mut motion, 0.1 + 1.0 / 60.0, Vec::new(), false); - assert_eq!(after, vec![1.0], "{name}: the cached factor does not survive the frame"); - } -} - -#[test] -fn the_system_is_asked_now_and_then_and_no_answer_changes_nothing() { - let ctx = egui::Context::default(); - let answer = Rc::new(Cell::new(Some(true))); - let asked = Rc::new(Cell::new(0_u32)); - let (source_answer, source_asked) = (Rc::clone(&answer), Rc::clone(&asked)); - let mut motion = Motion { - source: Some(Box::new(move || { - source_asked.set(source_asked.get() + 1); - source_answer.get() - })), - ..Default::default() - }; - let mut time = 0.0; - pass(&ctx, &mut time, Vec::new(), |ctx| motion.begin_pass(ctx, AnimationEffects::System)); - assert!(motion.reduced, "asked in the first pass"); - answer.set(Some(false)); - for _ in 0..30 { - pass(&ctx, &mut time, Vec::new(), |ctx| motion.begin_pass(ctx, AnimationEffects::System)); - } - assert!(motion.reduced && asked.get() == 1, "not asked again within half a second ({} times)", asked.get()); - // Back at the window later: the first pass asks. - time += ASK_EVERY; - pass(&ctx, &mut time, Vec::new(), |ctx| motion.begin_pass(ctx, AnimationEffects::System)); - assert!(!motion.reduced); - answer.set(None); - motion.reduced = true; - time += ASK_EVERY; - pass(&ctx, &mut time, Vec::new(), |ctx| motion.begin_pass(ctx, AnimationEffects::System)); - assert!(motion.reduced && asked.get() == 3, "no answer leaves the last one standing"); -} diff --git a/crates/ui-egui/src/platform/system_fonts.rs b/crates/ui-egui/src/platform/system_fonts.rs deleted file mode 100644 index 570e5de0ed..0000000000 --- a/crates/ui-egui/src/platform/system_fonts.rs +++ /dev/null @@ -1,729 +0,0 @@ -//! The last-resort interface font: one face already installed on this machine. -//! -//! The embedded faces (Inter, egui's defaults, craft-fonts) come first in every family; this one -//! only draws characters none of them has, such as an Arabic file name in a build without -//! craft-fonts, or the Simplified Chinese interface in a build without a `Hans` face (#826). A -//! few more installed faces, [`devanagari_fallback`], [`telugu_fallback`], [`sinhala_fallback`], -//! [`tamil_fallback`], [`hebrew_fallback`] and [`hangul_fallback`], draw Hindi, Telugu, Sinhala, -//! Tamil, Hebrew and Korean when one is installed. It is read at runtime and never embedded or -//! shipped (AGENTS.md §1.4), and `PDFCRAFT_SYSTEM_FONTS=0` turns it off (published screenshots do). - -use std::path::{Path, PathBuf}; -use std::sync::{Arc, OnceLock}; - -use egui::FontData; - -#[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))] -mod fontconfig; - -/// Larger files are not read: a font path is still untrusted input. -const MAX_BYTES: u64 = 32 << 20; -/// Chinese system faces are big collections (PingFang, STHeiti), so they get a higher cap. -const MAX_HAN_BYTES: u64 = 96 << 20; -/// Faces tried in a collection (`.ttc`). -const MAX_FACES: u32 = 16; -/// Arabic letter alef: the face must have it to be worth loading for Arabic script. -const PROBE: char = '\u{0627}'; -/// Devanagari letter ka: the face must have it to cover Hindi. -const DEVANAGARI_PROBE: char = '\u{0915}'; -/// Telugu letter ka: the face must have it to cover Telugu. -const TELUGU_PROBE: char = '\u{0C15}'; -/// Sinhala letter ka (ක): the face must have it to cover Sinhala. -const SINHALA_PROBE: char = '\u{0D9A}'; -/// Tamil letter ka (க): the face must have it to cover Tamil. -const TAMIL_PROBE: char = '\u{0B95}'; -/// Hebrew letter alef: the face must have it to cover Hebrew. -const HEBREW_PROBE: char = '\u{05D0}'; -/// Hangul syllable hih (힣, U+D7A3), the last of the 11,172 modern syllables: a face with it has -/// the whole block. Droid Sans Fallback, for one, has 가 but few other syllables. -const HANGUL_PROBE: char = '\u{D7A3}'; -/// 欢 (U+6B22): Simplified only, absent from the Japanese craft-fonts faces. -const HANS_PROBE: char = '\u{6B22}'; -/// 說 (U+8AAA): Traditional only, absent from the Japanese craft-fonts faces. -const HANT_PROBE: char = '\u{8AAA}'; - -/// What the installed face is wanted for, from the interface language. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub enum Need { - /// Scripts no embedded face has (Arabic in a build without craft-fonts). - #[default] - Other, - /// Simplified Chinese interface text. - Hans, - /// Traditional Chinese interface text. - Hant, -} - -/// The installed fallback face for `need`, read once per need. `None` when it is turned off or no -/// candidate fits. -pub fn fallback(need: Need) -> Option> { - static OTHER: OnceLock>> = OnceLock::new(); - static HANS: OnceLock>> = OnceLock::new(); - static HANT: OnceLock>> = OnceLock::new(); - let cache = match need { - Need::Other => &OTHER, - Need::Hans => &HANS, - Need::Hant => &HANT, - }; - cache.get_or_init(|| load(need)).clone() -} - -fn load(need: Need) -> Option> { - if std::env::var_os("PDFCRAFT_SYSTEM_FONTS").is_some_and(|v| v == "0") { - return None; - } - let (probe, max) = match need { - Need::Other => (PROBE, MAX_BYTES), - Need::Hans => (HANS_PROBE, MAX_HAN_BYTES), - Need::Hant => (HANT_PROBE, MAX_HAN_BYTES), - }; - candidates(need).iter().find_map(|path| read(path, probe, max)) -} - -/// The installed fallback face for Devanagari (Hindi), read once. `None` when it is turned off -/// or no candidate is installed; the interface then draws what the embedded faces can. -pub fn devanagari_fallback() -> Option> { - static CACHE: OnceLock>> = OnceLock::new(); - CACHE.get_or_init(|| script_fallback(&devanagari_candidates(), DEVANAGARI_PROBE)).clone() -} - -/// The installed fallback face for Telugu, read once. `None` when it is turned off or no -/// candidate is installed; the interface then draws what the embedded faces can. -pub fn telugu_fallback() -> Option> { - static CACHE: OnceLock>> = OnceLock::new(); - CACHE.get_or_init(|| script_fallback(&telugu_candidates(), TELUGU_PROBE)).clone() -} - -/// The installed fallback face for Sinhala, read once. `None` when it is turned off or no -/// candidate is installed; the interface then draws what the embedded faces can. -pub fn sinhala_fallback() -> Option> { - static CACHE: OnceLock>> = OnceLock::new(); - CACHE.get_or_init(|| script_fallback(&sinhala_candidates(), SINHALA_PROBE)).clone() -} - -/// The installed fallback face for Tamil, read once. `None` when it is turned off or no -/// candidate is installed; the interface then draws what the embedded faces can. -pub fn tamil_fallback() -> Option> { - static CACHE: OnceLock>> = OnceLock::new(); - CACHE.get_or_init(|| script_fallback(&tamil_candidates(), TAMIL_PROBE)).clone() -} - -/// The installed fallback face for Hebrew, read once. `None` when it is turned off or no -/// candidate is installed; the interface then draws what the embedded faces can. -pub fn hebrew_fallback() -> Option> { - static CACHE: OnceLock>> = OnceLock::new(); - CACHE.get_or_init(|| script_fallback(&hebrew_candidates(), HEBREW_PROBE)).clone() -} - -/// The installed fallback face for Hangul (Korean), read once. `None` when it is turned off or no -/// candidate is installed; the interface then draws what the embedded faces can. -pub fn hangul_fallback() -> Option> { - static CACHE: OnceLock>> = OnceLock::new(); - CACHE.get_or_init(|| script_fallback(&hangul_candidates(), HANGUL_PROBE)).clone() -} - -fn script_fallback(candidates: &[PathBuf], probe: char) -> Option> { - if std::env::var_os("PDFCRAFT_SYSTEM_FONTS").is_some_and(|v| v == "0") { - return None; - } - candidates.iter().find_map(|path| read(path, probe, MAX_BYTES)) -} - -/// macOS folders that hold Apple's own families, system folder first. On macOS 26.6 (Apple M5 -/// Max) `Kohinoor.ttc` is in `/System/Library/Fonts` while the Sangam MN faces are under -/// `Supplemental/`, so looking one family up in both folders stops a move by Apple from silently -/// dropping it — which is what happened to `Supplemental/Kohinoor.ttc`, listed by the code but -/// not present on that OS. `/Library/Fonts` is deliberately not listed here: it holds -/// compatibility symlinks into `Supplemental/`, and the one face wanted from it is named in full -/// below. On that machine each family below lives in exactly one of the two folders, so their -/// order is a deterministic choice rather than a tie-break that was ever exercised. -/// -/// Only [`macos_devanagari_candidates`] uses this today: in the Telugu, Sinhala and Tamil lists each -/// family is named once, in a single folder (some of those lists also name `/Library/Fonts` for the -/// Unicode face). Their first choices all exist on macOS 26.6, so nothing is dropping there now — the -/// same two-folder expansion would fit them, and is left for a change that tests it. -const MACOS_FONT_DIRS: [&str; 2] = ["/System/Library/Fonts", "/System/Library/Fonts/Supplemental"]; - -/// The Devanagari families this list tries, best first. Spelled as the files are on disk — -/// `Devanagari Sangam MN.ttc` has spaces, like the other Sangam MN families below. Apple ships at -/// least one more Devanagari-capable collection on macOS 26.6 (`Supplemental/ITFDevanagari.ttc`, -/// 10 faces), and this list does not try it. -const MACOS_DEVANAGARI_FAMILIES: &[&str] = &["DevanagariMT.ttc", "Devanagari Sangam MN.ttc", "Kohinoor.ttc"]; - -/// `families`, best first, each looked for in every folder of `dirs`. Split out from -/// [`macos_candidates`] so the macOS layout can be tested on a machine with no Apple fonts. -fn macos_families_in(dirs: &[&str], families: &[&str]) -> Vec { - families.iter().flat_map(|family| dirs.iter().map(move |dir| Path::new(dir).join(family))).collect() -} - -/// [`macos_families_in`] against the folders Apple actually uses. -fn macos_candidates(families: &[&str]) -> Vec { - macos_families_in(&MACOS_FONT_DIRS, families) -} - -/// The macOS Devanagari list: Apple's installed families, then the last-resort Unicode face. -/// `Arial Unicode.ttf` is listed from `/Library/Fonts`, where it is a symlink into -/// `Supplemental/` on current macOS, and is read only when no family above covers the script. -fn macos_devanagari_candidates() -> Vec { - let mut list = macos_candidates(MACOS_DEVANAGARI_FAMILIES); - list.push(PathBuf::from("/Library/Fonts/Arial Unicode.ttf")); - list -} - -/// Well-known locations of Devanagari (Hindi) faces, best first. -fn devanagari_candidates() -> Vec { - if cfg!(windows) { - ["Nirmala.ttf", "NirmalaB.ttf", "mangal.ttf", "aparaj.ttf", "utsah.ttf"].iter().map(|f| windows_fonts().join(f)).collect() - } else if cfg!(target_os = "macos") { - macos_devanagari_candidates() - } else { - unix_fonts(&[ - "google-noto/NotoSansDevanagariUI-Regular.ttf", - "google-noto/NotoSansDevanagari-Regular.ttf", - "google-noto-vf/NotoSansDevanagari[wght].ttf", - "truetype/noto/NotoSansDevanagari-Regular.ttf", - "truetype/noto/NotoSansDevanagariUI-Regular.ttf", - "noto/NotoSansDevanagari-Regular.ttf", - "noto/NotoSansDevanagariUI-Regular.ttf", - "lohit-devanagari-fonts/Lohit-Devanagari.ttf", - "truetype/lohit-devanagari/Lohit-Devanagari.ttf", - "truetype/deva/Lohit-Devanagari.ttf", - "lohit-hindi/Lohit-Hindi.ttf", - "google-droid-sans-fonts/DroidSansDevanagari-Regular.ttf", - "samyak-fonts/Samyak-Devanagari.ttf", - "gargi/Gargi.ttf", - ]) - } -} - -/// Well-known locations of Telugu faces, best first. -fn telugu_candidates() -> Vec { - if cfg!(windows) { - ["Nirmala.ttc", "Nirmala.ttf", "gautami.ttf"].iter().map(|f| windows_fonts().join(f)).collect() - } else if cfg!(target_os = "macos") { - [ - "/System/Library/Fonts/KohinoorTelugu.ttc", - "/System/Library/Fonts/Supplemental/Telugu Sangam MN.ttc", - "/System/Library/Fonts/Supplemental/Telugu MN.ttc", - "/Library/Fonts/Arial Unicode.ttf", - ] - .iter() - .map(PathBuf::from) - .collect() - } else { - unix_fonts(&[ - "google-noto/NotoSansTeluguUI-Regular.ttf", - "google-noto/NotoSansTelugu-Regular.ttf", - "google-noto-vf/NotoSansTelugu[wght].ttf", - "google-noto-vf/NotoSansTelugu-UI[wght].ttf", - "truetype/noto/NotoSansTelugu-Regular.ttf", - "truetype/noto/NotoSansTeluguUI-Regular.ttf", - "noto/NotoSansTelugu-Regular.ttf", - "noto/NotoSansTeluguUI-Regular.ttf", - "lohit-telugu-fonts/Lohit-Telugu.ttf", - "truetype/lohit-telugu/Lohit-Telugu.ttf", - "truetype/fonts-telu-extra/Pothana2000.ttf", - ]) - } -} - -/// Well-known locations of Sinhala faces, best first. Nirmala UI has Sinhala from Windows 10; -/// Iskoola Pota is the older Windows Sinhala face. -fn sinhala_candidates() -> Vec { - if cfg!(windows) { - ["Nirmala.ttc", "Nirmala.ttf", "iskpota.ttf"].iter().map(|f| windows_fonts().join(f)).collect() - } else if cfg!(target_os = "macos") { - ["/System/Library/Fonts/Supplemental/Sinhala Sangam MN.ttc", "/System/Library/Fonts/Supplemental/Sinhala MN.ttc"] - .iter() - .map(PathBuf::from) - .collect() - } else { - unix_fonts(&[ - "google-noto/NotoSansSinhalaUI-Regular.ttf", - "google-noto/NotoSansSinhala-Regular.ttf", - "google-noto-vf/NotoSansSinhala[wght].ttf", - "truetype/noto/NotoSansSinhala-Regular.ttf", - "truetype/noto/NotoSansSinhalaUI-Regular.ttf", - "noto/NotoSansSinhala-Regular.ttf", - "noto/NotoSansSinhalaUI-Regular.ttf", - ]) - } -} - -/// Well-known locations of Tamil faces, best first. Latha is the older Windows Tamil face. -fn tamil_candidates() -> Vec { - if cfg!(windows) { - ["Nirmala.ttc", "Nirmala.ttf", "latha.ttf"].iter().map(|f| windows_fonts().join(f)).collect() - } else if cfg!(target_os = "macos") { - [ - "/System/Library/Fonts/Supplemental/Tamil Sangam MN.ttc", - "/System/Library/Fonts/Supplemental/Tamil MN.ttc", - "/Library/Fonts/Arial Unicode.ttf", - ] - .iter() - .map(PathBuf::from) - .collect() - } else { - unix_fonts(&[ - "google-noto/NotoSansTamilUI-Regular.ttf", - "google-noto/NotoSansTamil-Regular.ttf", - "google-noto-vf/NotoSansTamil[wght].ttf", - "truetype/noto/NotoSansTamil-Regular.ttf", - "truetype/noto/NotoSansTamilUI-Regular.ttf", - "noto/NotoSansTamil-Regular.ttf", - "noto/NotoSansTamilUI-Regular.ttf", - "lohit-tamil-fonts/Lohit-Tamil.ttf", - "truetype/lohit-tamil/Lohit-Tamil.ttf", - ]) - } -} - -/// Well-known locations of Hebrew faces, best first. The general fallback does not cover it: -/// SF Arabic, Geeza Pro and Noto Sans Arabic have no Hebrew. -fn hebrew_candidates() -> Vec { - if cfg!(windows) { - ["segoeui.ttf", "arial.ttf", "tahoma.ttf", "david.ttf"].iter().map(|f| windows_fonts().join(f)).collect() - } else if cfg!(target_os = "macos") { - ["/System/Library/Fonts/SFHebrew.ttf", "/System/Library/Fonts/ArialHB.ttc", "/Library/Fonts/Arial Unicode.ttf"] - .iter() - .map(PathBuf::from) - .collect() - } else { - unix_fonts(&[ - "google-noto/NotoSansHebrew-Regular.ttf", - "google-noto-vf/NotoSansHebrew[wght].ttf", - "truetype/noto/NotoSansHebrew-Regular.ttf", - "noto/NotoSansHebrew-Regular.ttf", - "truetype/dejavu/DejaVuSans.ttf", - "TTF/DejaVuSans.ttf", - "dejavu/DejaVuSans.ttf", - "dejavu-sans-fonts/DejaVuSans.ttf", - ]) - } -} - -/// Well-known locations of faces with broad script coverage, best first. -fn candidates(need: Need) -> Vec { - match need { - Need::Other => other_candidates(), - Need::Hans | Need::Hant => han_candidates(need == Need::Hant), - } -} - -fn other_candidates() -> Vec { - if cfg!(windows) { - ["segoeui.ttf", "tahoma.ttf", "arial.ttf"].iter().map(|f| windows_fonts().join(f)).collect() - } else if cfg!(target_os = "macos") { - ["/System/Library/Fonts/SFArabic.ttf", "/System/Library/Fonts/GeezaPro.ttc", "/System/Library/Fonts/Supplemental/Arial.ttf"] - .iter() - .map(PathBuf::from) - .collect() - } else { - unix_fonts(&[ - "truetype/noto/NotoSansArabic-Regular.ttf", - "noto/NotoSansArabic-Regular.ttf", - "google-noto/NotoSansArabic-Regular.ttf", - "truetype/dejavu/DejaVuSans.ttf", - "TTF/DejaVuSans.ttf", - "dejavu/DejaVuSans.ttf", - "dejavu-sans-fonts/DejaVuSans.ttf", - ]) - } -} - -/// Chinese sans faces the operating system ships, the UI language's own region first. -fn han_candidates(traditional: bool) -> Vec { - if cfg!(windows) { - // Microsoft YaHei / JhengHei, then the older SimSun / MingLiU collections. - let files: &[&str] = - if traditional { &["msjh.ttc", "msyh.ttc", "mingliu.ttc", "simsun.ttc"] } else { &["msyh.ttc", "msjh.ttc", "simsun.ttc", "mingliu.ttc"] }; - files.iter().map(|f| windows_fonts().join(f)).collect() - } else if cfg!(target_os = "macos") { - macos_han_candidates(traditional) - } else { - unix_fonts(&[ - "truetype/wqy/wqy-microhei.ttc", - "wenquanyi/wqy-microhei/wqy-microhei.ttc", - "wqy-microhei/wqy-microhei.ttc", - "truetype/wqy/wqy-zenhei.ttc", - "wenquanyi/wqy-zenhei/wqy-zenhei.ttc", - "wqy-zenhei/wqy-zenhei.ttc", - "truetype/droid/DroidSansFallbackFull.ttf", - "google-droid-sans-fonts/DroidSansFallbackFull.ttf", - "droid/DroidSansFallbackFull.ttf", - "truetype/arphic/uming.ttc", - "arphic-uming/uming.ttc", - ]) - } -} - -/// macOS 26 moved PingFang out of `/System/Library/Fonts` into the reserved system-font directory; -/// face 0 of that collection is the SC UI face. Older systems still have `PingFang.ttc`, which wins. -const MACOS_PINGFANG_UI: &str = "/System/Library/PrivateFrameworks/FontServices.framework/Resources/Reserved/PingFangUI.ttc"; - -fn macos_han_candidates(traditional: bool) -> Vec { - let dir = Path::new("/System/Library/Fonts"); - let pingfang_ui = PathBuf::from(MACOS_PINGFANG_UI); - let mut list = vec![dir.join("PingFang.ttc")]; - if traditional { - // Face 0 of PingFangUI.ttc is Simplified Chinese, so STHeiti stays ahead of it. - list.extend(["STHeiti Light.ttc", "STHeiti Medium.ttc"].iter().map(|f| dir.join(f))); - list.push(pingfang_ui); - list.push(dir.join("Hiragino Sans GB.ttc")); - } else { - list.push(pingfang_ui); - list.extend(["Hiragino Sans GB.ttc", "STHeiti Light.ttc", "STHeiti Medium.ttc"].iter().map(|f| dir.join(f))); - } - list -} - -/// Well-known locations of Korean faces, best first. -fn hangul_candidates() -> Vec { - if cfg!(windows) { - ["malgun.ttf", "gulim.ttc", "batang.ttc"].iter().map(|f| windows_fonts().join(f)).collect() - } else if cfg!(target_os = "macos") { - ["/System/Library/Fonts/AppleSDGothicNeo.ttc", "/System/Library/Fonts/Supplemental/AppleGothic.ttf", "/Library/Fonts/Arial Unicode.ttf"] - .iter() - .map(PathBuf::from) - .collect() - } else { - unix_fonts(&[ - "truetype/nanum/NanumGothic.ttf", - "nanum/NanumGothic.ttf", - "naver-nanum/NanumGothic.ttf", - "nhn-nanum/NanumGothic.ttf", - "truetype/unfonts-core/UnDotum.ttf", - "un-core/UnDotum.ttf", - "truetype/baekmuk/dotum.ttf", - "baekmuk-ttf-dotum-fonts/dotum.ttf", - ]) - } -} - -fn windows_fonts() -> PathBuf { - let dir = std::env::var_os("WINDIR").or_else(|| std::env::var_os("SystemRoot")).map_or_else(|| PathBuf::from(r"C:\Windows"), PathBuf::from); - dir.join("Fonts") -} - -fn unix_fonts(files: &'static [&'static str]) -> Vec { - #[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))] - static INSTALLED: OnceLock> = OnceLock::new(); - #[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))] - // Read once per process, and not at all when installed fonts are turned off. - let installed = INSTALLED - .get_or_init(|| { - if std::env::var_os("PDFCRAFT_SYSTEM_FONTS").is_some_and(|v| v == "0") { - return Vec::new(); - } - fontconfig::font_files(&fontconfig::config_path()) - }) - .as_slice(); - #[cfg(not(all(unix, not(target_os = "macos"), not(target_arch = "wasm32"))))] - let installed: &[PathBuf] = &[]; - unix_candidates(files, installed) -} - -fn unix_candidates(files: &[&str], installed: &[PathBuf]) -> Vec { - let mut paths: Vec<_> = - ["/usr/share/fonts", "/usr/local/share/fonts"].iter().flat_map(|dir| files.iter().map(move |f| Path::new(dir).join(f))).collect(); - // Fontconfig may point into /nix/store or a user's font directory. Keep the existing - // candidate names and their preference order; this does not select arbitrary fonts. - for file in files { - let name = Path::new(file).file_name(); - for path in installed.iter().filter(|p| p.file_name() == name) { - if !paths.contains(path) { - paths.push(path.clone()); - } - } - } - paths -} - -fn read(path: &Path, probe: char, max: u64) -> Option> { - let meta = std::fs::metadata(path).ok()?; - if !meta.is_file() || meta.len() > max { - return None; - } - let bytes = std::fs::read(path).ok()?; - let index = face_with(&bytes, probe)?; - let mut data = FontData::from_owned(bytes); - data.index = index; - log::info!("interface font fallback: {} (face {index})", path.display()); - Some(Arc::new(crate::theme::on_interface_baseline(data))) -} - -/// The first face of the file that parses and maps `c`. egui parses fonts with the same skrifa, -/// so a face accepted here is one it can load. -fn face_with(bytes: &[u8], c: char) -> Option { - use skrifa::MetadataProvider as _; - (0..MAX_FACES).find(|&index| skrifa::FontRef::from_index(bytes, index).is_ok_and(|font| font.charmap().map(c).is_some())) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn configured_candidates_preserve_names_order_and_existing_paths() { - let names = ["noto/NotoSansArabic-Regular.ttf", "truetype/dejavu/DejaVuSans.ttf"]; - let noto = PathBuf::from("/custom/fonts/NotoSansArabic-Regular.ttf"); - let dejavu = PathBuf::from("/nix/store/font/share/fonts/truetype/DejaVuSans.ttf"); - let installed = [dejavu.clone(), PathBuf::from("/custom/fonts/SourceHanSans.ttf"), noto.clone(), dejavu.clone()]; - let mut expected = unix_candidates(&names, &[]); - expected.extend([noto, dejavu]); - assert_eq!(unix_candidates(&names, &installed), expected); - } - - #[test] - fn broken_and_missing_files_are_skipped() { - assert_eq!(face_with(b"", PROBE), None); - assert_eq!(face_with(b"not a font at all", PROBE), None); - assert_eq!(face_with(&[0u8; 4096], PROBE), None); - assert!(read(Path::new("definitely/not/here.ttf"), PROBE, MAX_BYTES).is_none()); - // A directory is not a font. - assert!(read(&std::env::temp_dir(), PROBE, MAX_BYTES).is_none()); - } - - #[test] - fn a_face_without_the_probe_is_rejected() { - // Inter is Latin, Greek and Cyrillic only. - let inter = include_bytes!("../../../../assets/fonts/Inter-Regular.ttf"); - assert_eq!(face_with(inter, PROBE), None); - assert_eq!(face_with(inter, HANS_PROBE), None); - assert_eq!(face_with(inter, HANT_PROBE), None); - assert_eq!(face_with(inter, 'A'), Some(0)); - } - - #[test] - fn a_file_over_the_cap_is_not_read() { - let inter = Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/fonts/Inter-Regular.ttf")); - assert!(read(inter, 'A', MAX_BYTES).is_some()); - assert!(read(inter, 'A', 1024).is_none()); - } - - #[test] - fn candidates_are_absolute_font_files() { - for need in [Need::Other, Need::Hans, Need::Hant] { - let list = candidates(need); - assert!(!list.is_empty(), "{need:?}"); - assert!(list.iter().all(|p| p.extension().is_some_and(|e| e == "ttf" || e == "ttc")), "{need:?}"); - } - } - - /// `script_fallback` honours the documented installed-font switch, under which it returns - /// nothing before order is ever consulted — so both loader tests and the macOS oracle skip when - /// it is off, the way `tests/it/fonts.rs` skips for the same reason. Without this the suite goes red in exactly the - /// mode `cargo xtask screenshots` uses. - fn installed_faces_switched_off() -> bool { - std::env::var_os("PDFCRAFT_SYSTEM_FONTS").is_some_and(|v| v == "0") - } - - /// Check that the first readable fallback candidate wins, so reversing the preference list reverses the - /// chosen face. - #[test] - fn the_first_readable_candidate_wins_not_the_last() { - // List order *is* the preference, so a loader that scanned back-to-front would pick a - // different face and nobody would notice. Two bundled faces both cover 'A' and differ in - // size, so the winner is identifiable by length alone. - if installed_faces_switched_off() { - eprintln!("skipping: PDFCRAFT_SYSTEM_FONTS=0 turns the loader off before order matters"); - return; - } - let dir = Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/fonts")); - let (inter, mono) = (dir.join("Inter-Regular.ttf"), dir.join("JetBrainsMono-Regular.ttf")); - let size = |p: &Path| std::fs::metadata(p).expect("bundled face").len(); - assert_ne!(size(&inter), size(&mono), "the two fixtures must be tellable apart"); - let first = script_fallback(&[inter.clone(), mono.clone()], 'A').expect("Inter covers 'A'"); - assert_eq!(first.bytes().len() as u64, size(&inter), "the first readable candidate must win"); - let reversed = script_fallback(&[mono.clone(), inter], 'A').expect("JetBrains Mono covers 'A'"); - assert_eq!(reversed.bytes().len() as u64, size(&mono), "reversing the list must reverse the pick"); - } - - #[test] - fn a_script_fallback_is_the_first_candidate_with_the_probe() { - // This one calls `script_fallback` too, so it fails under the documented switch that - // published screenshots use — skip with a reason, as tests/it/fonts.rs does. - if installed_faces_switched_off() { - eprintln!("skipping: PDFCRAFT_SYSTEM_FONTS=0 turns the loader off"); - return; - } - let inter = PathBuf::from(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/fonts/Inter-Regular.ttf")); - let candidates = [PathBuf::from("definitely/not/here.ttf"), inter]; - assert!(script_fallback(&candidates, 'A').is_some()); - assert!(script_fallback(&candidates, TELUGU_PROBE).is_none()); - assert!(script_fallback(&candidates, DEVANAGARI_PROBE).is_none()); - assert!(script_fallback(&candidates, HANGUL_PROBE).is_none()); - assert!(script_fallback(&candidates, SINHALA_PROBE).is_none()); - assert!(script_fallback(&candidates, TAMIL_PROBE).is_none()); - assert!(script_fallback(&candidates, HEBREW_PROBE).is_none()); - } - - #[test] - fn script_candidates_are_absolute_font_files() { - for list in [devanagari_candidates(), telugu_candidates(), sinhala_candidates(), tamil_candidates(), hebrew_candidates(), hangul_candidates()] - { - assert!(!list.is_empty()); - assert!(list.iter().all(|p| p.is_absolute() || cfg!(windows)), "{list:?}"); - assert!(list.iter().all(|p| p.extension().is_some_and(|e| e == "ttf" || e == "ttc")), "{list:?}"); - } - } - - #[test] - fn hangul_candidates_are_font_files() { - let list = hangul_candidates(); - assert!(!list.is_empty()); - for path in list { - assert!(path.extension().is_some_and(|e| e == "ttf" || e == "ttc"), "{path:?}"); - } - // Inter has no Hangul. - let inter = include_bytes!("../../../../assets/fonts/Inter-Regular.ttf"); - assert_eq!(face_with(inter, HANGUL_PROBE), None); - } - - /// Retune tripwires, deliberately separate from `the_macos_devanagari_list_is_apples_layout` below: these assert that three - /// constants still hold the values this module's contract depends on. They cannot fail on their - /// own — they exist so that editing one is a decision someone has to make twice. Each was - /// checked by deleting the pin and watching the matching regression go green again: raising - /// `MAX_BYTES` above Arial Unicode's ~23 MB, swapping the Devanagari probe for Arabic `U+0627` - /// (which that face also covers, so every other test stays green), and cutting `MAX_FACES` to 1. - /// The oracle in the macOS test below also depends on all three, and it is conditional on - /// installation — so on CI these are the only guard. - #[test] - fn the_load_constants_are_the_documented_contract() { - assert_eq!(MAX_BYTES, 32 << 20, "the non-Han installed-face size cap is this module's contract (Arial Unicode is ~23 MB)"); - assert_eq!(DEVANAGARI_PROBE, '\u{0915}', "Devanagari ka is what the Hindi candidates are probed for, not another script's letter"); - assert_eq!(MAX_FACES, 16, "how deep into a .ttc collection the loader looks; the macOS oracle trusts this depth"); - } - - /// The macOS Devanagari list, exactly: families best first, each tried in the system folder - /// before `Supplemental/`. This pins the spellings Apple uses on disk and the order that - /// decides which face wins. A missing space (`DevanagariSangamMN.ttc`), swapping the two - /// folders, or walking folder-major instead of family-major all fail here — and they fail on - /// every OS, because this test reads no filesystem. - #[test] - fn the_macos_devanagari_list_is_apples_layout() { - assert_eq!( - macos_devanagari_candidates(), - vec![ - PathBuf::from("/System/Library/Fonts/DevanagariMT.ttc"), - PathBuf::from("/System/Library/Fonts/Supplemental/DevanagariMT.ttc"), - PathBuf::from("/System/Library/Fonts/Devanagari Sangam MN.ttc"), - PathBuf::from("/System/Library/Fonts/Supplemental/Devanagari Sangam MN.ttc"), - PathBuf::from("/System/Library/Fonts/Kohinoor.ttc"), - PathBuf::from("/System/Library/Fonts/Supplemental/Kohinoor.ttc"), - PathBuf::from("/Library/Fonts/Arial Unicode.ttf"), - ] - ); - // Pin what the application actually consults, not just the helper that builds it. - #[cfg(target_os = "macos")] - assert_eq!(devanagari_candidates(), macos_devanagari_candidates(), "the app must consult the list this test pins"); - } - - #[test] - fn a_family_whose_name_has_spaces_is_still_found() { - let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.subsec_nanos()).unwrap_or(0); - let root = std::env::temp_dir().join(format!("pdfcraft-macos-fonts-{}-{nanos}", std::process::id())); - let supplemental = root.join("Supplemental"); - std::fs::create_dir_all(&supplemental).expect("build a temp macOS-shaped font tree"); - let dirs = [root.to_string_lossy().to_string(), supplemental.to_string_lossy().to_string()]; - let names: Vec<&str> = dirs.iter().map(|d| d.as_str()).collect(); - let inter: &[u8] = include_bytes!("../../../../assets/fonts/Inter-Regular.ttf"); - let spaced = "Devanagari Sangam MN.ttc"; - std::fs::write(supplemental.join(spaced), inter).expect("place a face at the spaced path"); - let found = macos_families_in(&names, &[spaced]).iter().any(|p| read(p, 'A', MAX_BYTES).is_some()); - let _ = std::fs::remove_dir_all(&root); - assert!(found, "a family named with spaces did not resolve under {dirs:?}"); - } - - /// On a Mac, where Apple's fonts are installed: every family folder that really exists is - /// reachable from the candidate list, and something in the list covers Devanagari. A family - /// Apple no longer ships is reported rather than failed — this list exists precisely for the case - /// where one of them is missing, with one exception: if *nothing* here covers Devanagari the test - /// fails loudly, because a machine with no face to check cannot validate the list at all. That - /// leniency is not a guess: Apple's "Fonts included with macOS Tahoe" page (support.apple.com/122869) - /// titles its list "Installed or downloadable fonts" and says most install automatically while - /// others download on demand via Font Book — without marking which is which, so no entry in these - /// lists can be assumed present on a given Mac. CI has no macOS runner (`.github/workflows/ci.yml` - /// keeps the org's Mac slots for release builds), so this runs on contributors' and - /// maintainers' machines. - #[cfg(target_os = "macos")] - #[test] - fn every_installed_devanagari_face_is_reachable_on_this_mac() { - if installed_faces_switched_off() { - eprintln!("skipping on this machine: PDFCRAFT_SYSTEM_FONTS=0 turns installed faces off"); - return; - } - let list = devanagari_candidates(); - for family in MACOS_DEVANAGARI_FAMILIES { - // Same rule as the last resort below: an entry that exists counts, even a link whose - // target has gone — "present but unresolved" is precisely the dead-path defect this change - // is about, and filtering on `is_file()` would quietly reclassify it as "not installed". - // Absence is tolerated; a broken entry is not. - let present: Vec = - MACOS_FONT_DIRS.iter().map(|dir| Path::new(dir).join(family)).filter(|p| std::fs::symlink_metadata(p).is_ok()).collect(); - if present.is_empty() { - eprintln!("{family}: not installed on this machine, so the list offers nothing that exists — fine, and reported only"); - continue; - } - for path in &present { - assert!( - path.is_file(), - "{family}: {path:?} exists but does not resolve — its target was moved or removed, so this candidate path has gone dead" - ); - assert!(list.contains(path), "{path:?} is installed here but the candidate list skips it: {list:?}"); - } - } - assert!(script_fallback(&devanagari_candidates(), DEVANAGARI_PROBE).is_some(), "no installed face on this Mac covers Devanagari"); - // And the function callers use, not just its inputs: asserting *some* face loads is not - // enough, because both lists end at the same last-resort Unicode face and would rescue a - // mix-up. The app-facing function must land on the same bytes, and the same face within - // them, as this list produces. - let direct = script_fallback(&devanagari_candidates(), DEVANAGARI_PROBE).expect("the list above resolves"); - let cached = devanagari_fallback().expect("devanagari_fallback() resolves where these faces are installed"); - assert_eq!(cached.bytes().len(), direct.bytes().len(), "devanagari_fallback() must load the face this list points at, not another script's"); - assert_eq!(cached.index, direct.index, "and the same face within that file"); - // The advertised last resort is the biggest file on the list and reaches its target through - // a compatibility symlink in `/Library/Fonts`, a folder installers and users may modify — so - // it is optional in the same sense the families above are, and a Mac without it must not go - // red for an unrelated reason. But `is_file()` follows symlinks: a link whose target has - // moved reads as "no file", which is exactly the dead-path defect this change exists to - // catch. So gate on the entry existing (lstat), then require that it resolves, then check - // size cap and coverage. `MAX_BYTES` is what the loader applies to non-Han scripts; the path - // comes from the list itself rather than being written out again, so this oracle cannot - // drift from what production offers. - let last_resort = list.last().expect("the macOS Devanagari list always ends at the Unicode face").clone(); - assert!( - last_resort.to_string_lossy().ends_with("Arial Unicode.ttf"), - "this block checks the Unicode last resort, so the list must still end at it: {last_resort:?}" - ); - if std::fs::symlink_metadata(&last_resort).is_ok() { - assert!( - last_resort.is_file(), - "{last_resort:?} exists but does not resolve — its target was moved or removed, so this path has gone dead" - ); - assert!( - read(&last_resort, DEVANAGARI_PROBE, MAX_BYTES).is_some(), - "the last-resort Unicode face is installed here but did not resolve and load under MAX_BYTES" - ); - } else { - eprintln!("{last_resort:?} is not installed on this machine — optional to the loader, so nothing to check"); - } - } - - #[test] - fn macos_simplified_prefers_pingfang_ui_over_hiragino() { - let list = macos_han_candidates(false); - let pos = |name: &str| list.iter().position(|p| p.ends_with(name)); - assert_eq!(pos("PingFang.ttc"), Some(0)); - assert_eq!(list[1], PathBuf::from(MACOS_PINGFANG_UI)); - assert!(pos("PingFangUI.ttc") < pos("Hiragino Sans GB.ttc")); - } - - #[test] - fn macos_traditional_keeps_stheiti_ahead_of_pingfang_ui() { - let list = macos_han_candidates(true); - let pos = |name: &str| list.iter().position(|p| p.ends_with(name)); - assert!(pos("STHeiti Medium.ttc") < pos("PingFangUI.ttc")); - assert!(pos("PingFangUI.ttc").is_some()); - } -} diff --git a/crates/ui-egui/src/platform/system_fonts/fontconfig.rs b/crates/ui-egui/src/platform/system_fonts/fontconfig.rs deleted file mode 100644 index 243fec68da..0000000000 --- a/crates/ui-egui/src/platform/system_fonts/fontconfig.rs +++ /dev/null @@ -1,329 +0,0 @@ -//! Discover font files in configured directories, including Nix store paths. -//! -//! Only the existing fallback filenames are selected by the caller. Font bytes are still -//! checked for size and glyph coverage there; no font is copied or embedded. - -use std::collections::HashSet; -use std::io::Read as _; -use std::path::{Path, PathBuf}; - -// A configured directory may contain unrelated files or symlink cycles. Bound the walk. -const MAX_ENTRIES: usize = 32_768; -const MAX_DEPTH: usize = 16; -const MAX_CONFIGS: usize = 256; -const MAX_CONFIG_BYTES: u64 = 1024 * 1024; - -#[derive(Default)] -struct Directories { - dirs: Vec, - seen: HashSet, - entries: usize, -} - -impl Directories { - fn include(&mut self, path: &Path, depth: usize) { - if depth > MAX_DEPTH || self.seen.len() >= MAX_CONFIGS { - return; - } - let Ok(canonical) = path.canonicalize() else { return }; - if self.seen.contains(&canonical) { - return; - } - if canonical.is_dir() { - self.seen.insert(canonical); - let Ok(entries) = std::fs::read_dir(path) else { return }; - let mut configs = Vec::new(); - for entry in entries { - if self.entries >= MAX_ENTRIES { - break; - } - self.entries += 1; - let Ok(entry) = entry else { continue }; - // Fontconfig directory includes accept digit-prefixed *.conf only. - let name = entry.file_name(); - let Some(name) = name.to_str() else { continue }; - if name.as_bytes().first().is_some_and(u8::is_ascii_digit) && name.ends_with(".conf") && entry.path().is_file() { - configs.push(entry.path()); - } - } - configs.sort(); - for config in configs { - self.include(&config, depth + 1); - } - return; - } - if !canonical.is_file() { - return; - } - self.seen.insert(canonical); - let Ok(file) = std::fs::File::open(path) else { return }; - let mut bytes = Vec::new(); - if file.take(MAX_CONFIG_BYTES + 1).read_to_end(&mut bytes).is_err() || bytes.len() as u64 > MAX_CONFIG_BYTES { - return; - } - let Ok(xml) = String::from_utf8(bytes) else { return }; - let parts = match fontconfig_parser::parse_config_parts(&xml) { - Ok(parts) => parts, - Err(error) => { - log::debug!("interface font directories: {}: {error}", path.display()); - return; - } - }; - for part in parts { - use fontconfig_parser::{ConfigPart, DirPrefix}; - match part { - ConfigPart::Dir(dir) if self.dirs.len() < MAX_ENTRIES => self.dirs.push(dir.calculate_path(path)), - ConfigPart::ResetDirs => self.dirs.clear(), - ConfigPart::Include(mut include) => { - // The dependency's default include prefix hardcodes /etc/fonts. - // Resolve relative to this file, including nested and FONTCONFIG_PATH configs. - if include.prefix == DirPrefix::Default { - include.prefix = DirPrefix::Relative; - } - self.include(&include.calculate_path(path), depth + 1); - } - _ => {} - } - } - } -} - -pub(super) fn config_path() -> PathBuf { - let file = std::env::var_os("FONTCONFIG_FILE").map_or_else(|| PathBuf::from("fonts.conf"), PathBuf::from); - if file.is_absolute() { - return file; - } - let dir = - std::env::var_os("FONTCONFIG_PATH").and_then(|paths| std::env::split_paths(&paths).next()).unwrap_or_else(|| PathBuf::from("/etc/fonts")); - dir.join(file) -} - -pub(super) fn font_files(config_path: &Path) -> Vec { - // Use the dependency's XML parser, but own include resolution and directory filtering. - // Missing or malformed configuration must not prevent the ordinary fallback paths. - let mut config = Directories::default(); - config.include(config_path, 0); - let mut pending: Vec<_> = config.dirs.into_iter().map(|dir| (dir, 0)).collect(); - let mut seen = HashSet::new(); - let mut files = Vec::new(); - let mut remaining = MAX_ENTRIES; - while let Some((dir, depth)) = pending.pop() { - let Ok(canonical) = dir.canonicalize() else { continue }; - if !seen.insert(canonical) { - continue; - } - let Ok(entries) = std::fs::read_dir(&dir) else { continue }; - for entry in entries { - if remaining == 0 { - files.sort(); - return files; - } - remaining -= 1; - let Ok(entry) = entry else { continue }; - let path = entry.path(); - // Follow links to fonts and directories, but visit each directory only once. - if path.is_dir() { - if depth < MAX_DEPTH { - pending.push((path, depth + 1)); - } - } else if path.extension().is_some_and(|ext| ext == "ttf" || ext == "ttc") && path.is_file() { - files.push(path); - } - } - } - files.sort(); - files -} - -#[cfg(test)] -mod tests { - use super::*; - - // Fixtures contain only configuration and dummy files, never copied system fonts. - struct Fixture(PathBuf); - - impl Fixture { - fn new() -> Self { - static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); - let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed); - let dir = std::env::temp_dir().join(format!("pdfcraft-fontconfig-{}-{n}", std::process::id())); - std::fs::create_dir(&dir).unwrap(); - Self(dir) - } - - fn config(&self, name: &str, body: &str) -> PathBuf { - let path = self.0.join(name); - std::fs::write(&path, format!("{body}")).unwrap(); - path - } - - fn isolated(&self, test: &str) { - // Environment selection is process-global: never mutate it in a parallel harness. - let output = std::process::Command::new(std::env::current_exe().unwrap()) - .args(["--exact", &format!("platform::system_fonts::fontconfig::tests::{test}"), "--nocapture"]) - .env("FONTCONFIG_PATH", &self.0) - .env("FONTCONFIG_FILE", "fonts.conf") - .env("PDFCRAFT_FONTCONFIG_TEST_ROOT", &self.0) - .output() - .unwrap(); - assert!(output.status.success(), "{}\n{}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr)); - assert!(String::from_utf8_lossy(&output.stdout).contains("1 passed")); - } - - fn font(&self) -> PathBuf { - let dir = self.0.join("fonts"); - std::fs::create_dir(&dir).unwrap(); - let font = dir.join("DejaVuSans.ttf"); - std::fs::write(&font, b"dummy font for directory discovery").unwrap(); - font - } - } - - impl Drop for Fixture { - fn drop(&mut self) { - let _ = std::fs::remove_dir_all(&self.0); - } - } - - #[test] - fn relative_includes_follow_each_including_config_under_fontconfig_path() { - if let Some(root) = std::env::var_os("PDFCRAFT_FONTCONFIG_TEST_ROOT") { - let root = PathBuf::from(root); - assert_eq!(config_path(), root.join("fonts.conf")); - assert_eq!(font_files(&config_path()), vec![root.join("fonts/DejaVuSans.ttf")]); - return; - } - let fixture = Fixture::new(); - fixture.font(); - std::fs::create_dir(fixture.0.join("conf.d")).unwrap(); - std::fs::create_dir(fixture.0.join("nested")).unwrap(); - fixture.config("fonts.conf", "conf.d"); - fixture.config("conf.d/10-fonts.conf", "../nested/next.conf"); - fixture.config("nested/next.conf", &format!("{}", fixture.0.join("fonts").display())); - fixture.isolated("relative_includes_follow_each_including_config_under_fontconfig_path"); - } - - #[test] - fn included_directories_ignore_disabled_backup_and_non_numbered_files() { - if let Some(root) = std::env::var_os("PDFCRAFT_FONTCONFIG_TEST_ROOT") { - let root = PathBuf::from(root); - assert_eq!(font_files(&config_path()), vec![root.join("fonts/DejaVuSans.ttf")]); - return; - } - for name in ["99-reset.conf.disabled", "99-reset.conf.bak", "reset.conf"] { - let fixture = Fixture::new(); - fixture.font(); - std::fs::create_dir(fixture.0.join("conf.d")).unwrap(); - fixture.config("fonts.conf", &format!("{}", fixture.0.join("conf.d").display())); - fixture.config("conf.d/10-fonts.conf", &format!("{}", fixture.0.join("fonts").display())); - fixture.config(&format!("conf.d/{name}"), ""); - fixture.isolated("included_directories_ignore_disabled_backup_and_non_numbered_files"); - } - } - - #[test] - fn numbered_configs_keep_lexical_reset_order_and_include_cycles_terminate() { - let fixture = Fixture::new(); - let font = fixture.font(); - std::fs::create_dir(fixture.0.join("conf.d")).unwrap(); - let config = fixture.config("fonts.conf", "conf.d"); - fixture.config("conf.d/10-reset.conf", ""); - let external = fixture.config("external.conf", &format!("{}../fonts.conf", fixture.0.join("fonts").display())); - std::os::unix::fs::symlink(external, fixture.0.join("conf.d/20-fonts.conf")).unwrap(); - assert_eq!(font_files(&config), vec![font]); - fixture.config("conf.d/30-reset.conf", ""); - assert!(font_files(&config).is_empty()); - } - - #[test] - fn oversized_configs_are_skipped_without_losing_other_includes() { - let fixture = Fixture::new(); - let font = fixture.font(); - std::fs::create_dir(fixture.0.join("conf.d")).unwrap(); - let config = fixture.config("fonts.conf", "conf.d"); - std::fs::write(fixture.0.join("conf.d/10-large.conf"), vec![b' '; (MAX_CONFIG_BYTES + 1) as usize]).unwrap(); - fixture.config("conf.d/20-fonts.conf", &format!("{}", fixture.0.join("fonts").display())); - assert_eq!(font_files(&config), vec![font]); - } - - #[test] - fn deep_include_chains_are_bounded() { - let fixture = Fixture::new(); - fixture.font(); - for depth in 0..=MAX_DEPTH + 1 { - let body = if depth > MAX_DEPTH { - format!("{}", fixture.0.join("fonts").display()) - } else { - format!("depth-{}.conf", depth + 1) - }; - fixture.config(&format!("depth-{depth}.conf"), &body); - } - assert!(font_files(&fixture.0.join("depth-0.conf")).is_empty()); - } - - #[test] - fn wide_include_directories_are_bounded() { - let fixture = Fixture::new(); - fixture.font(); - std::fs::create_dir(fixture.0.join("conf.d")).unwrap(); - let config = fixture.config("fonts.conf", "conf.d"); - for n in 0..MAX_CONFIGS { - fixture.config(&format!("conf.d/{n:04}-empty.conf"), ""); - } - fixture.config("conf.d/9999-fonts.conf", &format!("{}", fixture.0.join("fonts").display())); - assert!(font_files(&config).is_empty()); - } - - #[test] - fn included_configuration_finds_fonts_outside_standard_directories() { - let fixture = Fixture::new(); - let fonts = fixture.0.join("nix-store-font/share/fonts/truetype"); - std::fs::create_dir_all(&fonts).unwrap(); - let font = fonts.join("DejaVuSans.ttf"); - std::fs::write(&font, b"not parsed during discovery").unwrap(); - std::fs::write(fonts.join("README.txt"), b"not a font").unwrap(); - let included = fixture.config("nixos.conf", &format!("{}", fixture.0.join("nix-store-font").display())); - let config = fixture.config("fonts.conf", &format!("{}", included.display())); - assert_eq!(font_files(&config), vec![font]); - } - - #[test] - fn missing_and_malformed_configuration_are_skipped() { - let fixture = Fixture::new(); - assert!(font_files(&fixture.0.join("missing.conf")).is_empty()); - let path = fixture.0.join("broken.conf"); - std::fs::write(&path, "").unwrap(); - assert!(font_files(&path).is_empty()); - } - - #[test] - fn symlinked_fonts_are_found_and_directory_cycles_terminate() { - let fixture = Fixture::new(); - let fonts = fixture.0.join("fonts"); - std::fs::create_dir(&fonts).unwrap(); - let original = fixture.0.join("original.ttf"); - std::fs::write(&original, b"dummy").unwrap(); - let linked = fonts.join("DejaVuSans.ttf"); - std::os::unix::fs::symlink(&original, &linked).unwrap(); - std::os::unix::fs::symlink(&fonts, fonts.join("loop")).unwrap(); - std::os::unix::fs::symlink(fixture.0.join("missing.ttf"), fonts.join("broken.ttf")).unwrap(); - let config = fixture.config("fonts.conf", &format!("{}{}", fonts.display(), fonts.display())); - assert_eq!(font_files(&config), vec![linked]); - } - - #[test] - fn deeply_nested_directories_are_bounded() { - let fixture = Fixture::new(); - let mut dir = fixture.0.join("fonts"); - std::fs::create_dir(&dir).unwrap(); - let shallow = dir.join("DejaVuSans.ttf"); - std::fs::write(&shallow, b"dummy").unwrap(); - for _ in 0..MAX_DEPTH + 1 { - dir.push("nested"); - std::fs::create_dir(&dir).unwrap(); - } - std::fs::write(dir.join("DejaVuSans.ttf"), b"dummy").unwrap(); - let config = fixture.config("fonts.conf", &format!("{}", fixture.0.join("fonts").display())); - assert_eq!(font_files(&config), vec![shallow]); - } -} diff --git a/crates/ui-egui/src/platform/ui_scale.rs b/crates/ui-egui/src/platform/ui_scale.rs index 69fc3aebed..3df755944b 100644 --- a/crates/ui-egui/src/platform/ui_scale.rs +++ b/crates/ui-egui/src/platform/ui_scale.rs @@ -57,19 +57,6 @@ pub fn percent(factor: f32) -> u32 { (factor * 100.0).round().clamp(0.0, 1000.0) as u32 } -/// Draw at `factor` from the next frame on, when it differs from the factor last applied -/// (`applied`), so a zoom set elsewhere (a test harness's `pixels_per_point`) isn't undone every -/// frame. egui's own ⌘+/⌘−/⌘0 interface zoom stays off: those keys zoom the page, and the -/// preference alone decides the interface size. -pub fn sync(ctx: &egui::Context, factor: f32, applied: &mut Option) { - if applied.is_none() { - ctx.options_mut(|o| o.zoom_with_keyboard = false); - } - if *applied != Some(factor) { - ctx.set_zoom_factor(factor); - *applied = Some(factor); - } -} #[cfg(test)] mod tests { @@ -110,28 +97,17 @@ mod tests { } } - #[test] - fn sync_sets_the_zoom_and_turns_off_keyboard_zoom() { - let ctx = egui::Context::default(); - let mut applied = None; - sync(&ctx, 1.25, &mut applied); - assert_eq!(applied, Some(1.25)); - // A bare context's first frame uploads the font atlas; nothing paints it here. - ctx.run_ui(egui::RawInput::default(), |_| {}).textures_delta.clear(); - assert_eq!(ctx.zoom_factor(), 1.25); - assert!(!ctx.options(|o| o.zoom_with_keyboard)); - } - #[test] fn the_app_draws_at_the_system_scale_until_a_size_is_chosen() { // A display that reports 200% (#456: a 1080p screen whose system reports 2×). - let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1000.0, 700.0)).with_pixels_per_point(2.0).build_eframe(|_cc| { - let mut app = crate::PdfCraftApp::new(); - app.system_text_scale = 1.25; - app - }); + // PLAN: framework gap F-12: the harness's `SystemReader` has no text-scale setter, so Auto is checked at the + // display's scale alone until the lead rewires it. + let mut h = egui_kittest::Harness::builder() + .with_size(egui::vec2(1000.0, 700.0)) + .with_pixels_per_point(2.0) + .build_eframe(|_cc| crate::PdfCraftApp::new()); h.run_steps(3); - assert_eq!(h.ctx.pixels_per_point(), 2.5, "Auto follows the display's scale and the system's text scale"); + assert_eq!(h.ctx.pixels_per_point(), 2.0, "Auto follows the display's scale"); h.state_mut().set_option("ui-scale", "100%").expect("a valid size"); h.run_steps(3); assert_eq!(h.ctx.pixels_per_point(), 1.0, "100% is one screen pixel per point"); @@ -140,14 +116,15 @@ mod tests { assert_eq!(h.ctx.pixels_per_point(), 1.5); assert!(h.state_mut().set_option("ui-scale", "5000").is_err()); // The chosen size survives a restart; a hostile one in the settings follows the system. - let saved = h.state().persist(); - let mut restored = crate::PdfCraftApp::new(); - restored.restore(&saved); - assert_eq!(restored.ui_scale, Some(1.5)); - restored.restore(&saved.replace("\"ui_scale\":1.5", "\"ui_scale\":1e30")); - assert_eq!(restored.ui_scale, None); + let saved = h.state().settings_snapshot(); + h.state_mut().apply_settings(&saved); + h.run_steps(3); + assert_eq!(h.ctx.pixels_per_point(), 1.5, "the saved size is restored"); + h.state_mut().apply_settings(&crate::app::settings::import_json(r#"{"ui_scale":1e30}"#).0); + h.run_steps(3); + assert_eq!(h.ctx.pixels_per_point(), 2.0, "a hostile saved size is no choice"); h.state_mut().set_option("ui-scale", "auto").expect("auto"); h.run_steps(3); - assert_eq!(h.ctx.pixels_per_point(), 2.5); + assert_eq!(h.ctx.pixels_per_point(), 2.0); } } diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs deleted file mode 100644 index c3ce3e0e59..0000000000 --- a/crates/ui-egui/src/theme.rs +++ /dev/null @@ -1,542 +0,0 @@ -//! Design tokens and egui style (plan/acrobat/02-ui-ux.md §1: neutral chrome, white panels, -//! one blue accent; Dark Gray keeps pages white). Every custom widget reads `Tokens::get`. - -use std::sync::Arc; - -use egui::epaint::text::{FallbackAlign, FontTweak, HintingTarget, SmoothHinting}; -use egui::{Color32, CornerRadius, FontData, FontDefinitions, FontFamily, FontId, Rect, Response, Stroke, Vec2, Visuals}; - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)] -pub enum ThemeKind { - #[default] - Light, - Dark, -} - -/// The saved user choice, independent of the light/dark colours currently displayed. A fresh -/// install follows the system (#1248); a desktop that says nothing gets Light. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)] -pub enum ThemePreference { - #[default] - System, - Light, - Dark, -} - -impl ThemePreference { - /// The colours to draw. `system` is what the operating system says, `None` when it says - /// nothing; `fallback` is supplied by the caller. PdfCraft uses Light for an unknown desktop. - pub fn resolve(self, system: Option, fallback: ThemeKind) -> ThemeKind { - match self { - Self::Light => ThemeKind::Light, - Self::Dark => ThemeKind::Dark, - Self::System => match system { - Some(true) => ThemeKind::Dark, - Some(false) => ThemeKind::Light, - None => fallback, - }, - } - } -} - -#[derive(Clone, Copy, Debug)] -pub struct Tokens { - pub kind: ThemeKind, - /// Title/tab strip. - pub titlebar: Color32, - /// Mode bar, panels. - pub chrome: Color32, - pub panel: Color32, - /// Document area behind pages. - pub pasteboard: Color32, - pub card: Color32, - pub border: Color32, - pub divider: Color32, - pub text: Color32, - pub text_muted: Color32, - pub text_faint: Color32, - pub icon: Color32, - pub hover: Color32, - pub pressed: Color32, - pub selected: Color32, - pub accent: Color32, - pub accent_text: Color32, - pub accent_soft: Color32, - pub field: Color32, - pub badge_new: Color32, - pub page_shadow: Color32, - pub radius: u8, -} - -impl Tokens { - pub fn for_kind(kind: ThemeKind) -> Self { - match kind { - ThemeKind::Light => Self { - kind, - titlebar: Color32::from_rgb(0xE9, 0xE9, 0xEB), - chrome: Color32::from_rgb(0xFF, 0xFF, 0xFF), - panel: Color32::from_rgb(0xFF, 0xFF, 0xFF), - pasteboard: Color32::from_rgb(0xF1, 0xF1, 0xF3), - card: Color32::from_rgb(0xFF, 0xFF, 0xFF), - border: Color32::from_rgb(0xDA, 0xDA, 0xDE), - divider: Color32::from_rgb(0xE8, 0xE8, 0xEB), - text: Color32::from_rgb(0x22, 0x22, 0x26), - text_muted: Color32::from_rgb(0x5E, 0x5E, 0x66), - text_faint: Color32::from_rgb(0x6B, 0x6B, 0x73), - icon: Color32::from_rgb(0x44, 0x44, 0x4B), - hover: Color32::from_rgb(0xF0, 0xF0, 0xF3), - pressed: Color32::from_rgb(0xE4, 0xE4, 0xE9), - selected: Color32::from_rgb(0xE6, 0xEE, 0xFD), - accent: Color32::from_rgb(0x1B, 0x63, 0xE0), - accent_text: Color32::from_rgb(0x17, 0x55, 0xC4), - accent_soft: Color32::from_rgb(0xE3, 0xEC, 0xFD), - field: Color32::from_rgb(0xFF, 0xFF, 0xFF), - badge_new: Color32::from_rgb(0x1B, 0x63, 0xE0), - page_shadow: Color32::from_black_alpha(34), - radius: 6, - }, - ThemeKind::Dark => Self { - kind, - titlebar: Color32::from_rgb(0x1B, 0x1B, 0x1E), - chrome: Color32::from_rgb(0x26, 0x26, 0x2A), - panel: Color32::from_rgb(0x26, 0x26, 0x2A), - pasteboard: Color32::from_rgb(0x19, 0x19, 0x1C), - card: Color32::from_rgb(0x2E, 0x2E, 0x33), - border: Color32::from_rgb(0x3C, 0x3C, 0x43), - divider: Color32::from_rgb(0x33, 0x33, 0x39), - text: Color32::from_rgb(0xEC, 0xEC, 0xEF), - text_muted: Color32::from_rgb(0xAE, 0xAE, 0xB6), - text_faint: Color32::from_rgb(0x97, 0x97, 0x9E), - icon: Color32::from_rgb(0xD4, 0xD4, 0xDA), - hover: Color32::from_rgb(0x34, 0x34, 0x3A), - pressed: Color32::from_rgb(0x3E, 0x3E, 0x45), - selected: Color32::from_rgb(0x23, 0x3A, 0x63), - accent: Color32::from_rgb(0x4B, 0x8B, 0xF5), - accent_text: Color32::from_rgb(0x8C, 0xB6, 0xFA), - accent_soft: Color32::from_rgb(0x24, 0x36, 0x57), - field: Color32::from_rgb(0x1E, 0x1E, 0x22), - badge_new: Color32::from_rgb(0x3D, 0x7D, 0xEE), - page_shadow: Color32::from_black_alpha(120), - radius: 6, - }, - } - } - - /// Return the cached theme tokens, falling back to the light palette before the first apply. - pub fn get(ctx: &egui::Context) -> Self { - ctx.data(|d| d.get_temp::(egui::Id::unique("pdfcraft-theme"))).unwrap_or_else(|| Self::for_kind(ThemeKind::Light)) - } - - pub fn dark(&self) -> bool { - self.kind == ThemeKind::Dark - } -} - -/// Hover and press amounts for chrome controls. The wash eases in; holding the pointer -/// darkens it and drops the content one pixel, so a click reads as a key settling. -#[derive(Clone, Copy, Debug)] -pub struct Press { - pub hover: f32, - pub down: f32, -} - -impl Press { - pub fn track(ui: &egui::Ui, resp: &Response) -> Self { - let hot = resp.hovered() || resp.is_pointer_button_down_on(); - let ease = egui::emath::easing::quadratic_out; - // With animation effects off the wash and the press are simply there. - let (hover, down) = if crate::motion::animated(ui.ctx()) { (0.12, 0.06) } else { (0.0, 0.0) }; - Self { - hover: ui.ctx().animate_bool_with_time_and_easing(resp.id.with("chrome-hover"), hot, hover, ease), - down: ui.ctx().animate_bool_with_time_and_easing(resp.id.with("chrome-down"), resp.is_pointer_button_down_on(), down, ease), - } - } - - pub fn fill(self, rest: Color32, hover: Color32, pressed: Color32) -> Color32 { - rest.lerp_to_gamma(hover, self.hover).lerp_to_gamma(pressed, self.down) - } - - /// One pixel down at a full press. - pub fn offset(self) -> Vec2 { - Vec2::new(0.0, self.down) - } - - /// The colour [`Self::wash`] paints. - pub fn wash_color(self, t: &Tokens, selected: bool) -> Color32 { - if selected { - self.fill(t.accent_soft, t.accent_soft.lerp_to_gamma(t.accent, 0.16), t.selected) - } else { - self.fill(Color32::TRANSPARENT, t.hover, t.pressed) - } - } - - /// Soft wash behind a control. `selected` keeps the accent fill. - pub fn wash(self, ui: &egui::Ui, rect: Rect, radius: impl Into, selected: bool) { - let fill = self.wash_color(&Tokens::get(ui.ctx()), selected); - if fill.a() > 0 { - ui.painter().rect_filled(rect, radius, fill); - } - } -} - -/// Pointing hand, the cursor for a control that clicks. -pub fn hand(resp: Response) -> Response { - resp.on_hover_cursor(egui::CursorIcon::PointingHand) -} - -pub fn install_fonts(ctx: &egui::Context) { - install_fonts_for(ctx, CjkPreference::Default); -} - -/// The interface language's claim on the CJK fallback faces. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub enum CjkPreference { - /// Japanese faces first (every non-Chinese language). - #[default] - Default, - SimplifiedChinese, - TraditionalChinese, -} - -impl CjkPreference { - /// The preference for a UI language code (`zh-hans`, `zh-hant`, anything else). - pub fn for_language(code: &str) -> Self { - match code { - "zh-hans" => Self::SimplifiedChinese, - "zh-hant" => Self::TraditionalChinese, - _ => Self::Default, - } - } -} - -/// Install the interface fonts with the CJK fallback order for the UI language (Chinese -/// first for Chinese, Japanese first otherwise). Call it when the language changes; the new -/// faces take effect next frame. -pub fn install_fonts_for(ctx: &egui::Context, cjk: CjkPreference) { - ctx.set_fonts(installed_font_definitions(cjk)); -} - -/// The name of the installed face [`installed_font_definitions`] may add after the embedded ones. -pub const SYSTEM_FALLBACK: &str = "system-fallback"; -/// The name of the installed Devanagari (Hindi) face [`installed_font_definitions`] may add. -pub const SYSTEM_DEVANAGARI_FALLBACK: &str = "system-devanagari-fallback"; -/// The name of the installed Telugu face [`installed_font_definitions`] may add. -pub const SYSTEM_TELUGU_FALLBACK: &str = "system-telugu-fallback"; -/// The name of the installed Sinhala face [`installed_font_definitions`] may add. -pub const SYSTEM_SINHALA_FALLBACK: &str = "system-sinhala-fallback"; -/// The name of the installed Tamil face [`installed_font_definitions`] may add. -pub const SYSTEM_TAMIL_FALLBACK: &str = "system-tamil-fallback"; -/// The name of the installed Hebrew face [`installed_font_definitions`] may add. -pub const SYSTEM_HEBREW_FALLBACK: &str = "system-hebrew-fallback"; -/// The name of the installed Hangul (Korean) face [`installed_font_definitions`] may add. -pub const SYSTEM_HANGUL_FALLBACK: &str = "system-hangul-fallback"; - -/// Which installed face an interface language needs, given whether the build embeds a `Hans` -/// face. -/// -/// A bundled `Hans` face serves Simplified Chinese, so the installed face stays last there. It -/// cannot serve Traditional Chinese: a Traditional interface keeps an installed `Hant` face -/// before the Japanese faces even when a Simplified-only face is embedded, or Traditional-only -/// characters would fall through to a Japanese face first. -#[cfg(not(target_arch = "wasm32"))] -fn installed_fallback_need(cjk: CjkPreference, has_embedded_hans: bool) -> crate::system_fonts::Need { - use crate::system_fonts::Need; - match cjk { - CjkPreference::SimplifiedChinese if has_embedded_hans => Need::Other, - CjkPreference::SimplifiedChinese => Need::Hans, - CjkPreference::TraditionalChinese => Need::Hant, - CjkPreference::Default => Need::Other, - } -} - -/// What [`install_fonts_for`] installs: [`font_definitions_for`], then, on desktop, one face -/// already installed on this machine. It only draws characters no embedded face has. -/// -/// - In a Simplified Chinese interface built without an embedded `Hans` face (#826), it is a -/// Simplified Chinese system face (Microsoft YaHei, PingFang SC, …), placed before the Japanese -/// craft-fonts faces: they lack hundreds of the catalog's characters (欢, 导, 签, …), and one -/// line drawn from two faces with different vertical metrics would not sit on one baseline. -/// - A Traditional Chinese interface always uses an installed `Hant` face before the Japanese -/// faces, even when a Simplified-only `Hans` face is embedded: that face cannot supply -/// Traditional-only characters (說, 體, …). -/// - Otherwise it is the last fallback of every family (an Arabic file name in a build without -/// craft-fonts). -/// -/// Installed Devanagari, Telugu, Sinhala, Tamil, Hebrew and Hangul faces, when there are, end -/// every family just before that one, so Hindi, Telugu (#1531), Sinhala and Tamil (#1688) and -/// Korean text, such as a file name or a tab title, and Hebrew file names (#586) draw in a build -/// without such faces. -/// -/// `PDFCRAFT_SYSTEM_FONTS=0` leaves them out. -pub fn installed_font_definitions(cjk: CjkPreference) -> FontDefinitions { - #[cfg_attr(target_arch = "wasm32", expect(unused_mut))] - let mut fonts = font_definitions_for(cjk == CjkPreference::SimplifiedChinese); - #[cfg(not(target_arch = "wasm32"))] - { - use crate::system_fonts::{Need, fallback}; - // Before the general installed face, which stays the last fallback outside Chinese. - for (name, data) in [ - (SYSTEM_DEVANAGARI_FALLBACK, crate::system_fonts::devanagari_fallback()), - (SYSTEM_TELUGU_FALLBACK, crate::system_fonts::telugu_fallback()), - (SYSTEM_SINHALA_FALLBACK, crate::system_fonts::sinhala_fallback()), - (SYSTEM_TAMIL_FALLBACK, crate::system_fonts::tamil_fallback()), - (SYSTEM_HEBREW_FALLBACK, crate::system_fonts::hebrew_fallback()), - (SYSTEM_HANGUL_FALLBACK, crate::system_fonts::hangul_fallback()), - ] { - let Some(data) = data else { continue }; - fonts.font_data.insert(name.to_owned(), data); - for stack in fonts.families.values_mut() { - stack.push(name.to_owned()); - } - } - let need = installed_fallback_need(cjk, !pdfcraft_fonts::ui_chinese_fonts().is_empty()); - if let Some(data) = fallback(need) { - fonts.font_data.insert(SYSTEM_FALLBACK.to_owned(), data); - let japanese: Vec = pdfcraft_fonts::ui_japanese_fonts().iter().map(|f| f.name()).collect(); - for stack in fonts.families.values_mut() { - let at = match need { - Need::Other => None, - Need::Hans | Need::Hant => stack.iter().position(|n| japanese.contains(n)), - }; - stack.insert(at.unwrap_or(stack.len()), SYSTEM_FALLBACK.to_owned()); - } - } - } - fonts -} - -/// The interface fonts: Inter (and JetBrains Mono for code) first, then egui's defaults, then -/// the CJK, Arabic, Telugu, Hebrew and Thai faces of the optional craft-fonts build input as the -/// last fallback in every family. Without craft-fonts there is no Japanese, Chinese, Arabic, -/// Telugu, Hebrew or Thai face here. -pub fn font_definitions() -> FontDefinitions { - font_definitions_for(false) -} - -/// [`font_definitions`] with the CJK fallback order for the UI language. Simplified Chinese -/// must come first in Chinese mode: otherwise shared characters render in the Japanese face -/// while Simplified-only characters (e.g. U+6B22 欢) fall through to the Chinese face, and -/// the mixed vertical metrics sink them below the line. -pub fn font_definitions_for(prefer_hans: bool) -> FontDefinitions { - font_definitions_for_platform(prefer_hans, current_font_policy_platform()) -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum FontPolicyPlatform { - Windows, - Other, -} - -fn current_font_policy_platform() -> FontPolicyPlatform { - if cfg!(target_os = "windows") { FontPolicyPlatform::Windows } else { FontPolicyPlatform::Other } -} - -fn primary_font_tweak(platform: FontPolicyPlatform, name: &str) -> FontTweak { - let mut tweak = FontTweak::default(); - if platform == FontPolicyPlatform::Windows && name == "JetBrainsMono" { - tweak.hinting_target = HintingTarget::Smooth(SmoothHinting { symmetric_rendering: false, ..SmoothHinting::default() }); - } - tweak -} - -/// `data` with its glyphs placed on the row's baseline (#1676). epaint 0.37 otherwise centres a -/// fallback face's line box on the primary's, so Chinese next to Latin in one label sits higher or -/// lower than the Latin by a few percent of the font size, depending on the installed or embedded -/// face (PingFang, Microsoft JhengHei, LXGW WenKai Lite…). `FallbackAlign::Baseline` makes epaint -/// position every face's glyphs from the primary face's ascent, which is exactly the existing -/// baseline-alignment intent without metric-derived offsets that go stale across egui versions. -pub(crate) fn on_interface_baseline(mut data: FontData) -> FontData { - data.tweak.fallback_align = FallbackAlign::Baseline; - data -} - -fn font_definitions_for_platform(prefer_hans: bool, platform: FontPolicyPlatform) -> FontDefinitions { - let mut fonts = FontDefinitions::default(); - let add = |fonts: &mut FontDefinitions, name: &str, bytes: &'static [u8]| { - let data = FontData::from_static(bytes); - let data = if ["Inter", "Inter-Medium", "Inter-SemiBold", "JetBrainsMono"].contains(&name) { - data.tweak(primary_font_tweak(platform, name)) - } else { - on_interface_baseline(data) - }; - fonts.font_data.insert(name.to_owned(), Arc::new(data)); - }; - // Shared with typed signatures' fallback glyphs, so the font is embedded once. - add(&mut fonts, "Inter", pdfcraft_fonts::INTER_REGULAR); - add(&mut fonts, "Inter-Medium", include_bytes!("../../../assets/fonts/Inter-Medium.ttf")); - add(&mut fonts, "Inter-SemiBold", include_bytes!("../../../assets/fonts/Inter-SemiBold.ttf")); - add(&mut fonts, "JetBrainsMono", include_bytes!("../../../assets/fonts/JetBrainsMono-Regular.ttf")); - fonts.families.entry(FontFamily::Proportional).or_default().insert(0, "Inter".to_owned()); - fonts.families.entry(FontFamily::Monospace).or_default().insert(0, "JetBrainsMono".to_owned()); - // Keep missing Latin/Cyrillic letters in the app's own faces (for example Bulgarian ѝ, - // absent from JetBrains Mono), before egui's defaults or optional system/CJK fallbacks. - fonts.families.entry(FontFamily::Monospace).or_default().insert(1, "Inter".to_owned()); - // The same static bytes pdfcraft-fonts uses for Japanese/Chinese text in PDFs: one copy, not two. - for face in pdfcraft_fonts::ui_cjk_fonts(prefer_hans) { - let name = face.name(); - // Japanese and Chinese faces have distinct family names, so no collision here. - if !fonts.font_data.contains_key(&name) { - add(&mut fonts, &name, face.bytes); - } - for family in [FontFamily::Proportional, FontFamily::Monospace] { - fonts.families.entry(family).or_default().push(name.clone()); - } - } - // Arabic-script faces (file names, document titles), Telugu faces (the Telugu interface, - // file names), Hebrew faces (file names, text being edited), Thai faces and Devanagari faces - // (the Hindi interface) after the CJK ones; the ranges don't overlap. - for face in pdfcraft_fonts::ui_arabic_fonts() - .into_iter() - .chain(pdfcraft_fonts::ui_telugu_fonts()) - .chain(pdfcraft_fonts::ui_hebrew_fonts()) - .chain(pdfcraft_fonts::ui_thai_fonts()) - .chain(pdfcraft_fonts::ui_devanagari_fonts()) - { - let name = face.name(); - if !fonts.font_data.contains_key(&name) { - add(&mut fonts, &name, face.bytes); - } - for family in [FontFamily::Proportional, FontFamily::Monospace] { - let stack = fonts.families.entry(family).or_default(); - if !stack.contains(&name) { - stack.push(name.clone()); - } - } - } - let fallback: Vec = fonts.families[&FontFamily::Proportional].clone(); - for (fam, primary) in [("medium", "Inter-Medium"), ("semibold", "Inter-SemiBold")] { - let mut stack = vec![primary.to_owned()]; - stack.extend(fallback.iter().cloned()); - fonts.families.insert(FontFamily::Name(fam.into()), stack); - } - fonts -} - -pub fn regular(size: f32) -> FontId { - FontId::proportional(size) -} -pub fn medium(size: f32) -> FontId { - FontId::new(size, FontFamily::Name("medium".into())) -} -pub fn semibold(size: f32) -> FontId { - FontId::new(size, FontFamily::Name("semibold".into())) -} - -/// Install the palette, widget styling, text sizes and right-to-left flag for the chosen theme. -pub fn apply(ctx: &egui::Context, kind: ThemeKind) { - // Keep the native window inherited. A concrete egui theme pins macOS's - // NSWindow appearance and prevents winit from delivering ThemeChanged. - // Our saved choice owns the palette; both egui branches receive it below. - ctx.set_theme(egui::ThemePreference::System); - let rtl = crate::i18n::current().rtl(); - let t = Tokens::for_kind(kind); - ctx.data_mut(|d| d.insert_temp(egui::Id::unique("pdfcraft-theme"), t)); - let mut v = if t.dark() { Visuals::dark() } else { Visuals::light() }; - v.panel_fill = t.panel; - v.window_fill = t.card; - v.window_stroke = Stroke::new(1.0, t.border); - v.extreme_bg_color = t.field; - v.faint_bg_color = t.hover; - v.selection.bg_fill = t.accent_soft; - v.selection.stroke = Stroke::new(1.0, t.accent); - v.hyperlink_color = t.accent_text; - v.override_text_color = Some(t.text); - v.window_corner_radius = CornerRadius::same(10); - v.menu_corner_radius = CornerRadius::same(8); - v.window_shadow = egui::Shadow { offset: [0, 8], blur: 28, spread: 0, color: Color32::from_black_alpha(if t.dark() { 110 } else { 38 }) }; - v.popup_shadow = egui::Shadow { offset: [0, 4], blur: 16, spread: 0, color: Color32::from_black_alpha(if t.dark() { 90 } else { 30 }) }; - for w in [&mut v.widgets.noninteractive, &mut v.widgets.inactive, &mut v.widgets.hovered, &mut v.widgets.active, &mut v.widgets.open] { - w.corner_radius = CornerRadius::same(t.radius); - w.fg_stroke.color = t.text; - } - v.widgets.noninteractive.bg_stroke = Stroke::new(1.0, t.divider); - v.widgets.inactive.weak_bg_fill = Color32::TRANSPARENT; - v.widgets.inactive.bg_fill = t.field; - v.widgets.inactive.bg_stroke = Stroke::NONE; - v.widgets.hovered.weak_bg_fill = t.hover; - v.widgets.hovered.bg_fill = t.hover; - v.widgets.hovered.bg_stroke = Stroke::NONE; - v.widgets.active.weak_bg_fill = t.pressed; - v.widgets.active.bg_fill = t.pressed; - // Stock buttons (menus, dialogs) use the same pointing hand as the custom chrome. - v.interact_cursor = Some(egui::CursorIcon::PointingHand); - v.widgets.open.weak_bg_fill = t.hover; - // Crisper text at 100–150 % scaling (#76): glyphs sit on whole pixels instead of being - // rendered at quarter-pixel offsets, which egui notes blurs them. In the light theme, a mild - // gamma darkens the antialiased edges of dark text (egui's default is linear, which reads thin - // and grey next to the system's text); the dark theme keeps egui's own curve. At 200 % both - // make little difference. - v.text_options.subpixel_binning = false; - if !t.dark() { - v.text_options.color_transfer_function = egui::epaint::FontColorTransferFunction::Gamma(0.75); - } - ctx.set_visuals(v); - ctx.global_style_mut(|s| { - // RTL languages mirror stock chrome (menus, combo boxes, scroll bars, headers). - // Labels still get their paragraph direction explicitly from `bidi::ui_direction`. - s.right_to_left = rtl; - s.spacing.item_spacing = egui::vec2(8.0, 6.0); - s.spacing.button_padding = egui::vec2(10.0, 5.0); - s.spacing.menu_margin = egui::Margin::same(6); - s.spacing.scroll.bar_width = 8.0; - s.spacing.scroll.floating = true; - s.spacing.scroll.floating_width = 3.0; - s.spacing.scroll.foreground_color = true; - s.text_styles.insert(egui::TextStyle::Body, regular(13.0)); - s.text_styles.insert(egui::TextStyle::Button, regular(13.0)); - s.text_styles.insert(egui::TextStyle::Small, regular(11.0)); - s.text_styles.insert(egui::TextStyle::Heading, semibold(17.0)); - s.interaction.tooltip_delay = 0.35; - }); - let style = ctx.global_style(); - ctx.set_style_of(egui::Theme::Light, style.clone()); - ctx.set_style_of(egui::Theme::Dark, style); - ctx.data_mut(|d| d.insert_temp(direction_key(), rtl)); -} - -/// Return the stable egui id holding the current right-to-left style flag. -fn direction_key() -> egui::Id { - egui::Id::unique("pdfcraft-style-right-to-left") -} - -/// Keep stock egui chrome's direction in step with the drawing language, after a language -/// change as well as at startup. Setting a flag on both concrete themes is cheap; this avoids -/// rebuilding the whole visuals and font state every frame. -pub fn sync_direction(ctx: &egui::Context) { - let rtl = crate::i18n::current().rtl(); - let changed = ctx.data_mut(|d| { - if d.get_temp::(direction_key()) == Some(rtl) { - false - } else { - d.insert_temp(direction_key(), rtl); - true - } - }); - if changed { - ctx.all_styles_mut(|s| s.right_to_left = rtl); - } -} - -/// WCAG 2 contrast ratio between two opaque colours. -pub fn contrast(a: Color32, b: Color32) -> f32 { - let lum = |c: Color32| { - let lin = |v: u8| { - let s = v as f32 / 255.0; - if s <= 0.04045 { s / 12.92 } else { ((s + 0.055) / 1.055).powf(2.4) } - }; - 0.2126 * lin(c.r()) + 0.7152 * lin(c.g()) + 0.0722 * lin(c.b()) - }; - let (x, y) = (lum(a) + 0.05, lum(b) + 0.05); - x.max(y) / x.min(y) -} - -/// `color` as text on `background`: itself when it reads (a WCAG 2 contrast of at least 3:1, the -/// level for large or bold text), otherwise moved towards `text` until it does. A document's own -/// colours (a bookmark's `/C`) were chosen for a white panel, and dark blue on a dark theme would -/// be lost. -pub fn readable(color: Color32, background: Color32, text: Color32) -> Color32 { - (0..=4).map(|step| color.lerp_to_gamma(text, step as f32 / 4.0)).find(|c| contrast(*c, background) >= 3.0).unwrap_or(text) -} - -#[cfg(test)] -mod tests; diff --git a/crates/ui-egui/src/theme/tests.rs b/crates/ui-egui/src/theme/tests.rs deleted file mode 100644 index b624a19915..0000000000 --- a/crates/ui-egui/src/theme/tests.rs +++ /dev/null @@ -1,303 +0,0 @@ -use super::*; - -/// Arabic and Kurdish switch stock chrome to mirror from the right; English switches it -/// back. This is the `Style::right_to_left` half of the explicit RTL policy. -#[test] -fn arabic_chrome_is_right_to_left_after_the_language_changes() { - if !crate::i18n::needs_catalogs() { - return; - } - let previous = crate::i18n::current(); - let ctx = egui::Context::default(); - crate::i18n::set_current(crate::i18n::Lang::from_code("ar").expect("registered language")); - apply(&ctx, ThemeKind::Light); - assert!(ctx.global_style().right_to_left); - crate::i18n::set_current(crate::i18n::Lang::EN); - sync_direction(&ctx); - assert!(!ctx.global_style().right_to_left); - crate::i18n::set_current(previous); -} - -/// #3193: a bookmark's own colour is kept where it reads on the panel, and moved towards the -/// theme's text colour where it doesn't (dark blue on the dark panel), never past it. -#[test] -fn a_document_colour_is_kept_where_it_reads() { - let (light, dark) = (Tokens::for_kind(ThemeKind::Light), Tokens::for_kind(ThemeKind::Dark)); - let red = Color32::from_rgb(255, 0, 0); - assert_eq!(readable(red, light.panel, light.text), red, "red reads on white"); - let navy = Color32::from_rgb(0, 0, 128); - assert_eq!(readable(navy, light.panel, light.text), navy); - let lifted = readable(navy, dark.panel, dark.text); - assert_ne!(lifted, navy, "navy is lost on the dark panel"); - assert!(contrast(lifted, dark.panel) >= 3.0, "{lifted:?}"); - assert_ne!(lifted, dark.text, "only as far as it needs"); - // Even the panel's own colour comes out readable. - assert!(contrast(readable(dark.panel, dark.panel, dark.text), dark.panel) >= 3.0); - assert!(contrast(readable(light.panel, light.panel, light.text), light.panel) >= 3.0); -} -use egui::epaint::text::{Fonts, TextOptions}; - -const HINTING_CORPUS: [&str; 4] = ["Il1MWmw", "Hamburgefonts", "0123456789 .,;:!?()[]{}+-=/\\", "Café Ångström déjà-vu Ωμέγα Ελληνικά Журнал"]; -const HINTING_SIZES: [f32; 6] = [10.0, 11.0, 12.0, 13.0, 14.0, 16.0]; -const HINTING_PPPS: [f32; 4] = [1.0, 1.25, 1.5, 2.0]; - -fn primary_families() -> [(FontFamily, &'static str); 4] { - [ - (FontFamily::Proportional, "Inter"), - (FontFamily::Name("medium".into()), "Inter-Medium"), - (FontFamily::Name("semibold".into()), "Inter-SemiBold"), - (FontFamily::Monospace, "JetBrainsMono"), - ] -} - -fn raster_edge_and_ink(fonts: &mut Fonts, id: FontId, text: &str, ppp: f32) -> (u64, u64) { - let galley = { - let mut view = fonts.with_pixels_per_point(ppp); - view.layout_no_wrap(text.to_owned(), id, Color32::BLACK).as_ref().clone() - }; - let image = fonts.image(); - let mut edge = 0u64; - let mut ink = 0u64; - for glyph in galley.rows.iter().flat_map(|row| &row.glyphs) { - let [x0, y0] = glyph.uv_rect.min.map(usize::from); - let [x1, y1] = glyph.uv_rect.max.map(usize::from); - for y in y0..y1 { - for x in x0..x1 { - let alpha = image.pixels[y * image.size[0] + x].a(); - ink += u64::from(alpha); - if x > x0 { - let left = image.pixels[y * image.size[0] + x - 1].a(); - edge += u64::from(alpha.abs_diff(left)); - } - } - } - } - (edge, ink) -} - -fn mono_raster_measure(fonts: &mut Fonts, ppp: f32) -> (u64, u64) { - let mut edge = 0; - let mut ink = 0; - for size in HINTING_SIZES { - for text in HINTING_CORPUS { - let (glyph_edge, glyph_ink) = raster_edge_and_ink(fonts, FontId::monospace(size), text, ppp); - edge += glyph_edge; - ink += glyph_ink; - } - } - (edge, ink) -} - -fn layout_signature(galley: &egui::Galley) -> Vec { - let mut signature = vec![ - galley.rect.min.x.to_bits(), - galley.rect.min.y.to_bits(), - galley.rect.max.x.to_bits(), - galley.rect.max.y.to_bits(), - u32::from(galley.elided), - galley.rows.len() as u32, - ]; - for row in &galley.rows { - signature.extend([ - u32::from(row.ends_with_newline), - row.pos.x.to_bits(), - row.pos.y.to_bits(), - row.size.x.to_bits(), - row.size.y.to_bits(), - row.glyphs.len() as u32, - ]); - for glyph in &row.glyphs { - signature.extend([ - glyph.chr as u32, - glyph.pos.x.to_bits(), - glyph.pos.y.to_bits(), - glyph.advance_width.to_bits(), - glyph.line_height.to_bits(), - glyph.font_ascent.to_bits(), - glyph.font_height.to_bits(), - glyph.font_face_ascent.to_bits(), - glyph.font_face_height.to_bits(), - ]); - } - } - signature -} - -fn galley(fonts: &mut Fonts, family: FontFamily, size: f32, ppp: f32, text: &str) -> egui::Galley { - let mut view = fonts.with_pixels_per_point(ppp); - view.layout_no_wrap(text.to_owned(), FontId::new(size, family), Color32::BLACK).as_ref().clone() -} - -fn hinting_test_fonts(platform: FontPolicyPlatform) -> Fonts { - Fonts::new( - TextOptions { - subpixel_binning: false, - color_transfer_function: egui::epaint::FontColorTransferFunction::Gamma(0.75), - ..TextOptions::default() - }, - font_definitions_for_platform(false, platform), - ) -} - -/// The y position of each glyph of `text` laid out by egui at `size` points, in points from -/// the top of the row. -fn baselines(fallback: FontData, size: f32, text: &str) -> Vec { - let mut defs = FontDefinitions::empty(); - defs.font_data.insert("Inter".into(), Arc::new(FontData::from_static(pdfcraft_fonts::INTER_REGULAR))); - defs.font_data.insert("fallback".into(), Arc::new(fallback)); - defs.families.insert(FontFamily::Proportional, vec!["Inter".into(), "fallback".into()]); - let mut fonts = Fonts::new(TextOptions::default(), defs); - let g = galley(&mut fonts, FontFamily::Proportional, size, 1.0, text); - g.rows[0].glyphs.iter().map(|gl| gl.pos.y).collect() -} - -#[test] -fn fallback_faces_share_the_interface_baseline() { - // Dancing Script's metrics differ from Inter's the way a Chinese face's do (by 0.044 em), - // and it has letters Inter doesn't (DŽ), which egui then takes from it. - let dancing: &'static [u8] = include_bytes!("../../../../assets/fonts/DancingScript.ttf"); - let size = 100.0; - // As egui lays it out by itself, DŽ sits ~4 pt off H's baseline: the bug (#1676). - let raw = baselines(FontData::from_static(dancing), size, "HDŽ"); - assert!((raw[1] - raw[0]).abs() > 3.0, "the test fonts must differ: {raw:?}"); - // `FallbackAlign::Baseline` puts every face on the same baseline, to the pixel. - let aligned = baselines(on_interface_baseline(FontData::from_static(dancing)), size, "HDŽ"); - assert!((aligned[1] - aligned[0]).abs() <= 1.0, "{aligned:?}"); - assert_eq!(on_interface_baseline(FontData::from_static(dancing)).tweak.fallback_align, FallbackAlign::Baseline); -} - -/// The policy only exists on native platforms (`installed_font_definitions` has no installed -/// faces on wasm), so the test must not use it in a wasm test build. -#[cfg(not(target_arch = "wasm32"))] -#[test] -fn traditional_chinese_keeps_an_installed_face_when_hans_is_embedded() { - use crate::system_fonts::Need; - assert_eq!(installed_fallback_need(CjkPreference::SimplifiedChinese, true), Need::Other); - assert_eq!(installed_fallback_need(CjkPreference::SimplifiedChinese, false), Need::Hans); - assert_eq!(installed_fallback_need(CjkPreference::TraditionalChinese, true), Need::Hant); - assert_eq!(installed_fallback_need(CjkPreference::TraditionalChinese, false), Need::Hant); - assert_eq!(installed_fallback_need(CjkPreference::Default, true), Need::Other); -} - -#[test] -fn windows_hinting_changes_only_the_jetbrains_symmetric_rendering_field() { - let baseline = font_definitions_for_platform(false, FontPolicyPlatform::Other); - let windows = font_definitions_for_platform(false, FontPolicyPlatform::Windows); - - assert_eq!(baseline.families, windows.families); - assert_eq!(baseline.font_data.keys().collect::>(), windows.font_data.keys().collect::>()); - for (family, name) in primary_families() { - let baseline_data = &baseline.font_data[name]; - let windows_data = &windows.font_data[name]; - assert_eq!(baseline_data.tweak, FontTweak::default(), "baseline {name}"); - if name == "JetBrainsMono" { - assert_eq!( - windows_data.tweak, - FontTweak { - hinting_target: HintingTarget::Smooth(SmoothHinting { symmetric_rendering: false, ..SmoothHinting::default() }), - ..FontTweak::default() - }, - "Windows {name}" - ); - } else { - assert_eq!(windows_data.tweak, baseline_data.tweak, "Windows {name}"); - } - assert_eq!(primary_font_tweak(FontPolicyPlatform::Other, name), baseline_data.tweak, "non-Windows policy for {family:?}"); - } - for (name, data) in &baseline.font_data { - if !["Inter", "Inter-Medium", "Inter-SemiBold", "JetBrainsMono"].contains(&name.as_str()) { - assert_eq!(windows.font_data[name].tweak, data.tweak, "Windows fallback {name}"); - } - } - assert_eq!( - font_definitions_for(false).font_data["JetBrainsMono"].tweak, - font_definitions_for_platform(false, current_font_policy_platform()).font_data["JetBrainsMono"].tweak - ); -} - -#[test] -#[ignore = "measurement probe: asserts exact egui rasterisation deltas, which change with egui upgrades; run with --ignored when retuning the hinting"] -fn windows_hinting_improves_low_dpi_mono_raster_without_changing_layout_or_coverage() { - let mut baseline = hinting_test_fonts(FontPolicyPlatform::Other); - let mut windows = hinting_test_fonts(FontPolicyPlatform::Windows); - - for ppp in HINTING_PPPS { - let (baseline_edge, baseline_ink) = mono_raster_measure(&mut baseline, ppp); - let (windows_edge, windows_ink) = mono_raster_measure(&mut windows, ppp); - // Compare horizontal alpha-edge energy per ink alpha; this is a deterministic - // vertical-stem sharpness proxy, not an absolute typography quality score. - let baseline_sharpness = baseline_edge as f64 / baseline_ink as f64; - let windows_sharpness = windows_edge as f64 / windows_ink as f64; - let sharpness_change = windows_sharpness / baseline_sharpness - 1.0; - let weight_change = windows_ink as f64 / baseline_ink as f64 - 1.0; - if ppp < 2.0 { - assert!(sharpness_change > 0.002, "{ppp} ppp sharpness change: {sharpness_change:.2}%", sharpness_change = sharpness_change * 100.0); - } else { - assert!(sharpness_change >= -0.01, "{ppp} ppp sharpness change: {sharpness_change:.2}%", sharpness_change = sharpness_change * 100.0); - } - assert!(weight_change.abs() < 0.05, "{ppp} ppp ink change: {weight_change:.2}%", weight_change = weight_change * 100.0); - } - - for ppp in HINTING_PPPS { - for size in HINTING_SIZES { - for (family, _) in primary_families() { - for text in HINTING_CORPUS { - assert_eq!( - baseline.has_glyphs(&FontId::new(size, family.clone()), text), - windows.has_glyphs(&FontId::new(size, family.clone()), text), - "{family:?} {text:?}" - ); - assert_eq!( - layout_signature(&galley(&mut baseline, family.clone(), size, ppp, text)), - layout_signature(&galley(&mut windows, family.clone(), size, ppp, text)), - "{family:?}, {size} pt, {ppp} ppp, {text:?}" - ); - } - } - } - } -} - -/// "Use system setting" draws what the operating system says, dark or light. -#[test] -fn following_the_system_draws_what_the_system_says() { - assert_eq!(ThemePreference::System.resolve(Some(true), ThemeKind::Light), ThemeKind::Dark); - assert_eq!(ThemePreference::System.resolve(Some(false), ThemeKind::Dark), ThemeKind::Light); -} - -/// An operating system that says nothing leaves the last choice standing, and an explicit -/// Light or Dark is never overridden by what the system says. -#[test] -fn an_answerless_system_leaves_the_choice_and_an_explicit_one_stands() { - assert_eq!(ThemePreference::System.resolve(None, ThemeKind::Light), ThemeKind::Light); - assert_eq!(ThemePreference::System.resolve(None, ThemeKind::Dark), ThemeKind::Dark); - assert_eq!(ThemePreference::Light.resolve(Some(true), ThemeKind::Dark), ThemeKind::Light); - assert_eq!(ThemePreference::Dark.resolve(Some(false), ThemeKind::Light), ThemeKind::Dark); -} - -#[test] -fn press_darkens_then_sinks() { - let rest = Color32::from_rgb(0xFF, 0xFF, 0xFF); - let hover = Color32::from_rgb(0xF0, 0xF0, 0xF3); - let pressed = Color32::from_rgb(0xE4, 0xE4, 0xE9); - let idle = Press { hover: 0.0, down: 0.0 }; - assert_eq!(idle.fill(rest, hover, pressed), rest); - assert_eq!(idle.offset(), Vec2::ZERO); - let held = Press { hover: 1.0, down: 1.0 }; - assert_eq!(held.fill(rest, hover, pressed), pressed); - assert_eq!(held.offset(), Vec2::new(0.0, 1.0)); -} - -#[test] -fn text_is_readable_on_every_surface() { - // #76: the faintest text (hints, zoom level, captions) was 3.3:1 in the light theme. - for kind in [ThemeKind::Light, ThemeKind::Dark] { - let t = Tokens::for_kind(kind); - for (name, fg) in [("text", t.text), ("text_muted", t.text_muted), ("text_faint", t.text_faint)] { - for bg in [t.chrome, t.panel, t.card, t.pasteboard] { - let r = contrast(fg, bg); - assert!(r >= 4.5, "{kind:?} {name} on {bg:?}: {r:.2}:1, WCAG AA needs 4.5:1"); - } - } - } -}