EffectCraft: An open-source motion graphics and compositing tool written by scratch in pure Rust
Merge origin/main into fix/1089-fedora-fonts.
Vikram Bhaskaran835a793096c0
diff --cc crates/text/src/fonts.rsindex 3087f80da,a973335f4..a0f798236--- a/crates/text/src/fonts.rs+++ b/crates/text/src/fonts.rs@@@ -363,69 -385,14 +385,69 @@@ pub fn scan_system() -> usize}/// Scan the system font folders again, adding fonts installed since the last scan (faces already-/// known are kept, so font ids stay valid). Returns the number of faces added.+/// known are kept, so font ids stay valid). Returns the number of faces added. This walks every+/// fontconfig directory, so the UI calls [`start_rescan`] instead of running it on the frame thread.pub fn rescan_system() -> usize {- let _scan = SCAN.lock().unwrap_or_else(|e| e.into_inner());+ let _scan = SCAN.lock().unwrap_or_else(std::sync::PoisonError::into_inner);let n = if cfg!(target_arch = "wasm32") { 0 } else { add_source(&DirectorySource::system()) };- db().write().unwrap_or_else(|e| e.into_inner()).scanned = true;+ db().write().unwrap_or_else(std::sync::PoisonError::into_inner).scanned = true;n}+/// A rescan started by [`start_rescan`], if one is in flight or finished and not yet polled.+#[cfg(not(target_arch = "wasm32"))]+static RESCAN: std::sync::Mutex<Option<std::thread::JoinHandle<usize>>> = std::sync::Mutex::new(None);++/// Start [`rescan_system`] on a background thread. Returns false when a rescan is already+/// running, the thread could not be spawned, or this build has no system font folders (wasm).+pub fn start_rescan() -> bool {+ #[cfg(target_arch = "wasm32")]+ {+ false+ }+ #[cfg(not(target_arch = "wasm32"))]+ {- let mut slot = RESCAN.lock().unwrap_or_else(|e| e.into_inner());++ let mut slot = RESCAN.lock().unwrap_or_else(std::sync::PoisonError::into_inner);+ if slot.as_ref().is_some_and(|h| !h.is_finished()) {+ return false;+ }+ match std::thread::Builder::new().name("font-rescan".into()).spawn(rescan_system) {+ Ok(handle) => {+ *slot = Some(handle);+ true+ }+ Err(_) => false,+ }+ }+}++/// Whether a background rescan is still walking the font folders.+pub fn rescan_busy() -> bool {+ #[cfg(target_arch = "wasm32")]+ {+ false+ }+ #[cfg(not(target_arch = "wasm32"))]+ {- RESCAN.lock().unwrap_or_else(|e| e.into_inner()).as_ref().is_some_and(|h| !h.is_finished())++ RESCAN.lock().unwrap_or_else(std::sync::PoisonError::into_inner).as_ref().is_some_and(|h| !h.is_finished())+ }+}++/// Faces added by the latest background rescan, once that thread has finished. `None` while it+/// is still running or when nothing was started.+pub fn poll_rescan() -> Option<usize> {+ #[cfg(target_arch = "wasm32")]+ {+ None+ }+ #[cfg(not(target_arch = "wasm32"))]+ {- let mut slot = RESCAN.lock().unwrap_or_else(|e| e.into_inner());++ let mut slot = RESCAN.lock().unwrap_or_else(std::sync::PoisonError::into_inner);+ let finished = slot.as_ref().is_some_and(std::thread::JoinHandle::is_finished);+ if finished { slot.take().and_then(|h| h.join().ok()) } else { None }+ }+}+/// Start the system font scan on a background thread, so the font menus are complete by the/// time someone opens them without the first open waiting for the scan. Native only; on wasm/// (no threads, no font folders) this does nothing.diff --cc crates/text/src/fonts/tests.rsindex 000000000,079a001e0..96da72c72mode 000000,100644..100644--- a/crates/text/src/fonts/tests.rs+++ b/crates/text/src/fonts/tests.rs@@@ -1,0 -1,480 +1,482 @@@+ use super::*;++ /// Concurrent language requests must neither choose another context's font nor reuse its+ /// cached family order. Synthetic fonts in a child process keep this independent of the host+ /// font installation and of other tests that exercise the process-global database/locale.+ #[test]+ #[cfg(not(target_arch = "wasm32"))]+ fn cjk_requests_keep_their_language_and_cache_entries() {+ const CHILD: &str = "EFFECTCRAFT_TEST_ISOLATED_CJK";+ if std::env::var_os(CHILD).is_none() {+ let output = std::process::Command::new(std::env::current_exe().unwrap())+ .args(["--exact", "fonts::tests::cjk_requests_keep_their_language_and_cache_entries", "--nocapture"])+ .env(CHILD, "1")+ .output()+ .unwrap();+ assert!(output.status.success(), "{}\n{}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr));+ return;+ }+ let families = [("ja", "Yu Gothic"), ("zh-hans", "Microsoft YaHei"), ("zh-hant", "Microsoft JhengHei"), ("ko", "Malgun Gothic")];+ let mut expected = Vec::new();+ {+ let mut d = db().write().unwrap();+ d.scanned = true; // This test process uses only bundled and synthetic fonts.+ for (language, family) in families {+ let mut data = test_font(family);+ let table = data[12..12 + 8 * 16].as_chunks::<16>().0.iter().find(|t| &t[..4] == b"cmap").unwrap();+ let cmap = u32::from_be_bytes(table[8..12].try_into().unwrap()) as usize + 12;+ // Map 页 to the fixture's triangle glyph instead of its private-use range.+ // All four fonts cover the probe, so coverage cannot choose the right language.+ for (offset, value) in [(16, '页' as u16), (24, '页' as u16), (30, 2u16.wrapping_sub('页' as u16))] {+ data[cmap + offset..cmap + offset + 2].copy_from_slice(&value.to_be_bytes());+ }+ let data = Arc::new(data);+ let names = read_faces_bytes(&data).into_iter().next().unwrap();+ let id = push(&mut d, info_from(names, FaceData::Shared(data), "test"));+ expected.push((language, id));+ }+ }+ let base = resolve("Inter", "Regular").face;+ for &(_, id) in &expected {+ assert!(face(id).has_char('页'));+ }+ // Force the original interleaving: Chinese starts, then Japanese replaces the global+ // language before Chinese looks up its probe. The explicit request must still win.+ set_cjk_locale("zh-hans");+ set_cjk_locale("ja");+ assert_eq!(fallback_for('页', base), expected[0].1);+ assert_eq!(fallback_for_locale('页', base, "zh-hans"), expected[1].1);+ // Do not clear the cache here: different policies must coexist in the same cache.+ for _ in 0..3 {+ for &(language, id) in &expected {+ assert_eq!(fallback_for_locale('页', base, language), id, "{language}");+ }+ }+ let barrier = Arc::new(std::sync::Barrier::new(expected.len()));+ let threads: Vec<_> = expected+ .into_iter()+ .map(|(language, id)| {+ let barrier = barrier.clone();+ std::thread::spawn(move || {+ barrier.wait();+ for _ in 0..128 {+ set_cjk_locale(if language == "ja" { "zh-hans" } else { "ja" });+ assert_eq!(fallback_for_locale('页', base, language), id, "{language}");+ }+ })+ })+ .collect();+ for thread in threads {+ thread.join().unwrap();+ }+ }++ #[test]+ fn extra_font_dirs_come_from_a_path_list() {+ assert!(extra_dirs(None).is_empty());+ let v = std::env::join_paths(["/a/fonts", "/b/more"]).unwrap_or_default();+ assert_eq!(extra_dirs(Some(&v)), vec![PathBuf::from("/a/fonts"), PathBuf::from("/b/more")]);+ assert!(extra_dirs(Some(std::ffi::OsStr::new(""))).is_empty());+ }++ #[test]+ fn bundled_families_and_resolution() {+ let fams = families();+ let inter = fams.iter().find(|(f, _)| f == "Inter").expect("Inter");+ for s in ["Regular", "Medium", "SemiBold", "Bold", "Italic"] {+ assert!(inter.1.iter().any(|x| x == s), "{s} in {:?}", inter.1);+ }+ assert!(fams.iter().any(|(f, _)| f == "Noto Serif"));+ assert!(fams.iter().any(|(f, _)| f == "JetBrains Mono"));+ let b = resolve("inter", "bold");+ assert_eq!(face(b.face).info.style, "Bold");+ assert!(!b.synth_bold);+ let faces = all_faces();+ assert!(faces.iter().any(|f| f.info.family == "Noto Serif" && f.info.style == "Regular" && f.info.origin == "bundled"));+ // A real installed Bold Italic takes priority. Partial installed families can instead+ // supply the nearest weight/slant, so neither synthesis flag is fixed by the OS.+ for family in ["Noto Serif", "Inter"] {+ let resolved = resolve(family, "Bold Italic");+ let selected = face(resolved.face);+ assert!(selected.info.family.eq_ignore_ascii_case(family));+ assert!(!resolved.missing);+ let candidates: Vec<_> = faces.iter().filter(|f| f.info.family.eq_ignore_ascii_case(family)).collect();+ if let Some(exact) = candidates.iter().find(|f| f.info.style.eq_ignore_ascii_case("Bold Italic")) {+ assert_eq!(resolved.face, exact.id, "real style wins for {family}");+ assert!(!resolved.synth_bold && !resolved.synth_italic);+ } else {+ // Italic mismatch dominates any supported font weight distance.+ let distance = |f: &Face| u32::from(f.info.weight.abs_diff(700)) + if f.info.italic { 0 } else { 1_000 };+ let nearest = candidates.iter().map(|f| distance(f)).min().unwrap();+ assert_eq!(distance(&selected), nearest, "closest available style for {family}");+ assert_eq!(resolved.synth_bold, selected.info.weight <= 500);+ assert_eq!(resolved.synth_italic, !selected.info.italic);+ }+ }+ }++ #[test]+ fn missing_family_falls_back_to_inter() {+ let r = resolve("No Such Font Family 123", "Regular");+ assert_eq!(face(r.face).info.family, "Inter");+ assert!(r.missing);+ }++ /// Native: the system scan reads name tables only and resolves families installed there.+ #[test]+ fn system_scan_finds_fonts() {+ let t = std::time::Instant::now();+ scan_system(); // (another test may have triggered the scan already)+ let n = all_faces().iter().filter(|f| f.info.origin == "system").count();+ eprintln!("system fonts: {n} faces in {:?}", t.elapsed());+ assert_eq!(scan_system(), 0, "scans once");++ // A minimum face count on Linux belongs with the native-fonts gate in #1591. A container++ // that has fontconfig and only a handful of faces must still pass this portable test.+ if cfg!(target_os = "macos") {+ assert!(n > 20, "{n}");+ let r = resolve("Helvetica", "Bold");+ assert_eq!(face(r.face).info.family, "Helvetica");+ let l = crate::layout_text("Helvetica", &crate::TextStyle { family: "Helvetica".into(), size: 30.0, ..Default::default() }, &Default::default());+ assert!(!l.missing_font && l.glyphs.iter().all(|g| g.id != 0));+ }+ }++ #[test]+ fn postscript_and_full_names_resolve() {+ // Bundled Inter: name id 6 is `Inter-Bold`, name id 4 is `Inter Bold`.+ let ps = resolve("Inter-Bold", "");+ assert_eq!(face(ps.face).info.style, "Bold");+ assert!(!ps.missing && !ps.synth_bold);+ let full = resolve("inter semibold", "");+ assert_eq!(face(full.face).info.style, "SemiBold");+ assert!(!full.missing);+ // A family name still wins over a name lookup.+ assert_eq!(face(resolve("Inter", "Bold").face).info.style, "Bold");+ }++ /// #1563: a variable font's named instances are styles of its family. `fontStyle = "Black"`,+ /// the instance's PostScript name (`font = "Figtree-Black"`) and its full name select the+ /// instance's axis values instead of the default instance made bold synthetically, and the+ /// font menus list every instance.+ #[test]+ fn variable_named_instances_resolve_and_list() {+ const FAMILY: &str = "EffectCraft Instance Test";+ let instances = [+ ("Light", 300.0, Some("EffectCraftInstanceTest-Light")),+ ("Regular", 400.0, Some("EffectCraftInstanceTest-Regular")),+ ("Black", 900.0, Some("EffectCraftInstanceTest-Black")),+ ("Extra Bold", 800.0, None),+ ];+ assert_eq!(add_font_data(crate::sfnt::test_font::variable(FAMILY, &instances, true)).len(), 1);+ let wght = |r: &Resolved| instance_variations(r);+ // By style name.+ let black = resolve(FAMILY, "Black");+ assert!(!black.missing && !black.synth_bold && !black.synth_italic, "{black:?}");+ assert_eq!(wght(&black), vec![("wght".to_string(), 900.0)]);+ assert_eq!(wght(&resolve(FAMILY, "regular")), vec![("wght".to_string(), 400.0)]);+ // The face's own style is its default instance: no axis values to set.+ let light = resolve(FAMILY, "Light");+ assert_eq!((light.face, light.instance), (black.face, None));+ // A style the family lacks takes the nearest instance's weight, no synthetic bold.+ let bold = resolve(FAMILY, "Bold");+ assert!(!bold.synth_bold, "{bold:?}");+ assert_eq!(wght(&bold), vec![("wght".to_string(), 800.0)]);+ // By PostScript name, the font's own and the derived one, and by full name.+ let ps = resolve("EffectCraftInstanceTest-Black", "Regular");+ assert!(!ps.missing && ps.face == black.face, "{ps:?}");+ assert_eq!(wght(&ps), vec![("wght".to_string(), 900.0)]);+ assert_eq!(wght(&resolve("EffectCraftInstanceTest-ExtraBold", "")), vec![("wght".to_string(), 800.0)]);+ assert_eq!(wght(&resolve("effectcraft instance test extra bold", "")), vec![("wght".to_string(), 800.0)]);+ // The font menu lists every instance, in weight order.+ let fams = families();+ let styles = &fams.iter().find(|(f, _)| f == FAMILY).unwrap().1;+ assert_eq!(styles, &["Light", "Regular", "Extra Bold", "Black"]);+ // Static fonts are untouched.+ assert_eq!(resolve("Inter", "Bold").instance, None);+ }++ /// Axis values set on the text win over the instance's; the others keep the instance's.+ #[test]+ fn explicit_variations_override_the_instance() {+ let base = vec![("wdth".to_string(), 75.0), ("wght".to_string(), 900.0)];+ assert_eq!(merge_variations(&base, &[("wght".to_string(), 450.0)]), vec![("wdth".to_string(), 75.0), ("wght".to_string(), 450.0)]);+ assert_eq!(merge_variations(&base, &[]), base);+ assert_eq!(merge_variations(&[], &[("opsz".to_string(), 12.0)]), vec![("opsz".to_string(), 12.0)]);+ }++ #[test]+ fn scripts_are_classified() {+ assert_eq!(script_of('あ'), FallbackScript::Japanese);+ assert_eq!(script_of('カ'), FallbackScript::Japanese);+ assert_eq!(script_of('한'), FallbackScript::Korean);+ assert_eq!(script_of('水'), FallbackScript::Han);+ assert_eq!(script_of('、'), FallbackScript::Han);+ assert_eq!(script_of('A'), FallbackScript::Han);+ assert_eq!(script_of('\u{20000}'), FallbackScript::Han);+ assert_eq!(script_of('A'), FallbackScript::Other);+ assert_eq!(script_of('م'), FallbackScript::Arabic);+ assert_eq!(script_of('\u{fefb}'), FallbackScript::Arabic);+ assert_eq!(script_of('\u{5d0}'), FallbackScript::Hebrew);+ assert_eq!(script_of('क'), FallbackScript::Indic);+ assert_eq!(script_of('த'), FallbackScript::Indic);+ assert_eq!(script_of('ก'), FallbackScript::Thai);+ assert_eq!(script_of('ა'), FallbackScript::Georgian);+ assert_eq!(script_of('\u{1c90}'), FallbackScript::Georgian, "Mtavruli");+ assert_eq!(script_of('\u{feff}'), FallbackScript::Other, "the byte order mark is no Arabic letter");+ }++ /// Native: Arabic, Hebrew, Indic and Thai text in a Latin-only family falls back to the+ /// platform's plain text family for its script (#394), not to the first installed face that+ /// covers it (on Windows a calligraphic Arabic face sorts first). Skipped per script where no+ /// family from its list is installed.+ #[test]+ fn other_scripts_fall_back_to_a_plain_system_family() {+ scan_system();+ let inter = resolve("Inter", "Regular").face;+ for (c, families) in [('م', ARABIC_FAMILIES), ('א', HEBREW_FAMILIES), ('क', INDIC_FAMILIES), ('த', INDIC_FAMILIES), ('ก', THAI_FAMILIES)] {+ let covering = families.iter().any(|n| resolve_in(n, "Regular").is_some_and(|r| face(r.face).has_char(c)));+ if !covering {+ eprintln!("{c}: no family from the list is installed; skipping");+ continue;+ }+ let f = face(fallback_for(c, inter));+ assert!(f.has_char(c), "{c}: {} lacks it", f.info.family);+ assert!(families.iter().any(|n| f.info.family.eq_ignore_ascii_case(n)), "{c} → {}", f.info.family);+ }+ }++ /// Native: Mkhedruli in a Latin-only family falls back to a family from the Georgian list,+ /// ahead of faces already loaded and of the scan order. Skipped where no family from the list+ /// is installed.+ #[test]+ fn georgian_falls_back_to_a_georgian_system_family() {+ scan_system();+ let c = 'ა';+ if !GEORGIAN_FAMILIES.iter().any(|n| resolve_in(n, "Regular").is_some_and(|r| face(r.face).has_char(c))) {+ eprintln!("no Georgian family from the list is installed; skipping");+ return;+ }+ let f = face(fallback_for(c, resolve("Inter", "Regular").face));+ assert!(f.has_char(c), "{} lacks it", f.info.family);+ assert!(GEORGIAN_FAMILIES.iter().any(|n| f.info.family.eq_ignore_ascii_case(n)), "{c} → {}", f.info.family);+ }++ /// Native: Japanese text in a Latin-only family falls back to an installed Japanese family+ /// (whichever the platform ships) instead of the missing-glyph box, without any layer having+ /// loaded a CJK font first. Skipped where no family from the list is installed.+ #[test]+ fn cjk_falls_back_to_a_system_family() {+ scan_system();+ let inter = resolve("Inter", "Bold").face;+ let installed = JAPANESE_FAMILIES.iter().any(|f| resolve_in(f, "Regular").is_some());+ if !installed {+ eprintln!("no Japanese family installed; skipping");+ return;+ }+ for c in ['水', 'あ', 'ア', '。'] {+ let id = fallback_for(c, inter);+ let f = face(id);+ assert!(f.has_char(c), "{c}: {} {} lacks it", f.info.family, f.info.style);+ assert!(JAPANESE_FAMILIES.iter().any(|n| f.info.family.eq_ignore_ascii_case(n)), "{c} → {}", f.info.family);+ }+ // The bold cut of the fallback family is chosen for bold text when the family has one.+ let f = face(fallback_for('水', inter));+ let (w, _) = style_wants(&f.info.style);+ let has_bold = all_faces().iter().any(|g| g.info.family == f.info.family && style_wants(&g.info.style).0 >= 600);+ assert!(!has_bold || w >= 600, "{} {}", f.info.family, f.info.style);+ // Cached: the second call is a lookup.+ assert_eq!(fallback_for('水', inter), f.id);+ }++ /// A minimal TrueType font built in code (no font file in the repo): U+0020 and U+E000 map to+ /// an empty glyph, U+E001 to a triangle.+ fn blank_glyph_font() -> Vec<u8> {+ test_font("Blank Glyph Test")+ }++ /// The blank-glyph test font under another family name.+ fn test_font(family: &str) -> Vec<u8> {+ fn u16s(v: &[u16]) -> Vec<u8> {+ v.iter().flat_map(|x| x.to_be_bytes()).collect()+ }+ let delta_space = 1u16.wrapping_sub(0x20);+ let cmap4 = {+ let mut t = u16s(&[4, 0, 0, 6, 4, 1, 2]);+ t.extend(u16s(&[0x20, 0xE001, 0xFFFF, 0, 0x20, 0xE000, 0xFFFF, delta_space, 0x2001, 1, 0, 0, 0]));+ let len = t.len() as u16;+ t[2..4].copy_from_slice(&len.to_be_bytes());+ t+ };+ let mut cmap = u16s(&[0, 1, 3, 1, 0, 12]);+ cmap.extend(cmap4);+ // glyph 2: one contour of three on-curve points (100,0) (500,0) (300,600)+ let mut glyf = u16s(&[1, 100, 0, 500, 600, 2, 0]);+ glyf.extend([1u8, 1, 1]);+ glyf.extend(u16s(&[100, 400, (-200i16) as u16, 0, 0, 600]));+ glyf.push(0);+ let loca = u16s(&[0, 0, 0, (glyf.len() / 2) as u16]);+ let mut head = u16s(&[1, 0, 1, 0, 0, 0, 0x5F0F, 0x3CF5, 0, 1000]);+ head.extend([0u8; 16]);+ head.extend(u16s(&[100, 0, 500, 600, 0, 8, 2, 0, 0]));+ let mut hhea = u16s(&[1, 0, 800, (-200i16) as u16, 0, 600, 0, 0, 500, 1, 0, 0]);+ hhea.extend([0u8; 8]);+ hhea.extend(u16s(&[0, 3]));+ let hmtx = u16s(&[600, 0, 600, 0, 600, 0]);+ let maxp = u16s(&[1, 0, 3, 3, 1, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0]);+ let strings: Vec<Vec<u8>> = [family, "Regular"].iter().map(|s| s.encode_utf16().flat_map(|u| u.to_be_bytes()).collect()).collect();+ let mut name = u16s(&[0, 2, 30]);+ let mut off = 0;+ for (id, st) in strings.iter().enumerate() {+ name.extend(u16s(&[3, 1, 0x409, id as u16 + 1, st.len() as u16, off]));+ off += st.len() as u16;+ }+ strings.iter().for_each(|st| name.extend(st));+ let tables: [(&[u8; 4], Vec<u8>); 8] =+ [(b"cmap", cmap), (b"glyf", glyf), (b"head", head), (b"hhea", hhea), (b"hmtx", hmtx), (b"loca", loca), (b"maxp", maxp), (b"name", name)];+ let mut out = u16s(&[1, 0, tables.len() as u16, 128, 3, 0]);+ let mut offset = 12 + 16 * tables.len();+ let mut body = vec![];+ for (tag, data) in &tables {+ out.extend(*tag);+ out.extend([0u8; 4]);+ out.extend((offset as u32).to_be_bytes());+ out.extend((data.len() as u32).to_be_bytes());+ let padded = data.len().div_ceil(4) * 4;+ body.extend(data);+ body.resize(body.len() + padded - data.len(), 0);+ offset += padded;+ }+ out.extend(body);+ out+ }++ /// A face that maps a character to an empty glyph doesn't cover it, so fallback skips it+ /// (#285); a blank space still counts, and a drawn glyph is found as before.+ #[test]+ fn an_empty_glyph_does_not_cover_its_character() {+ let ids = add_font_data(blank_glyph_font());+ let &[id] = ids.as_slice() else { panic!("one face expected: {ids:?}") };+ let f = face(id);+ assert_eq!(f.info.family, "Blank Glyph Test");+ assert!(f.glyph('\u{e000}').is_some(), "the cmap maps it");+ assert!(!f.has_char('\u{e000}'), "but its glyph is empty");+ assert!(f.has_char('\u{e001}'), "a drawn glyph covers its character");+ assert!(f.has_char(' '), "a space is blank by nature");+ let inter = resolve("Inter", "Regular").face;+ assert_ne!(fallback_for('\u{e000}', inter), id, "fallback never picks the empty glyph");+ assert_eq!(fallback_for('\u{e001}', inter), id, "fallback finds the drawn one");+ }++ /// A Microsoft family that isn't installed renders in its installed metric-compatible+ /// substitute instead of Inter, and still reports itself missing (#1677).+ #[test]+ fn microsoft_families_resolve_to_metric_compatible_substitutes() {+ add_font_data(test_font("Carlito"));+ add_font_data(test_font("Caladea"));+ let calibri = resolve("Calibri", "Regular");+ assert_eq!(face(calibri.face).info.family, "Carlito");+ assert!(calibri.missing, "the original name stays missing for Find Missing Fonts");+ let cambria = resolve("Cambria", "Bold");+ assert_eq!(face(cambria.face).info.family, "Caladea");+ assert!(cambria.missing);+ let unknown = resolve("No Such Family 1677", "Regular");+ assert_eq!(face(unknown.face).info.family, DEFAULT_FAMILY);+ assert!(unknown.missing);+ }++ #[test]+ fn the_han_order_follows_the_cjk_locale() {+ // Chinese first for any Chinese tag, whether or not it names a script.+ for tag in ["zh", "zh-CN", "zh_Hans", "ZH-Hant-TW.UTF-8", "zh_MO"] {+ assert_eq!(han_order_for(tag)[0], FallbackScript::Han, "{tag}");+ }+ assert_eq!(han_order_for("ko-KR"), [FallbackScript::Korean, FallbackScript::Japanese, FallbackScript::Han]);+ // Japanese, and anything else, keeps the Japanese face first for Han text.+ for tag in ["ja_JP.UTF-8", "en-US", "de", ""] {+ assert_eq!(han_order_for(tag), [FallbackScript::Japanese, FallbackScript::Han, FallbackScript::Korean], "{tag}");+ }+ // The host's request is what `han_order` reads (the ui test covers the effect on the+ // registered fallbacks; this only checks that clearing it returns to the environment).+ assert_eq!(requested_cjk_locale(), None, "tests run without a request");+ assert_eq!(han_order(), han_order_for(&active_cjk_locale()));+ }++ #[test]+ fn the_chinese_family_list_follows_the_script_the_locale_asks_for() {+ for tag in ["zh", "zh-CN", "zh_Hans", "zh_CN.UTF-8", "zh-SG"] {+ assert_eq!(chinese_families_for(tag), SIMPLIFIED_CHINESE_FAMILIES, "{tag}");+ }+ for tag in ["zh-Hant", "zh-Hant-TW", "zh_TW", "zh-HK", "zh_MO.UTF-8"] {+ assert_eq!(chinese_families_for(tag), TRADITIONAL_CHINESE_FAMILIES, "{tag}");+ }+ // Each list carries its own script's faces and not the other's, which is the point of+ // splitting them: `PingFang SC` covers the same code points as `PingFang TC`, so the+ // fallback search would have kept it and drawn Simplified forms in a Traditional interface.+ assert!(SIMPLIFIED_CHINESE_FAMILIES.iter().any(|f| f.contains("PingFang SC") && !f.contains("Source")));+ assert!(!SIMPLIFIED_CHINESE_FAMILIES.iter().any(|f| f.contains("TC") || f.contains("JhengHei")));+ assert!(TRADITIONAL_CHINESE_FAMILIES.iter().any(|f| f.contains("PingFang TC")));+ assert!(!TRADITIONAL_CHINESE_FAMILIES.iter().any(|f| f.contains(" SC") || f.contains("YaHei") || f.contains("WenQuanYi")));+ assert!(TRADITIONAL_CHINESE_FAMILIES.iter().any(|f| f.contains("Heiti TC") || f.contains("Hiragino Sans CNS")));+ // The arm the fallback itself walks: Han hands over the list the locale's script picked.+ assert_eq!(families_for(FallbackScript::Han, CjkLocale::from_tag(&active_cjk_locale())), chinese_families_for(&active_cjk_locale()));+ // Han text is the only thing these lists serve; the Japanese order does not change.+ assert_eq!(han_order_for("ja_JP.UTF-8")[0], FallbackScript::Japanese);+ }++ #[test]+ fn the_rendered_order_keeps_the_print_face_first() {+ // A composed frame renders with these lists, so they keep the platform's print order: the+ // interface prefers the platform's UI faces on its own (see `install_script_fallbacks` in+ // the ui crate), and an existing project must not render differently because a window's+ // chrome changed.+ let pos = |list: &[&str], name: &str| list.iter().position(|f| *f == name).unwrap_or(usize::MAX);+ assert!(+ pos(JAPANESE_FAMILIES, "Yu Gothic") < pos(JAPANESE_FAMILIES, "Yu Gothic UI"),+ "the print face must come before its UI sibling: {JAPANESE_FAMILIES:?}"+ );+ for name in ["Meiryo UI", "MS UI Gothic"] {+ assert!(!JAPANESE_FAMILIES.contains(&name), "{name} belongs to the interface order, not this list");+ }+ assert_eq!(SIMPLIFIED_CHINESE_FAMILIES[0], "Microsoft YaHei");+ assert_eq!(TRADITIONAL_CHINESE_FAMILIES[0], "Microsoft JhengHei");+ for name in ["Microsoft YaHei UI", "Microsoft JhengHei UI", "PMingLiU"] {+ assert!(+ !SIMPLIFIED_CHINESE_FAMILIES.contains(&name) && !TRADITIONAL_CHINESE_FAMILIES.contains(&name),+ "{name} belongs to the interface order, not these lists"+ );+ }+ }++ #[test]+ fn bundled_ui_fonts_cover_the_ukrainian_alphabet() {+ const ALPHABET: &str = "АБВГҐДЕЄЖЗИІЇЙКЛМНОПРСТУФХЦЧШЩЬЮЯабвгґдеєжзиіїйклмнопрстуфхцчшщьюя’«»";+ for (name, bytes) in+ [("Inter Regular", INTER_REGULAR), ("Inter Medium", INTER_MEDIUM), ("Inter SemiBold", INTER_SEMIBOLD), ("JetBrains Mono", JETBRAINS_MONO_REGULAR)]+ {+ let font = FontRef::new(bytes).unwrap();+ for c in ALPHABET.chars() {+ assert!(covers(&font, c), "{name} cannot draw {c}");+ }+ }+ }++ #[test]+ fn metrics_and_coverage() {+ let f = face(resolve("Inter", "Regular").face);+ let m = f.metrics(100.0);+ assert!(m.ascent > 80.0 && m.ascent < 110.0, "{m:?}");+ assert!(m.descent > 10.0 && m.descent < 40.0);+ assert!(m.cap_height > 60.0 && m.cap_height < 80.0);+ assert!(f.has_char('A') && f.has_char('Ж'));+ assert!(!f.has_char('\u{5d0}'), "Inter has no Hebrew");+ assert!(f.has_feature(b"liga") || f.has_feature(b"calt"));+ }++ #[test]+ fn unknown_face_id_returns_bundled_default() {+ let fallback = face(usize::MAX);+ assert_eq!(fallback.id, 0);+ assert_eq!(fallback.info.family, DEFAULT_FAMILY);+ assert!(fallback.font().is_some());+ assert!(Arc::ptr_eq(&fallback, &face(0)));+ }diff --cc crates/ui-egui/src/app/frame.rsindex 000000000,d41e0a9d0..0f6d9566cmode 000000,100644..100644--- a/crates/ui-egui/src/app/frame.rs+++ b/crates/ui-egui/src/app/frame.rs@@@ -1,0 -1,553 +1,556 @@@+ use super::clipboard::copy_image;+ use super::window::fit_window;+ use super::*;++ impl EffectcraftApp {+ /// Completed, non-discarded UI passes since launch.+ pub fn ui_passes(&self) -> u64 {+ self.ui_pass_seq+ }++ // ---------------------------------------------------------------- control channel++ pub(crate) fn raise_for_control(&mut self, ctx: &egui::Context) {+ ctx.request_repaint();+ }++ /// Handle the control channel for this tick: drain queued requests plus previously deferred ones, run each+ /// through `control::handle`, answer `Done` immediately, retry `Retry` until its three-second deadline, hold+ /// input/job/screenshot replies until their event happens and finish job waiters. Retry timeouts and refused+ /// screenshots are answered as `{"ok": false, "error": ...}`; the receiver is kept for the next tick.+ fn drain_control(&mut self, ctx: &egui::Context, now: f64) {+ let Some(rx) = self.control_rx.take() else { return };+ let mut reqs: Vec<(ControlRequest, f64)> = std::mem::take(&mut self.deferred);+ while let Ok(req) = rx.try_recv() {+ reqs.push((req, now + 3.0));+ }+ for (req, deadline) in reqs {+ let reply = req.reply.clone();+ match control::handle(self, ctx, &req, now) {+ control::Outcome::Done(v) => {+ let _ = reply.send(v);+ }+ control::Outcome::Retry(msg) => {+ if now < deadline {+ self.deferred.push((req, deadline));+ ctx.request_repaint();+ } else {+ let _ = reply.send(json!({"ok": false, "error": msg}));+ }+ }+ control::Outcome::AfterInput => {+ self.input_waiters.push(reply);+ // The reply waits for a real UI pass: a hidden window must run one.+ self.want_paint = true;+ }+ control::Outcome::AwaitJobs(w) => {+ self.job_waiters.push((w, reply));+ ctx.request_repaint();+ }+ control::Outcome::Screenshot { path, target } => {+ // A covered or minimized window presents no frames (macOS skips its redraws), so+ // a screenshot would never arrive and nothing would tick its timeout. The+ // hidden-window capture path (a pending screenshot forces a pass in 0.37) needs+ // a native platform run before this gate is removed; the web build never paints+ // a hidden tab.+ if ctx.input(|i| i.viewport().occluded == Some(true) || i.viewport().minimized == Some(true)) {+ let _ = reply.send(json!({"ok": false, "error": "window is covered or minimized: call ui.focus first (render.frame renders comp pixels without the window)"}));+ continue;+ }+ self.admit_screenshot(ctx, path, target, reply);+ }+ }+ }+ self.control_rx = Some(rx);+ self.finish_job_waiters(ctx);+ }++ /// Reply to the control requests whose offloaded jobs ended.+ fn finish_job_waiters(&mut self, ctx: &egui::Context) {+ if self.job_waiters.is_empty() {+ return;+ }+ self.session.poll_render();+ self.session.poll_offload();+ let waiters = std::mem::take(&mut self.job_waiters);+ for (w, reply) in waiters {+ if w.pending(self) {+ self.job_waiters.push((w, reply));+ } else {+ let v = w.finish(self);+ let _ = reply.send(v);+ }+ }+ if !self.job_waiters.is_empty() {+ ctx.request_repaint_after(std::time::Duration::from_millis(50));+ }+ }++ // ---------------------------------------------------------------- frame++ /// Apply the engine events drained this tick: open a comp, show a toast, open a URL, run a frontend command,+ /// purge frame caches or copy an image; command and clipboard failures go to `app.ui.status`.+ pub(super) fn handle_events(&mut self, ctx: &egui::Context) {+ for ev in self.session.drain_events() {+ match ev {+ effectcraft_engine::Event::OpenComp(c) => {+ panels::viewers::on_open_comp(self, c);+ self.ui.timeline.pps = None;+ }+ effectcraft_engine::Event::Toast { message, .. } => self.toast = Some((message, self.now)),+ effectcraft_engine::Event::OpenUrl(url) => ctx.open_url(egui::OpenUrl::new_tab(url)),+ // Frames are keyed by content: an edit keeps those of comps it doesn't touch.+ effectcraft_engine::Event::ProjectChanged { .. } => {}+ effectcraft_engine::Event::Frontend { command, params } => {+ if let Err(e) = crate::menus::frontend(self, ctx, &command, params) {+ self.ui.status = e;+ }+ }+ effectcraft_engine::Event::PurgeCaches => self.frames.clear(),+ effectcraft_engine::Event::CopyImage { width, height, rgba } => {+ if let Err(e) = copy_image(ctx, width, height, &rgba) {+ self.ui.status = e;+ }+ }+ }+ }+ }++ /// The app's only non-paint entry: one tick of background work.+ ///+ /// This runs for every eframe logic callback, including the logic-only ticks of a hidden+ /// window (which never reach [`Self::draw`]). It must therefore do no input handling, no+ /// layout and no presentation: engine/job queues, autosave, playback, audio, the control+ /// channel, screenshots and the close guard. Everything here is idempotent for a pass that+ /// `Context::request_discard` replays.+ pub fn tick(&mut self, ctx: &egui::Context, frame: &eframe::Frame) {+ self.now = self.clock.now();+ // The compositor exists before the first paint and while hidden (device-loss handling+ // must run there too).+ self.init_gpu(frame);+ self.apply_gpu_failure(ctx);+ if self.gpu_failure_applied == Some(true) {+ self.close_after_device_loss(ctx);+ return;+ }+ // Focus comes from the fresh viewport copy; a full pass's `InputState::focused` is only a+ // fallback (a logic-only tick leaves it at the previous pass's value).+ let focused = ctx.input(|i| i.viewport().focused.or(Some(i.focused)));+ self.focused = focused.unwrap_or(self.focused);+ // The interface language's fallback fonts are installed in `draw` (fonts need a pass), but+ // commands handled here use the right catalog already.+ let language = crate::i18n::language(self);+ crate::i18n::set_current(language);++ // #1089: a font-menu rescan runs off the UI thread. Poll it on the logic tick so the++ // status and the menu update even when the window is not painting.++ crate::panels::text_panels::poll_font_rescan(self, ctx);+ if self.styled_language != language {+ self.want_paint = true;+ }+ // Frames and worker completions wake the app even while it is hidden.+ self.frames.set_context(ctx);+ updates_ui::tick(self, ctx);+ if self.session.render_job.is_some() {+ self.session.poll_render();+ ctx.request_repaint_after(std::time::Duration::from_millis(100));+ }+ if self.session.track_job.is_some() {+ self.session.poll_track();+ ctx.request_repaint_after(std::time::Duration::from_millis(50));+ }+ if self.session.mask_job.is_some() {+ self.session.poll_mask_track();+ ctx.request_repaint_after(std::time::Duration::from_millis(50));+ }+ // Background tasks (Content-Aware Fill, Scene Edit Detection, imports).+ if !self.session.tasks.is_empty() {+ self.session.poll_jobs();+ ctx.request_repaint_after(std::time::Duration::from_millis(100));+ }+ // Analyses running in a worker (the web app).+ if !self.session.offloaded.is_empty() {+ self.session.poll_offload();+ ctx.request_repaint_after(std::time::Duration::from_millis(100));+ }+ // Warp Stabilizer: finish analyses and start queued (re-)analyses in the background.+ if self.session.warp_job.is_some() || !self.session.warp_pending.is_empty() {+ self.session.poll_warp(true);+ self.session.poll_roto(true);+ ctx.request_repaint_after(std::time::Duration::from_millis(100));+ }+ // Roto Brush propagation and Object Matte tracking / Freeze: finish jobs (a Freeze writes+ // its mattes) and start queued ones in the background.+ if self.session.roto_job.is_some() || !self.session.roto_pending.is_empty() {+ self.session.poll_roto(true);+ ctx.request_repaint_after(std::time::Duration::from_millis(100));+ }+ // 3D Camera Tracker: likewise (tracking, then solving).+ if self.session.camera_job.is_some() || !self.session.camera_pending.is_empty() {+ self.session.poll_camera(true);+ ctx.request_repaint_after(std::time::Duration::from_millis(100));+ }+ self.run_script_tasks(ctx);+ self.run_dialog_answers();+ self.handle_events(ctx);+ if let Some(rx) = self.command_inbox.take() {+ while let Ok(id) = rx.try_recv() {+ if let Err(e) = menus::invoke(self, ctx, &id, json!({})) {+ self.ui.status = e;+ }+ }+ self.command_inbox = Some(rx);+ }+ // A close request (the window's button, Quit, `app.quit`) must be answered while hidden.+ // An answered file dialog can change the project, so the answers above run first. The host+ // calls `panels::unsaved::quit_on_close` last in its `logic`.+ panels::unsaved::on_close_requested(self, ctx);+ let title = panels::unsaved::window_title(self);+ if title != self.window_title {+ ctx.send_viewport_cmd(egui::ViewportCommand::Title(title.clone()));+ self.window_title = title;+ }+ self.tick_autosave(ctx);+ self.tick_workspace_autosave(ctx);+ let now = self.now;+ prefs_live::tick(self, ctx, now);+ // Playback advances without a paint (its frames and the audio clock are background work).+ // Idle prefetch keeps its old condition: it only runs once a viewer has drawn.+ if (self.playback.playing || self.last_viewer_scale.is_some())+ && let Some(cid) = self.session.active_comp_id()+ {+ let (scale, active) = (self.last_viewer_scale.unwrap_or(1.0), self.input_active);+ self.advance_playback(ctx, scale, now, active, cid);+ }+ self.drain_control(ctx, now);+ // Screenshot completion, deadlines and issuance are app-side work: the callback only+ // stores pixels and wakes this viewport.+ self.tick_screenshots(ctx);+ // Time-based FPS readout over UI passes (a hidden logic-only tick is not a frame).+ let dt = (now - self.last_time) as f32;+ if dt > 0.0 && dt < 2.0 {+ self.fps = self.fps * 0.9 + (1.0 / dt).min(480.0) * 0.1;+ }+ self.last_time = now;+ // A hidden window paints when work needs a UI pass: queued input and waits, a settled+ // screenshot, or playback into a child viewport.+ let focused = self.focused;+ let child_viewports = !self.ui.dock.layout.floating.is_empty() || prefs_live::video_preview_active(self, focused);+ let paint = self.want_paint+ || !self.synthetic.is_empty()+ || !self.input_waiters.is_empty()+ || self.pending_screenshots.iter().any(|s| s.slot.is_none())+ || (self.playback.playing && child_viewports);+ if paint {+ self.request_hidden_paint(ctx);+ }+ }++ /// Ask the host for a UI pass even when the window is minimized or occluded.+ ///+ /// Native eframe honours `RequestPaintWhileHidden`; the shared web backend does not carry it+ /// yet (a browser does not paint a hidden tab), so the web build only requests a normal+ /// repaint and hidden web screenshots/input remain unqualified.+ fn request_hidden_paint(&mut self, ctx: &egui::Context) {+ self.want_paint = false;+ #[cfg(not(target_arch = "wasm32"))]+ ctx.send_viewport_cmd(egui::ViewportCommand::RequestPaintWhileHidden);+ ctx.request_repaint();+ }++ /// Install the theme and fonts for the current language. Fonts need a real pass: the pass+ /// that installs them draws nothing, and the next pass draws with them (the two-pass warm-up+ /// the app has always had). Never call this from a logic-only tick.+ fn ui_setup(&mut self, ctx: &egui::Context) {+ panels::viewer_text::install_hooks(ctx);+ let language = crate::i18n::language(self);+ crate::i18n::set_current(language);+ if (!self.styled || self.styled_language != language) && self.synthetic_in_flight {+ // The install needs a pass that draws nothing, but this pass has already applied a+ // synthetic batch: defer the theme/font install by one pass instead of dropping the+ // input (feeds are only put into a pass that can draw).+ ctx.request_repaint();+ return;+ }+ if !self.styled || self.styled_language != language {+ theme::install(ctx, &self.tokens, language);+ self.styled_language = language;+ if !self.styled {+ fit_window(ctx);+ self.styled = true;+ }+ self.fonts_ready = false;+ ctx.request_repaint();+ } else if !self.fonts_ready {+ // The pass after the install draws: egui has the new font definitions by now.+ self.fonts_ready = true;+ ctx.request_repaint();+ }+ }++ /// One UI pass: setup, input-driven shortcuts, layout and painting. Called from+ /// `eframe::App::ui` and by tests with the root `Ui`.+ pub fn draw(&mut self, ui: &mut egui::Ui, frame: &eframe::Frame) {+ panels::viewer_text::begin_ui(ui.ctx());+ self.draw_inner(ui, frame);+ // All exits, including fonts/device loss, observe this pass's real custom availability.+ panels::viewer_text::finish_ime(self, ui);+ }++ /// Context creators install these hooks before the first full pass.+ pub fn install_ime_reset_hooks(ctx: &egui::Context) {+ panels::viewer_text::install_hooks(ctx);+ }++ /// Host wrappers call this after their last logic mutation, without replaying UI events.+ pub fn finish_ime_logic(&self, ctx: &egui::Context) {+ panels::viewer_text::finish_logic(self, ctx);+ }++ /// One UI pass after the IME begin hook: close on an applied GPU failure, run `ui_setup`, skip drawing until+ /// fonts are ready, draw the frame, finish pointer wrapping, pump queued wasm frames, record input activity,+ /// publish the completed pass's geometry and pass sequence, acknowledge applied synthetic input and answer+ /// `AfterInput` replies only after a non-discarded pass. Requests repaints while frames are in flight.+ fn draw_inner(&mut self, ui: &mut egui::Ui, frame: &eframe::Frame) {+ let ctx = ui.ctx().clone();+ if self.gpu_failure_applied == Some(true) {+ self.close_after_device_loss(&ctx);+ return;+ }+ self.ui_setup(&ctx);+ if !self.fonts_ready {+ // A pass that installs fonts draws nothing. No synthetic batch is in flight here (the+ // hook feeds input only to a ready app), and events egui already applied are never+ // fed again: that would double the pointer/key state of one click.+ ctx.request_repaint();+ return;+ }+ self.frame(ui);+ #[cfg(not(target_arch = "wasm32"))]+ pointer_wrap::finish_native(&ctx, frame);+ // wasm32: no frame threads; render queued frames now, between UI frames.+ if cfg!(target_arch = "wasm32") && self.frames.pump(std::time::Duration::from_millis(if self.playback.playing { 24 } else { 40 })) {+ ctx.request_repaint();+ }+ // Input belongs to this known UI phase: record it for the next tick.+ let active = ctx.input(|i| !i.events.is_empty() || i.pointer.any_down() || i.pointer.is_moving());+ self.input_active = active;+ self.last_pointer_down = ctx.input(|i| i.pointer.any_down());+ // Geometry of a completed pass (a discarded pass is laid out again; only the final one+ // describes the surface the next capture will see). Window position is irrelevant.+ if !ctx.will_discard() {+ let rect = ctx.content_rect();+ let ppp = ctx.pixels_per_point();+ let changed = self.draw_geom.is_none_or(|g| g.rect.size() != rect.size() || g.ppp != ppp);+ if changed {+ self.geometry_epoch = self.geometry_epoch.wrapping_add(1);+ }+ self.draw_geom = Some(DrawGeometry { rect, ppp, epoch: self.geometry_epoch });+ self.ui_pass_seq = self.ui_pass_seq.saturating_add(1);+ }+ // A batch is acknowledged once a UI pass applied it, even if layout was later discarded.+ self.mark_synthetic_applied();+ // `AfterInput` replies wait for the final (non-discarded) pass that applied the last+ // synthetic event: a hidden request is answered only after its forced pass, and a pass+ // egui throws away cannot produce an early success reply.+ if !ctx.will_discard() && self.synthetic.is_empty() {+ for w in self.input_waiters.drain(..) {+ let _ = w.send(json!({"ok": true, "result": null}));+ }+ } else if !self.input_waiters.is_empty() {+ self.want_paint = true;+ ctx.request_repaint();+ }+ if self.frames.inflight() > 0 {+ ctx.request_repaint_after(std::time::Duration::from_millis(30));+ }+ }++ /// The panels, menus, dialogs and overlays of one pass.+ fn frame(&mut self, ui: &mut egui::Ui) {+ let ctx = ui.ctx().clone();+ // Only a viewer that draws in *this* pass records a scale: a closed viewer, the Home+ // screen or another comp must stop idle prefetch at a stale scale.+ self.last_viewer_scale = None;+ self.apply_prefs(&ctx);+ // Video Preview is a second viewport: only a real pass can update it.+ prefs_live::frame(self, &ctx);+ self.auto.begin_frame();+ let tab_had_widget_focus = ctx.egui_wants_keyboard_input();+ menus::handle_shortcuts(self, &ctx);+ if !ctx.input(|i| i.pointer.primary_down()) {+ self.ui.viewer.property_interacting = false;+ }+ let t = self.tokens;+ let full = ui.max_rect();+ if self.dialog.is_some() {+ ui.disable();+ }+ ui.painter().rect_filled(full, 0.0, t.app_bg);+ let mut top = full.min.y;+ if self.ui.show_menu_bar {+ let mb = egui::Rect::from_min_size(full.min, egui::vec2(full.width(), 24.0));+ let mut child = ui.new_child(egui::UiBuilder::new().max_rect(mb));+ child.painter().rect_filled(mb, 0.0, t.header_bg);+ menus::menu_bar(self, &mut child);+ top = mb.max.y;+ }+ let header_h = 40.0;+ let header = egui::Rect::from_min_size(egui::pos2(full.min.x, top), egui::vec2(full.width(), header_h));+ header::show(self, ui, header);+ let body = egui::Rect::from_min_max(egui::pos2(full.min.x + 4.0, header.max.y + 2.0), egui::pos2(full.max.x - 4.0, full.max.y - 4.0));+ self.dock_area(ui, body);+ #[cfg(not(target_arch = "wasm32"))]+ prefs_live::dropped_files(self, ui, full);+ if !tab_had_widget_focus {+ menus::handle_tab_shortcut(self, &ctx);+ }+ panels::precomp::mini_flowchart(self, &ctx);+ panels::home::capture_thumbnail(self);+ panels::dialogs::show(self, &ctx);+ updates_ui::show(self, &ctx);+ panels::scriptui_view::sync_panels(self);+ panels::scriptui_view::show_windows(self, &ctx);+ panels::learn::coach(self, &ctx);+ let lift = panels::media_panels::import_card(self, ui, full);+ self.draw_toast(ui, full, lift);+ }++ /// Workspace-layout auto-save: a background write that also runs while hidden, once the+ /// pointer has lifted.+ fn tick_workspace_autosave(&mut self, ctx: &egui::Context) {+ if self.session.config.is_none() || !self.workspace_store.has_changes(&self.ui) || self.last_pointer_down {+ return;+ }+ if self.workspace_store.due(self.now) {+ self.save_workspace_state();+ }+ if self.workspace_store.has_changes(&self.ui) {+ ctx.request_repaint_after(std::time::Duration::from_secs(1));+ }+ }++ pub(super) fn save_workspace_state(&mut self) {+ if let Err(error) = self.workspace_store.save(self.session.config.as_deref(), &self.ui) {+ if self.workspace_store.error.as_ref() != Some(&error) {+ log::warn!("{error}");+ self.ui.status = error.clone();+ }+ self.workspace_store.error = Some(error);+ }+ }++ /// The status message or the latest toast, bottom left (`lift` points higher while the+ /// Importing card is there).+ fn draw_toast(&mut self, ui: &mut egui::Ui, full: egui::Rect, lift: f32) {+ let now = self.now;+ let msg = if !self.ui.status.is_empty() {+ Some(self.ui.status.clone())+ } else {+ self.toast.as_ref().filter(|(_, at)| now - at < 4.0).map(|(m, _)| m.clone())+ };+ if let Some(m) = msg {+ let t = &self.tokens;+ let galley = ui.painter().layout_no_wrap(m.clone(), Tokens::ui(12.0), t.text);+ let r = egui::Rect::from_min_size(egui::pos2(full.min.x + 16.0, full.max.y - 44.0 - lift), galley.size() + egui::vec2(24.0, 14.0));+ ui.painter().rect_filled(r, 6.0, t.panel_bg);+ ui.painter().rect_stroke(r, 6.0, egui::Stroke::new(1.0, t.field_border), egui::StrokeKind::Inside);+ ui.painter().galley(r.min + egui::vec2(12.0, 7.0), galley, t.text);+ self.auto.add("toast", r, &m);+ let resp = ui.interact(r, egui::Id::unique("toast"), egui::Sense::click());+ if resp.clicked() {+ self.ui.status.clear();+ self.toast = None;+ }+ ui.ctx().request_repaint_after(std::time::Duration::from_millis(500));+ if !self.ui.status.is_empty() {+ let since: f64 = ui.data(|d| d.get_temp(egui::Id::unique("status-since")).unwrap_or(now));+ ui.data_mut(|d| d.insert_temp(egui::Id::unique("status-since"), since));+ if now - since > 5.0 {+ self.ui.status.clear();+ ui.data_mut(|d| d.remove::<f64>(egui::Id::unique("status-since")));+ }+ }+ }+ }+ }++ impl EffectcraftApp {+ /// Scripts' `app.scheduleTask` tasks that are due (repeating ones keep a ScriptUI panel+ /// fresh): errors as a toast, the last line printed in the status bar, and a repaint when+ /// the next one is due.+ fn run_script_tasks(&mut self, ctx: &egui::Context) {+ if self.session.script_ui.task_hosts.is_empty() {+ return;+ }+ let previous_comp = self.session.active_comp_id();+ let Some(r) = effectcraft_engine::scriptui::ScriptUi::run_tasks(&mut self.session) else { return };+ if self.session.active_comp_id().is_some() && self.session.active_comp_id() != previous_comp {+ self.ui.start_screen = false;+ }+ if let Some(msg) = r["errors"].as_array().and_then(|e| e.first()).and_then(|e| e["message"].as_str()) {+ self.toast = Some((format!("Scheduled script task: {msg}"), self.now));+ } else if let Some(line) = r["output"].as_array().and_then(|o| o.last()).and_then(|l| l.as_str()) {+ self.ui.status = line.to_string();+ }+ if let Some(next) = r["next"].as_u64() {+ ctx.request_repaint_after(std::time::Duration::from_millis(next));+ }+ }++ /// Auto-save a dirty project when the interval has passed (Settings ▸ Project ▸ Auto-Save).+ fn tick_autosave(&mut self, ctx: &egui::Context) {+ // Monotonic app time: a wall-clock jump must not skip or repeat an auto-save.+ let now = self.now;+ if let Some(Err(e)) = self.session.autosave_tick(now) {+ self.ui.status = e.to_string();+ }+ if self.session.prefs.auto_save.enabled {+ ctx.request_repaint_after(std::time::Duration::from_secs(30));+ }+ // File ▸ Watch Folder: look for new projects every 10 seconds.+ if self.session.state.watch_folder.is_some() {+ let key = egui::Id::unique("watchFolder.lastPoll");+ let last: f64 = ctx.data(|d| d.get_temp(key)).unwrap_or(0.0);+ if now - last >= 10.0 {+ ctx.data_mut(|d| d.insert_temp(key, now));+ match self.session.execute("file.watchFolder.poll", serde_json::json!({})) {+ Ok(r) => {+ if let Some(n) = r["rendered"].as_array().map(Vec::len).filter(|n| *n > 0) {+ self.ui.status = format!("Watch Folder: rendered {n} project(s)");+ }+ }+ Err(e) => self.ui.status = e.to_string(),+ }+ }+ ctx.request_repaint_after(std::time::Duration::from_secs(10));+ }+ self.tick_footage_reload(ctx, now);+ }++ /// Settings ▸ Import ▸ Reload Footage Changed on Disk: every two seconds, and as soon as the+ /// window comes back to the front (after saving in another app), stamp the footage files on a+ /// worker thread and reload the ones that changed.+ fn tick_footage_reload(&mut self, ctx: &egui::Context, now: f64) {+ use effectcraft_engine::footage_reload;+ if let Some(Err(e)) = footage_reload::poll_scan(&mut self.session) {+ self.ui.status = e.to_string();+ }+ let (last_key, focus_key) = (egui::Id::unique("footageReload.lastScan"), egui::Id::unique("footageReload.focused"));+ let focused = self.focused;+ let was_focused: bool = ctx.data(|d| d.get_temp(focus_key)).unwrap_or(focused);+ ctx.data_mut(|d| d.insert_temp(focus_key, focused));+ if self.session.prefs.import.auto_reload_footage == "off" || self.session.project.items.is_empty() {+ return;+ }+ let last: f64 = ctx.data(|d| d.get_temp(last_key)).unwrap_or(0.0);+ if now - last >= 2.0 || (focused && !was_focused) {+ ctx.data_mut(|d| d.insert_temp(last_key, now));+ footage_reload::start_scan(&mut self.session);+ }+ if self.session.footage_scan.is_some() {+ ctx.request_repaint_after(std::time::Duration::from_millis(100));+ } else {+ ctx.request_repaint_after(std::time::Duration::from_secs(2));+ }+ }+ }diff --cc crates/ui-egui/src/panels/text_panels.rsindex 28f41e3b6,8a8e604e2..70de9c282--- a/crates/ui-egui/src/panels/text_panels.rs+++ b/crates/ui-egui/src/panels/text_panels.rs@@@ -571,18 -629,7 +629,18 @@@ struct FontSearchselected: usize,}+ /// Shared font menu for Character and Properties: search, recent fonts and previews.+/// Finish a font rescan started from the font menu and report how many faces it added.+/// While the scan is still walking font folders, ask for another frame so the menu updates.+pub(crate) fn poll_font_rescan(app: &mut EffectcraftApp, ctx: &egui::Context) {+ if effectcraft_engine::text::fonts::rescan_busy() {+ ctx.request_repaint_after(std::time::Duration::from_millis(100));+ }+ if let Some(n) = effectcraft_engine::text::fonts::poll_rescan() {+ app.ui.status = format!("{} +{n}", tr("Rescan Fonts"));+ }+}+- /// Shared font menu for Character and Properties: search, recent fonts and previews.pub(super) fn font_picker(app: &mut EffectcraftApp, ui: &mut egui::Ui, id: egui::Id, rect: Rect, current: &str, auto: &str, enabled: bool) -> Option<String> {let state_id = id.with("search-state");app.auto.add(auto, rect, "Font family");@@@ -633,139 -680,131 +691,140 @@@return None;}app.auto.add(&format!("{auto}.toggle"), arrow, "Close font list");- let mut chosen = None;- let screen = ui.ctx().content_rect();- let below = screen.bottom() - rect.bottom() - 16.0;- let above = below < 100.0 && rect.top() - screen.top() > below;- let max_height = (if above { rect.top() - screen.top() - 16.0 } else { below }).clamp(28.0, 380.0);- let anchor = if above { rect.left_top() } else { rect.left_bottom() };- let pivot = if above { Align2::LEFT_BOTTOM } else { Align2::LEFT_TOP };widgets::note_open_popup_list(ui.ctx());- let area = egui::Area::new(id.with("area")).order(egui::Order::Foreground).pivot(pivot).fixed_pos(anchor).show(ui.ctx(), |ui| {- egui::Frame::popup(ui.style()).show(ui, |ui| {- ui.set_width(rect.width().max(180.0));- // Filter row: a checkbox that keeps only the variable fonts.- let filter_h = 22.0;- let row = ui.add_sized([ui.available_width(), filter_h], egui::Button::selectable(false, ""));- let box_rect = Rect::from_min_size(row.rect.min, vec2(18.0, filter_h));- let label_rect = Rect::from_min_max(pos2(box_rect.max.x + 2.0, row.rect.min.y), row.rect.max);- let boxed = widgets::checkbox(ui, box_rect, only_variable, &t, id.with("variable-check"));- ui.painter().text(label_rect.left_center(), Align2::LEFT_CENTER, tr("Variable fonts only"), Tokens::ui(11.5), t.text);- app.auto.add(&format!("{auto}.variable"), row.rect, "Variable fonts only");- let toggled = row.clicked() || boxed.clicked();- if toggled {- only_variable = !only_variable;- ui.data_mut(|d| d.insert_temp(variable_id, only_variable));- // Typing goes on into the search field.- ui.memory_mut(|m| m.request_focus(search_id));- }- // #1089: fonts installed after launch appear without restarting. The button is its own- // row: the popup is only 180 px wide, so a control pinned to the filter row covers- // "Variable fonts only". The scan itself runs off the UI thread (`poll_font_rescan`).- let rescan_h = 22.0;- let (resc, _) = ui.allocate_exact_size(vec2(ui.available_width(), rescan_h), egui::Sense::hover());- if widgets::text_button(ui, resc, tr("Rescan Fonts"), false, &t, id.with("rescan")).clicked() && effectcraft_engine::text::fonts::start_rescan() {- app.ui.status = format!("{}…", tr("Rescan Fonts"));- }- app.auto.add(&format!("{auto}.rescan"), resc, "Rescan Fonts");- let query = state.query.trim().to_lowercase();- let mut seen = std::collections::HashSet::new();- let filtered: Vec<_> = rows- .iter()- .filter(|r| {- !r.family.is_empty()- && (!only_variable || r.variable)- && (query.is_empty()- || ((r.family.to_lowercase().contains(&query) || r.display.to_lowercase().contains(&query)) && seen.insert(&r.family)))- })- .collect();- if fresh {- state.selected = filtered.iter().position(|r| r.family == current).unwrap_or(0);- }- if search.changed() || toggled {- state.selected = 0;- }- let last = filtered.len().saturating_sub(1);- state.selected = state.selected.min(last);- if down {- state.selected = state.selected.saturating_add(1).min(last);- }- if up {- state.selected = state.selected.saturating_sub(1);+ let changed = search.changed();+ let mut open = true;+ // The search lives in the field; the menu's header is the filter row, its list the fonts.+ let menu = craft_ui::combo::Menu::new(ui, &search)+ .open(&mut open)+ .height(380.0)+ .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside)+ .style(egui::style::StyleModifier::default());+ let app_ref = &mut *app;+ let header = |ui: &mut egui::Ui| {+ ui.set_width(rect.width().max(180.0));+ // Filter row: a checkbox that keeps only the variable fonts.+ let filter_h = 22.0;+ let row = ui.add_sized([ui.available_width(), filter_h], egui::Button::selectable(false, ""));+ let box_rect = Rect::from_min_size(row.rect.min, vec2(18.0, filter_h));+ let label_rect = Rect::from_min_max(pos2(box_rect.max.x + 2.0, row.rect.min.y), row.rect.max);+ let boxed = widgets::checkbox(ui, box_rect, only_variable, &t, id.with("variable-check"));+ ui.painter().text(label_rect.left_center(), Align2::LEFT_CENTER, tr("Variable fonts only"), Tokens::ui(11.5), t.text);+ app_ref.auto.add(&format!("{auto}.variable"), row.rect, "Variable fonts only");++ // #1089: fonts installed after launch appear without restarting. The button is its own++ // row: the popup is only 180 px wide, so a control pinned to the filter row covers++ // "Variable fonts only". The scan itself runs off the UI thread (`poll_font_rescan`).++ let rescan_h = 22.0;++ let (resc, _) = ui.allocate_exact_size(vec2(ui.available_width(), rescan_h), egui::Sense::hover());++ if widgets::text_button(ui, resc, tr("Rescan Fonts"), false, &t, id.with("rescan")).clicked() && effectcraft_engine::text::fonts::start_rescan() {++ app_ref.ui.status = format!("{}…", tr("Rescan Fonts"));++ }++ app_ref.auto.add(&format!("{auto}.rescan"), resc, "Rescan Fonts");+ let toggled = row.clicked() || boxed.clicked();+ if toggled {+ only_variable = !only_variable;+ ui.data_mut(|d| d.insert_temp(variable_id, only_variable));+ // Typing goes on into the search field.+ ui.memory_mut(|m| m.request_focus(search_id));+ }+ let query = state.query.trim().to_lowercase();+ let mut seen = std::collections::HashSet::new();+ let filtered: Vec<_> = rows+ .iter()+ .filter(|r| {+ !r.family.is_empty()+ && (!only_variable || r.variable)+ && (query.is_empty() || ((r.family.to_lowercase().contains(&query) || r.display.to_lowercase().contains(&query)) && seen.insert(&r.family)))+ })+ .collect();+ if fresh {+ state.selected = filtered.iter().position(|r| r.family == current).unwrap_or(0);+ }+ if changed || toggled {+ state.selected = 0;+ }+ let last = filtered.len().saturating_sub(1);+ state.selected = state.selected.min(last);+ if down {+ state.selected = state.selected.saturating_add(1).min(last);+ }+ if up {+ state.selected = state.selected.saturating_sub(1);+ }+ let entered = if enter { filtered.get(state.selected).map(|r| r.family.clone()) } else { None };+ (app_ref, filtered, query.is_empty(), state.selected, changed || toggled, entered)+ };+ let list = |ui: &mut egui::Ui,+ (app, filtered, all, selected, restart, entered): (+ &mut EffectcraftApp,+ Vec<&effectcraft_engine::FontRow>,+ bool,+ usize,+ bool,+ Option<String>,+ )| {+ if restart {+ ui.scroll_to_cursor(Some(egui::Align::TOP));+ }+ let mut chosen = entered;+ if filtered.is_empty() {+ let r = ui.label(tr("No matching fonts"));+ app.auto.add(&format!("{auto}.empty"), r.rect, "No matching fonts");+ }+ let mut was_recent = false;+ for (index, r) in filtered.iter().enumerate() {+ if all && was_recent && !r.recent {+ ui.separator();}- if enter {- chosen = filtered.get(state.selected).map(|r| r.family.clone());+ was_recent = r.recent;+ let row_width = ui.available_width();+ let label_width = if preview { (row_width - 100.0).max(40.0) } else { row_width };+ let resp = ui.add_sized([row_width, 24.0], egui::Button::selectable(index == selected, ""));+ resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, ui.is_enabled(), index == selected, &r.display));+ let label_rect = Rect::from_min_size(resp.rect.min + vec2(5.0, 0.0), vec2(label_width - 5.0, resp.rect.height()));+ ui.painter().with_clip_rect(label_rect.intersect(ui.clip_rect())).text(+ label_rect.left_center(),+ Align2::LEFT_CENTER,+ &r.display,+ Tokens::ui(12.0),+ t.text,+ );+ if ui.is_rect_visible(resp.rect) {+ app.auto.add(&format!("{auto}.option.{}", r.family), resp.rect, &r.display);}- // Give the result list its actual height even when the previous query had- // only one row. A cached tiny Area must not collapse a reopened long list.- let filter_room = filter_h + rescan_h + ui.spacing().item_spacing.y * 2.0;- let height = (filtered.len() as f32 * (24.0 + ui.spacing().item_spacing.y) + 16.0).clamp(28.0, (max_height - filter_room).max(28.0));- // A minimum, from below the filter row (a maximum would move the cursor back up).- ui.set_min_height(height);- let mut scroll = egui::ScrollArea::vertical().id_salt(id.with("results")).max_height(height).min_scrolled_height(height);- if search.changed() || toggled {- scroll = scroll.vertical_scroll_offset(0.0);+ if index == selected && (fresh || up || down) {+ resp.scroll_to_me(None);}- scroll.show(ui, |ui| {- if filtered.is_empty() {- let r = ui.label(tr("No matching fonts"));- app.auto.add(&format!("{auto}.empty"), r.rect, "No matching fonts");- }- let mut was_recent = false;- for (index, r) in filtered.iter().enumerate() {- if query.is_empty() && was_recent && !r.recent {- ui.separator();- }- was_recent = r.recent;- let row_width = ui.available_width();- let label_width = if preview { (row_width - 100.0).max(40.0) } else { row_width };- let resp = ui.add_sized([row_width, 24.0], egui::Button::selectable(index == state.selected, ""));- resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, ui.is_enabled(), index == state.selected, &r.display));- let label_rect = Rect::from_min_size(resp.rect.min + vec2(5.0, 0.0), vec2(label_width - 5.0, resp.rect.height()));- ui.painter().with_clip_rect(label_rect.intersect(ui.clip_rect())).text(- label_rect.left_center(),- Align2::LEFT_CENTER,- &r.display,- Tokens::ui(12.0),- t.text,- );- if ui.is_rect_visible(resp.rect) {- app.auto.add(&format!("{auto}.option.{}", r.family), resp.rect, &r.display);+ if preview && ui.is_rect_visible(resp.rect) {+ let key = egui::Id::unique(("font-preview", &r.family));+ let lines: std::sync::Arc<Vec<Vec<[f32; 2]>>> = match ui.data(|d| d.get_temp(key)) {+ Some(l) => l,+ None => {+ let l = std::sync::Arc::new(effectcraft_engine::font_preview(&r.family, 14.0));+ ui.data_mut(|d| d.insert_temp(key, l.clone()));+ l}- if index == state.selected && (fresh || up || down) {- resp.scroll_to_me(None);- }- if preview && ui.is_rect_visible(resp.rect) {- let key = egui::Id::unique(("font-preview", &r.family));- let lines: std::sync::Arc<Vec<Vec<[f32; 2]>>> = match ui.data(|d| d.get_temp(key)) {- Some(l) => l,- None => {- let l = std::sync::Arc::new(effectcraft_engine::font_preview(&r.family, 14.0));- ui.data_mut(|d| d.insert_temp(key, l.clone()));- l- }- };- // Scaled and placed to fit the row's preview column, and clipped to the row (#577).- let room = Rect::from_min_max(pos2(resp.rect.max.x - 95.0, resp.rect.min.y + 1.0), pos2(resp.rect.max.x - 6.0, resp.rect.max.y - 1.0));- if let Some((k, o)) = fit_preview(&lines, room, resp.rect.center().y + 5.0) {- let painter = ui.painter().with_clip_rect(resp.rect.intersect(ui.clip_rect()));- for poly in lines.iter() {- let pts: Vec<egui::Pos2> =- poly.iter().filter(|p| p[0].is_finite() && p[1].is_finite()).map(|p| (o + vec2(p[0], p[1]) * k).to_pos2()).collect();- painter.add(egui::Shape::line(pts, egui::Stroke::new(1.0, t.text_dim)));- }- }- }- if resp.clicked() {- chosen = Some(r.family.clone());+ };+ // Scaled and placed to fit the row's preview column, and clipped to the row (#577).+ let room = Rect::from_min_max(pos2(resp.rect.max.x - 95.0, resp.rect.min.y + 1.0), pos2(resp.rect.max.x - 6.0, resp.rect.max.y - 1.0));+ if let Some((k, o)) = fit_preview(&lines, room, resp.rect.center().y + 5.0) {+ let painter = ui.painter().with_clip_rect(resp.rect.intersect(ui.clip_rect()));+ for poly in lines.iter() {+ let pts: Vec<egui::Pos2> =+ poly.iter().filter(|p| p[0].is_finite() && p[1].is_finite()).map(|p| (o + vec2(p[0], p[1]) * k).to_pos2()).collect();+ painter.add(egui::Shape::line(pts, egui::Stroke::new(1.0, t.text_dim)));}- resp.on_hover_text(&r.display);}- });- });- });- let outside = widgets::pressed_outside(ui.ctx(), &area.response) && !ui.input(|i| i.pointer.interact_pos().is_some_and(|p| rect.contains(p)));- if chosen.is_some() || outside || escape {+ }+ if resp.clicked() {+ chosen = Some(r.family.clone());+ }+ resp.on_hover_text(&r.display);+ }+ chosen+ };+ let chosen = menu.show_ui_with_header(header, list).flatten();+ if chosen.is_some() || !open || escape {ui.data_mut(|d| {d.insert_temp(id.with("open"), false);d.remove::<FontSearch>(state_id);diff --cc crates/ui-egui/tests/it/ui_font_search.rsindex 0d9c7b79a,122003abe..b3c1a919a--- a/crates/ui-egui/tests/it/ui_font_search.rs+++ b/crates/ui-egui/tests/it/ui_font_search.rs@@@ -177,23 -177,36 +177,57 @@@ fn font_menu_filters_variable_fonts()assert_eq!(layer_doc(&h.state().session, LayerId(lid)).unwrap().font, "Inter", "filtering changes nothing");}+ /// The font menu grows back when a query that matched nothing is cleared, while the search+ /// field keeps its place and the keyboard; a click on a row then picks that font.+ #[test]+ fn font_menu_grows_back_after_an_empty_search() {+ let mut s = Session::default();+ s.execute("comp.new", json!({"width": 320, "height": 180})).unwrap();+ let lid = s.execute("layer.newText", json!({"text": "Grow", "font": "Inter"})).unwrap()["layer"].as_u64().unwrap();+ let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).build_eframe(move |_| EffectcraftApp::new(s));+ h.state_mut().show_panel(PanelKind::Character);+ h.run_steps(3);+ let rows = |h: &Harness<'_, EffectcraftApp>| h.state().auto.query("character.font.option.").len();+ let search = |h: &Harness<'_, EffectcraftApp>| h.state().auto.find("character.font.search").map(|e| e.rect);+ click(&mut h, "character.font");+ h.run_steps(2);+ let (full, field) = (rows(&h), search(&h));+ assert!(full > 3, "the open menu shows the fonts: {full} rows");+ let query = "no_such_font_123456789";+ type_text(&mut h, query);+ assert_eq!(rows(&h), 0);+ assert!(h.state().auto.find("character.font.empty").is_some());+ for pressed in query.chars().flat_map(|_| [true, false]) {+ h.input_mut().events.push(Event::Key { key: Key::Backspace, physical_key: None, pressed, repeat: false, modifiers: Modifiers::NONE });+ }+ h.run_steps(3);+ // (Within a row: the list scrolls to the current font on opening and to the top when cleared.)+ assert!(rows(&h) + 1 >= full, "cleared, the menu shows as many fonts as when it opened: {} of {full}", rows(&h));+ assert_eq!(search(&h), field, "the search field stays put");+ // The field still has the keyboard: typing filters again.+ type_text(&mut h, "JetBrains");+ assert!(rows(&h) > 0 && h.state().auto.query("character.font.option.").iter().all(|r| r.label.contains("JetBrains")));+ click(&mut h, "character.font.option.JetBrains Mono");+ assert_eq!(layer_doc(&h.state().session, LayerId(lid)).unwrap().font, "JetBrains Mono", "a click on a row picks the font");+ }+++/// #1089: the font menu can re-run the system scan without restarting the app, and the press+/// does not also flip the "Variable fonts only" filter.+#[test]+fn font_menu_rescan_button_adds_fonts_installed_later() {+ let mut s = Session::default();+ s.execute("comp.new", json!({"width": 320, "height": 180})).unwrap();+ s.execute("layer.newText", json!({"text": "Keep this text", "font": "Inter"})).unwrap();+ let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).build_eframe(move |_| EffectcraftApp::new(s));+ h.state_mut().show_panel(PanelKind::Character);+ h.run_steps(3);+ click(&mut h, "character.font");+ h.run_steps(3);+ assert!(h.state().auto.find("character.font.rescan").is_some(), "the filter row offers a rescan");+ click(&mut h, "character.font.rescan");+ assert!(h.state().ui.status.contains("Rescan Fonts"), "the status reports the rescan: {}", h.state().ui.status);+ // The popup stays open, the variable filter did not flip, and the list still has the bundled families.+ assert!(h.state().auto.find("character.font.search").is_some(), "the popup stays open");+ let rows = h.state().auto.query("character.font.option.");+ assert!(rows.iter().any(|r| r.label == "Inter"), "{:?}", rows.iter().map(|r| &r.label).collect::<Vec<_>>());+}