GitCorner

Code

ossartcraftvectorcraft🌐
2bc41aeb8602
//! Type → Find Font…: the fonts the document uses (missing ones marked), Find (select the text
//! using a font), Change / Change All to another font from the list Replace With Font From shows
//! (the document's fonts, the recent fonts or every installed font), and Find in Folder… (the
//! missing fonts' files, in the Missing Fonts dialog: `ui.findFontsInFolder`). Find In limits Find
//! to the active artboard or the selected layers.

use std::sync::Arc;

use egui::Ui;
use serde_json::{Value, json};

use crate::VectorcraftApp;
use crate::caches::{FindFontCache, FontsKey};
use crate::state::Dialog;
use crate::theme::Tokens;
use crate::widgets;

/// Open the dialog.
pub fn open(app: &mut VectorcraftApp) {
    open_at(app, 0);
}

/// Open the dialog on the first font the document misses, to replace it (Missing Fonts' Find
/// Fonts).
pub fn open_on_missing(app: &mut VectorcraftApp) {
    let first = document_fonts(app, false).0.iter().position(|f| matches!(f["status"].as_str(), Some("missing" | "substitute")));
    open_at(app, first.unwrap_or(0));
}

/// Open the dialog with the document's font `selected` (an index into `text.fonts`) chosen,
/// System's font ([`system_family`]) to change to, and the last Find In choice (Document at first).
fn open_at(app: &mut VectorcraftApp, selected: usize) {
    let find_in = FIND_IN.iter().find(|f| **f == app.ui.find_font_in).copied().unwrap_or("document");
    let (used, _) = document_fonts(app, false);
    let source = "system";
    let rows = replacement_rows(app, source, &used);
    let family = system_family();
    let style = rows.iter().find(|r| r.family.eq_ignore_ascii_case(&family)).map(|r| r.style.clone()).unwrap_or_default();
    app.ui.dialog = Some(Dialog::new(
        "findFont",
        json!({ "selected": selected, "family": family, "style": style, "selectionOnly": false, "replaceFrom": source, "rows": rows_json(&rows), "findIn": find_in }),
    ));
}

/// The font System chooses: Source Sans 3 when it is installed, otherwise the font menu's first
/// family (none when the menu is empty).
fn system_family() -> String {
    system_family_in(installed, &vectorcraft_text::FontDb::global().menu_family_list())
}

/// [`system_family`] for the installed check `is_installed` and the font menu `menu`.
fn system_family_in(is_installed: impl Fn(&str) -> bool, menu: &[String]) -> String {
    const PREFERRED: &str = "Source Sans 3";
    if is_installed(PREFERRED) { PREFERRED.to_string() } else { menu.first().cloned().unwrap_or_default() }
}

/// Replace With Font From's lists (the `replaceFrom` field): the document's fonts, the recent
/// fonts and every installed font.
const SOURCES: [&str; 3] = ["document", "recent", "system"];
const SOURCE_LABELS: [&str; 3] = ["Document", "Recent", "System"];

/// The families Replace With Font From lists. `None` is System: the font menu, every installed
/// family. Document lists the families `text.fonts` names, once each, in its order; Recent lists
/// the font menu's recent families (newest first, Number of Recent Fonts at most) that are
/// installed.
fn replacement_families(app: &VectorcraftApp, source: &str, used: &[Value]) -> Option<Vec<String>> {
    let names: Vec<String> = match source {
        "document" => used.iter().filter_map(|f| f["family"].as_str()).map(str::to_string).collect(),
        "recent" => {
            let installed = vectorcraft_text::FontDb::global().menu_family_list();
            app.recent_fonts().iter().filter_map(|r| installed.iter().find(|f| f.eq_ignore_ascii_case(r)).cloned()).collect()
        }
        _ => return None,
    };
    let mut out: Vec<String> = vec![];
    for n in names {
        if !out.iter().any(|o| o.eq_ignore_ascii_case(&n)) {
            out.push(n);
        }
    }
    Some(out)
}

/// A row of Replace With Font: a family and one of its styles (`""` is the family's closest style),
/// so one click picks both.
#[derive(Clone, Debug, PartialEq)]
struct Row {
    family: String,
    style: String,
}

/// What the row says: the family and its style, or the family alone for its closest style.
fn row_label(family: &str, style: &str) -> String {
    if style.is_empty() { family.to_string() } else { format!("{family} {style}") }
}

/// Does a row match the search `query` (lower case): its family and style, as typed.
fn row_matches(family: &str, style: &str, query: &str) -> bool {
    query.is_empty() || format!("{family} {style}").to_lowercase().contains(query)
}

/// Replace With Font's rows for `source` ([`SOURCES`]). Document lists the family and style pairs
/// `text.fonts` names, once each, in its order; Recent and System list their families with each
/// family's closest style and then its styles.
fn replacement_rows(app: &VectorcraftApp, source: &str, used: &[Value]) -> Vec<Row> {
    let db = vectorcraft_text::FontDb::global();
    let mut rows: Vec<Row> = vec![];
    match source {
        "document" => {
            for f in used {
                let (family, style) = (f["family"].as_str().unwrap_or_default(), f["style"].as_str().unwrap_or_default());
                if rows.iter().any(|r| r.family.eq_ignore_ascii_case(family) && r.style.eq_ignore_ascii_case(style)) {
                    continue;
                }
                rows.push(Row { family: family.to_string(), style: style.to_string() });
            }
        }
        "recent" => {
            for family in replacement_families(app, "recent", used).unwrap_or_default() {
                push_family(&mut rows, db, &family);
            }
        }
        _ => {
            for family in db.menu_family_list().iter() {
                push_family(&mut rows, db, family);
            }
        }
    }
    rows
}

/// Add `family` to `rows`: each style once, the closest style first, every row naming its style.
fn push_family(rows: &mut Vec<Row>, db: &vectorcraft_text::FontDb, family: &str) {
    if family.is_empty() {
        return;
    }
    let mut styles = db.styles(family);
    // The style a style-less request picks comes first, by its own name, not again without one. Its
    // name comes from the catalog's metadata: the rows of every family would otherwise have to read
    // the family's font files.
    if let Some(closest) = db.closest_style(family)
        && let Some(i) = styles.iter().position(|s| s.eq_ignore_ascii_case(&closest))
    {
        let style = styles.remove(i);
        styles.insert(0, style);
    }
    if styles.is_empty() {
        rows.push(Row { family: family.to_string(), style: String::new() });
        return;
    }
    for style in styles {
        rows.push(Row { family: family.to_string(), style });
    }
}

/// `rows` as the dialog stores them (`{"family": …, "style": …}`).
fn rows_json(rows: &[Row]) -> Value {
    Value::Array(rows.iter().map(|r| json!({ "family": r.family, "style": r.style })).collect())
}

/// Can the replacement name that very face: `family` and `style` both exist, no stand-in. A row of
/// an unavailable style stays listed, but only a font with that style is chosen as the replacement.
fn exact(family: &str, style: &str) -> bool {
    !family.is_empty() && vectorcraft_text::FontDb::global().resolve(family, style).is_some_and(|(_, m)| m == vectorcraft_text::FontMatch::Exact)
}

/// Can a row be chosen as the replacement: its family is installed and the style is the font's own
/// (or the family names no styles, and its closest style stands for them).
fn listed(row: &Row) -> bool {
    installed(&row.family) && (row.style.is_empty() || exact(&row.family, &row.style))
}

/// Is `family` installed: it resolves to a face of its own, as `text.replaceFont` requires.
fn installed(family: &str) -> bool {
    !family.is_empty()
        && vectorcraft_text::FontDb::global().resolve(family, "Regular").is_some_and(|(_, m)| m != vectorcraft_text::FontMatch::Missing)
}

/// Can Change and Change All replace with the dialog's font: a family is chosen, it is installed,
/// and it is one of the list Replace With Font From shows (System's list is the font menu).
fn can_replace(d: &Dialog, families: Option<&[String]>) -> bool {
    let family = d.str("family");
    let style = d.str("style");
    if !style.is_empty() && !exact(&family, &style) {
        return false;
    }
    match families {
        Some(list) => can_replace_in(&family, installed, list),
        None => can_replace_in(&family, installed, &vectorcraft_text::FontDb::global().menu_family_list()),
    }
}

/// [`can_replace`] for the installed check `is_installed` and the shown list `list`.
fn can_replace_in(family: &str, is_installed: impl Fn(&str) -> bool, list: &[String]) -> bool {
    is_installed(family) && list.iter().any(|f| f.eq_ignore_ascii_case(family))
}

/// Show list `source` ([`SOURCES`]): the chosen family stays when the list has it and it is
/// installed, otherwise the list's first installed family (none when there is none) is chosen in
/// its closest style. System chooses [`system_family`].
fn set_source(app: &VectorcraftApp, d: &mut Dialog, source: &str, used: &[Value]) {
    d.fields.insert("replaceFrom".into(), json!(source));
    let rows = replacement_rows(app, source, used);
    d.fields.insert("rows".into(), rows_json(&rows));
    // The chosen font stays only when the new list has that family and style; otherwise the family
    // and the style both come from a row the list shows, so Change replaces with what is listed.
    let (family, style) = (d.str("family"), d.str("style"));
    if rows.iter().any(|r| r.family.eq_ignore_ascii_case(&family) && r.style.eq_ignore_ascii_case(&style) && listed(r)) {
        return;
    }
    let system = if source == "system" { system_family() } else { String::new() };
    let pick =
        rows.iter().find(|r| !system.is_empty() && r.family.eq_ignore_ascii_case(&system) && listed(r)).or_else(|| rows.iter().find(|r| listed(r)));
    d.fields.insert("family".into(), json!(pick.map(|r| r.family.clone()).unwrap_or_default()));
    d.fields.insert("style".into(), json!(pick.map(|r| r.style.clone()).unwrap_or_default()));
}

/// Find In's choices (the `findIn` field): the whole document, the active artboard, or the layers
/// highlighted in the Layers panel (else the current layer).
const FIND_IN: [&str; 3] = ["document", "artboard", "layers"];
const FIND_IN_LABELS: [&str; 3] = ["Document", "Artboard", "Layers"];

/// The `scope` Find passes `select.font` for Find In choice `find_in`. A document without
/// artboards, or without a layer to look in, is looked through whole.
fn find_scope(app: &VectorcraftApp, find_in: &str) -> Value {
    let Some(st) = app.session.active() else { return json!("document") };
    let n = st.doc.artboards.len();
    match find_in {
        "artboard" if n > 0 => json!({ "artboards": [crate::panels::artboards::selected(app, n)] }),
        "layers" => {
            let is_layer = |id: &vectorcraft_doc::NodeId| st.doc.node(*id).is_some_and(vectorcraft_doc::Node::is_layer);
            let mut layers: Vec<u64> = st.highlighted_rows().into_iter().filter(is_layer).map(|id| id.0).collect();
            if layers.is_empty() {
                layers.extend(st.current_layer().map(|id| id.0));
            }
            if layers.is_empty() { json!("document") } else { json!({ "layers": layers }) }
        }
        _ => json!("document"),
    }
}

