GitCorner

Code

ossartcraftvectorcraft🌐
2bc41aeb8602
//! File → New: category tabs (Recent, Saved and the built-in categories of `file.newPresets`)
//! over a grid of preset cards, and a Preset Details column (name and Save Preset, size and
//! units, orientation, artboards, bleed, background contents, Advanced Options, More Settings);
//! Close and Create. More Settings opens a pop-up over the dialog with the artboard layout, spacing
//! and columns, editing the same fields. Save Preset turns the top of Preset Details into the
//! preset's name, Cancel and Save, and hides Close and Create until the preset is saved or canceled;
//! the rows under it stay editable and are what the preset stores. Manage Profiles opens a pop-up
//! listing the New Document profiles (`file.newProfiles`), each with Edit, which closes the dialog
//! and opens the profile as a document, and Reset, which brings back the shipped profile.
//!
//! Fields: `file.new`'s params (`preset`, `name`, `width`, `height` (pt), `units`, `artboards`,
//! `artboardLayout`, `bleed`, `backgroundContents`, `colorMode`, `rasterEffectsPpi`,
//! `previewMode`, `alignNewObjectsToPixelGrid`, `profile`), plus `category` (the tab), `advanced` (Advanced Options open), `bleedLinked` and
//! `presetName` (Save Preset's name). Setting `preset` fills the fields from that preset; changing
//! any of them afterwards makes the settings custom. The dialog opens in Preferences › Units ›
//! General, also on a Recent entry made in other units (one in pixels, or a saved preset in the
//! units it was saved in, keeps its units); units chosen
//! in the Units menu or set with `ui.dialog.set` stay when another tab or preset is chosen.

use serde_json::{Map, Value, json};
use vectorcraft_doc::Unit;
use vectorcraft_engine::cmd::newdoc::{self, ArtboardLayout, DocSettings, MAX_ARTBOARDS, PreviewMode, RASTER_PPI};

use super::{DialogSpec, form};
use crate::state::Dialog;
use crate::theme::{self, Tokens};
use crate::{VectorcraftApp, widgets};

pub(super) const KIND: &str = "newDocument";
/// New Document with its More Settings pop-up open.
pub(super) const MORE: &str = "newDocumentMore";
/// New Document with its Manage Profiles pop-up open.
pub(super) const PROFILES: &str = "newDocumentProfiles";

pub(super) const SPEC: DialogSpec = DialogSpec { inputs: |_| &["presetName"], ..DialogSpec::window(show, confirm) };
pub(super) const MORE_SPEC: DialogSpec = SPEC;

/// The fields `file.new` takes.
const PARAMS: [&str; 14] = [
    "preset",
    "name",
    "width",
    "height",
    "units",
    "artboards",
    "artboardLayout",
    "bleed",
    "backgroundContents",
    "colorMode",
    "rasterEffectsPpi",
    "previewMode",
    "alignNewObjectsToPixelGrid",
    "profile",
];
/// The preset the fields were last filled from, as `apply` set them; a Recent or Saved card keeps
/// its own units here, which the units chosen in Preset Details don't change.
const APPLIED: &str = "__applied";
/// Preset Details is saving a preset (Save Preset's name, Cancel and Save are showing).
const SAVING: &str = "__saving";
/// Preset Details has drawn the saving top: set from the mode's second frame, so the first one fills
/// in the default name and focuses it.
const SAVING_SHOWN: &str = "__savingShown";
/// The units were chosen in the Units menu (or set with `ui.dialog.set`): presets chosen after that
/// keep the chosen units.
const UNITS_CHOSEN: &str = "__unitsChosen";
/// The units New Document offers (all ten).
const UNITS: [Unit; 10] = [
    Unit::Pixels,
    Unit::Points,
    Unit::Picas,
    Unit::Inches,
    Unit::Millimeters,
    Unit::Centimeters,
    Unit::Feet,
    Unit::Yards,
    Unit::Meters,
    Unit::FeetInches,
];
const BACKGROUNDS: [(&str, &str); 2] = [("transparent", "Transparent (Default)"), ("white", "White")];
const COLOR_MODES: [(&str, &str); 2] = [("rgb", "RGB Color"), ("cmyk", "CMYK Color")];
/// Width of the Preset Details column.
const DETAILS: f32 = 292.0;
/// Height of the dialog's content.
const HEIGHT: f32 = 600.0;
/// Height of the top of Preset Details in either state: the rows under it don't move.
const HEADER: f32 = 100.0;
/// Width of the More Settings pop-up's rows.
const MORE_WIDTH: f32 = 310.0;

/// Open New Document on the most recent settings (or Letter), named after the next untitled
/// document, in Preferences › Units › General.
pub fn open(app: &mut VectorcraftApp) {
    let category = if app.session.prefs.recent_new_docs.is_empty() { "Print" } else { "Recent" };
    let mut d = Dialog::new(KIND, json!({ "category": category, "name": app.session.peek_untitled(), "advanced": false }));
    if !apply_first(app, &mut d, category) {
        apply(&mut d, &DocSettings { units: app.session.default_units(), ..DocSettings::default() });
    }
    app.ui.dialog = Some(d);
}

/// Fill the fields from the first preset of `category`, as opening the dialog and choosing a tab
/// do; false when the category has none. The most recent entry keeps its size and takes
/// Preferences › Units › General, as the built-in presets do, unless it is in pixels or it is a
/// saved preset in the units it was saved in. Its card stays the chosen one and shows those units;
/// choosing another card brings back that card's own units.
fn apply_first(app: &VectorcraftApp, d: &mut Dialog, category: &str) -> bool {
    let Some(first) = newdoc::category(&app.session, category).and_then(|v| v.into_iter().next()) else { return false };
    // `file.new` reads a named preset in its own units, and names the entry Custom in others.
    let as_saved = newdoc::find(&app.session, &first.name).is_some_and(|p| p.units == first.units);
    if !category.eq_ignore_ascii_case("Recent") || first.units == Unit::Pixels || as_saved {
        apply(d, &first);
        return true;
    }
    let own = first.units;
    apply(d, &DocSettings { units: app.session.default_units(), ..first });
    // The card is still the entry it was: its own units say which entry it is.
    if let Some(Value::Object(a)) = d.fields.get_mut(APPLIED) {
        a.insert("units".into(), json!(own.label()));
    }
    true
}

/// `field` of New Document `d` is about to be set by `ui.dialog.set`: setting the units is a choice
/// that presets chosen after it keep.
pub(super) fn note_set(d: &mut Dialog, field: &str) {
    if field == "units" {
        d.fields.insert(UNITS_CHOSEN.into(), json!(true));
    }
}

/// Fill the fields from a preset, keeping the units when they were chosen in the Units menu.
fn apply(d: &mut Dialog, s: &DocSettings) {
    let chosen = if d.bool(UNITS_CHOSEN) { d.fields.get("units").cloned() } else { None };
    let Value::Object(mut v) = s.to_json() else { return };
    for k in ["size", "orientation"] {
        v.remove(k);
    }
    if let Some(name) = v.remove("name") {
        v.insert("preset".into(), name);
    }
    d.fields.insert("bleedLinked".into(), json!(s.bleed.iter().all(|b| *b == s.bleed[0])));
    for (k, val) in &v {
        d.fields.insert(k.clone(), val.clone());
    }
    d.fields.insert(APPLIED.into(), Value::Object(v));
    if let Some(u) = chosen {
        d.fields.insert("units".into(), u);
    }
}

/// Keep the fields and the chosen preset in step: a new `preset` (also from `ui.dialog.set`) fills
/// the fields; a changed field makes the settings custom.
fn sync(app: &VectorcraftApp, d: &mut Dialog) {
    let preset = d.str("preset");
    match d.fields.get(APPLIED).and_then(Value::as_object) {
        Some(a) if a.get("preset").and_then(Value::as_str) == Some(preset.as_str()) => {
            // Unchanged fields keep the preset (falling through would apply it again); the units
            // only change how the sizes show.
            let edited = a.iter().any(|(k, v)| k != "preset" && k != "units" && d.fields.get(k) != Some(v));
            if edited {
                d.fields.insert("preset".into(), json!(""));
                d.fields.remove(APPLIED);
            }
        }
        _ if !preset.is_empty() => match newdoc::find(&app.session, &preset) {
            Some(s) => apply(d, &s),
            None => {
                d.fields.remove(APPLIED);
            }
        },
        _ => {}
    }
}

/// Create the document; the dialog stays open when that fails (bad size, …). While a preset is being
/// saved this is its Save, and no document is created.
fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
    if d.bool(SAVING) {
        let mut d = d.clone();
        let r = save_preset(app, &mut d);
        if r.is_ok() {
            app.ui.dialog = Some(d);
        }
        return r;
    }
    let p = params(app, d);
    let r = app.run("file.new", Value::Object(p));
    if let Ok(r) = &r {
        app.ui.dialog = None;
        report_profile(app, r);
    }
    r
}

/// Say in the status bar when `file.new`'s result `r` reports a profile it could not read, or
/// color profiles its file carries that can't be used.
fn report_profile(app: &mut VectorcraftApp, r: &Value) {
    if let Some(e) = r.get("profileError") {
        let (name, reason) = (e["profile"].as_str().unwrap_or_default(), e["reason"].as_str().unwrap_or_default());
        app.status(format!("The {name} profile could not be read, so the new document has the default settings: {reason}"));
    } else if let Some(w) = r["warnings"].as_array().filter(|w| !w.is_empty()) {
        app.status(w.iter().filter_map(Value::as_str).collect::<Vec<_>>().join("; "));
    }
}

/// New Without Dialog (`file.newWithoutDialog`, Cmd+Alt+N): create the document [`open`] would
/// offer, as its Create would, without showing the dialog. A dialog already open stays open.
pub fn create_without_dialog(app: &mut VectorcraftApp) -> Result<Value, String> {
    let shown = app.ui.dialog.take();
    open(app);
    let offered = app.ui.dialog.take();
    app.ui.dialog = shown;
    let p = offered.map(|d| params(app, &d)).unwrap_or_default();
    let r = app.run("file.new", Value::Object(p));
    if let Ok(r) = &r {
        report_profile(app, r);
    }
    r
}

/// The `file.new` params of the fields.
fn params(app: &VectorcraftApp, d: &Dialog) -> Map<String, Value> {
    let mut p: Map<String, Value> = PARAMS.iter().filter_map(|k| Some((k.to_string(), d.fields.get(*k)?.clone()))).collect();
    // Recent entries such as "Custom" aren't presets file.new knows.
    if newdoc::find(&app.session, &d.str("preset")).is_none() {
        p.remove("preset");
    }
    p
}

/// The units the size fields show.
fn unit(d: &Dialog) -> Unit {
    Unit::named(&d.str("units")).unwrap_or_default()
}

/// The artboard layout fields.
fn layout(d: &Dialog) -> (ArtboardLayout, u64, f64, bool) {
    let l = d.fields.get("artboardLayout");
    let get = |k: &str| l.and_then(|l| l.get(k));
    (
        get("layout").and_then(Value::as_str).and_then(ArtboardLayout::parse).unwrap_or_default(),
        get("columns").and_then(Value::as_u64).unwrap_or(1),
        get("spacing").and_then(Value::as_f64).unwrap_or(20.0),
        get("rightToLeft").and_then(Value::as_bool).unwrap_or(false),
    )
}

fn set_layout(d: &mut Dialog, key: &str, v: Value) {
    let mut l = d.fields.get("artboardLayout").cloned().filter(Value::is_object).unwrap_or_else(|| json!({}));
    l[key] = v;
    d.fields.insert("artboardLayout".into(), l);
}

/// The New Document dialog window `id` in the shared modal frame.
fn window(ctx: &egui::Context, id: &str, margin: i8, add: impl FnOnce(&mut egui::Ui)) {
    super::modal::show(ctx, id, egui::Id::unique(("dialog", id)), -20.0, margin, add);
}

/// Whether More Settings' or Manage Profiles' pop-up is open over New Document.
pub(crate) fn popup_open(d: &Dialog) -> bool {
    d.kind == MORE || d.kind == PROFILES
}

/// Close New Document's More Settings or Manage Profiles pop-up, or else leave its Save Preset,
/// keeping the fields. False when none is showing, or `d` is another dialog.
pub(super) fn close_popup(d: &mut Dialog) -> bool {
    if d.kind != KIND && !popup_open(d) {
        return false;
    }
    if popup_open(d) {
        d.kind = KIND.into();
        return true;
    }
    let saving = d.bool(SAVING);
    if saving {
        d.fields.insert(SAVING.into(), json!(false));
        d.fields.remove(SAVING_SHOWN);
    }
    saving
}

/// What the buttons of a window asked for.
#[derive(Default)]
struct Buttons {
    create: bool,
    close: bool,
    /// More Settings' pop-up was open as the frame began: Enter is the pop-up's.
    popup: bool,
    /// A preset was being saved as the frame began: nothing creates the document this frame.
    saving: bool,
}

impl Buttons {
    /// Act on the buttons (Enter also creates) once the window is drawn.
    fn finish(self, app: &mut VectorcraftApp, ctx: &egui::Context, d: Dialog) {
        let enter = !self.popup && crate::shortcuts::pressed_anew(ctx, egui::Key::Enter) && !ctx.memory(|m| m.focused().is_some());
        let create = !self.saving && !d.bool(SAVING) && (self.create || enter);
        app.ui.dialog = Some(d);
        if self.close {
            app.ui.dialog = None;
        } else if create && let Err(e) = super::confirm(app) {
            app.status(e);
        }
    }
}

fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
    let Some(mut d) = app.ui.dialog.clone() else { return };
    sync(app, &mut d);
    let t = Tokens::get(ctx);
    let mut b = Buttons { popup: popup_open(&d), saving: d.bool(SAVING), ..Default::default() };
    window(ctx, KIND, 0, |ui| {
        // No heading: the top margin (14) and the empty part of the category tabs' row (30) move the
        // window.
        super::modal::drag_band(ui, ui.max_rect().top() + 44.0);
        ui.horizontal_top(|ui| {
            egui::Frame::NONE.inner_margin(egui::Margin { left: 22, right: 14, top: 14, bottom: 18 }).show(ui, |ui| {
                ui.vertical(|ui| {
                    ui.set_width(640.0);
                    ui.set_min_height(HEIGHT - 32.0);
                    b.create |= presets(app, ui, &mut d);
                });
            });
            egui::Frame::NONE.fill(t.panel_darker).inner_margin(egui::Margin::same(18)).show(ui, |ui| {
                ui.vertical(|ui| {
                    ui.set_width(DETAILS);
                    ui.set_min_height(HEIGHT);
                    details(app, ui, &mut d, &mut b);
                });
            });
        });
        // While More Settings' pop-up is open, a click outside it only closes it.
        if b.popup {
            ui.interact(ui.min_rect(), ui.scope_id().with("newdoc-popup-shield"), egui::Sense::CLICK | egui::Sense::DRAG);
        }
    });
    b.finish(app, ctx, d);
}

/// The category tabs and the chosen category's preset cards: a click chooses one, a double-click
/// also creates it (true then).
fn presets(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
    let t = Tokens::get(ui.ctx());
    let names: Vec<&str> = newdoc::category_names().collect();
    let cat = names.iter().position(|n| n.eq_ignore_ascii_case(&d.str("category"))).unwrap_or(0);
    if let Some(i) = widgets::tab_bar(ui, &names, cat) {
        d.fields.insert("category".into(), json!(names[i]));
        // A tab opens on its first preset, so the details match its cards.
        if let Some(c) = names.get(i) {
            apply_first(app, d, c);
        }
    }
    let list = names.get(cat).and_then(|c| newdoc::category(&app.session, c)).unwrap_or_default();
    ui.add_space(14.0);
    let heading = if cat == 0 {
        tl!("RECENT")
    } else if cat == 1 {
        tl!("SAVED")
    } else {
        tl!("BLANK DOCUMENT PRESETS")
    };
    ui.label(egui::RichText::new(format!("{heading} ({})", list.len())).font(theme::semibold(11.0)).color(t.text_dim));
    ui.add_space(10.0);
    if list.is_empty() {
        let hint = if cat == 1 { tl!("Presets you save with the Save Preset button appear here.") } else { tl!("Documents you create appear here.") };
        ui.label(egui::RichText::new(hint).color(t.text_dim));
        return false;
    }
    let mut create = false;
    egui::ScrollArea::vertical().id_salt(("newdoc-presets", cat)).max_height(HEIGHT - 110.0).auto_shrink([false, false]).show(ui, |ui| {
        ui.horizontal_wrapped(|ui| {
            ui.spacing_mut().item_spacing = egui::vec2(12.0, 12.0);
            let (w, h, preset, units) = (d.f64("width", 0.0), d.f64("height", 0.0), d.str("preset"), unit(d));
            // The fields were last filled from this preset's card; Recent keeps one entry per size
            // and units, so the units tell two entries of one size apart.
            let chosen = d
                .fields
                .get(APPLIED)
                .filter(|a| a.get("preset").and_then(Value::as_str) == Some(preset.as_str()))
                .and_then(Value::as_object)
                .cloned();
            for s in &list {
                // The built-in presets' cards show the chosen orientation (square sizes have none);
                // Recent and Saved show each entry as it was made, so a portrait and a landscape A3
                // are two cards (#2860).
                let mut card = s.clone();
                if cat > 1 && ((w > h && card.height > card.width) || (h > w && card.width > card.height)) {
                    std::mem::swap(&mut card.width, &mut card.height);
                }
                // The built-in presets all share the units chosen in Preset Details.
                if cat > 1 {
                    card.units = units;
                }
                let selected = chosen.as_ref().is_some_and(|a| {
                    a.get("preset").and_then(Value::as_str) == Some(card.name.as_str())
                        && a.get("width").and_then(Value::as_f64) == Some(card.width)
                        && a.get("height").and_then(Value::as_f64) == Some(card.height)
                        && (cat > 1 || a.get("units").and_then(Value::as_str) == Some(s.units.label()))
                });
                // The chosen card shows the units chosen in Preset Details, which the new document
                // will have (#2078); the others keep their own, so choosing one document's units
                // doesn't restyle the whole tab.
                if selected {
                    card.units = units;
                }
                let resp = preset_card(ui, &card, selected);
                if resp.clicked() || resp.double_clicked() {
                    apply(d, &card);
                    // The card is still the entry it was, whatever units it shows: its own units say
                    // which entry it is, so a chosen card stays chosen after a units change.
                    if cat < 2
                        && let Some(Value::Object(a)) = d.fields.get_mut(APPLIED)
                    {
                        a.insert("units".into(), json!(s.units.label()));
                    }
                }
                create |= resp.double_clicked();
            }
        });
    });
    create
}

/// Is `name` a built-in preset's? Those are ours (translated); Recent and Saved hold the names of
/// the user's documents and presets, shown as they are.
fn is_builtin_preset(name: &str) -> bool {
    newdoc::CATEGORIES.iter().any(|(_, _, _, presets)| presets.iter().any(|(n, ..)| *n == name))
}

/// A preset's name as shown: a built-in one translated, the user's as it is.
pub(crate) fn preset_name(name: &str) -> &str {
    if is_builtin_preset(name) { tl!(name) } else { name }
}

/// A preset card: a page-proportioned thumbnail, the name and the size (New Document, the Home
/// screen). Returns the card's response.
pub fn preset_card(ui: &mut egui::Ui, s: &DocSettings, selected: bool) -> egui::Response {
    let t = Tokens::get(ui.ctx());
    let label = preset_name(&s.name);
    let (r, resp) = ui.allocate_exact_size(egui::vec2(146.0, 150.0), egui::Sense::click());
    let p = ui.painter();
    p.rect_filled(r, egui::CornerRadius::same(6), if resp.hovered() || selected { t.hover } else { t.panel_darker });
    if selected {
        p.rect_stroke(r, egui::CornerRadius::same(6), egui::Stroke::new(2.0, t.accent), egui::StrokeKind::Inside);
    }
    let k = (60.0 / s.width.max(s.height).max(1e-9)) as f32;
    let page = egui::Rect::from_center_size(
        r.center_top() + egui::vec2(0.0, 48.0),
        egui::vec2((s.width as f32 * k).max(4.0), (s.height as f32 * k).max(4.0)),
    );
    p.rect_filled(page.translate(egui::vec2(2.0, 2.0)), 0.0, egui::Color32::from_black_alpha(80));
    p.rect_filled(page, 0.0, egui::Color32::WHITE);
    // The name on up to two lines, then the size.
    let mut job = egui::text::LayoutJob::single_section(
        label.to_string(),
        egui::TextFormat { font_id: theme::semibold(11.5), color: t.text_strong, ..Default::default() },
    );
    job.halign = egui::Align::Center;
    job.wrap = egui::text::TextWrapping { max_width: r.width() - 14.0, max_rows: 2, break_anywhere: false, overflow_character: Some('…') };
    let name = ui.fonts_mut(|f| f.layout_job(job));
    let name_h = name.size().y;
    p.galley(egui::pos2(r.center().x, r.top() + 94.0), name, t.text_strong);
    p.text(egui::pos2(r.center().x, r.top() + 98.0 + name_h), egui::Align2::CENTER_TOP, s.size_label(), egui::FontId::proportional(11.0), t.text_dim);
    resp.on_hover_text(label)
}