/// Run the dialog's button `button` (find, change or changeAll) on the document font `from`.
fn run_button(app: &mut VectorcraftApp, d: &Dialog, button: &str, from: &Value) -> Result<Value, String> {
    match button {
        "find" => {
            let scope = find_scope(app, &d.str("findIn"));
            app.run("select.font", json!({ "family": from["family"], "style": from["style"], "scope": scope }))
        }
        "change" => change(app, d, from, false),
        _ => change(app, d, from, true),
    }
}

fn fonts(app: &mut VectorcraftApp) -> Vec<Value> {
    app.session.execute("text.fonts", &json!({})).ok().and_then(|v| v.as_array().cloned()).unwrap_or_default()
}

/// The active document's fonts ([`fonts`]) and, when `missing` is asked for, whether it misses a
/// font ([`vectorcraft_engine::cmd::fontfiles::missing_fonts`]; `false` when it is not asked
/// for). Both are kept in [`crate::CanvasCache::find_font`] and worked out again only for another
/// document, another version of its content or another font generation. No document: no fonts.
fn document_fonts(app: &mut VectorcraftApp, missing: bool) -> (Arc<Vec<Value>>, bool) {
    let Some(st) = app.session.active() else { return (Arc::default(), false) };
    // The generation is read first: fonts loaded while the answers are worked out leave the entry
    // under the older generation, so the next frame works them out again.
    let key = FontsKey { uid: st.uid, doc: Arc::downgrade(&st.doc), generation: vectorcraft_text::FontDb::global().generation() };
    if app.canvas.find_font.as_ref().is_none_or(|c| c.key != key) {
        let fonts = Arc::new(fonts(app));
        app.canvas.find_font = Some(FindFontCache { key, fonts, missing: None });
    }
    if missing
        && let Some(c) = app.canvas.find_font.as_mut()
        && c.missing.is_none()
        && let Some(st) = app.session.active()
    {
        c.missing = Some(!vectorcraft_engine::cmd::fontfiles::missing_fonts(&st.doc).is_empty());
    }
    let c = app.canvas.find_font.as_ref();
    (c.map(|c| c.fonts.clone()).unwrap_or_default(), missing && c.and_then(|c| c.missing).unwrap_or(false))
}

pub fn confirm(app: &mut VectorcraftApp) -> Result<Value, String> {
    if let Some(ctx) = app.ui_ctx.clone() {
        clear_search(&ctx);
    }
    app.ui.dialog = None;
    Ok(Value::Null)
}

/// Forget the replacement search: the next open starts with an empty one.
pub(crate) fn clear_search(ctx: &egui::Context) {
    let (source_key, query_id) = (egui::Id::unique("ff-search-source"), egui::Id::unique("ff-search"));
    ctx.data_mut(|m| {
        m.remove::<String>(source_key);
        m.remove::<String>(query_id);
    });
}

/// Replace the selected document font with the chosen one (`all`: everywhere, else the selection).
fn change(app: &mut VectorcraftApp, d: &Dialog, from: &Value, all: bool) -> Result<Value, String> {
    let style = d.str("style");
    let to = if style.is_empty() { json!({ "family": d.str("family") }) } else { json!({ "family": d.str("family"), "style": style }) };
    app.run("text.replaceFont", json!({ "from": { "family": from["family"], "style": from["style"] }, "to": to, "selectionOnly": !all }))
}

pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
    let Some(mut d) = app.ui.dialog.clone() else { return };
    let t = Tokens::get(ctx);
    // Find in Folder… shows when the document misses fonts, fonts used only in its symbols included.
    let can_pick = crate::picks::can(app, &crate::picks::PickRequest::Folder);
    let (list, offer_folder) = document_fonts(app, can_pick);
    let mut close = false;
    let mut find_in_folder = false;
    let mut act: Option<&str> = None;
    // Escape over an open dropdown list closes only the list, which closes itself while it is drawn.
    let popup_open = egui::Popup::is_any_open(ctx);
    // The replacement-font search, kept in egui memory: cleared when the dialog closes, and when
    // the source changes.
    let source_key = egui::Id::unique("ff-search-source");
    let query_id = egui::Id::unique("ff-search");
    crate::dialogs::modal::show(ctx, tl!("Find Font"), egui::Id::unique("dialog-find-font"), -40.0, 22, |ui: &mut Ui| {
        ui.set_width(380.0);
        crate::dialogs::modal::heading(ui, tl!("Find Font"));
        ui.add_space(10.0);
        widgets::subheader(ui, &crate::i18n::fmt(tl!("Fonts in Document: {count}"), &[("count", &list.len().to_string())]));
        let sel = d.fields.get("selected").and_then(Value::as_u64).unwrap_or(0) as usize;
        egui::Frame::NONE.fill(t.input).stroke(egui::Stroke::new(1.0, t.input_border)).inner_margin(egui::Margin::same(4)).show(ui, |ui| {
            ui.set_min_height(120.0);
            ui.set_width(ui.available_width());
            egui::ScrollArea::vertical().id_salt("ff-document-list").max_height(160.0).auto_shrink([false, true]).show(ui, |ui| {
                for (i, f) in list.iter().enumerate() {
                    let (note, color) = font_note(f);
                    let label = format!("{} {}{note}  ({})", f["family"].as_str().unwrap_or(""), f["style"].as_str().unwrap_or(""), f["runs"]);
                    let text = egui::RichText::new(label).color(color.unwrap_or(t.text));
                    if ui.selectable_label(i == sel, text).clicked() {
                        d.fields.insert("selected".into(), json!(i));
                    }
                }
            });
        });
        // The missing fonts' files, looked for in a folder (the Missing Fonts dialog).
        if offer_folder {
            ui.add_space(6.0);
            find_in_folder = ui.button(tl!("Find in Folder…")).clicked();
        }
        ui.add_space(10.0);
        widgets::subheader(ui, tl!("Replace With Font"));
        let source = d.str("replaceFrom");
        ui.horizontal(|ui| {
            widgets::field_label(ui, tl!("Replace With Font From"));
            let at = SOURCES.iter().position(|s| *s == source).unwrap_or(2);
            if let Some(i) = widgets::dropdown_named(ui, "ff-from", Some(tl!("Replace With Font From")), SOURCE_LABELS[at], &SOURCE_LABELS, 120.0) {
                set_source(app, &mut d, SOURCES[i], &list);
            }
        });
        let families = replacement_families(app, &d.str("replaceFrom"), &list);
        // The rows Replace With Font lists for the source: one click picks the family and its style.
        let rows: Vec<(String, String)> = d
            .fields
            .get("rows")
            .and_then(Value::as_array)
            .map(|a| {
                a.iter()
                    .map(|r| (r["family"].as_str().unwrap_or_default().to_string(), r["style"].as_str().unwrap_or_default().to_string()))
                    .collect()
            })
            .unwrap_or_default();
        let (fam, style) = (d.str("family"), d.str("style"));
        // A search like the Character panel's font menu: the family and style are filtered as typed.
        // A new source starts with an empty search.
        let source = d.str("replaceFrom");
        if ui.data(|m| m.get_temp::<String>(source_key).as_deref() != Some(source.as_str())) {
            ui.data_mut(|m| {
                m.insert_temp(source_key, source.clone());
                m.insert_temp(query_id, String::new());
            });
        }
        let query = widgets::search_field(ui, query_id, tl!("Search")).to_lowercase();
        let shown: Vec<&(String, String)> = rows.iter().filter(|(f, s)| row_matches(f, s, &query)).collect();
        let mut picked: Option<(String, String, bool)> = None;
        // Ten rows at a time, whichever height the rows get from the style.
        let row = (ui.spacing().interact_size.y.max(ui.text_style_height(&egui::TextStyle::Body)) + ui.spacing().item_spacing.y).max(18.0);
        egui::Frame::NONE.fill(t.input).stroke(egui::Stroke::new(1.0, t.input_border)).inner_margin(egui::Margin::same(4)).show(ui, |ui| {
            ui.set_width(ui.available_width());
            let area = egui::ScrollArea::vertical()
                .id_salt("ff-rows-list")
                // Ten rows at most, and no taller than the rows there are: a search of three fonts
                // leaves a list three rows tall.
                .max_height((shown.len() as f32 * row).clamp(row, 10.0 * row))
                .auto_shrink([false, true])
                .scroll_bar_visibility(egui::scroll_area::ScrollBarVisibility::AlwaysVisible);
            area.show_rows(ui, row, shown.len(), |ui, range| {
                for i in range {
                    let Some((f, s)) = shown.get(i) else { continue };
                    let is_selected = f.eq_ignore_ascii_case(&fam) && s.eq_ignore_ascii_case(&style);
                    let resp = ui.selectable_label(is_selected, row_label(f, s));
                    if resp.clicked() {
                        picked = Some((f.clone(), s.clone(), resp.double_clicked()));
                    }
                }
            });
        });
        if let Some((f, s, twice)) = picked {
            d.fields.insert("family".into(), json!(f));
            d.fields.insert("style".into(), json!(s));
            if twice && can_replace(&d, families.as_deref()) {
                act = Some("change");
            }
        }
        ui.add_space(14.0);
        ui.horizontal(|ui| {
            widgets::field_label(ui, tl!("Find In"));
            let at = FIND_IN.iter().position(|s| *s == d.str("findIn")).unwrap_or(0);
            if let Some(i) = widgets::dropdown_named(ui, "ff-find-in", Some(tl!("Find In")), FIND_IN_LABELS[at], &FIND_IN_LABELS, 120.0) {
                d.fields.insert("findIn".into(), json!(FIND_IN[i]));
            }
        });
        ui.add_space(6.0);
        // An empty list (Recent before any font was applied) leaves nothing to change to.
        let replace = sel < list.len() && can_replace(&d, families.as_deref());
        ui.horizontal(|ui| {
            let has = sel < list.len();
            if ui.add_enabled(has, egui::Button::new(tl!("Find"))).clicked() {
                act = Some("find");
            }
            if ui.add_enabled(replace, egui::Button::new(tl!("Change"))).on_hover_text(tl!("In the selected objects")).clicked() {
                act = Some("change");
            }
            if ui.add_enabled(replace, egui::Button::new(tl!("Change All"))).clicked() {
                act = Some("changeAll");
            }
            ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                if widgets::primary_button(ui, tl!("Done")).clicked() {
                    close = true;
                }
            });
        });
    });
    app.ui.find_font_in = d.str("findIn");
    let sel = d.fields.get("selected").and_then(Value::as_u64).unwrap_or(0) as usize;
    if let (Some(a), Some(from)) = (act, list.get(sel)) {
        match run_button(app, &d, a, from) {
            // The rows are a snapshot: the document's fonts and the recent fonts have moved on.
            Ok(_) if a != "find" => {
                let (used, _) = document_fonts(app, false);
                d.fields.insert("rows".into(), rows_json(&replacement_rows(app, &d.str("replaceFrom"), &used)));
            }
            Ok(_) => {}
            Err(e) => app.ui.status = e,
        }
    }
    if close || (!popup_open && crate::shortcuts::pressed_anew(ctx, egui::Key::Escape)) {
        app.ui.dialog = None;
        // The next open starts with an empty search.
        clear_search(ctx);
    } else if app.ui.dialog.is_some() {
        app.ui.dialog = Some(d);
    }
    // Missing Fonts takes the dialog's place, searching the folder picked; the next Find Font
    // starts with an empty search.
    if find_in_folder {
        match app.run("ui.findFontsInFolder", json!({})) {
            Ok(_) => clear_search(ctx),
            Err(e) => app.ui.status = e,
        }
    }
}