/// The Preset Details column.
fn details(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, b: &mut Buttons) {
    let t = Tokens::get(ui.ctx());
    ui.spacing_mut().item_spacing = egui::vec2(6.0, 4.0);
    let top = ui.cursor().top();
    let saving = d.bool(SAVING);
    if saving {
        let opening = !d.bool(SAVING_SHOWN);
        d.fields.insert(SAVING_SHOWN.into(), json!(true));
        save_header(app, ui, d, opening);
    } else {
        d.fields.remove(SAVING_SHOWN);
        ui.label(egui::RichText::new(tl!("PRESET DETAILS")).font(theme::semibold(11.0)).color(t.text_dim));
        ui.add_space(8.0);
        let caption = form::caption(ui, tl!("Document Name"));
        ui.horizontal(|ui| {
            ui.label_inputs_by(caption.id, |ui| form::text(ui, d, "name", DETAILS - 50.0));
            if widgets::icon_button(ui, "save", tl!("Save Preset"), false, 26.0).clicked() {
                d.fields.insert(SAVING.into(), json!(true));
            }
        });
    }
    ui.add_space((HEADER - (ui.cursor().top() - top)).max(0.0));
    let unit = unit(d);
    let caption = form::caption(ui, tl!("Width"));
    ui.horizontal(|ui| {
        ui.label_inputs_by(caption.id, |ui| form::length(ui, d, "width", unit, DETAILS - 124.0));
        ui.name_inputs(tl!("Units"), |ui| units_dropdown(ui, d, 112.0));
    });
    ui.add_space(4.0);
    ui.horizontal_top(|ui| {
        ui.vertical(|ui| {
            let caption = form::caption(ui, tl!("Height"));
            ui.label_inputs_by(caption.id, |ui| form::length(ui, d, "height", unit, 104.0));
        });
        ui.add_space(6.0);
        ui.vertical(|ui| {
            form::caption(ui, tl!("Orientation"));
            orientation(ui, d);
        });
        ui.add_space(6.0);
        ui.vertical(|ui| {
            let caption = form::caption(ui, tl!("Artboards"));
            ui.label_inputs_by(caption.id, |ui| artboards(ui, d, "newdoc-artboards", 76.0));
        });
    });
    ui.add_space(8.0);
    form::caption(ui, tl!("Bleed"));
    form::bleed(ui, d, unit, 52.0);
    ui.add_space(8.0);
    let caption = form::caption(ui, tl!("Background Contents"));
    ui.label_inputs_by(caption.id, |ui| background(ui, d, DETAILS - 34.0));
    ui.add_space(8.0);
    advanced(ui, d, 110.0, DETAILS - 116.0);
    ui.add_space(12.0);
    more_settings(ui, d);
    if saving {
        return;
    }
    ui.add_space(6.0);
    b.close |= manage_profiles(app, ui, d);
    // Close and Create at the bottom right.
    ui.add_space((HEIGHT - (ui.cursor().top() - top) - 28.0).max(12.0));
    ui.allocate_ui_with_layout(egui::vec2(ui.available_width(), 28.0), egui::Layout::right_to_left(egui::Align::Center), |ui| {
        b.create |= widgets::primary_button(ui, tl!("Create")).clicked();
        ui.add_space(8.0);
        b.close |= widgets::secondary_button(ui, tl!("Close")).clicked();
    });
}

/// The key under which a layer remembers that its first field should take the keyboard focus.
fn pending_focus(ui: &egui::Ui) -> egui::Id {
    ui.layer_id().id.with("newdoc-focus")
}

/// Draw `add`; its first enabled field takes the keyboard focus, with its text selected, when
/// `opening` says so or a failed Save asked for it.
fn focus_first<R>(ui: &mut egui::Ui, opening: bool, add: impl FnOnce(&mut egui::Ui) -> R) -> R {
    let pending = pending_focus(ui);
    if opening {
        ui.data_mut(|m| m.insert_temp(pending, true));
    }
    // The first frame of a new window only measures it: no field can take the focus until the next.
    let focus = !ui.is_sizing_pass() && ui.data(|m| m.get_temp::<bool>(pending)).unwrap_or(false);
    if focus {
        ui.data_mut(|m| m.insert_temp(widgets::dialog_focus_flag(), true));
    }
    let r = add(ui);
    if focus && ui.data_mut(|m| m.remove_temp::<bool>(widgets::dialog_focus_flag())).is_none() {
        ui.data_mut(|m| m.remove::<bool>(pending));
    }
    r
}

/// The top of Preset Details while a preset is being saved: the heading, the preset's name, Cancel
/// and Save. Enter in the name is Save. `opening` on the mode's first frame.
fn save_header(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, opening: bool) {
    let t = Tokens::get(ui.ctx());
    if opening && d.str("presetName").is_empty() {
        d.fields.insert("presetName".into(), json!(new_preset_name(app)));
    }
    ui.label(egui::RichText::new(tl!("Save Document Preset")).font(theme::semibold(13.0)).color(t.text));
    ui.add_space(5.0);
    let name = focus_first(ui, opening, |ui| form::text_edit_named(ui, d, "presetName", tl!("Preset Name"), DETAILS - 14.0));
    let enter = name.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter));
    ui.add_space(4.0);
    let (mut save, mut cancel) = (enter, false);
    ui.allocate_ui_with_layout(egui::vec2(ui.available_width(), 28.0), egui::Layout::right_to_left(egui::Align::Center), |ui| {
        save |= widgets::primary_button(ui, tl!("Save")).clicked();
        ui.add_space(8.0);
        cancel = widgets::secondary_button(ui, tl!("Cancel")).clicked();
    });
    if cancel {
        d.fields.insert(SAVING.into(), json!(false));
        d.fields.remove(SAVING_SHOWN);
    } else if save && let Err(e) = save_preset(app, d) {
        app.status(e);
        let pending = pending_focus(ui);
        ui.data_mut(|m| m.insert_temp(pending, true));
    }
}

/// Save Preset's default name: the first "Preset N" no saved preset has (`file.newPresets.save`
/// replaces a preset of the same name).
fn new_preset_name(app: &VectorcraftApp) -> String {
    let saved = &app.session.prefs.new_doc_presets;
    let template = "Preset {number}";
    (1..=saved.len() + 1)
        .map(|n| crate::i18n::fmt(tl!(template), &[("number", &n.to_string())]))
        .find(|name| !saved.iter().any(|p| p.name.trim().eq_ignore_ascii_case(name.trim())))
        .unwrap_or_default()
}

/// Save the fields as the preset named `presetName` and leave saving, on the saved preset.
fn save_preset(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<Value, String> {
    let mut p: Map<String, Value> = PARAMS.iter().filter_map(|k| Some((k.to_string(), d.fields.get(*k)?.clone()))).collect();
    p.insert("name".into(), json!(d.str("presetName")));
    p.remove("preset");
    let r = app.run("file.newPresets.save", Value::Object(p))?;
    d.fields.insert(SAVING.into(), json!(false));
    d.fields.remove(SAVING_SHOWN);
    // The next Save Preset offers a new default name instead of this preset's.
    d.fields.remove("presetName");
    d.fields.insert("category".into(), json!("Saved"));
    d.fields.insert("preset".into(), r["name"].clone());
    d.fields.remove(APPLIED);
    Ok(r)
}

/// The More Settings button and its pop-up, which holds what Preset Details doesn't: the artboard
/// layout, spacing and columns. Done, a click outside it and Escape close it; the fields it edited
/// stay as they are.
fn more_settings(ui: &mut egui::Ui, d: &mut Dialog) {
    let button = widgets::flat_button(ui, tl!("More Settings"), DETAILS);
    let mut open = (d.kind == MORE) != button.clicked();
    let mut done = false;
    let opening = button.ctx.read_response(egui::Popup::default_response_id(&button)).is_none();
    egui::Popup::from_response(&button)
        .open_bool(&mut open)
        .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside)
        .align(egui::RectAlign::TOP_END)
        .accessible_name(tl!("More Settings"))
        .show(|ui| done = more_settings_popup(ui, opening, d));
    if open && !done {
        d.kind = MORE.into();
    } else if d.kind == MORE {
        d.kind = KIND.into();
    }
}

/// The Manage Profiles button and its pop-up: a row per New Document profile with Edit, which opens
/// the profile as a document and closes New Document (true then), and Reset, which deletes an edited
/// profile's file so the shipped profile applies again. A click outside it and Escape close it.
fn manage_profiles(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
    let button = widgets::flat_button(ui, tl!("Manage Profiles"), DETAILS);
    let mut open = (d.kind == PROFILES) != button.clicked();
    let mut chosen: Option<(&str, &str)> = None;
    let has_folder = app.session.new_doc_profile_dir().is_some();
    egui::Popup::from_response(&button)
        .open_bool(&mut open)
        .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside)
        .align(egui::RectAlign::TOP_END)
        .accessible_name(tl!("Manage Profiles"))
        .show(|ui| {
            ui.set_width(MORE_WIDTH);
            let t = Tokens::get(ui.ctx());
            ui.label(egui::RichText::new(tl!("NEW DOCUMENT PROFILES")).font(theme::semibold(11.0)).color(t.text_dim));
            ui.add_space(6.0);
            for name in newdoc::profile_names() {
                let customized = app.session.new_doc_profile_customized(name);
                ui.horizontal(|ui| {
                    ui.label(tl!(name));
                    ui.allocate_ui_with_layout(egui::vec2(ui.available_width(), 24.0), egui::Layout::right_to_left(egui::Align::Center), |ui| {
                        if ui.add_enabled_ui(customized, |ui| widgets::secondary_button(ui, tl!("Reset"))).inner.clicked() {
                            chosen = Some(("file.newProfiles.reset", name));
                        }
                        // Without a profiles folder (the web, runs without preferences) there is nothing to edit.
                        if ui.add_enabled_ui(has_folder, |ui| widgets::secondary_button(ui, tl!("Edit"))).inner.clicked() {
                            chosen = Some(("file.newProfiles.edit", name));
                        }
                    });
                });
            }
        });
    if open {
        d.kind = PROFILES.into();
    } else if d.kind == PROFILES {
        d.kind = KIND.into();
    }
    let Some((cmd, name)) = chosen else { return false };
    match app.run(cmd, json!({ "name": name })) {
        Ok(_) => cmd == "file.newProfiles.edit",
        Err(e) => {
            app.status(e);
            false
        }
    }
}

/// More Settings' pop-up. True when Done (or Enter) finished with it.
fn more_settings_popup(ui: &mut egui::Ui, opening: bool, d: &mut Dialog) -> bool {
    const L: f32 = 150.0;
    let t = Tokens::get(ui.ctx());
    let (lay, cols, spacing, rtl) = layout(d);
    let n = d.f64("artboards", 1.0);
    let several = n > 1.0;
    let room = ui.ctx().content_rect().size() - egui::Vec2::splat(4.0 * super::EDGE_GAP) - egui::vec2(0.0, 44.0);
    focus_first(ui, opening, |ui| {
        egui::ScrollArea::both().id_salt("newdoc-popup-rows").max_width(room.x.max(0.0)).max_height(room.y.max(0.0)).show(ui, |ui| {
            ui.set_width(MORE_WIDTH);
            ui.label(egui::RichText::new(tl!("More Settings")).font(theme::semibold(13.0)).color(t.text));
            ui.add_space(6.0);
            widgets::label_row(ui, tl!("Number of Artboards:"), L, |ui| artboards(ui, d, "newdoc-popup-artboards", 76.0));
            widgets::label_row(ui, "", L, |ui| {
                for (l, icon) in [
                    (ArtboardLayout::GridByRow, "dc-grid-view"),
                    (ArtboardLayout::GridByColumn, "grid-3x3"),
                    (ArtboardLayout::Row, "arrow-left-right"),
                    (ArtboardLayout::Column, "arrow-up-down"),
                ] {
                    if widgets::icon_button_enabled(ui, icon, l.label(), lay == l, several, 26.0).clicked() {
                        set_layout(d, "layout", json!(l.id()));
                    }
                }
                ui.add_space(6.0);
                if widgets::icon_button_enabled(ui, "chevrons-left", tl!("Change to Right-to-Left Layout"), rtl, several, 26.0).clicked() {
                    set_layout(d, "rightToLeft", json!(!rtl));
                }
            });
            ui.add_enabled_ui(several, |ui| {
                widgets::label_row(ui, tl!("Spacing:"), L, |ui| {
                    if let Some(v) = widgets::num_field(ui, "newdoc-spacing", Some(spacing), unit(d), 100.0) {
                        set_layout(d, "spacing", json!(v.max(0.0)));
                    }
                });
                let grid = matches!(lay, ArtboardLayout::GridByRow | ArtboardLayout::GridByColumn);
                ui.add_enabled_ui(grid, |ui| {
                    widgets::label_row(ui, tl!("Columns:"), L, |ui| {
                        if let Some(v) = widgets::spin_plain(ui, "newdoc-columns", cols as f64, "", 0, 76.0, 1.0, 1.0, &[]) {
                            set_layout(d, "columns", json!(v.round().clamp(1.0, n) as u64));
                        }
                    });
                });
            });
        });
    });
    ui.add_space(8.0);
    // A bad value in a field keeps the pop-up open, as it keeps a dialog open.
    let rejected = ui.data_mut(|m| m.remove_temp::<bool>(widgets::dialog_reject_commit_flag())).unwrap_or(false);
    let enter = !rejected && ui.input(|i| i.key_pressed(egui::Key::Enter)) && ui.memory(|m| m.focused().is_none());
    let row = egui::vec2(ui.min_rect().width(), ui.spacing().interact_size.y);
    let mut done = false;
    ui.allocate_ui_with_layout(row, egui::Layout::right_to_left(egui::Align::Center), |ui| {
        done = widgets::primary_button(ui, tl!("Done")).clicked() || enter;
    });
    done
}

fn units_dropdown(ui: &mut egui::Ui, d: &mut Dialog, width: f32) {
    let labels = UNITS.map(Unit::label);
    if let Some(u) = widgets::dropdown(ui, "newdoc-units", unit(d).label(), &labels, width).and_then(|i| UNITS.get(i)) {
        d.fields.insert("units".into(), json!(u.label()));
        d.fields.insert(UNITS_CHOSEN.into(), json!(true));
    }
}

/// Portrait and landscape: choosing the other one swaps width and height (a turned preset is still
/// that preset).
fn orientation(ui: &mut egui::Ui, d: &mut Dialog) {
    let (w, h) = (d.f64("width", 612.0), d.f64("height", 792.0));
    let landscape = w > h;
    ui.horizontal(|ui| {
        ui.spacing_mut().item_spacing.x = 2.0;
        for (is_landscape, tip) in [(false, tl!("Portrait")), (true, tl!("Landscape"))] {
            if widgets::orientation_button(ui, is_landscape, landscape == is_landscape, tip) && landscape != is_landscape {
                d.fields.insert("width".into(), json!(h));
                d.fields.insert("height".into(), json!(w));
                if let Some(Value::Object(a)) = d.fields.get_mut(APPLIED)
                    && a.get("width") == Some(&json!(w))
                    && a.get("height") == Some(&json!(h))
                {
                    a.insert("width".into(), json!(h));
                    a.insert("height".into(), json!(w));
                }
            }
        }
    });
}

fn artboards(ui: &mut egui::Ui, d: &mut Dialog, id: &str, width: f32) {
    let n = d.f64("artboards", 1.0);
    ui.horizontal(|ui| {
        if let Some(v) = widgets::spin_plain(ui, id, n, "", 0, width, 1.0, 1.0, &[]) {
            d.fields.insert("artboards".into(), json!(v.round().clamp(1.0, MAX_ARTBOARDS as f64) as u64));
        }
    });
}

/// Background Contents with its chip: white, or white slashed in red for transparent.
fn background(ui: &mut egui::Ui, d: &mut Dialog, width: f32) {
    let t = Tokens::get(ui.ctx());
    let cur = d.str("backgroundContents");
    let shown = BACKGROUNDS.iter().find(|(v, _)| *v == cur).map_or(BACKGROUNDS[0].1, |(_, l)| l);
    ui.horizontal(|ui| {
        if let Some((v, _)) = widgets::dropdown(ui, "newdoc-background", shown, &BACKGROUNDS.map(|b| b.1), width).and_then(|i| BACKGROUNDS.get(i)) {
            d.fields.insert("backgroundContents".into(), json!(v));
        }
        let (chip, _) = ui.allocate_exact_size(egui::vec2(22.0, 22.0), egui::Sense::hover());
        ui.painter().rect_filled(chip, 2.0, egui::Color32::WHITE);
        if cur != "white" {
            ui.painter().line_segment([chip.left_bottom(), chip.right_top()], egui::Stroke::new(1.5, t.bleed));
        }
        ui.painter().rect_stroke(chip, 2.0, egui::Stroke::new(1.0, t.input_border), egui::StrokeKind::Inside);
    });
}

/// A dropdown bound to `d.fields[key]` over (value, label) pairs.
fn choice(ui: &mut egui::Ui, d: &mut Dialog, key: &str, options: &[(Value, String)], width: f32) {
    let cur = d.fields.get(key).cloned().unwrap_or_default();
    let shown = options
        .iter()
        .find(|(v, _)| *v == cur || v.as_f64().is_some_and(|x| cur.as_f64() == Some(x)))
        .map_or_else(|| cur.to_string(), |(_, l)| l.clone());
    let labels: Vec<&str> = options.iter().map(|(_, l)| l.as_str()).collect();
    if let Some((v, _)) = widgets::dropdown(ui, ("newdoc", key), &shown, &labels, width).and_then(|i| options.get(i)) {
        d.fields.insert(key.into(), v.clone());
    }
}

/// The collapsible Advanced Options: Color Mode, Raster Effects, Preview Mode and Align New Objects
/// to Pixel Grid.
fn advanced(ui: &mut egui::Ui, d: &mut Dialog, label: f32, field: f32) {
    let open = d.bool("advanced");
    if widgets::section_toggle(ui, tl!("Advanced Options"), open) {
        d.fields.insert("advanced".into(), json!(!open));
    }
    if !open {
        return;
    }
    let colors: Vec<(Value, String)> = COLOR_MODES.iter().map(|(v, l)| (json!(v), l.to_string())).collect();
    let ppi: Vec<(Value, String)> = RASTER_PPI.iter().map(|(v, l)| (json!(v), l.to_string())).collect();
    let previews: Vec<(Value, String)> =
        PreviewMode::ALL.iter().map(|m| (json!(m.id()), form::humanize(m.id()).trim_end_matches(':').to_string())).collect();
    for (key, name, options) in [
        ("colorMode", tl!("Color Mode"), &colors),
        ("rasterEffectsPpi", tl!("Raster Effects"), &ppi),
        ("previewMode", tl!("Preview Mode"), &previews),
    ] {
        widgets::label_row(ui, name, label, |ui| choice(ui, d, key, options, field));
    }
    wrapping_check(ui, d, "alignNewObjectsToPixelGrid", tl!("Align New Objects to Pixel Grid"));
}

/// A checkbox for the boolean field `key` whose `label` (already translated) wraps within the
/// column; a click on the box or the label toggles the field.
fn wrapping_check(ui: &mut egui::Ui, d: &mut Dialog, key: &str, label: &str) {
    let t = Tokens::get(ui.ctx());
    let on = d.bool(key);
    let toggled = ui
        .horizontal_top(|ui| {
            let boxed = widgets::check_box(ui, label, on, true);
            let text = egui::RichText::new(label).font(egui::FontId::proportional(12.5)).color(t.text);
            let clicked = ui.add(egui::Label::new(text).wrap().sense(egui::Sense::click())).clicked();
            boxed || clicked
        })
        .inner;
    if toggled {
        d.fields.insert(key.into(), json!(!on));
    }
}

#[cfg(test)]
mod tests {
    use egui::accesskit::Role;
    use egui_kittest::kittest::{NodeT, Queryable};
    use serde_json::json;
    use vectorcraft_engine::Session;

    use crate::VectorcraftApp;

    /// Cards translate the built-in presets' names only: Recent and Saved show the user's names.
    #[test]
    fn only_built_in_preset_names_are_translated() {
        assert!(super::is_builtin_preset("Letter") && super::is_builtin_preset("Phone 390×844"));
        assert!(!super::is_builtin_preset("Black") && !super::is_builtin_preset("Untitled-1"));
        assert_eq!(super::preset_name("Black"), "Black");
    }