/// What a Find Font row says after the font's name (`text.fonts` row): a missing family, a style
/// standing in for another, characters the font lacks; and the colour to flag it with.
pub(crate) fn font_note(f: &Value) -> (String, Option<egui::Color32>) {
    let lacking = f["missingGlyphs"].as_u64().unwrap_or(0);
    let glyphs =
        if lacking > 0 { crate::i18n::fmt(tl!("  — {n} characters from another font"), &[("n", &lacking.to_string())]) } else { String::new() };
    match f["status"].as_str() {
        Some("missing") => (format!("{}{glyphs}", tl!("  — missing")), Some(egui::Color32::from_rgb(230, 90, 90))),
        Some("substitute") => {
            let used = f["resolved"]["style"].as_str().unwrap_or("");
            (
                format!("{}{glyphs}", crate::i18n::fmt(tl!("  — substituted by {style}"), &[("style", used)])),
                Some(egui::Color32::from_rgb(220, 160, 60)),
            )
        }
        _ if lacking > 0 => (glyphs, Some(egui::Color32::from_rgb(220, 160, 60))),
        _ => (String::new(), None),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn dialog_draws_and_changes_all() {
        let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
        app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
        app.session.execute("text.create", &json!({"x": 10, "y": 40, "text": "Hi", "font": "Missing Family"})).unwrap();
        open(&mut app);
        let ctx = egui::Context::default();
        crate::theme::install_fonts(&ctx);
        let mut out = ctx.run_ui(egui::RawInput::default(), |ui| show(&mut app, ui.ctx()));
        out.textures_delta.clear();
        let d = app.ui.dialog.clone().unwrap();
        let from = fonts(&mut app)[0].clone();
        assert_eq!(from["missing"], true);
        change(&mut app, &d, &from, true).unwrap();
        assert_eq!(fonts(&mut app)[0]["family"], "Source Sans 3");
    }

    /// Find In passes Find the active artboard, or the selected layers (else the current
    /// layer), as `select.font`'s scope.
    #[test]
    fn find_in_limits_find_to_the_artboard_or_the_layers() {
        let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
        app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
        app.session.execute("artboard.new", &json!({"x": 200, "y": 0, "width": 100, "height": 100})).unwrap();
        let text = |app: &mut VectorcraftApp, x: i32| {
            app.session.execute("text.create", &json!({"x": x, "y": 40, "text": "Hi", "font": "Inter"})).unwrap()["id"].as_u64().unwrap()
        };
        let first = text(&mut app, 10);
        let layer = app.session.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap();
        let second = text(&mut app, 210);
        let third = text(&mut app, 20);
        let ctx = egui::Context::default();
        crate::theme::install_fonts(&ctx);
        // Choose Find In on the open dialog, draw a frame, then press Find.
        let find = |app: &mut VectorcraftApp, find_in: &str| {
            open(app);
            app.ui.dialog.as_mut().unwrap().fields.insert("findIn".into(), json!(find_in));
            let mut out = ctx.run_ui(egui::RawInput::default(), |ui| show(app, ui.ctx()));
            out.textures_delta.clear();
            let d = app.ui.dialog.clone().unwrap();
            let from = fonts(app).into_iter().find(|f| f["family"] == "Inter").unwrap();
            run_button(app, &d, "find", &from).unwrap();
            let mut ids: Vec<u64> = app.session.active().unwrap().selection.objects.iter().map(|id| id.0).collect();
            ids.sort_unstable();
            ids
        };
        open(&mut app);
        assert_eq!(app.ui.dialog.as_ref().unwrap().str("findIn"), "document");
        assert_eq!(find(&mut app, "document"), [first, second, third]);
        // Without a view, the active artboard is the first.
        assert_eq!(find(&mut app, "artboard"), [first, third]);
        assert_eq!(find_scope(&app, "layers"), json!({ "layers": [layer] }));
        assert_eq!(find(&mut app, "layers"), [second, third]);
        // Closing and opening the dialog again keeps the last choice.
        app.ui.dialog = None;
        open(&mut app);
        assert_eq!(app.ui.dialog.as_ref().unwrap().str("findIn"), "layers");
    }

    /// Change All leaves locked text in its font, and the status bar says so.
    #[test]
    fn change_all_clears_the_skip_warning_after_unlocking_text() {
        let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
        app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
        app.session.execute("text.create", &json!({"x": 10, "y": 40, "text": "Hi", "font": "Missing Family"})).unwrap();
        app.session.execute("object.lock", &json!({})).unwrap();
        open(&mut app);
        let d = app.ui.dialog.clone().unwrap();
        let from = fonts(&mut app)[0].clone();
        let r = change(&mut app, &d, &from, true).unwrap();
        assert_eq!(r["runs"], 0, "{r}");
        assert_eq!(fonts(&mut app)[0]["family"], "Missing Family");
        assert_eq!(app.ui.status, "some text is hidden or locked, so its font wasn't replaced");
        app.run("object.unlockAll", json!({})).unwrap();
        assert_eq!(app.ui.status, "", "unlocking the skipped text clears the warning");
        let r = change(&mut app, &d, &from, true).unwrap();
        assert_eq!(r["runs"], 1, "{r}");
        assert!(r.get("warning").is_none(), "{r}");
        assert_eq!(app.ui.status, "");
        app.ui.status = "Saved another document".into();
        let r = app.run("text.replaceFont", json!({"from": {"family": "Missing Family"}, "to": {"family": "Source Sans 3"}})).unwrap();
        assert_eq!(r["runs"], 0, "{r}");
        assert_eq!(app.ui.status, "Saved another document");
    }

    #[test]
    fn replacement_keeps_only_font_warnings_that_still_apply() {
        let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
        app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
        app.session.execute("text.create", &json!({"x": 10, "y": 40, "text": "Hi", "font": "Missing Family"})).unwrap();
        app.session.execute("text.create", &json!({"x": 10, "y": 70, "text": "Bye", "font": "Missing Family"})).unwrap();
        app.session.execute("object.lock", &json!({})).unwrap();
        app.session.execute("text.create", &json!({"x": 10, "y": 90, "text": "Other", "font": "Inter"})).unwrap();

        let replace = |app: &mut VectorcraftApp, from: &str, from_style: Option<&str>, style: &str| {
            app.run("text.replaceFont", json!({"from": {"family": from, "style": from_style}, "to": {"family": "Source Sans 3", "style": style}}))
                .unwrap()
        };
        let first = replace(&mut app, "Missing Family", Some("Regular"), "Black Wide");
        assert_eq!(first["runs"], 1, "{first}");
        assert_eq!(first["skipped"], 1, "{first}");
        let style_warning = first["warning"].as_str().unwrap().split_once("; ").unwrap().1.to_string();
        assert!(style_warning.contains("Source Sans 3 Black Wide is drawn in Source Sans 3"), "{style_warning}");

        let unrelated = replace(&mut app, "Inter", None, "Regular");
        assert_eq!(unrelated["runs"], 1, "{unrelated}");
        assert!(unrelated.get("warning").is_none(), "{unrelated}");
        assert_eq!(app.ui.status, first["warning"].as_str().unwrap());

        app.run("object.unlockAll", json!({})).unwrap();
        let second = replace(&mut app, "Missing Family", None, "Regular");
        assert_eq!(second["runs"], 1, "{second}");
        assert!(second.get("warning").is_none(), "{second}");
        assert_eq!(app.ui.status, style_warning);

        let third = replace(&mut app, "Source Sans 3", Some("Black Wide"), "Regular");
        assert_eq!(third["runs"], 1, "{third}");
        assert!(third.get("warning").is_none(), "{third}");
        assert_eq!(app.ui.status, "");
    }

    #[test]
    fn a_style_specific_retry_clears_a_family_wide_skipped_warning() {
        let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
        app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
        app.session.execute("text.create", &json!({"x": 10, "y": 40, "text": "Hi", "font": "Missing Family"})).unwrap();
        app.session.execute("text.create", &json!({"x": 10, "y": 70, "text": "Bye", "font": "Missing Family"})).unwrap();
        app.session.execute("object.lock", &json!({})).unwrap();
        let first = app
            .run("text.replaceFont", json!({"from": {"family": "Missing Family"}, "to": {"family": "Source Sans 3", "style": "Regular"}}))
            .unwrap();
        assert_eq!((first["runs"].as_u64(), first["skipped"].as_u64()), (Some(1), Some(1)));
        app.run("object.unlockAll", json!({})).unwrap();
        let second = app
            .run(
                "text.replaceFont",
                json!({"from": {"family": "Missing Family", "style": "Regular"}, "to": {"family": "Source Sans 3", "style": "Regular"}}),
            )
            .unwrap();
        assert_eq!(second["runs"], 1, "{second}");
        assert!(second.get("warning").is_none(), "{second}");
        assert_eq!(app.ui.status, "");
    }

    #[test]
    fn new_text_in_the_source_font_does_not_keep_an_old_skip_warning() {
        let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
        let replace = |app: &mut VectorcraftApp, from: &str, style: &str| {
            app.run("text.replaceFont", json!({"from": {"family": from}, "to": {"family": "Source Sans 3", "style": style}})).unwrap()
        };
        app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
        app.session.execute("text.create", &json!({"x": 10, "y": 30, "text": "Editable", "font": "Missing Family"})).unwrap();
        let skipped = app.session.execute("text.create", &json!({"x": 10, "y": 60, "text": "Locked", "font": "Missing Family"})).unwrap()["id"]
            .as_u64()
            .unwrap();
        app.session.execute("object.lock", &json!({})).unwrap();
        let first = replace(&mut app, "Missing Family", "Regular");
        assert_eq!((first["runs"].as_u64(), first["skipped"].as_u64()), (Some(1), Some(1)));
        app.session.execute("text.create", &json!({"x": 10, "y": 90, "text": "New", "font": "Missing Family"})).unwrap();
        app.run("object.unlockAll", json!({})).unwrap();
        app.session.active_mut().unwrap().selection.objects = vec![vectorcraft_doc::NodeId(skipped)];
        let second = app
            .run("text.replaceFont", json!({"from": {"family": "Missing Family"}, "to": {"family": "Source Sans 3"}, "selectionOnly": true}))
            .unwrap();
        assert_eq!(second["runs"], 1, "{second}");
        assert!(second.get("warning").is_none(), "{second}");
        assert_eq!(app.ui.status, "");
        assert!(fonts(&mut app).iter().any(|font| font["family"] == "Missing Family"));
    }

    #[test]
    fn unlocking_skipped_text_clears_its_warning() {
        let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
        app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
        app.session.execute("text.create", &json!({"x": 10, "y": 30, "text": "Other", "font": "Inter"})).unwrap();
        app.session.execute("text.create", &json!({"x": 10, "y": 60, "text": "Locked", "font": "Missing Family"})).unwrap();
        app.session.execute("object.lock", &json!({})).unwrap();
        let first = app.run("text.replaceFont", json!({"from": {"family": "Missing Family"}, "to": {"family": "Source Sans 3"}})).unwrap();
        assert_eq!(first["skipped"], 1);
        app.run("object.unlockAll", json!({})).unwrap();
        assert_eq!(app.ui.status, "");
        let unrelated = app.run("text.replaceFont", json!({"from": {"family": "Inter"}, "to": {"family": "Source Sans 3"}})).unwrap();
        assert_eq!(unrelated["runs"], 1);
        assert_eq!(app.ui.status, "");
    }

    #[test]
    fn a_document_revision_refreshes_the_skip_warning_on_tick() {
        let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
        app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
        app.session.execute("text.create", &json!({"x": 10, "y": 60, "text": "Locked", "font": "Missing Family"})).unwrap();
        app.session.execute("object.lock", &json!({})).unwrap();
        let first = app.run("text.replaceFont", json!({"from": {"family": "Missing Family"}, "to": {"family": "Source Sans 3"}})).unwrap();
        assert_eq!(first["skipped"], 1);
        assert!(!app.ui.status.is_empty());

        app.session.execute("object.unlockAll", &json!({})).unwrap();
        let ctx = egui::Context::default();
        app.begin_host_iteration();
        let mut out = ctx.run_ui(egui::RawInput::default(), |ui| app.tick(ui.ctx()));
        out.textures_delta.clear();
        assert_eq!(app.ui.status, "");
    }

    #[test]
    fn a_selection_only_retry_ignores_unselected_text_in_the_same_font() {
        let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
        app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
        app.session.execute("text.create", &json!({"x": 10, "y": 40, "text": "Outside", "font": "Missing Family"})).unwrap();
        let selected = app.session.execute("text.create", &json!({"x": 10, "y": 70, "text": "Selected", "font": "Missing Family"})).unwrap()["id"]
            .as_u64()
            .unwrap();
        app.session.execute("object.lock", &json!({})).unwrap();
        app.session.active_mut().unwrap().selection.objects = vec![vectorcraft_doc::NodeId(selected)];
        let params = json!({"from": {"family": "Missing Family"}, "to": {"family": "Source Sans 3"}, "selectionOnly": true});
        let first = app.run("text.replaceFont", params.clone()).unwrap();
        assert_eq!((first["runs"].as_u64(), first["skipped"].as_u64()), (Some(0), Some(1)));
        app.run("object.unlockAll", json!({})).unwrap();
        app.session.active_mut().unwrap().selection.objects = vec![vectorcraft_doc::NodeId(selected)];
        let second = app.run("text.replaceFont", params).unwrap();
        assert_eq!(second["runs"], 1, "{second}");
        assert!(second.get("warning").is_none(), "{second}");
        assert_eq!(app.ui.status, "");
        assert!(app.session.execute("text.fonts", &json!({})).unwrap().as_array().unwrap().iter().any(|font| font["family"] == "Missing Family"));
    }

    #[test]
    fn a_changed_selection_keeps_the_original_warning_scope() {
        let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
        app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
        app.session.execute("text.create", &json!({"x": 10, "y": 30, "text": "Outside", "font": "Missing Family"})).unwrap();
        let added = app.session.execute("text.create", &json!({"x": 10, "y": 60, "text": "Added", "font": "Missing Family"})).unwrap()["id"]
            .as_u64()
            .unwrap();
        let skipped = app.session.execute("text.create", &json!({"x": 10, "y": 90, "text": "Locked", "font": "Missing Family"})).unwrap()["id"]
            .as_u64()
            .unwrap();
        app.session.execute("object.lock", &json!({})).unwrap();
        app.session.active_mut().unwrap().selection.objects = vec![vectorcraft_doc::NodeId(skipped)];
        let params = json!({"from": {"family": "Missing Family"}, "to": {"family": "Source Sans 3"}, "selectionOnly": true});
        let first = app.run("text.replaceFont", params.clone()).unwrap();
        assert_eq!(first["skipped"], 1, "{first}");
        app.run("object.unlockAll", json!({})).unwrap();
        app.session.active_mut().unwrap().selection.objects = vec![vectorcraft_doc::NodeId(skipped), vectorcraft_doc::NodeId(added)];
        let second = app.run("text.replaceFont", params).unwrap();
        assert_eq!(second["runs"], 2, "{second}");
        assert!(second.get("warning").is_none(), "{second}");
        assert_eq!(app.ui.status, "");
        assert!(app.session.execute("text.fonts", &json!({})).unwrap().as_array().unwrap().iter().any(|font| font["family"] == "Missing Family"));
    }

    #[test]
    fn changing_selection_does_not_clear_a_skipped_font_warning() {
        let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
        app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
        let selected = app.session.execute("text.create", &json!({"x": 10, "y": 40, "text": "Locked", "font": "Missing Family"})).unwrap()["id"]
            .as_u64()
            .unwrap();
        app.session.execute("object.lock", &json!({})).unwrap();
        app.session.active_mut().unwrap().selection.objects = vec![vectorcraft_doc::NodeId(selected)];
        let first = app
            .run("text.replaceFont", json!({"from": {"family": "Missing Family"}, "to": {"family": "Source Sans 3"}, "selectionOnly": true}))
            .unwrap();
        assert_eq!(first["skipped"], 1, "{first}");
        let warning = app.ui.status.clone();
        app.session.execute("text.create", &json!({"x": 10, "y": 70, "text": "Other", "font": "Inter"})).unwrap();
        let unrelated =
            app.run("text.replaceFont", json!({"from": {"family": "Inter"}, "to": {"family": "Source Sans 3"}, "selectionOnly": true})).unwrap();
        assert_eq!(unrelated["runs"], 1, "{unrelated}");
        assert!(unrelated.get("warning").is_none(), "{unrelated}");
        assert_eq!(app.ui.status, warning);
        app.run("object.unlockAll", json!({})).unwrap();
        let retry = app.run("text.replaceFont", json!({"from": {"family": "Missing Family"}, "to": {"family": "Source Sans 3"}})).unwrap();
        assert_eq!(retry["runs"], 1, "{retry}");
        assert!(retry.get("warning").is_none(), "{retry}");
        assert_eq!(app.ui.status, "");
    }

    #[test]
    fn replacing_a_font_in_another_document_keeps_the_original_warning() {
        let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
        app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
        app.session.execute("text.create", &json!({"x": 10, "y": 40, "text": "Locked", "font": "Missing Family"})).unwrap();
        app.session.execute("object.lock", &json!({})).unwrap();
        let first = app.run("text.replaceFont", json!({"from": {"family": "Missing Family"}, "to": {"family": "Source Sans 3"}})).unwrap();
        assert_eq!(first["skipped"], 1, "{first}");
        let warning = app.ui.status.clone();
        let original_uid = app.session.active().unwrap().uid;

        app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
        app.session.execute("text.create", &json!({"x": 10, "y": 40, "text": "Other", "font": "Inter"})).unwrap();
        let second = app.run("text.replaceFont", json!({"from": {"family": "Inter"}, "to": {"family": "Source Sans 3"}})).unwrap();
        assert_eq!(second["runs"], 1, "{second}");
        assert_eq!(app.ui.status, warning);
        app.session.set_active(0);
        assert_eq!(app.session.active().unwrap().uid, original_uid);
        assert_eq!(app.ui.status, warning);
    }

    #[test]
    fn a_comma_in_a_substituted_style_keeps_its_warning() {
        let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
        app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
        app.session.execute("text.create", &json!({"x": 10, "y": 40, "text": "Hi", "font": "Missing Family"})).unwrap();
        app.session.execute("text.create", &json!({"x": 10, "y": 70, "text": "Other", "font": "Inter"})).unwrap();
        let first = app
            .run("text.replaceFont", json!({"from": {"family": "Missing Family"}, "to": {"family": "Source Sans 3", "style": "Black, Wide"}}))
            .unwrap();
        let warning = first["warning"].as_str().unwrap().to_string();
        assert!(warning.contains("Black, Wide"), "{warning}");
        let unrelated = app.run("text.replaceFont", json!({"from": {"family": "Inter"}, "to": {"family": "Source Serif 4"}})).unwrap();
        assert_eq!(unrelated["runs"], 1, "{unrelated}");
        assert!(unrelated.get("warning").is_none(), "{unrelated}");
        assert_eq!(app.ui.status, warning);
    }

    #[test]
    fn an_unrelated_substituted_style_does_not_keep_a_resolved_warning() {
        let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
        app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
        app.session.execute("text.create", &json!({"x": 10, "y": 40, "text": "Hi", "font": "Missing Family"})).unwrap();
        app.session.execute("text.create", &json!({"x": 10, "y": 70, "text": "Other", "font": "Inter"})).unwrap();
        app.run("text.replaceFont", json!({"from": {"family": "Inter"}, "to": {"family": "Source Sans 3", "style": "Narrow"}})).unwrap();
        let first = app
            .run("text.replaceFont", json!({"from": {"family": "Missing Family"}, "to": {"family": "Source Sans 3", "style": "Black, Wide"}}))
            .unwrap();
        assert!(first["warning"].as_str().is_some_and(|warning| warning.contains("Black, Wide")), "{first}");
        let resolved = app
            .run(
                "text.replaceFont",
                json!({"from": {"family": "Source Sans 3", "style": "Black, Wide"}, "to": {"family": "Inter", "style": "Regular"}}),
            )
            .unwrap();
        assert!(resolved.get("warning").is_none(), "{resolved}");
        assert_eq!(app.ui.status, "");
    }

    #[test]
    fn find_in_folder_puts_the_missing_fonts_dialog_in_find_fonts_place() {
        let dir = std::fs::canonicalize(vectorcraft_testkit::temp_dir("find-font-folder")).unwrap();
        let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
        app.session.search_rules = Some(vectorcraft_engine::cmd::findfiles::Rules { user_content: vec![dir.clone()], ..Default::default() });
        app.session.search_threads = Some(1);
        app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
        assert!(!crate::menus::enabled(&app, "ui.findFontsInFolder"), "no folder picker (the web)");
        let picked = dir.to_string_lossy().into_owned();
        app.services.pick_folder = Some(Box::new(move || Some(picked.clone())));
        assert!(crate::menus::enabled(&app, "ui.findFontsInFolder"));
        // Nothing missing: no button, and no folder is asked for.
        open(&mut app);
        let text = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx()));
        assert!(text.contains("Fonts in Document") && !text.contains("Find in Folder…"), "{text}");
        assert_eq!(app.run("ui.findFontsInFolder", json!({})).err().as_deref(), Some("No fonts are missing in this document"));
        app.session.execute("text.create", &json!({"x": 10, "y": 40, "text": "Hi", "font": "Missing Family"})).unwrap();
        let text = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx()));
        assert!(text.contains("Find in Folder…"), "{text}");
        app.run("ui.findFontsInFolder", json!({})).unwrap();
        let d = app.ui.dialog.as_ref().unwrap();
        assert_eq!((d.kind.as_str(), d.str("folder")), (crate::dialogs::missing_fonts::KIND, dir.to_string_lossy().into_owned()));
        assert_eq!(d.fields["fonts"][0]["family"], "Missing Family");
        assert!(app.ui.dialog_search.is_some());
        crate::dialogs::cancel(&mut app);
    }

    /// A document set in Inter and Source Serif 4 (Inter twice), with Inter the one recent font.
    fn two_font_document() -> VectorcraftApp {
        let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
        app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
        for (y, font) in [(20, "Inter"), (40, "Source Serif 4"), (60, "Inter")] {
            app.session.execute("text.create", &json!({"x": 10, "y": y, "text": "Hi", "font": font})).unwrap();
        }
        app.ui.recent_fonts = vec!["Inter".into()];
        app
    }

    #[test]
    fn replace_with_font_from_lists_the_document_s_recent_or_installed_fonts() {
        let mut app = two_font_document();
        let used = fonts(&mut app);
        let mut document = replacement_families(&app, "document", &used).unwrap();
        document.sort();
        assert_eq!(document, ["Inter", "Source Serif 4"]);
        assert_eq!(replacement_families(&app, "recent", &used).unwrap(), ["Inter"]);
        assert_eq!(replacement_families(&app, "system", &used), None, "System is the font menu of every installed family");
        open(&mut app);
        assert_eq!(app.ui.dialog.as_ref().unwrap().str("replaceFrom"), "system");
        for source in SOURCES {
            let mut d = app.ui.dialog.clone().unwrap();
            set_source(&app, &mut d, source, &used);
            let listed = replacement_families(&app, source, &used);
            assert!(can_replace(&d, listed.as_deref()), "{source}: {}", d.str("family"));
            app.ui.dialog = Some(d);
            let text = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx()));
            assert!(text.contains("Replace With Font From"), "{text}");
        }
    }

    /// One headless frame of the dialog: every text it painted, with where.
    fn frame(ctx: &egui::Context, app: &mut VectorcraftApp, events: Vec<egui::Event>) -> Vec<(String, egui::Rect)> {
        fn collect(s: &egui::epaint::Shape, out: &mut Vec<(String, egui::Rect)>) {
            match s {
                egui::epaint::Shape::Text(t) => out.push((t.galley.text().to_string(), egui::Rect::from_min_size(t.pos, t.galley.size()))),
                egui::epaint::Shape::Vec(v) => v.iter().for_each(|s| collect(s, out)),
                _ => {}
            }
        }
        let raw = egui::RawInput { events, ..Default::default() };
        let mut out = ctx.run_ui(raw, |ui| show(app, ui.ctx()));
        let mut texts = vec![];
        for c in &out.shapes {
            collect(&c.shape, &mut texts);
        }
        out.textures_delta.clear();
        texts
    }

    /// The texts of a [`frame`] that are in `labels`, in order.
    fn painted(frame: &[(String, egui::Rect)], labels: &[String]) -> Vec<String> {
        frame.iter().map(|(t, _)| t.clone()).filter(|t| labels.contains(t)).collect()
    }

    /// A click at `at`: the press on one frame, the release on the next.
    fn click(ctx: &egui::Context, app: &mut VectorcraftApp, at: egui::Pos2) {
        let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
        frame(ctx, app, vec![egui::Event::PointerMoved(at), button(true)]);
        frame(ctx, app, vec![button(false)]);
        frame(ctx, app, vec![]);
    }

    /// A document set in `families`, one text each.
    fn many_font_document(families: &[&str]) -> VectorcraftApp {
        let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
        app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
        for (i, family) in families.iter().enumerate() {
            app.session.execute("text.create", &json!({"x": 10, "y": 10.0 + i as f64 * 20.0, "text": "Hi", "font": family})).unwrap();
        }
        app
    }

    /// The catalog's closest style is the face a style-less request resolves to, and finding it reads
    /// no font file.
    #[test]
    fn the_closest_style_is_the_face_a_style_less_request_gets() {
        let db = vectorcraft_text::FontDb::global();
        for family in ["Source Sans 3", "Inter"] {
            let closest = db.closest_style(family).unwrap_or_else(|| panic!("{family} is installed"));
            let face = db.face(family, "").unwrap_or_else(|| panic!("{family} resolves"));
            assert_eq!(closest, face.style, "{family}");
        }
    }

    /// A document font drawn in a substitute style stays listed, but it is not chosen as the
    /// replacement and Change stays off for it: only a style the font has can be the target.
    #[test]
    fn a_substituted_style_is_listed_but_not_chosen() {
        let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
        app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
        // A style Source Sans 3 has none of: its closest style stands in.
        app.session.execute("text.create", &json!({"x": 10, "y": 40, "text": "Hi", "font": "Source Sans 3", "style": "Black Wide"})).unwrap();
        app.session.execute("text.create", &json!({"x": 10, "y": 70, "text": "Hi", "font": "Inter"})).unwrap();
        open(&mut app);
        let used = fonts(&mut app);
        assert!(used.iter().any(|f| f["family"] == "Source Sans 3" && f["style"] == "Black Wide" && f["status"] == "substitute"), "{used:?}");
        let rows = replacement_rows(&app, "document", &used);
        let stand_in = Row { family: "Source Sans 3".into(), style: "Black Wide".into() };
        assert!(rows.contains(&stand_in), "the row stays listed: {rows:?}");
        let mut d = app.ui.dialog.clone().unwrap();
        set_source(&app, &mut d, "document", &used);
        assert_eq!((d.str("family").as_str(), d.str("style").as_str()), ("Inter", "Regular"), "the first font whose style it has");
        d.fields.insert("family".into(), json!("Source Sans 3"));
        d.fields.insert("style".into(), json!("Black Wide"));
        assert!(!can_replace(&d, replacement_families(&app, "document", &used).as_deref()), "Change stays off for the stand-in style");
    }

    /// A new source picks the family and the style from a row its list shows, so Change replaces with
    /// what is listed rather than a closest style of its own choosing.
    #[test]
    fn a_new_source_picks_a_row_its_list_shows() {
        let mut app = two_font_document();
        let used = fonts(&mut app);
        let mut d = Dialog::new("findFont", json!({"family": "Inter", "style": "", "selected": 0, "replaceFrom": "system"}));
        set_source(&app, &mut d, "document", &used);
        assert_eq!((d.str("family").as_str(), d.str("style").as_str()), ("Inter", "Regular"), "the document's own row");
        d.fields.insert("family".into(), json!("Inter"));
        d.fields.insert("style".into(), json!("Black Wide"));
        set_source(&app, &mut d, "document", &used);
        assert_eq!((d.str("family").as_str(), d.str("style").as_str()), ("Inter", "Regular"), "a pair the list lacks gives way");
    }

    /// Confirming the dialog with Enter forgets the replacement search, as Done and Escape do.
    #[test]
    fn confirming_the_dialog_clears_the_replacement_search() {
        let mut app = two_font_document();
        let ctx = egui::Context::default();
        crate::theme::install_fonts(&ctx);
        app.ui_ctx = Some(ctx.clone());
        open(&mut app);
        let query_id = egui::Id::unique("ff-search");
        ctx.data_mut(|m| m.insert_temp(query_id, "times".to_string()));
        confirm(&mut app).unwrap();
        assert!(app.ui.dialog.is_none(), "the dialog closes");
        assert_eq!(ctx.data(|m| m.get_temp::<String>(query_id)), None, "the search text is gone");
    }

    /// The rows follow a replacement: Change All in the Document source leaves the list showing the
    /// document's fonts as they are now.
    #[test]
    fn the_rows_refresh_after_a_change() {
        let mut app = two_font_document();
        open(&mut app);
        let ctx = egui::Context::default();
        crate::theme::install_fonts(&ctx);
        frame(&ctx, &mut app, vec![]);
        let used = fonts(&mut app);
        let mut d = app.ui.dialog.clone().unwrap();
        set_source(&app, &mut d, "document", &used);
        d.fields.insert("family".into(), json!("Source Serif 4"));
        d.fields.insert("style".into(), json!(""));
        app.ui.dialog = Some(d);
        frame(&ctx, &mut app, vec![]);
        let texts = frame(&ctx, &mut app, vec![]);
        let change_all = texts.iter().find(|(t, _)| t == "Change All").map(|(_, r)| r.center()).expect("Change All is shown");
        click(&ctx, &mut app, change_all);
        assert!(fonts(&mut app).iter().all(|f| f["family"] == "Source Serif 4"), "the document changed");
        let rows = app.ui.dialog.as_ref().expect("the dialog stays open").fields["rows"].as_array().cloned().unwrap_or_default();
        let families: Vec<&str> = rows.iter().filter_map(|r| r["family"].as_str()).collect();
        assert!(
            !families.is_empty() && families.iter().all(|f| *f == "Source Serif 4"),
            "the rows list the document's fonts after the change: {families:?}"
        );
    }

    /// Closing the dialog clears the replacement search: the next open starts with an empty one.
    #[test]
    fn closing_the_dialog_clears_the_replacement_search() {
        let mut app = two_font_document();
        open(&mut app);
        let ctx = egui::Context::default();
        crate::theme::install_fonts(&ctx);
        frame(&ctx, &mut app, vec![]);
        let query_id = egui::Id::unique("ff-search");
        let source_id = egui::Id::unique("ff-search-source");
        ctx.data_mut(|m| {
            m.insert_temp(query_id, "times".to_string());
            m.insert_temp(source_id, "system".to_string());
        });
        let escape = egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() };
        frame(&ctx, &mut app, vec![escape]);
        frame(&ctx, &mut app, vec![]);
        assert!(app.ui.dialog.is_none(), "Escape closes the dialog");
        assert_eq!(ctx.data(|m| m.get_temp::<String>(query_id)), None, "the search text is gone");
        assert_eq!(ctx.data(|m| m.get_temp::<String>(source_id)), None, "the source it was typed under is gone");
    }

    /// A context with the app's fonts and theme that the app knows as its own, for [`app_frame`].
    fn app_ctx(app: &mut VectorcraftApp) -> egui::Context {
        let ctx = egui::Context::default();
        crate::theme::install_fonts(&ctx);
        crate::theme::apply(&ctx, Default::default());
        app.ui_ctx = Some(ctx.clone());
        ctx
    }

    /// One 1200 × 900 frame with `events` through the app's key handling and then the dialogs, as
    /// the app runs them; the center of the text `label` if the frame shows it.
    fn app_frame(ctx: &egui::Context, app: &mut VectorcraftApp, events: Vec<egui::Event>, label: &str) -> Option<egui::Pos2> {
        let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 900.0));
        let raw = egui::RawInput { screen_rect: Some(screen), events, ..Default::default() };
        let mut out = ctx.run_ui(raw, |ui| {
            crate::shortcuts::handle(app, ui.ctx());
            crate::dialogs::show(app, ui.ctx());
        });
        out.textures_delta.clear();
        out.shapes.iter().find_map(|s| match &s.shape {
            egui::Shape::Text(t) if t.galley.text() == label => Some(egui::Rect::from_min_size(t.pos, t.galley.size()).center()),
            _ => None,
        })
    }

    /// Clicks the text `label` through [`app_frame`].
    fn app_click(ctx: &egui::Context, app: &mut VectorcraftApp, label: &str) {
        app_frame(ctx, app, vec![], label);
        let at = app_frame(ctx, app, vec![], label).unwrap_or_else(|| panic!("no {label:?} shown"));
        let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
        app_frame(ctx, app, vec![egui::Event::PointerMoved(at), button(true)], label);
        app_frame(ctx, app, vec![button(false)], label);
        app_frame(ctx, app, vec![], label);
    }

    /// An Escape key event: pressed, or let go.
    fn escape_key(pressed: bool, repeat: bool) -> egui::Event {
        egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed, repeat, modifiers: Default::default() }
    }

    /// Presses and lets go of Escape through [`app_frame`].
    fn app_escape(ctx: &egui::Context, app: &mut VectorcraftApp) {
        app_frame(ctx, app, vec![escape_key(true, false)], "");
        app_frame(ctx, app, vec![escape_key(false, false)], "");
    }

    /// Types `query` into the replacement search under the dialog's source, as the search field
    /// keeps it.
    fn seed_search(ctx: &egui::Context, app: &VectorcraftApp, query: &str) {
        let source = app.ui.dialog.as_ref().expect("Find Font is open").str("replaceFrom");
        ctx.data_mut(|m| {
            m.insert_temp(egui::Id::unique("ff-search-source"), source);
            m.insert_temp(egui::Id::unique("ff-search"), query.to_string());
        });
    }

    /// The replacement search and the source it was typed under, as egui memory keeps them.
    fn search_state(ctx: &egui::Context) -> (Option<String>, Option<String>) {
        ctx.data(|m| (m.get_temp::<String>(egui::Id::unique("ff-search")), m.get_temp::<String>(egui::Id::unique("ff-search-source"))))
    }

    /// Escape with Replace With Font From's or Find In's list open closes only the list: Find Font
    /// stays open with its source and its search, holding Escape down leaves it open, and the next
    /// press closes it and forgets the search.
    #[test]
    fn escape_over_an_open_dropdown_closes_only_the_dropdown() {
        for current in ["System", "Document"] {
            let mut app = two_font_document();
            let ctx = app_ctx(&mut app);
            open(&mut app);
            app_frame(&ctx, &mut app, vec![], "");
            seed_search(&ctx, &app, "inter");
            app_click(&ctx, &mut app, current);
            assert!(egui::Popup::is_any_open(&ctx), "{current}: the list is open");
            app_frame(&ctx, &mut app, vec![escape_key(true, false)], "");
            for _ in 0..3 {
                app_frame(&ctx, &mut app, vec![escape_key(true, true)], "");
            }
            app_frame(&ctx, &mut app, vec![escape_key(false, false)], "");
            assert!(!egui::Popup::is_any_open(&ctx), "{current}: Escape closes the list");
            let d = app.ui.dialog.as_ref().unwrap_or_else(|| panic!("{current}: Find Font stays open"));
            assert_eq!((d.kind.as_str(), d.str("replaceFrom"), d.str("findIn")), ("findFont", "system".into(), "document".into()), "{current}");
            assert_eq!(search_state(&ctx), (Some("inter".into()), Some("system".into())), "{current}: the search is kept");
            app_escape(&ctx, &mut app);
            assert!(app.ui.dialog.is_none(), "{current}: the next Escape closes Find Font");
            assert_eq!(search_state(&ctx), (None, None), "{current}: closing forgets the search");
        }
    }

    /// Escape and Done, through the app's key handling, each close Find Font and forget the
    /// replacement search and its source.
    #[test]
    fn escape_and_done_through_the_app_clear_the_replacement_search() {
        for how in ["Escape", "Done"] {
            let mut app = two_font_document();
            let ctx = app_ctx(&mut app);
            open(&mut app);
            app_frame(&ctx, &mut app, vec![], "");
            seed_search(&ctx, &app, "inter");
            if how == "Escape" {
                app_escape(&ctx, &mut app);
            } else {
                app_click(&ctx, &mut app, "Done");
            }
            assert!(app.ui.dialog.is_none(), "{how} closes Find Font");
            assert_eq!(search_state(&ctx), (None, None), "{how} forgets the search");
            open(&mut app);
            app_frame(&ctx, &mut app, vec![], "");
            assert_eq!(search_state(&ctx), (Some(String::new()), Some("system".into())), "{how}: the next open starts with an empty search");
        }
    }

    /// Find in Folder… that opens Missing Fonts forgets Find Font's search; with no folder picked,
    /// Find Font stays open with its search.
    #[test]
    fn find_in_folder_forgets_the_search_once_missing_fonts_opens() {
        let dir = std::fs::canonicalize(vectorcraft_testkit::temp_dir("find-font-folder-search")).unwrap();
        for picks in [false, true] {
            let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
            app.session.search_rules = Some(vectorcraft_engine::cmd::findfiles::Rules { user_content: vec![dir.clone()], ..Default::default() });
            app.session.search_threads = Some(1);
            app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
            app.session.execute("text.create", &json!({"x": 10, "y": 40, "text": "Hi", "font": "Missing Family"})).unwrap();
            let picked = picks.then(|| dir.to_string_lossy().into_owned());
            app.services.pick_folder = Some(Box::new(move || picked.clone()));
            let ctx = app_ctx(&mut app);
            open(&mut app);
            app_frame(&ctx, &mut app, vec![], "");
            seed_search(&ctx, &app, "inter");
            app_click(&ctx, &mut app, "Find in Folder…");
            let kind = app.ui.dialog.as_ref().map(|d| d.kind.clone());
            if picks {
                assert_eq!(kind.as_deref(), Some(crate::dialogs::missing_fonts::KIND), "Missing Fonts takes Find Font's place");
                assert_eq!(search_state(&ctx), (None, None), "the search is forgotten");
                crate::dialogs::cancel(&mut app);
            } else {
                assert_eq!(kind.as_deref(), Some("findFont"), "with no folder picked, Find Font stays open");
                assert_eq!(search_state(&ctx), (Some("inter".into()), Some("system".into())), "and keeps its search");
            }
        }
    }

    /// The wheel over the rows scrolls them, and leaves the document's font list where it was: two
    /// lists, two scrollbars.
    #[test]
    fn the_rows_list_scrolls_with_the_wheel_alone() {
        let families = ["Arial", "Georgia", "Verdana", "Tahoma", "Courier New", "Times New Roman", "Consolas", "Impact"];
        let mut app = many_font_document(&families);
        open(&mut app);
        let ctx = egui::Context::default();
        crate::theme::install_fonts(&ctx);
        frame(&ctx, &mut app, vec![]);
        let texts = frame(&ctx, &mut app, vec![]);
        let used = fonts(&mut app);
        let doc_labels: Vec<String> = used
            .iter()
            .map(|f| {
                let (note, _) = font_note(f);
                format!("{} {}{note}  ({})", f["family"].as_str().unwrap_or(""), f["style"].as_str().unwrap_or(""), f["runs"])
            })
            .collect();
        let rows = replacement_rows(&app, "system", &used);
        let labels: Vec<String> = rows.iter().map(|r| row_label(&r.family, &r.style)).collect();
        let at = |texts: &[(String, egui::Rect)], text: &str| texts.iter().find(|(t, _)| t == text).map(|(_, r)| *r);
        let start = at(&texts, &labels[0]).expect("the rows start at their top");
        let (doc_before, rows_before) = (painted(&texts, &doc_labels), painted(&texts, &labels));
        assert!(!doc_before.is_empty(), "the document's fonts are listed: {doc_before:?}");
        assert!(!rows_before.is_empty(), "{rows_before:?}");
        let wheel = egui::Event::MouseWheel {
            unit: egui::MouseWheelUnit::Line,
            delta: egui::vec2(0.0, -20.0),
            phase: egui::TouchPhase::Move,
            modifiers: Default::default(),
            source: egui::MouseWheelSource::Unknown,
        };
        frame(&ctx, &mut app, vec![egui::Event::PointerMoved(start.center()), wheel]);
        for _ in 0..30 {
            frame(&ctx, &mut app, vec![]);
        }
        let texts = frame(&ctx, &mut app, vec![]);
        assert!(at(&texts, &labels[0]).is_none(), "the wheel scrolls the first rows out of view");
        assert_ne!(painted(&texts, &labels), rows_before, "the wheel scrolls the rows");
        assert_eq!(painted(&texts, &doc_labels), doc_before, "the document's font list stays where it was");
    }
    /// The search filters the rows by family and style, whatever case was typed.
    #[test]
    fn the_search_filters_rows_by_family_and_style() {
        assert!(row_matches("Arial", "Bold", ""), "no search lists every row");
        assert!(row_matches("Arial", "Bold", "arial"));
        assert!(row_matches("Arial", "Bold", "rial b"));
        assert!(row_matches("Source Sans 3", "Semibold", "sans 3 sem"));
        assert!(!row_matches("Arial", "Bold", "times"));
        assert!(!row_matches("Arial", "Bold", "bold italic"));
    }

    /// Replace With Font's rows: Document lists the family and style pairs the document uses, once
    /// each; Recent and System list each family with its closest style first and then its styles.
    #[test]
    fn replacement_rows_pick_a_family_and_its_style() {
        let mut app = two_font_document();
        let used = fonts(&mut app);
        let document = replacement_rows(&app, "document", &used);
        assert_eq!(
            document,
            [Row { family: "Inter".into(), style: "Regular".into() }, Row { family: "Source Serif 4".into(), style: "Regular".into() }],
            "one row per family and style the document uses"
        );
        let db = vectorcraft_text::FontDb::global();
        let closest = db.closest_style("Inter").expect("Inter is installed");
        let recent = replacement_rows(&app, "recent", &used);
        assert_eq!(recent.first(), Some(&Row { family: "Inter".into(), style: closest.clone() }), "the closest style comes first, by name");
        assert!(recent.iter().all(|r| r.family == "Inter"), "{recent:?}");
        assert_eq!(recent.len(), db.styles("Inter").len(), "each style once, the closest not repeated");
        assert!(recent.iter().all(|r| !r.style.is_empty()), "every row names its style: {recent:?}");
        let system = replacement_rows(&app, "system", &used);
        assert!(system.iter().any(|r| r.family == "Source Sans 3" && r.style == "Regular"), "{system:?}");
        assert!(!system.iter().any(|r| r.family.starts_with('.')), "the font menu's hidden families stay out");
        // A composite font is a family without styles of its own, listed by its name alone.
        assert!(system.iter().all(|r| !r.style.is_empty() || db.styles(&r.family).is_empty()), "no nameless rows: {system:?}");
        let menu = db.menu_family_list();
        let listed: std::collections::BTreeSet<&str> = system.iter().map(|r| r.family.as_str()).collect();
        assert_eq!(listed.len(), menu.len(), "every family the font menu shows is listed");
        let mut unique = system.clone();
        unique.dedup();
        assert_eq!(unique.len(), system.len(), "no family and style is listed twice");
        // The dialog stores the rows when it opens and when the source changes, and a picked row
        // sets both fields Change then uses.
        open(&mut app);
        assert_eq!(app.ui.dialog.as_ref().unwrap().fields["rows"].as_array().map(Vec::len), Some(system.len()));
        let mut d = app.ui.dialog.clone().unwrap();
        set_source(&app, &mut d, "document", &used);
        assert_eq!(d.fields["rows"].as_array().map(Vec::len), Some(document.len()));
        d.fields.insert("family".into(), json!("Inter"));
        d.fields.insert("style".into(), json!("Regular"));
        let from = used.iter().find(|f| f["family"] == "Source Serif 4").unwrap().clone();
        change(&mut app, &d, &from, true).unwrap();
        assert!(fonts(&mut app).iter().all(|f| f["family"] == "Inter"));
    }

    #[test]
    fn change_all_replaces_with_a_font_from_the_document() {
        let mut app = two_font_document();
        open(&mut app);
        let used = fonts(&mut app);
        let mut d = app.ui.dialog.clone().unwrap();
        set_source(&app, &mut d, "document", &used);
        d.fields.insert("family".into(), json!("Inter"));
        let from = used.iter().find(|f| f["family"] == "Source Serif 4").unwrap().clone();
        change(&mut app, &d, &from, true).unwrap();
        let families: Vec<Value> = fonts(&mut app).iter().map(|f| f["family"].clone()).collect();
        assert_eq!(families, [json!("Inter")]);
    }

    /// A font applied with Change All becomes Recent's first family.
    #[test]
    fn change_all_adds_the_new_font_to_recent() {
        let mut app = two_font_document();
        open(&mut app);
        let used = fonts(&mut app);
        let mut d = app.ui.dialog.clone().unwrap();
        d.fields.insert("family".into(), json!("Source Serif 4"));
        let from = used.iter().find(|f| f["family"] == "Inter").unwrap().clone();
        change(&mut app, &d, &from, true).unwrap();
        let used = fonts(&mut app);
        assert_eq!(replacement_families(&app, "recent", &used).unwrap(), ["Source Serif 4", "Inter"]);
    }

    /// A Change All that changes no text (the font's only text is locked) leaves Recent as it was.
    #[test]
    fn a_change_all_that_changes_nothing_leaves_recent_unchanged() {
        let mut app = two_font_document();
        app.run("select.font", json!({"family": "Source Serif 4"})).unwrap();
        app.run("object.lock", json!({})).unwrap();
        open(&mut app);
        let used = fonts(&mut app);
        let mut d = app.ui.dialog.clone().unwrap();
        d.fields.insert("family".into(), json!("Source Sans 3"));
        let from = used.iter().find(|f| f["family"] == "Source Serif 4").unwrap().clone();
        assert_eq!(change(&mut app, &d, &from, true).unwrap()["runs"], 0);
        assert_eq!(app.ui.recent_fonts, ["Inter"]);
    }

    /// Change to another name of an installed family records the family's own name in Recent.
    #[test]
    fn change_records_the_family_s_own_name_in_recent() {
        let mut app = two_font_document();
        open(&mut app);
        let used = fonts(&mut app);
        let mut d = app.ui.dialog.clone().unwrap();
        d.fields.insert("family".into(), json!("SourceSerif4-Regular"));
        let from = used.iter().find(|f| f["family"] == "Inter").unwrap().clone();
        assert_eq!(change(&mut app, &d, &from, true).unwrap()["runs"], 2);
        assert_eq!(app.ui.recent_fonts, ["Source Serif 4", "Inter"]);
    }

    #[test]
    fn an_empty_recent_list_leaves_nothing_to_change_to() {
        let mut app = two_font_document();
        app.ui.recent_fonts.clear();
        open(&mut app);
        let used = fonts(&mut app);
        let mut d = app.ui.dialog.clone().unwrap();
        set_source(&app, &mut d, "recent", &used);
        assert_eq!(replacement_families(&app, "recent", &used).unwrap(), Vec::<String>::new());
        assert_eq!(d.str("family"), "");
        assert!(!can_replace(&d, Some(&[])));
        app.ui.dialog = Some(d);
        let text = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx()));
        assert!(text.contains("Recent"), "{text}");
        assert_eq!(app.ui.status, "");
    }

    /// Document lists a missing family, but Change and Change All stay off for it, in every list.
    #[test]
    fn a_missing_document_font_is_listed_but_not_offered_to_change_to() {
        let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
        app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
        for (y, font) in [(20, "Missing Family"), (40, "Inter")] {
            app.session.execute("text.create", &json!({"x": 10, "y": y, "text": "Hi", "font": font})).unwrap();
        }
        open(&mut app);
        let used = fonts(&mut app);
        let document = replacement_families(&app, "document", &used).unwrap();
        assert!(document.iter().any(|f| f == "Missing Family"), "{document:?}");
        let mut d = app.ui.dialog.clone().unwrap();
        d.fields.insert("family".into(), json!("Missing Family"));
        set_source(&app, &mut d, "document", &used);
        assert_eq!(d.str("family"), "Inter", "the first installed family is chosen");
        assert!(can_replace(&d, Some(&document)));
        d.fields.insert("family".into(), json!("Missing Family"));
        assert!(!can_replace(&d, Some(&document)));
        assert!(!can_replace(&d, None), "System");
        set_source(&app, &mut d, "system", &used);
        assert!(can_replace(&d, None), "System chooses an installed family: {}", d.str("family"));
        // A document set only in a missing family leaves nothing to change to.
        app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
        app.session.execute("text.create", &json!({"x": 10, "y": 20, "text": "Hi", "font": "Missing Family"})).unwrap();
        let used = fonts(&mut app);
        set_source(&app, &mut d, "document", &used);
        assert_eq!(d.str("family"), "");
        assert!(!can_replace(&d, replacement_families(&app, "document", &used).as_deref()));
    }

    /// An empty Recent list clears the font; System then chooses an installed one again.
    #[test]
    fn system_after_an_empty_recent_list_chooses_an_installed_font() {
        let mut app = two_font_document();
        app.ui.recent_fonts.clear();
        open(&mut app);
        let used = fonts(&mut app);
        let mut d = app.ui.dialog.clone().unwrap();
        set_source(&app, &mut d, "recent", &used);
        assert_eq!(d.str("family"), "");
        set_source(&app, &mut d, "system", &used);
        assert_eq!((d.str("family").as_str(), d.str("style").as_str()), ("Source Sans 3", "Regular"), "the family's first listed style");
        assert!(can_replace(&d, None));
    }

    /// The dialog opens on System's font: Source Sans 3 when it is installed, otherwise the font
    /// menu's first family.
    #[test]
    fn the_dialog_opens_on_an_installed_font() {
        let menu = ["Inter".to_string(), "Source Serif 4".to_string()];
        assert_eq!(system_family_in(|_| true, &menu), "Source Sans 3");
        assert_eq!(system_family_in(|f| f != "Source Sans 3", &menu), "Inter");
        assert_eq!(system_family_in(|_| false, &[]), "");
        let mut app = two_font_document();
        open(&mut app);
        let d = app.ui.dialog.clone().unwrap();
        assert_eq!(d.str("family"), system_family());
        assert!(can_replace(&d, None), "{}", d.str("family"));
    }

    /// A family that is installed but left out of the font menu (a hidden `.` family that
    /// Document lists) cannot be changed to from System.
    #[test]
    fn system_offers_only_the_font_menu_s_families() {
        let menu = ["Inter".to_string()];
        assert!(can_replace_in("inter", |_| true, &menu));
        assert!(!can_replace_in(".Hidden", |_| true, &menu));
        assert!(!can_replace_in("Inter", |_| false, &menu));
        let hidden = vectorcraft_text::FontDb::global().family_list().iter().find(|f| f.starts_with('.') && installed(f)).cloned();
        if let Some(hidden) = hidden {
            let mut app = two_font_document();
            open(&mut app);
            let used = fonts(&mut app);
            let mut d = app.ui.dialog.clone().unwrap();
            d.fields.insert("family".into(), json!(hidden));
            assert!(!can_replace(&d, None), "{hidden}");
            set_source(&app, &mut d, "system", &used);
            assert_eq!(d.str("family"), system_family());
        }
    }

    #[test]
    fn rows_flag_missing_fonts_substituted_styles_and_lacking_characters() {
        let row = |status: &str, glyphs: u64| json!({"status": status, "resolved": {"style": "W4"}, "missingGlyphs": glyphs});
        assert_eq!(font_note(&row("exact", 0)), (String::new(), None));
        assert!(font_note(&row("missing", 0)).0.contains("missing"));
        assert!(font_note(&row("substitute", 0)).0.contains("substituted by W4"));
        let (note, color) = font_note(&row("exact", 2));
        assert!(note.contains("2 characters") && color.is_some());
    }

    /// The font list the dialog keeps for the active document.
    fn kept_list(app: &VectorcraftApp) -> Arc<Vec<Value>> {
        app.canvas.find_font.as_ref().expect("the dialog kept the document's fonts").fonts.clone()
    }

    /// The kept list and Find in Folder… are what `text.fonts` and `missing_fonts` give now.
    fn assert_current(app: &mut VectorcraftApp, shown: &str, why: &str) {
        let listed = fonts(app);
        assert_eq!(*kept_list(app), listed, "{why}: the list");
        let missing = app.session.active().is_some_and(|st| !vectorcraft_engine::cmd::fontfiles::missing_fonts(&st.doc).is_empty());
        let picks = crate::picks::can(app, &crate::picks::PickRequest::Folder);
        assert_eq!(shown.contains("Find in Folder…"), picks && missing, "{why}: Find in Folder… {shown}");
    }

    /// A document set in a missing family and in Inter, with a folder picker.
    fn missing_font_document() -> VectorcraftApp {
        let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
        app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
        for (y, font) in [(20, "Missing Family"), (40, "Inter")] {
            app.session.execute("text.create", &json!({"x": 10, "y": y, "text": "Hi", "font": font})).unwrap();
        }
        app.services.pick_folder = Some(Box::new(|| None));
        app
    }

    /// Frames that change nothing in the document, a new selection included, keep the font list
    /// and the missing-font answer worked out on the first; the answer is worked out only once a
    /// folder picker is there.
    #[test]
    fn the_font_list_is_worked_out_once_per_document_version() {
        let mut app = missing_font_document();
        let picker = app.services.pick_folder.take();
        open(&mut app);
        assert!(kept_over_frames(&mut app, "no folder picker"), "frames of one document version keep its list");
        assert_eq!(app.canvas.find_font.as_ref().and_then(|c| c.missing), None, "no picker: the document is not searched for missing fonts");
        app.services.pick_folder = picker;
        assert!(kept_over_frames(&mut app, "a folder picker"), "a picker alone keeps the list");
        assert_eq!(app.canvas.find_font.as_ref().and_then(|c| c.missing), Some(true));
        app.run("select.all", json!({})).unwrap();
        assert!(kept_over_frames(&mut app, "a new selection"), "a new selection keeps the list");
    }

    /// Draws frames of the dialog and tells whether they kept the list kept before them. Another
    /// test thread that changes the available fonts meanwhile makes the dialog work the list out
    /// again, so the frames are drawn again until the fonts stay as they are.
    fn kept_over_frames(app: &mut VectorcraftApp, why: &str) -> bool {
        for _ in 0..20 {
            // The generation the kept list was worked out under: the database's generation only
            // counts up, so the same one after the frames means no fonts changed in between.
            let before = kept_list(app);
            let generation = app.canvas.find_font.as_ref().map(|c| c.key.generation);
            let shown = crate::tests_labels::painted_text(app, |app, ui| show(app, ui.ctx()));
            assert_current(app, &shown, why);
            if Some(vectorcraft_text::FontDb::global().generation()) == generation {
                return Arc::ptr_eq(&before, &kept_list(app));
            }
        }
        panic!("{why}: the available fonts kept changing")
    }

    /// An edit, its undo and a Change All each give the list of the document as it is then.
    #[test]
    fn an_edit_works_the_font_list_out_again() {
        let mut app = missing_font_document();
        open(&mut app);
        crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx()));
        let first = kept_list(&app);
        app.run("text.replaceFont", json!({"from": {"family": "Missing Family"}, "to": {"family": "Inter"}})).unwrap();
        let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx()));
        assert_current(&mut app, &shown, "after the replacement");
        assert!(!shown.contains("Find in Folder…"), "nothing is missing: {shown}");
        assert_eq!(kept_list(&app).len(), 1, "{:?}", kept_list(&app));
        app.run("edit.undo", json!({})).unwrap();
        let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx()));
        assert_current(&mut app, &shown, "after the undo");
        assert_eq!(*kept_list(&app), *first, "the undo brings back the first list");
        let mut d = app.ui.dialog.clone().unwrap();
        d.fields.insert("family".into(), json!("Source Serif 4"));
        d.fields.insert("style".into(), json!(""));
        let from = first.iter().find(|f| f["family"] == "Inter").unwrap().clone();
        change(&mut app, &d, &from, true).unwrap();
        let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx()));
        assert_current(&mut app, &shown, "after Change All");
        assert!(kept_list(&app).iter().any(|f| f["family"] == "Source Serif 4"), "{:?}", kept_list(&app));
    }

    /// Fonts that become available, a composite font defined among them, give the list and the
    /// missing-font answer as they are with those fonts.
    #[test]
    fn other_available_fonts_work_the_font_list_out_again() {
        const FAMILY: &str = "Find Font Kept List CF";
        let mut app = missing_font_document();
        app.session.execute("text.create", &json!({"x": 10, "y": 60, "text": "Ab12", "font": FAMILY})).unwrap();
        open(&mut app);
        crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx()));
        // The same document under another generation of the font database: what is kept for it no
        // longer counts.
        let entry = app.canvas.find_font.as_mut().unwrap();
        entry.key.generation = u64::MAX;
        entry.fonts = Arc::default();
        entry.missing = Some(false);
        let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx()));
        assert_current(&mut app, &shown, "another font generation");
        let row = |app: &VectorcraftApp| kept_list(app).iter().find(|f| f["family"] == FAMILY).cloned().unwrap();
        assert_eq!(row(&app)["status"], "missing");
        let generation = vectorcraft_text::FontDb::global().generation();
        let parts = json!({"name": FAMILY, "parts": {"kanji": {"font": "Source Sans 3"}, "roman": {"font": "JetBrains Mono"}, "numerals": {"font": "Inter"}}});
        app.run("type.compositeFonts.set", json!({"fonts": [parts]})).unwrap();
        assert_ne!(vectorcraft_text::FontDb::global().generation(), generation, "defining a composite font is a new generation");
        let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx()));
        assert_current(&mut app, &shown, "the composite font defined");
        assert_eq!(row(&app)["status"], "exact");
        app.run("type.compositeFonts.set", json!({"fonts": []})).unwrap();
        let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx()));
        assert_current(&mut app, &shown, "the composite font taken out");
        assert_eq!(row(&app)["status"], "missing");
    }

    /// Another document in front, and pattern editing entered and canceled, each give the list of
    /// the document in front as it is then.
    #[test]
    fn the_font_list_follows_the_document_in_front() {
        let mut app = missing_font_document();
        app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
        let id = app.session.execute("text.create", &json!({"x": 10, "y": 40, "text": "Hi", "font": "Source Serif 4"})).unwrap()["id"].clone();
        app.services.pick_folder = Some(Box::new(|| None));
        open(&mut app);
        let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx()));
        assert_current(&mut app, &shown, "the second document");
        app.session.set_active(0);
        let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx()));
        assert_current(&mut app, &shown, "the first document");
        assert!(shown.contains("Find in Folder…"), "{shown}");
        app.session.set_active(1);
        app.run("select.set", json!({"ids": [id]})).unwrap();
        app.run("object.pattern.make", json!({"name": "Kept List"})).unwrap();
        assert!(app.session.active().unwrap().doc.pattern_edit.is_some(), "pattern editing");
        let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx()));
        assert_current(&mut app, &shown, "pattern editing");
        app.run("object.pattern.cancel", json!({})).unwrap();
        let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx()));
        assert_current(&mut app, &shown, "pattern editing canceled");
    }

    /// CPU time of this thread in nanoseconds where the system reports it (Linux), else `None`.
    fn thread_cpu_ns() -> Option<u128> {
        std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok()
    }

    /// Time the font list and the missing-font answer a Find Font frame reads, for a document of
    /// 2,000 point-type objects of 50 characters each and one of 20, set in five installed faces
    /// and a missing family, with a folder picker: worked out on every frame as `text.fonts` and
    /// `missing_fonts` (each frame before they were kept), on the first frame of a document version
    /// ([`document_fonts`] with nothing kept) and on later frames. Per run, the large document
    /// draws 120 frames and the small one 12,000 (so the thread's CPU clock, which advances in
    /// steps of a few milliseconds, sees them), and later frames number 1,000,000; the sides
    /// alternate, and the median time per frame of 7 runs is printed.
    /// Run with `cargo test --release -p vectorcraft-ui-egui --lib find_font_list_timing -- --ignored --nocapture`.
    #[test]
    #[ignore = "manual timing probe; performance depends on machine load"]
    fn find_font_list_timing() {
        const KEPT: u32 = 1_000_000;
        const FACES: [(&str, &str); 6] = [
            ("Inter", "Regular"),
            ("Inter", "Medium"),
            ("Source Sans 3", "Bold"),
            ("Source Serif 4", "Regular"),
            ("JetBrains Mono", "Regular"),
            ("Missing Family", "Regular"),
        ];
        for (objects, frames) in [(2_000, 120), (20, 12_000)] {
            let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
            app.session.execute("file.new", &json!({"width": 2000, "height": 2000})).unwrap();
            for i in 0..objects {
                let (family, style) = FACES[i % FACES.len()];
                let text: String = (0..50).map(|c| char::from(b'a' + ((i + c) % 26) as u8)).collect();
                let (x, y) = ((i % 20 * 90) as f64, (i / 20 * 18) as f64 + 20.0);
                app.session.execute("text.create", &json!({"x": x, "y": y, "text": text, "font": family, "style": style})).unwrap();
            }
            app.services.pick_folder = Some(Box::new(|| None));
            let every_frame = |app: &mut VectorcraftApp| {
                let list = fonts(app);
                let offer = crate::picks::can(app, &crate::picks::PickRequest::Folder)
                    && app.session.active().is_some_and(|st| !vectorcraft_engine::cmd::fontfiles::missing_fonts(&st.doc).is_empty());
                (list, offer)
            };
            let expected = every_frame(&mut app);
            assert!(expected.1 && expected.0.len() == FACES.len(), "{expected:?}");
            let kept = document_fonts(&mut app, true);
            assert_eq!((kept.0.to_vec(), kept.1), expected, "the kept answers are the ones worked out every frame");
            // Each side's answers for one frame: the number of fonts listed and Find in Folder….
            let time = |app: &mut VectorcraftApp, frames: u32, f: &mut dyn FnMut(&mut VectorcraftApp) -> (usize, bool)| {
                let (cpu, wall) = (thread_cpu_ns(), std::time::Instant::now());
                for _ in 0..frames {
                    assert_eq!(f(app), (FACES.len(), true));
                }
                let ns = thread_cpu_ns().zip(cpu).map_or_else(|| wall.elapsed().as_nanos(), |(b, a)| b - a);
                ns as f64 / f64::from(frames) / 1000.0
            };
            let (mut full, mut first, mut later) = (vec![], vec![], vec![]);
            for _ in 0..7 {
                full.push(time(&mut app, frames, &mut |app| {
                    let (list, offer) = every_frame(app);
                    (list.len(), offer)
                }));
                first.push(time(&mut app, frames, &mut |app| {
                    app.canvas.find_font = None;
                    let (list, offer) = document_fonts(app, true);
                    (list.len(), offer)
                }));
                later.push(time(&mut app, KEPT, &mut |app| {
                    let (list, offer) = document_fonts(app, true);
                    (list.len(), offer)
                }));
            }
            let median = |v: &mut Vec<f64>| {
                v.sort_by(f64::total_cmp);
                v[v.len() / 2]
            };
            let clock = if thread_cpu_ns().is_some() { "thread CPU time" } else { "wall-clock time" };
            eprintln!("{objects} text objects of 50 characters; {clock} per frame, median of 7 runs");
            eprintln!("worked out every frame ({frames} frames a run):    {:>12.3} us  {full:.3?}", median(&mut full));
            eprintln!("first frame of a version ({frames} a run):         {:>12.3} us  {first:.3?}", median(&mut first));
            eprintln!("later frames of the version ({KEPT} a run): {:>12.4} us  {later:.4?}", median(&mut later));
        }
    }
}