    fn frame(app: &mut VectorcraftApp) -> egui::FullOutput {
        let ctx = egui::Context::default();
        crate::theme::install_fonts(&ctx);
        crate::theme::apply(&ctx, Default::default());
        let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 1000.0))), ..Default::default() };
        let mut out = ctx.run_ui(raw, |ui| crate::dialogs::show(app, ui.ctx()));
        out.textures_delta.clear();
        out
    }

    fn set(app: &mut VectorcraftApp, k: &str, v: serde_json::Value) {
        app.ui.dialog.as_mut().unwrap().fields.insert(k.into(), v);
    }

    fn field(app: &VectorcraftApp, k: &str) -> serde_json::Value {
        app.ui.dialog.as_ref().unwrap().fields.get(k).cloned().unwrap_or_default()
    }

    /// Recent shows each entry as it was made: a portrait and a landscape A3 are two cards of
    /// their own orientations, and only the chosen one is selected (#2860).
    #[test]
    fn recent_cards_keep_the_orientation_they_were_made_in() {
        let mut app = VectorcraftApp::new(Session::new(), Default::default());
        let a3 = vectorcraft_engine::cmd::newdoc::find(&app.session, "A3").unwrap();
        let landscape = vectorcraft_engine::cmd::newdoc::DocSettings { width: a3.height, height: a3.width, ..a3.clone() };
        app.session.prefs.recent_new_docs = vec![landscape, a3];
        app.run("file.newDialog", json!({})).unwrap();
        assert_eq!(field(&app, "category"), json!("Recent"));
        // Frames half a second apart on one context: the first lays the dialog out, and its fade
        // in is over by the last.
        let ctx = egui::Context::default();
        crate::theme::install_fonts(&ctx);
        let mut time = 0.0;
        let mut run = |app: &mut VectorcraftApp| {
            time += 0.5;
            let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 1000.0)));
            let raw = egui::RawInput { screen_rect, time: Some(time), ..Default::default() };
            let mut out = ctx.run_ui(raw, |ui| crate::dialogs::show(app, ui.ctx()));
            out.textures_delta.clear();
            out
        };
        run(&mut app);
        run(&mut app);
        let out = run(&mut app);
        fn walk(s: &egui::Shape, out: &mut Vec<egui::Shape>) {
            match s {
                egui::Shape::Vec(v) => v.iter().for_each(|s| walk(s, out)),
                s => out.push(s.clone()),
            }
        }
        let mut shapes = vec![];
        out.shapes.iter().for_each(|c| walk(&c.shape, &mut shapes));
        // The page thumbnails (white, 60 on their long side) and the selected card's outline.
        let thumbs: Vec<egui::Vec2> = shapes
            .iter()
            .filter_map(|s| match s {
                egui::Shape::Rect(r) if r.fill == egui::Color32::WHITE && (r.rect.width().max(r.rect.height()) - 60.0).abs() < 0.01 => {
                    Some(r.rect.size())
                }
                _ => None,
            })
            .collect();
        assert_eq!((thumbs.iter().filter(|s| s.x > s.y).count(), thumbs.iter().filter(|s| s.y > s.x).count()), (1, 1), "{thumbs:?}");
        let selected =
            shapes.iter().filter(|s| matches!(s, egui::Shape::Rect(r) if r.stroke.width == 2.0 && r.rect.size() == egui::vec2(146.0, 150.0))).count();
        assert_eq!(selected, 1, "one card chosen");
    }

    /// A double-click on a preset card creates the document from it (#663); a click only chooses it.
    #[test]
    fn a_double_clicked_preset_creates_the_document() {
        let mut app = VectorcraftApp::new(Session::new(), Default::default());
        app.run("file.newDialog", json!({})).unwrap();
        set(&mut app, "category", json!("Mobile"));
        let ctx = egui::Context::default();
        crate::theme::install_fonts(&ctx);
        // Frames 50 ms apart, so two clicks a frame apart make a double-click.
        let mut time = 0.0;
        let mut run = |app: &mut VectorcraftApp, events| {
            time += 0.05;
            let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 1000.0)));
            let raw = egui::RawInput { screen_rect, events, time: Some(time), ..Default::default() };
            let mut out = ctx.run_ui(raw, |ui| crate::dialogs::show(app, ui.ctx()));
            out.textures_delta.clear();
            out
        };
        run(&mut app, vec![]);
        // The first card of the category, found by its size line.
        let card = |app: &mut VectorcraftApp, run: &mut dyn FnMut(&mut VectorcraftApp, Vec<egui::Event>) -> egui::FullOutput| {
            let out = run(app, vec![]);
            let mut texts = vec![];
            fn walk(s: &egui::Shape, out: &mut Vec<(String, egui::Rect)>) {
                match s {
                    egui::Shape::Text(t) => out.push((t.galley.text().to_string(), t.visual_bounding_rect())),
                    egui::Shape::Vec(v) => v.iter().for_each(|s| walk(s, out)),
                    _ => {}
                }
            }
            out.shapes.iter().for_each(|c| walk(&c.shape, &mut texts));
            texts.into_iter().find(|(t, _)| t.starts_with("Phone 393")).map(|(_, r)| r.center()).unwrap()
        };
        let at = card(&mut app, &mut run);
        let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
        run(&mut app, vec![egui::Event::PointerMoved(at), press(true)]);
        run(&mut app, vec![press(false)]);
        assert!(app.ui.dialog.is_some() && app.session.documents().is_empty(), "a click only chooses it");
        assert!(field(&app, "preset").as_str().is_some_and(|p| p == "Phone 393×852"), "{:?}", field(&app, "preset"));
        run(&mut app, vec![press(true)]);
        run(&mut app, vec![press(false)]);
        assert!(app.ui.dialog.is_none(), "the double-click created it: {:?}", app.ui.status);
        assert_eq!(app.session.documents().len(), 1);

        // While a preset is being saved, a click fills the fields and a double-click creates nothing.
        app.run("file.newDialog", json!({})).unwrap();
        set(&mut app, "category", json!("Mobile"));
        set(&mut app, "preset", json!("Letter"));
        set(&mut app, super::SAVING, json!(true));
        // Far enough from the clicks above that the next two count as a click and a double-click.
        for _ in 0..12 {
            run(&mut app, vec![]);
        }
        let at = card(&mut app, &mut run);
        let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
        run(&mut app, vec![egui::Event::PointerMoved(at), press(true)]);
        run(&mut app, vec![press(false)]);
        assert!(field(&app, "preset").as_str().is_some_and(|p| p == "Phone 393×852"), "a click fills the fields: {:?}", field(&app, "preset"));
        run(&mut app, vec![press(true)]);
        run(&mut app, vec![press(false)]);
        run(&mut app, vec![]);
        assert_eq!(app.session.documents().len(), 1, "nothing was created while saving");
        assert_eq!(field(&app, super::SAVING), json!(true));
    }

    /// A category tab opens on its first preset, so Orientation matches its (landscape) cards, and
    /// the orientation buttons turn the cards, keeping the chosen one selected (#2084).
    #[test]
    fn the_web_tab_is_landscape_and_orientation_turns_the_cards() {
        let mut app = VectorcraftApp::new(Session::new(), Default::default());
        app.run("file.newDialog", json!({})).unwrap();
        let ctx = egui::Context::default();
        crate::theme::install_fonts(&ctx);
        let mut time = 0.0;
        let mut run = |app: &mut VectorcraftApp, events| {
            time += 0.5;
            let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 1000.0)));
            let raw = egui::RawInput { screen_rect, events, time: Some(time), ..Default::default() };
            let mut out = ctx.run_ui(raw, |ui| crate::dialogs::show(app, ui.ctx()));
            out.textures_delta.clear();
            out
        };
        fn walk(s: &egui::Shape, out: &mut Vec<egui::Shape>) {
            match s {
                egui::Shape::Vec(v) => v.iter().for_each(|s| walk(s, out)),
                s => out.push(s.clone()),
            }
        }
        let shapes = |out: &egui::FullOutput| {
            let mut v = vec![];
            out.shapes.iter().for_each(|c| walk(&c.shape, &mut v));
            v
        };
        let click = |app: &mut VectorcraftApp, run: &mut dyn FnMut(&mut VectorcraftApp, Vec<egui::Event>) -> egui::FullOutput, at: egui::Pos2| {
            let press =
                |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
            run(app, vec![egui::Event::PointerMoved(at), press(true)]);
            run(app, vec![press(false)]);
            run(app, vec![egui::Event::PointerGone]);
            run(app, vec![])
        };
        run(&mut app, vec![]);
        let out = run(&mut app, vec![]);
        let web = shapes(&out)
            .into_iter()
            .find_map(|s| match s {
                egui::Shape::Text(t) if t.galley.text() == "Web" => Some(t.visual_bounding_rect().center()),
                _ => None,
            })
            .unwrap();
        let out = click(&mut app, &mut run, web);
        assert_eq!(field(&app, "category"), json!("Web"));
        let (w, h) = (field(&app, "width").as_f64().unwrap(), field(&app, "height").as_f64().unwrap());
        assert!(w > h, "the Web tab reads landscape like its cards: {w}×{h} ({:?})", field(&app, "preset"));
        // The page thumbnails (white, 60 on their long side) and the selected card's outline.
        let thumbs = |out: &egui::FullOutput| -> Vec<egui::Vec2> {
            shapes(out)
                .into_iter()
                .filter_map(|s| match s {
                    egui::Shape::Rect(r) if r.fill == egui::Color32::WHITE && (r.rect.width().max(r.rect.height()) - 60.0).abs() < 0.01 => {
                        Some(r.rect.size())
                    }
                    _ => None,
                })
                .collect()
        };
        let selected = |out: &egui::FullOutput| {
            shapes(out).iter().any(|s| matches!(s, egui::Shape::Rect(r) if r.stroke.width == 2.0 && r.rect.size() == egui::vec2(146.0, 150.0)))
        };
        assert!(thumbs(&out).iter().all(|s| s.x >= s.y) && selected(&out));
        // Portrait: the outlined sheet 12 wide, 16 tall.
        let portrait = shapes(&out)
            .into_iter()
            .find_map(|s| match s {
                egui::Shape::Path(p) if p.closed && p.points.len() == 5 => {
                    let r = egui::Rect::from_points(&p.points);
                    ((r.width() - 12.0).abs() < 0.01 && (r.height() - 16.0).abs() < 0.01).then(|| r.center())
                }
                _ => None,
            })
            .unwrap();
        let out = click(&mut app, &mut run, portrait);
        let (w, h) = (field(&app, "width").as_f64().unwrap(), field(&app, "height").as_f64().unwrap());
        assert!(h > w, "portrait: {w}×{h}");
        let t = thumbs(&out);
        assert!(!t.is_empty() && t.iter().all(|s| s.y >= s.x), "the cards turned: {t:?}");
        assert!(selected(&out), "the turned preset stays chosen: {:?}", field(&app, "preset"));
    }

    /// The document's name field has a caption of its own under the Preset Details heading, the
    /// column stays inside the dialog's height with Advanced Options open in both states, and saving
    /// a preset replaces only the top of the column: the rows under it do not move.
    #[test]
    fn the_name_field_is_captioned_and_the_column_fits() {
        let mut app = VectorcraftApp::new(Session::new(), Default::default());
        app.run("file.newDialog", json!({})).unwrap();
        set(&mut app, "advanced", json!(true));
        let ctx = egui::Context::default();
        crate::theme::install_fonts(&ctx);
        let mut time = 0.0;
        let mut run = |app: &mut VectorcraftApp| {
            time += 0.5;
            let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 1000.0)));
            let raw = egui::RawInput { screen_rect, time: Some(time), ..Default::default() };
            let mut out = ctx.run_ui(raw, |ui| crate::dialogs::show(app, ui.ctx()));
            out.textures_delta.clear();
            out
        };
        fn walk(s: &egui::Shape, out: &mut Vec<(String, egui::Rect)>) {
            match s {
                egui::Shape::Text(t) => out.push((t.galley.text().to_string(), t.visual_bounding_rect())),
                egui::Shape::Vec(v) => v.iter().for_each(|s| walk(s, out)),
                _ => {}
            }
        }
        let mut texts_of = |app: &mut VectorcraftApp| {
            run(app);
            let out = run(app);
            let mut texts = vec![];
            out.shapes.iter().for_each(|c| walk(&c.shape, &mut texts));
            texts
        };
        let texts = texts_of(&mut app);
        let at = |texts: &[(String, egui::Rect)], name: &str| {
            texts.iter().find(|(t, _)| t == name).map(|(_, r)| *r).unwrap_or_else(|| panic!("{name} is missing: {texts:?}"))
        };
        let (heading, caption, value) = (at(&texts, "PRESET DETAILS"), at(&texts, "Document Name"), at(&texts, "Untitled-1"));
        assert!(heading.bottom() <= caption.top() && caption.bottom() <= value.top(), "{heading:?} {caption:?} {value:?}");
        let used = at(&texts, "Create").bottom() - heading.top();
        assert!(used <= super::HEIGHT, "the column used {used}");
        let width = at(&texts, "Width").top();

        set(&mut app, super::SAVING, json!(true));
        let saving = texts_of(&mut app);
        for gone in ["PRESET DETAILS", "Document Name", "Close", "Create"] {
            assert!(saving.iter().all(|(t, _)| t != gone), "{gone} shows while saving");
        }
        let (heading, cancel) = (at(&saving, "Save Document Preset"), at(&saving, "Cancel"));
        assert!(heading.bottom() <= cancel.top());
        assert!(cancel.bottom() <= at(&saving, "Width").top(), "Cancel and Save are above the rows");
        assert_eq!(at(&saving, "Width").top(), width, "the rows stay where they were");
        let used = at(&saving, "More Settings").bottom() - heading.top();
        assert!(used <= super::HEIGHT, "the column used {used}");
    }

    #[test]
    fn a_preset_fills_the_details_and_create_makes_the_document() {
        let mut app = VectorcraftApp::new(Session::new(), Default::default());
        app.run("file.newDialog", json!({})).unwrap();
        frame(&mut app);
        assert_eq!((field(&app, "category"), field(&app, "preset"), field(&app, "name")), (json!("Print"), json!("Letter"), json!("Untitled-1")));
        // Choosing a preset (as `ui.dialog.set` does) fills the fields.
        set(&mut app, "category", json!("Film & Video"));
        set(&mut app, "preset", json!("4K UHD"));
        frame(&mut app);
        assert_eq!((field(&app, "width"), field(&app, "units"), field(&app, "colorMode")), (json!(3840.0), json!("Pixels"), json!("rgb")));
        set(&mut app, "artboards", json!(4));
        set(&mut app, "artboardLayout", json!({"layout": "gridByRow", "columns": 2, "spacing": 10}));
        set(&mut app, "bleed", json!([0, 0, 0, 0]));
        set(&mut app, "previewMode", json!("pixel"));
        set(&mut app, "backgroundContents", json!("white"));
        frame(&mut app);
        assert_eq!(field(&app, "preset"), json!(""), "editing makes the settings custom");
        crate::dialogs::confirm(&mut app).unwrap();
        assert!(app.ui.dialog.is_none());
        let st = app.session.active().unwrap();
        let rects: Vec<_> = st.doc.artboards.iter().map(|a| (a.rect.x0, a.rect.y0)).collect();
        assert_eq!(rects, [(0.0, 0.0), (3850.0, 0.0), (0.0, 2170.0), (3850.0, 2170.0)]);
        assert_eq!(st.doc.setup.background, vectorcraft_doc::Background::White);
        assert!(app.ui.view.pixel_preview, "Pixel preview mode");
        // Next time Recent opens on it.
        app.run("file.newDialog", json!({})).unwrap();
        assert_eq!((field(&app, "category"), field(&app, "name")), (json!("Recent"), json!("Untitled-2")));
        frame(&mut app);
    }

    #[test]
    fn every_category_and_more_settings_draw_and_save_preset_saves() {
        let mut app = VectorcraftApp::new(Session::new(), Default::default());
        app.run("file.newDialog", json!({})).unwrap();
        set(&mut app, "advanced", json!(true));
        for c in vectorcraft_engine::cmd::newdoc::category_names() {
            set(&mut app, "category", json!(c));
            let out = frame(&mut app);
            assert!(!out.shapes.is_empty());
        }
        // More Settings edits the same fields.
        app.ui.dialog.as_mut().unwrap().kind = super::MORE.into();
        set(&mut app, "artboards", json!(3));
        frame(&mut app);
        assert_eq!(field(&app, "artboards"), json!(3));
        // Save Preset.
        set(&mut app, "category", json!("Print"));
        set(&mut app, "preset", json!("A5"));
        frame(&mut app);
        let p = app.run("file.newPresets.save", json!({"name": "Zine", "preset": "A5"}));
        assert!(p.is_ok());
        app.ui.dialog.as_mut().unwrap().kind = super::KIND.into();
        set(&mut app, "category", json!("Saved"));
        set(&mut app, "preset", json!("Zine"));
        frame(&mut app);
        assert!((field(&app, "width").as_f64().unwrap() - 148.0 * 72.0 / 25.4).abs() < 1e-6, "A5 wide");
        crate::dialogs::confirm(&mut app).unwrap();
        assert_eq!(app.session.prefs.recent_new_docs[0].name, "Zine");
    }

    type Harness = egui_kittest::Harness<'static, VectorcraftApp>;

    /// New Document open in a harness of `size`, with the app's key handling and the dialogs drawn.
    fn harness(size: egui::Vec2) -> Harness {
        let mut app = VectorcraftApp::new(Session::new(), Default::default());
        app.run("file.newDialog", json!({})).unwrap();
        let mut fonts = false;
        let mut h = egui_kittest::Harness::builder().with_size(size).build_ui_state(
            move |ui, app: &mut VectorcraftApp| {
                if !std::mem::replace(&mut fonts, true) {
                    crate::theme::install_fonts(ui.ctx());
                    return;
                }
                crate::shortcuts::handle(app, ui.ctx());
                crate::dialogs::show(app, ui.ctx());
            },
            app,
        );
        h.run_steps(5);
        h
    }

    fn big() -> Harness {
        harness(egui::vec2(1400.0, 1000.0))
    }

    /// Open a pop-up as a control client would, with `artboards` set, and let it draw.
    fn open_more(h: &mut Harness, artboards: u64) {
        set(h.state_mut(), "artboards", json!(artboards));
        h.state_mut().ui.dialog.as_mut().unwrap().kind = super::MORE.into();
        h.run_steps(4);
    }

    fn kind(h: &Harness) -> String {
        h.state().ui.dialog.as_ref().unwrap().kind.clone()
    }

    /// A primary click at `at`, as a pointer makes it.
    fn click_at(h: &mut Harness, at: egui::Pos2) {
        h.event(egui::Event::PointerMoved(at));
        h.run_steps(1);
        h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() });
        h.run_steps(1);
        h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() });
        h.run_steps(3);
    }

    /// Press Save Preset, leaving the preset's name focused.
    fn start_saving(h: &mut Harness) {
        h.get_by_label("Save Preset").click();
        h.run_steps(4);
    }

    /// Replace the text of field `label` with `text` and press Enter.
    fn enter_in(h: &mut Harness, label: &str, text: &str) {
        let all = egui::Modifiers { ctrl: true, command: true, ..Default::default() };
        h.get_by_role_and_label(Role::TextInput, label).focus();
        h.run_steps(2);
        h.key_press_modifiers(all, egui::Key::A);
        h.get_by_role_and_label(Role::TextInput, label).type_text(text);
        h.run_steps(2);
        h.key_press(egui::Key::Enter);
        h.run_steps(3);
    }

    /// More Settings opens over New Document with only what Preset Details lacks, its first field
    /// takes the keyboard focus, and Done leaves New Document open with what the pop-up set.
    #[test]
    fn more_settings_is_a_popup_holding_only_the_artboard_layout() {
        let mut h = big();
        h.get_by_label("More Settings").click();
        h.run_steps(4);
        assert_eq!(kind(&h), super::MORE);
        assert!(h.get_by_role_and_label(Role::TextInput, "Number of Artboards:").is_focused(), "the pop-up's first field has the focus");
        for shown in ["Number of Artboards:", "Spacing:", "Columns:", "Create", "Close"] {
            let _ = h.get_by_label(shown);
        }
        for gone in [
            "Name:",
            "Profile:",
            "Size:",
            "Width:",
            "Height:",
            "Units:",
            "Orientation:",
            "Bleed:",
            "Background Contents:",
            "Create Document",
            "Templates…",
        ] {
            assert!(h.query_by_label(gone).is_none(), "{gone} is in the pop-up");
        }
        h.get_by_label("Done").click();
        h.run_steps(3);
        assert_eq!(kind(&h), super::KIND, "Done goes back to New Document");
        assert!(h.query_by_label("Spacing:").is_none());
        assert!(h.state().session.documents().is_empty());
    }

    /// Escape, a click outside and `ui.dialog.cancel` each close only the pop-up, and the fields it
    /// edited stay set. Escape on New Document itself then closes the dialog.
    #[test]
    fn a_popup_closes_on_its_own_and_keeps_the_values() {
        let mut h = big();
        open_more(&mut h, 4);
        h.get_by_label(super::ArtboardLayout::Column.label()).click();
        h.run_steps(3);
        assert_eq!(kind(&h), super::MORE, "a click inside keeps it open");
        h.key_press(egui::Key::Escape);
        h.run_steps(3);
        assert_eq!(kind(&h), super::KIND, "Escape closes only the pop-up");
        assert_eq!(field(h.state(), "artboardLayout")["layout"], json!("column"));
        h.key_press(egui::Key::Escape);
        h.run_steps(3);
        assert!(h.state().ui.dialog.is_none(), "the next Escape closes New Document");

        let mut h = big();
        open_more(&mut h, 4);
        let outside = h.get_by_label("PRESET DETAILS").rect().center();
        click_at(&mut h, outside);
        assert_eq!(kind(&h), super::KIND, "a click outside closes the pop-up");
        assert_eq!(field(h.state(), "artboards"), json!(4));

        open_more(&mut h, 4);
        crate::dialogs::cancel(h.state_mut());
        assert_eq!(kind(&h), super::KIND, "ui.dialog.cancel closes only the pop-up");
        set(h.state_mut(), super::SAVING, json!(true));
        crate::dialogs::cancel(h.state_mut());
        assert_eq!((kind(&h), field(h.state(), super::SAVING)), (super::KIND.to_string(), json!(false)), "and Save Preset's");
        crate::dialogs::cancel(h.state_mut());
        assert!(h.state().ui.dialog.is_none(), "with no pop-up it cancels New Document");
    }

    /// A click that lands on Create, Close, a preset card or a category tab while the pop-up is open
    /// only closes the pop-up: New Document stays open with the values the pop-up set.
    #[test]
    fn a_click_outside_the_popup_does_not_reach_the_dialog() {
        let mut reached = vec![];
        for target in ["Create", "Close", "card", "Web"] {
            let mut h = big();
            open_more(&mut h, 4);
            let (category, preset) = (field(h.state(), "category"), field(h.state(), "preset"));
            let at = if target == "card" {
                // The Print tab's second card: the first is the chosen one.
                let tab = h.get_by_label("Print").rect();
                egui::pos2(tab.left() + 146.0 + 12.0 + 73.0, tab.bottom() + 120.0)
            } else {
                h.get_by_label(target).rect().center()
            };
            click_at(&mut h, at);
            let kept = h.state().ui.dialog.is_some()
                && kind(&h) == super::KIND
                && h.state().session.documents().is_empty()
                && field(h.state(), "artboards") == json!(4)
                && (field(h.state(), "category"), field(h.state(), "preset")) == (category, preset);
            if !kept {
                reached.push(target);
            }
        }
        assert!(reached.is_empty(), "the click reached {reached:?}");
    }

    /// Enter applies the field and closes the pop-up. It does not create the document.
    #[test]
    fn enter_in_a_popup_does_not_create_the_document() {
        let mut h = big();
        open_more(&mut h, 3);
        enter_in(&mut h, "Spacing:", "25");
        assert_eq!(kind(&h), super::KIND, "Enter closes the pop-up");
        assert_eq!(field(h.state(), "artboardLayout")["spacing"], json!(25.0));
        assert!(h.state().session.documents().is_empty(), "no document was made");
    }

    /// One artboard disables the layout, Spacing and Columns; Columns stays within the artboards
    /// and Spacing is not negative.
    #[test]
    fn the_popup_keeps_the_layout_rules() {
        let mut h = big();
        open_more(&mut h, 1);
        for name in [super::ArtboardLayout::Row.label(), "Change to Right-to-Left Layout"] {
            assert!(h.get_by_label(name).accesskit_node().is_disabled(), "{name}");
        }
        for name in ["Spacing:", "Columns:"] {
            assert!(h.get_by_role_and_label(Role::TextInput, name).accesskit_node().is_disabled(), "{name}");
        }
        open_more(&mut h, 3);
        assert!(!h.get_by_role_and_label(Role::TextInput, "Spacing:").accesskit_node().is_disabled());
        enter_in(&mut h, "Columns:", "99");
        assert_eq!(field(h.state(), "artboardLayout")["columns"], json!(3));
        open_more(&mut h, 3);
        enter_in(&mut h, "Spacing:", "-5");
        assert_eq!(field(h.state(), "artboardLayout")["spacing"], json!(0.0));
    }

    /// Saving swaps the top of Preset Details for the heading, the preset's name, Cancel and Save, and
    /// hides Close and Create; the rows under it stay editable, and Enter in one of them neither saves
    /// nor creates.
    #[test]
    fn save_preset_is_a_mode_of_the_panel() {
        let mut h = big();
        start_saving(&mut h);
        let _ = (h.get_by_label("Save Document Preset"), h.get_by_label("Cancel"), h.get_by_label("Save"));
        for gone in ["PRESET DETAILS", "Create", "Close"] {
            assert!(h.query_by_label(gone).is_none(), "{gone} shows while saving");
        }
        assert!(h.query_by_role_and_label(Role::TextInput, "Document Name").is_none(), "the document's name is hidden");
        let _ = (h.get_by_label("Advanced Options"), h.get_by_label("More Settings"));
        enter_in(&mut h, "Artboards", "2");
        assert_eq!(field(h.state(), "artboards"), json!(2), "the rows stay editable");
        assert_eq!(field(h.state(), super::SAVING), json!(true), "Enter in a row does not save");
        assert!(h.state().session.documents().is_empty() && h.state().session.prefs.new_doc_presets.is_empty());
        h.get_by_label("More Settings").click();
        h.run_steps(4);
        assert_eq!(kind(&h), super::MORE, "More Settings opens while saving");
    }

    /// Save Preset focuses the default name with its text selected, Enter in it is Save, and the
    /// saved preset keeps the fields.
    #[test]
    fn enter_in_the_preset_name_saves() {
        let mut h = big();
        set(h.state_mut(), "artboards", json!(3));
        h.run_steps(2);
        start_saving(&mut h);
        assert_eq!(field(h.state(), "presetName"), json!("Preset 1"));
        assert!(h.get_by_role_and_label(Role::TextInput, "Preset Name").is_focused());
        h.event(egui::Event::Text("Trio".into()));
        h.run_steps(2);
        assert_eq!(field(h.state(), "presetName"), json!("Trio"), "typing replaced the selected text");
        h.key_press(egui::Key::Enter);
        h.run_steps(3);
        let saved = h.state().session.prefs.new_doc_presets.iter().find(|p| p.name == "Trio").expect("Enter saved it");
        assert_eq!(saved.artboards, 3);
        assert_eq!((field(h.state(), super::SAVING), field(h.state(), "artboards")), (json!(false), json!(3)), "the fields stay");
        assert_eq!(field(h.state(), "name"), json!("Untitled-1"));
        assert!(h.state().session.documents().is_empty() && h.state().ui.dialog.is_some());
    }

    /// Save Preset's default name is the first "Preset N" no saved preset has, after a save as well.
    #[test]
    fn the_next_save_offers_a_new_name() {
        let mut h = big();
        start_saving(&mut h);
        assert_eq!(field(h.state(), "presetName"), json!("Preset 1"));
        h.get_by_label("Save").click();
        h.run_steps(3);
        start_saving(&mut h);
        assert_eq!(field(h.state(), "presetName"), json!("Preset 2"), "not the saved preset's name");
        set(h.state_mut(), "presetName", json!("preset 3"));
        h.run_steps(2);
        h.get_by_label("Save").click();
        h.run_steps(3);
        start_saving(&mut h);
        assert_eq!(field(h.state(), "presetName"), json!("Preset 2"), "not a name a saved preset has");
    }

    /// A New Document that opens already saving (as a control client can set it) fills in and focuses
    /// the default name, also after the last one was closed while saving.
    #[test]
    fn a_dialog_that_opens_saving_fills_in_the_name() {
        let mut h = big();
        start_saving(&mut h);
        h.state_mut().ui.dialog = None;
        h.run_steps(2);
        h.state_mut().run("file.newDialog", json!({})).unwrap();
        set(h.state_mut(), super::SAVING, json!(true));
        h.run_steps(4);
        assert_eq!(field(h.state(), "presetName"), json!("Preset 1"));
        assert!(h.get_by_role_and_label(Role::TextInput, "Preset Name").is_focused());
    }

    /// Enter that is still held after Enter saved a preset does not create the document.
    #[test]
    fn a_held_enter_after_a_save_does_not_create() {
        let mut h = big();
        start_saving(&mut h);
        let enter = |repeat| egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat, modifiers: Default::default() };
        // Pressed and not released: the next presses are the key's repeats.
        h.event(enter(false));
        h.run_steps(1);
        assert_eq!(field(h.state(), super::SAVING), json!(false), "Enter saved");
        for _ in 0..3 {
            h.event(enter(true));
            h.run_steps(1);
        }
        assert!(h.state().session.documents().is_empty() && h.state().ui.dialog.is_some());
    }

    /// Escape in the mode is Cancel: it saves nothing, keeps edits made to the fields, and New Document
    /// stays open. The Cancel button does the same.
    #[test]
    fn escape_and_cancel_leave_saving_and_keep_the_edits() {
        let mut h = big();
        start_saving(&mut h);
        set(h.state_mut(), "artboards", json!(5));
        h.run_steps(2);
        h.key_press(egui::Key::Escape);
        h.run_steps(3);
        assert_eq!((field(h.state(), super::SAVING), field(h.state(), "artboards")), (json!(false), json!(5)), "Escape keeps the edits");
        assert!(h.state().session.prefs.new_doc_presets.is_empty(), "and saves nothing");
        assert!(h.state().ui.dialog.is_some(), "and New Document stays open");

        start_saving(&mut h);
        h.get_by_label("Cancel").click();
        h.run_steps(3);
        assert_eq!(field(h.state(), super::SAVING), json!(false));
        let _ = h.get_by_label("Create");
    }

    /// `ui.dialog.confirm` while saving is Save: it stores the preset and creates no document.
    #[test]
    fn confirm_while_saving_does_not_create_a_document() {
        let mut app = VectorcraftApp::new(Session::new(), Default::default());
        app.run("file.newDialog", json!({})).unwrap();
        frame(&mut app);
        set(&mut app, super::SAVING, json!(true));
        set(&mut app, "presetName", json!("Zed"));
        crate::dialogs::confirm(&mut app).unwrap();
        assert!(app.session.documents().is_empty() && app.session.prefs.new_doc_presets.iter().any(|p| p.name == "Zed"));
        assert_eq!((field(&app, super::SAVING), field(&app, "category")), (json!(false), json!("Saved")));
        set(&mut app, super::SAVING, json!(true));
        set(&mut app, "presetName", json!(""));
        assert!(crate::dialogs::confirm(&mut app).is_err(), "an empty name is refused");
        assert_eq!(field(&app, super::SAVING), json!(true));
        assert!(app.session.documents().is_empty());
    }

    /// The preset keeps the artboard layout, spacing and columns set in More Settings' pop-up
    /// (#4893), and New Document stays open on it. An empty name stays in the mode.
    #[test]
    fn save_preset_saves_what_more_settings_set() {
        let mut h = big();
        open_more(&mut h, 4);
        enter_in(&mut h, "Spacing:", "30");
        open_more(&mut h, 4);
        h.get_by_label(super::ArtboardLayout::Column.label()).click();
        h.run_steps(3);
        h.get_by_label("Change to Right-to-Left Layout").click();
        h.run_steps(3);
        h.get_by_label("Done").click();
        h.run_steps(3);
        h.get_by_label("Save Preset").click();
        h.run_steps(4);
        assert!(field(h.state(), super::SAVING) == json!(true) && h.get_by_role_and_label(Role::TextInput, "Preset Name").is_focused());
        let _ = (h.get_by_label("Save"), h.get_by_label("Cancel"));
        set(h.state_mut(), "presetName", json!("   "));
        h.run_steps(2);
        h.get_by_label("Save").click();
        h.run_steps(3);
        assert_eq!(field(h.state(), super::SAVING), json!(true), "an empty name stays in the mode");
        set(h.state_mut(), "presetName", json!("Strip"));
        h.run_steps(2);
        h.get_by_label("Save").click();
        h.run_steps(3);
        let saved = h.state().session.prefs.new_doc_presets.iter().find(|p| p.name == "Strip").expect("saved");
        assert_eq!(saved.artboards, 4);
        assert!(saved.right_to_left);
        assert_eq!((saved.layout, saved.spacing), (super::ArtboardLayout::Column, 30.0));
        assert_eq!(
            (field(h.state(), "category"), field(h.state(), "preset"), field(h.state(), super::SAVING)),
            (json!("Saved"), json!("Strip"), json!(false))
        );
        assert_eq!(kind(&h), super::KIND, "New Document stays open");
        assert!(h.state().session.documents().is_empty());
    }

    /// Advanced Options › Align New Objects to Pixel Grid is checked for a Web preset and unchecked
    /// for Letter; the checkbox changes it and makes the settings custom, Save Preset keeps it, and
    /// Create makes the document with it.
    #[test]
    fn align_new_objects_checkbox_follows_the_preset_and_reaches_the_document() {
        const KEY: &str = "alignNewObjectsToPixelGrid";
        const LABEL: &str = "Align New Objects to Pixel Grid";
        let mut h = big();
        assert_eq!((field(h.state(), "preset"), field(h.state(), KEY)), (json!("Letter"), json!(false)));
        set(h.state_mut(), "category", json!("Web"));
        set(h.state_mut(), "preset", json!("Web 1920×1080"));
        set(h.state_mut(), "advanced", json!(true));
        h.run_steps(3);
        assert_eq!(field(h.state(), KEY), json!(true));
        h.get_by_role_and_label(egui::accesskit::Role::CheckBox, LABEL).click();
        h.run_steps(3);
        assert_eq!((field(h.state(), "preset"), field(h.state(), KEY)), (json!(""), json!(false)), "custom settings");
        set(h.state_mut(), "category", json!("Print"));
        set(h.state_mut(), "preset", json!("Letter"));
        h.run_steps(3);
        assert_eq!(field(h.state(), KEY), json!(false));
        h.get_by_role_and_label(egui::accesskit::Role::Label, LABEL).click();
        h.run_steps(3);
        assert_eq!(field(h.state(), KEY), json!(true), "a click on the label toggles it too");
        h.get_by_label("Save Preset").click();
        h.run_steps(4);
        set(h.state_mut(), "presetName", json!("Pixel Letter"));
        h.run_steps(2);
        h.get_by_label("Save").click();
        h.run_steps(3);
        let saved = h.state().session.prefs.new_doc_presets.iter().find(|p| p.name == "Pixel Letter").expect("saved");
        assert!(saved.align_new_objects_to_pixel_grid);
        assert_eq!((field(h.state(), "preset"), field(h.state(), KEY)), (json!("Pixel Letter"), json!(true)));
        h.get_by_label("Create").click();
        h.run_steps(3);
        assert!(h.state().ui.dialog.is_none());
        assert!(h.state().session.active().unwrap().doc.setup.align_new_objects_to_pixel_grid);
    }

    /// Create, then the new document's units.
    fn create(h: &mut Harness) -> vectorcraft_doc::Unit {
        h.get_by_label("Create").click();
        h.run_steps(3);
        assert!(h.state().ui.dialog.is_none(), "{:?}", h.state().ui.status);
        h.state().session.active().unwrap().doc.units
    }

    /// With Preferences › Units › General in millimeters, New Document opens on the most recent
    /// entry in millimeters even though that entry was made in points, and New Without Dialog makes
    /// the same document. An entry in pixels stays in pixels, as the screen presets do.
    #[test]
    fn the_dialog_opens_in_the_general_units_over_a_recent_entry() {
        use vectorcraft_doc::Unit::{Millimeters as Mm, Pixels as Px};
        let mut h = big();
        h.state_mut().run("file.new", json!({"units": "Points"})).unwrap();
        h.state_mut().run("prefs.set", json!({"key": "unitsGeneral", "value": "Millimeters", "documentUnits": false})).unwrap();
        assert_eq!(h.state().session.prefs.recent_new_docs[0].units, vectorcraft_doc::Unit::Points);
        h.state_mut().run("file.newDialog", json!({})).unwrap();
        h.run_steps(3);
        assert_eq!((field(h.state(), "category"), field(h.state(), "units")), (json!("Recent"), json!("Millimeters")));
        assert_eq!(create(&mut h), Mm, "the dialog's Create");
        h.state_mut().run("file.new", json!({"units": "Points"})).unwrap();
        h.state_mut().run("file.newWithoutDialog", json!({})).unwrap();
        assert_eq!(h.state().session.active().unwrap().doc.units, Mm, "New Without Dialog");
        h.state_mut().run("file.new", json!({"preset": "Web 1920×1080"})).unwrap();
        h.state_mut().run("file.newDialog", json!({})).unwrap();
        h.run_steps(3);
        assert_eq!(field(h.state(), "units"), json!("Pixels"));
        assert_eq!(create(&mut h), Px);
    }

    /// A Recent entry that is a saved preset in the units it was saved in opens in those units, so
    /// Create keeps the preset's name in Recent; the General unit is millimeters.
    #[test]
    fn a_recent_saved_preset_keeps_its_units_and_name() {
        let mut h = big();
        h.state_mut().run("file.newPresets.save", json!({"name": "Zine", "width": "5.5 in", "height": "8.5 in", "units": "Inches"})).unwrap();
        h.state_mut().run("file.new", json!({"preset": "Zine"})).unwrap();
        h.state_mut().run("prefs.set", json!({"key": "unitsGeneral", "value": "Millimeters", "documentUnits": false})).unwrap();
        h.state_mut().run("file.newDialog", json!({})).unwrap();
        h.run_steps(3);
        assert_eq!((field(h.state(), "preset"), field(h.state(), "units")), (json!("Zine"), json!("Inches")));
        assert_eq!(create(&mut h), vectorcraft_doc::Unit::Inches);
        let recent = &h.state().session.prefs.recent_new_docs;
        assert_eq!((recent.len(), recent[0].name.as_str()), (1, "Zine"), "{recent:?}");
    }

    /// Units set with `ui.dialog.set` while More Settings or Manage Profiles is open stay chosen
    /// when a preset is chosen after them.
    #[test]
    fn units_set_over_a_popup_stay_chosen() {
        for popup in [super::MORE, super::PROFILES] {
            let mut app = VectorcraftApp::new(Session::new(), Default::default());
            app.run("file.newDialog", json!({})).unwrap();
            let d = app.ui.dialog.as_mut().unwrap();
            d.kind = popup.into();
            crate::dialogs::set_field(d, "units".into(), json!("Millimeters"));
            crate::dialogs::set_field(d, "preset".into(), json!("A4"));
            d.kind = super::KIND.into();
            let ctx = egui::Context::default();
            crate::theme::install_fonts(&ctx);
            let mut out = ctx.run_ui(egui::RawInput::default(), |ui| crate::dialogs::show(&mut app, ui.ctx()));
            out.textures_delta.clear();
            assert_eq!((field(&app, "preset"), field(&app, "units")), (json!("A4"), json!("Millimeters")), "{popup}");
        }
    }

    /// Millimeters chosen in the Units menu stay chosen when another tab or preset is chosen after
    /// them, and reach the new document.
    #[test]
    fn units_chosen_in_the_menu_survive_tabs_and_presets() {
        use vectorcraft_doc::Unit::Millimeters as Mm;
        let mut h = big();
        assert_eq!((field(h.state(), "category"), field(h.state(), "units")), (json!("Print"), json!("Points")));
        h.get_by_role_and_label(Role::ComboBox, "Units").click();
        h.run_steps(3);
        h.get_by_label("Millimeters").click();
        h.run_steps(3);
        assert_eq!(field(h.state(), "units"), json!("Millimeters"));
        // A Recent entry made in inches, which the Recent tab opens on.
        h.state_mut().run("file.new", json!({"width": "8.5 in", "height": "11 in", "units": "Inches"})).unwrap();
        for tab in ["Web", "Recent", "Print"] {
            h.get_by_role_and_label(Role::Button, tab).click();
            h.run_steps(3);
            assert_eq!((field(h.state(), "category"), field(h.state(), "units")), (json!(tab), json!("Millimeters")), "the {tab} tab");
        }
        // A preset chosen by name, as `ui.dialog.set` chooses it.
        crate::dialogs::set_field(h.state_mut().ui.dialog.as_mut().unwrap(), "preset".into(), json!("A4"));
        h.run_steps(3);
        assert_eq!(
            (field(h.state(), "width"), field(h.state(), "units")),
            (json!(vectorcraft_doc::Unit::Millimeters.to_pt(210.0)), json!("Millimeters"))
        );
        assert_eq!(create(&mut h), Mm);
    }

    /// A long translation of Align New Objects to Pixel Grid wraps inside the Preset Details column.
    #[test]
    fn align_new_objects_label_wraps_inside_the_details_column() {
        const LABEL: &str = "Στοίχιση νέων αντικειμένων στο πλέγμα εικονοστοιχείων";
        crate::i18n::set_current(crate::i18n::Lang::from_code("el").unwrap());
        let mut h = big();
        set(h.state_mut(), "advanced", json!(true));
        h.run_steps(3);
        let boxed = h.get_by_role_and_label(egui::accesskit::Role::CheckBox, LABEL).rect();
        let text = h.get_by_role_and_label(egui::accesskit::Role::Label, LABEL).rect();
        crate::i18n::set_current(crate::i18n::Lang::EN);
        assert!(text.right() <= boxed.left() + super::DETAILS + 0.5, "{boxed:?} {text:?}");
        assert!(text.height() > boxed.height(), "the label takes two lines: {text:?}");
    }

    /// In a small window the pop-up stays on screen, and its button stays in view under rows that scroll.
    #[test]
    fn the_popup_stays_inside_a_small_window() {
        let mut h = harness(egui::vec2(480.0, 260.0));
        open_more(&mut h, 3);
        let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(480.0, 260.0));
        for label in ["Number of Artboards:", "Done"] {
            assert!(screen.contains_rect(h.get_by_label(label).rect()), "{label} is off screen");
        }
    }

    /// A color profile in the profile's file that can't be used, which `file.new` reports, shows in
    /// the status bar.
    #[test]
    fn profile_warnings_show_in_the_status_bar() {
        let mut app = VectorcraftApp::new(Session::new(), Default::default());
        super::report_profile(&mut app, &json!({"index": 0, "warnings": ["the color profile X can't be used"]}));
        assert_eq!(app.ui.status, "the color profile X can't be used");
    }

    /// Manage Profiles lists a row per profile; Reset is off until a profile has been edited, Escape
    /// closes only the pop-up, and Edit opens the profile as a document and closes New Document.
    #[test]
    fn manage_profiles_edits_and_resets_the_profiles() {
        let dir = std::env::temp_dir().join(format!("vc-ui-newdoc-profiles-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        let mut h = big();
        // Without a profiles folder Edit is off too.
        h.get_by_label("Manage Profiles").click();
        h.run_steps(4);
        assert!(h.get_all_by_label("Edit").all(|b| b.accesskit_node().is_disabled()));
        h.key_press(egui::Key::Escape);
        h.run_steps(3);
        h.state_mut().session.attach_new_doc_profiles(dir.clone());
        h.get_by_label("Manage Profiles").click();
        h.run_steps(4);
        assert_eq!(kind(&h), super::PROFILES);
        assert_eq!(h.get_all_by_label("Edit").count(), 7);
        assert!(h.get_all_by_label("Reset").all(|b| b.accesskit_node().is_disabled()));
        h.key_press(egui::Key::Escape);
        h.run_steps(3);
        assert_eq!(kind(&h), super::KIND, "Escape closes only the pop-up");
        // An edited profile's Reset deletes its file.
        h.state_mut().run("file.newProfiles.edit", json!({"name": "Web"})).unwrap();
        h.state_mut().run("file.newDialog", json!({})).unwrap();
        h.run_steps(3);
        h.get_by_label("Manage Profiles").click();
        h.run_steps(4);
        assert_eq!(h.get_all_by_label("Reset").filter(|b| !b.accesskit_node().is_disabled()).count(), 1);
        h.get_all_by_label("Reset").find(|b| !b.accesskit_node().is_disabled()).unwrap().click();
        h.run_steps(3);
        assert!(!dir.join("Web.vectorcraft").exists());
        // Edit on the third row (Print).
        h.get_all_by_label("Edit").nth(2).unwrap().click();
        h.run_steps(3);
        assert!(h.state().ui.dialog.is_none(), "{:?}", h.state().ui.status);
        assert_eq!(h.state().session.active().unwrap().doc.title, "Print");
        assert!(dir.join("Print.vectorcraft").is_file());
        let _ = std::fs::remove_dir_all(&dir);
    }
}