GitCorner

Code

ossartcraftvectorcraft🌐
2bc41aeb8602
//! Character panel: font family / style, size, leading, kerning, tracking, vertical and horizontal
//! scale, baseline shift, character rotation, the anti-aliasing method and the All Caps, Small Caps,
//! Superscript, Subscript, Underline and Strikethrough toggles and the Language menu.

use std::cell::RefCell;
use std::collections::HashSet;
use std::rc::Rc;
use std::sync::{Arc, Mutex, OnceLock, Weak};

use egui::{Key, Ui, vec2};
use serde_json::{Value, json};
use vectorcraft_doc::setup::{LANGUAGES, char_language_name};
use vectorcraft_doc::text::TypeAntiAlias;
use vectorcraft_doc::{CharStyle, NodeId, NodeKind};
use vectorcraft_engine::DocState;
use vectorcraft_tools::{Mods, ToolKey};

use super::{pstate, set_pstate};
use crate::VectorcraftApp;
use crate::theme::Tokens;
use crate::widgets::{self, SpinPick, menu_item};

/// The Font Size and Leading dropdowns' presets in points (Leading's after its Auto entry), shown
/// in the type unit.
pub const SIZE_PRESETS: [f64; 15] = [6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 14.0, 18.0, 21.0, 24.0, 36.0, 48.0, 60.0, 72.0];
/// The Kerning and Tracking dropdowns' presets in 1/1000 em.
pub const TRACKING_PRESETS: [f64; 14] = [-100.0, -75.0, -50.0, -25.0, -10.0, -5.0, 0.0, 5.0, 10.0, 25.0, 50.0, 75.0, 100.0, 200.0];
pub const SCALE_PRESETS: [f64; 8] = [25.0, 50.0, 75.0, 90.0, 100.0, 110.0, 125.0, 150.0];
/// Insert Aki Left and Right presets, in thousandths of an em: none, a quarter, half and a whole
/// full-width space.
pub const AKI_PRESETS: [f64; 4] = [0.0, 250.0, 500.0, 1000.0];
/// Tsume presets, in percent.
pub const TSUME_PRESETS: [f64; 5] = [0.0, 25.0, 50.0, 75.0, 100.0];
/// Adjust Horizontal and Vertical Diacritic Position presets, in thousandths of an em.
pub const DIACRITIC_PRESETS: [f64; 7] = [-200.0, -100.0, -50.0, 0.0, 50.0, 100.0, 200.0];

/// The stored character style: the selected range's (or the caret's) while the Type
/// tool edits text, else the first selected text object's first run (including groups). With it, the paragraph
/// attributes of the paragraph the selection starts in (else of the first paragraph).
/// Font/paragraph controls and named-style capture use this; dimensional fields use `shared_effective`.
pub(crate) fn text_style(app: &VectorcraftApp) -> Option<(CharStyle, vectorcraft_doc::ParaStyle)> {
    if let Some((id, a, b)) = text_editing(app)
        && let Some(NodeKind::Text(t)) = app.session.active().and_then(|d| d.doc.node(id)).map(|n| &n.kind)
    {
        return Some((vectorcraft_text::edit::insertion_style(&t.runs, a, b), t.para_at(t.paragraphs_in(a, a).start).clone()));
    }
    let t = first_selected_text(app)?;
    Some((t.first_style(), t.para_at(0).clone()))
}

/// The first selected text descendant, shared by Character and Paragraph controls.
pub(crate) fn first_selected_text(app: &VectorcraftApp) -> Option<&vectorcraft_doc::TextObject> {
    match &first_selected_text_node(app)?.kind {
        NodeKind::Text(t) => Some(t.as_ref()),
        _ => None,
    }
}

/// The node of [`first_selected_text`]: the first text object among the selected objects and
/// their descendants, in selection order, then paint order within each selected object.
pub(crate) fn first_selected_text_node(app: &VectorcraftApp) -> Option<&vectorcraft_doc::Node> {
    let st = app.session.active()?;
    for node in st.selection.objects.iter().filter_map(|id| st.doc.node(*id)) {
        let mut text = None;
        node.walk(&mut |n| {
            if text.is_none() && matches!(n.kind, NodeKind::Text(_)) {
                text = Some(n);
            }
        });
        if text.is_some() {
            return text;
        }
    }
    None
}

/// A boolean on every selected text object (`Some(true)` / `Some(false)`), or `None` when they
/// differ. When the Type tool edits text, only that object counts.
pub(crate) fn shared_text_flag(app: &VectorcraftApp, f: impl Fn(&vectorcraft_doc::TextObject) -> bool) -> Option<bool> {
    if let Some((id, _, _)) = text_editing(app) {
        return app.session.active().and_then(|st| st.doc.node(id)).and_then(|n| match &n.kind {
            NodeKind::Text(t) => Some(f(t)),
            _ => None,
        });
    }
    let st = app.session.active()?;
    let mut value: Option<bool> = None;
    let mut mixed = false;
    let mut saw = false;
    for node in st.selection.objects.iter().filter_map(|id| st.doc.node(*id)) {
        node.walk(&mut |n| {
            if let NodeKind::Text(t) = &n.kind {
                saw = true;
                if mixed {
                    return;
                }
                let v = f(t);
                match value {
                    None => value = Some(v),
                    Some(a) if a == v => {}
                    Some(_) => mixed = true,
                }
            }
        });
    }
    if !saw || mixed { None } else { value }
}

/// `f` of the character styles the panels act on: the runs the Type tool's selection covers (the
/// caret's style at a caret), else every run of every frame of the selected stories
/// ([`selected_stories`]). `None` (a blank field) where they differ, or with no type.
pub(crate) fn shared<T: PartialEq>(app: &VectorcraftApp, f: impl Fn(&CharStyle) -> T) -> Option<T> {
    shared_styles(app, |_, _, style, _| Some(f(style)))
}

/// The fonts (family and style) of the character styles the panels act on ([`shared`]), each
/// once, in the order the runs come.
pub(crate) fn selected_fonts(app: &VectorcraftApp) -> Vec<(String, String)> {
    let fonts = std::cell::RefCell::new(Vec::<(String, String)>::new());
    shared_styles(app, |_, _, style, _| {
        let mut fonts = fonts.borrow_mut();
        if !fonts.iter().any(|(family, face)| *family == style.font_family && *face == style.font_style) {
            fonts.push((style.font_family.clone(), style.font_style.clone()));
        }
        Some(())
    });
    fonts.into_inner()
}

/// Dimensional controls use document units and tolerate arithmetic roundoff when comparing
/// compensated runs. Keep raw styles available to font/paragraph controls and style definitions,
/// even if a collapsed affine prevents editing dimensions.
fn shared_effective(app: &VectorcraftApp, f: impl Fn(&CharStyle) -> f64) -> Option<f64> {
    shared_styles(app, |t, _, style, _| t.effective_char_style(style).map(|s| Metric(f(&s)))).map(|v| v.0)
}

/// The Leading shown: each character's own, or for Auto leading the share of the em size their
/// font height reference gives them ([`vectorcraft_text::FontDb::em_size`]) that their paragraph's
/// Justification › Auto Leading sets, as the layout uses. An inline graphic keeps its size.
fn shared_leading(app: &VectorcraftApp) -> Option<f64> {
    let db = vectorcraft_text::FontDb::global();
    shared_styles(app, |t, para, style, inline| {
        let s = t.effective_char_style(style)?;
        let em = if inline { s.size } else { db.em_size(&s, t.vertical) };
        Some(Metric(para.effective_leading(&CharStyle { size: em, ..s })))
    })
    .map(|v| v.0)
}

pub(crate) struct Metric(pub(crate) f64);

impl PartialEq for Metric {
    fn eq(&self, other: &Self) -> bool {
        (self.0 - other.0).abs() <= 1e-9 * self.0.abs().max(other.0.abs()).max(1.0)
    }
}

/// `f` of each character style in the selection, with its text object, the paragraph the
/// characters are in (a run that spans paragraphs counts once for each) and whether the run is an
/// inline graphic.
fn shared_styles<T: PartialEq>(
    app: &VectorcraftApp,
    f: impl Fn(&vectorcraft_doc::TextObject, &vectorcraft_doc::ParaStyle, &CharStyle, bool) -> Option<T>,
) -> Option<T> {
    let mut acc = Shared::None;
    each_style(app, |t, para, style, inline| acc.add(f(t, para, style, inline)));
    acc.value().flatten()
}

/// Whether `f` holds for any of the character styles [`shared`] reads.
pub(crate) fn any_style(app: &VectorcraftApp, f: impl Fn(&CharStyle) -> bool) -> bool {
    let mut any = false;
    each_style(app, |_, _, style, _| any = any || f(style));
    any
}

/// Call `f` with each character style the panels act on, as [`shared_styles`] describes: the
/// caret's style at a Type tool caret, else each piece of the runs the Type tool's selection
/// covers, else of every run of every frame of the selected stories.
fn each_style(app: &VectorcraftApp, mut f: impl FnMut(&vectorcraft_doc::TextObject, &vectorcraft_doc::ParaStyle, &CharStyle, bool)) {
    let Some(st) = app.session.active() else {
        return;
    };
    let text = |id: NodeId| match st.doc.node(id).map(|n| &n.kind) {
        Some(NodeKind::Text(t)) => Some(t),
        _ => None,
    };
    if let Some((id, a, b)) = text_editing(app) {
        let Some(t) = text(id) else {
            return;
        };
        if b <= a {
            let para = t.plain_text().get(..a).map_or(0, |s| s.bytes().filter(|&c| c == b'\n').count());
            f(t, t.para_at(para), &vectorcraft_text::edit::insertion_style(&t.runs, a, b), false);
            return;
        }
        match text_story(app) {
            // After Select All in threaded text: all the text of every frame of the story.
            Some(story) => {
                for t in story.into_iter().filter_map(text) {
                    each_paragraph_run(t, None, |para, style, inline| f(t, para, style, inline));
                }
            }
            None => each_paragraph_run(t, Some((a, b)), |para, style, inline| f(t, para, style, inline)),
        }
    } else {
        for t in selected_story_texts(app) {
            each_paragraph_run(t, None, |para, style, inline| f(t, para, style, inline));
        }
    }
}

/// `f` of the paragraph and style of each piece of `t`'s runs that lies in one paragraph (a
/// paragraph's closing line break belongs to it), and whether the run is an inline graphic: the
/// pieces within bytes `a..b`, or with no range every run's, empty ones included. With no range, a
/// final empty paragraph (the text ends in a line break) counts too, with the style of the run
/// before it, as the caret there types.
fn each_paragraph_run<'a>(
    t: &'a vectorcraft_doc::TextObject,
    range: Option<(usize, usize)>,
    mut f: impl FnMut(&'a vectorcraft_doc::ParaStyle, &'a CharStyle, bool),
) {
    let (mut end, mut para) = (0, 0);
    // The style of the last character and whether it is a line break: the paragraph after it has
    // no characters of its own.
    let mut last: Option<(&'a CharStyle, bool)> = None;
    for r in &t.runs {
        if r.text.is_empty() {
            if range.is_none_or(|(a, b)| a < end && end < b) {
                f(t.para_at(para), &r.style, r.inline.is_some());
            }
            continue;
        }
        for piece in r.text.split_inclusive('\n') {
            let start = end;
            end += piece.len();
            if range.is_none_or(|(a, b)| start < b && end > a) {
                f(t.para_at(para), &r.style, r.inline.is_some());
            }
            para += usize::from(piece.ends_with('\n'));
            last = Some((&r.style, piece.ends_with('\n')));
        }
    }
    if range.is_none()
        && let Some((style, true)) = last
    {
        f(t.para_at(para), style, false);
    }
}

/// The value a run of styles share so far ([`shared`]).
pub(crate) enum Shared<T> {
    None,
    Same(T),
    Differ,
}

impl<T: PartialEq> Shared<T> {
    pub(crate) fn add(&mut self, v: T) {
        match self {
            Shared::None => *self = Shared::Same(v),
            Shared::Same(x) if *x != v => *self = Shared::Differ,
            _ => {}
        }
    }
    pub(crate) fn value(self) -> Option<T> {
        match self {
            Shared::Same(v) => Some(v),
            _ => None,
        }
    }
}

fn style(app: &mut VectorcraftApp, p: Value) {
    char_cmd(app, "text.setStyle", p);
}
pub(crate) fn format(app: &mut VectorcraftApp, p: Value) {
    char_cmd(app, "text.setFormat", p);
}

/// [`format`] that returns the command's result: `text.setRangeStyle` on the range the Type tool
/// has selected (the whole text when nothing is selected) while it edits text, else
/// `text.setFormat` on the selected stories ([`selected_stories`]).
pub(crate) fn run_format(app: &mut VectorcraftApp, mut p: Value) -> Result<Value, String> {
    let Some((id, a, b)) = text_editing_kept(app)? else {
        target_selected_stories(app, &mut p);
        return app.run("text.setFormat", p);
    };
    if let Some(first) = text_story(app).and_then(|story| story.first().copied()) {
        return story_style(app, first, p);
    }
    p["id"] = json!(id.0);
    if b > a {
        p["start"] = json!(a);
        p["end"] = json!(b);
    }
    app.run("text.setRangeStyle", p)
}

/// The Tate-chu-yoko Settings Up/Down and Left/Right the characters the panels act on share, in
/// document points; `None` where they differ, or with no type.
pub(crate) fn shared_tcy_offsets(app: &VectorcraftApp) -> (Option<f64>, Option<f64>) {
    (shared_effective(app, |s| s.tcy_up_down), shared_effective(app, |s| s.tcy_left_right))
}

/// The Warichu Settings the characters the panels act on share: Lines, Line Gap (document
/// points), Scale (percent) and Alignment; `None` for each that differs, or with no type.
pub(crate) struct SharedWarichu {
    pub lines: Option<u8>,
    pub gap: Option<f64>,
    pub scale: Option<f64>,
    pub align: Option<vectorcraft_doc::WarichuAlign>,
}

pub(crate) fn shared_warichu(app: &VectorcraftApp) -> SharedWarichu {
    SharedWarichu {
        lines: shared(app, |s| s.warichu_lines),
        gap: shared_effective(app, |s| s.warichu_gap),
        scale: shared(app, |s| s.warichu_scale),
        align: shared(app, |s| s.warichu_align),
    }
}

/// Apply character attributes: to the selected range while the Type tool edits text (the whole
/// object when nothing is selected), else to every frame of the selected stories
/// ([`selected_stories`]).
fn char_cmd(app: &mut VectorcraftApp, cmd: &str, mut p: Value) {
    if text_editing(app).is_none() {
        target_selected_stories(app, &mut p);
        app.run(cmd, p).ok();
        return;
    }
    range_style(app, p);
}

/// Set the Kerning field's `value` (a number, "auto", or "optical"). At a caret in text the Type tool edits
/// it is the pair kerning after the character before the caret, as Alt+←/→ steps it
/// (`type.step`), or at the start of a line the space before the character after it, where Auto
/// and Optical set no space (#5111); nowhere to set at an empty line's start. Else it is a
/// character attribute like the others: the selected range, or all the text.
fn set_kerning(app: &mut VectorcraftApp, value: Value) {
    let Ok(editing) = text_editing_kept(app) else { return };
    let Some((id, a, b)) = editing else {
        format(app, json!({"kerning": value}));
        return;
    };
    if b > a {
        range_style(app, json!({"kerning": value}));
        return;
    }
    let Some(NodeKind::Text(t)) = app.session.active().and_then(|st| st.doc.node(id)).map(|n| &n.kind) else { return };
    let Some((target, before)) = vectorcraft_text::edit::caret_kerning_target(&t.plain_text(), a) else { return };
    let params = if before {
        json!({"id": id.0, "start": target.start, "end": target.end, "kerningBefore": value.as_f64().unwrap_or(0.0)})
    } else {
        json!({"id": id.0, "start": target.start, "end": target.end, "kerning": value})
    };
    app.run("text.setRangeStyle", params).ok();
}

/// The kerning at the caret, in 1/1000 em, using the layout the canvas draws: the pair before it,
/// or at the start of a line the space before the character after it.
fn caret_kerning(app: &VectorcraftApp, ui: &Ui) -> Option<(f64, bool)> {
    let (id, a, b) = text_editing(app)?;
    if a != b {
        return None;
    }
    let NodeKind::Text(t) = &app.session.active()?.doc.node(id)?.kind else { return None };
    let text = t.plain_text();
    let (target, before) = vectorcraft_text::edit::caret_kerning_target(&text, a)?;
    let start = target.start;
    let style = vectorcraft_text::edit::style_at(&t.runs, start + 1);
    if before {
        return Some((style.kerning_before, false));
    }
    if let Some(v) = style.kerning {
        return Some((v, false));
    }
    let state = app.session.active()?;
    let key = (state.uid, state.revision, id, a);
    let slot = ui.scope_id().with("caret-kerning");
    if let Some((cached_key, value)) = ui.ctx().data(|d| d.get_temp::<((u64, u64, NodeId, usize), f64)>(slot))
        && cached_key == key
    {
        return Some((value, true));
    }
    let original = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
    let value = vectorcraft_engine::cmd::effective_kerning(vectorcraft_text::FontDb::global(), t, &original, start, a);
    let value = value.round();
    ui.ctx().data_mut(|d| d.insert_temp(slot, (key, value)));
    Some((value, true))
}

/// The check marks of the Kerning menu's Auto and Optical entries for the selection's kerning
/// `mode` (Optical on, manual value). A manual value checks neither, as it sets the spacing even
/// with Optical on. A selection that mixes modes checks neither, and the menu still lists both.
fn kerning_methods(mode: Option<(bool, Option<f64>)>) -> (Option<bool>, Option<bool>) {
    let (automatic, optical) = mode.map_or((false, false), |(optical, manual)| (!optical && manual.is_none(), optical && manual.is_none()));
    (Some(automatic), Some(optical))
}

/// The faces Type › Bold and Type › Italic switch to.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Face {
    Bold,
    Italic,
}

/// Words of a style name that set its weight: a style without any is the family's regular weight.
const WEIGHTS: [&str; 16] = [
    "thin",
    "hairline",
    "extralight",
    "ultralight",
    "light",
    "book",
    "medium",
    "semibold",
    "demibold",
    "demi",
    "bold",
    "extrabold",
    "ultrabold",
    "heavy",
    "black",
    "ultra",
];

/// Words that name the regular weight, upright: not part of what Bold and Italic keep.
const PLAIN: [&str; 5] = ["regular", "normal", "roman", "plain", "upright"];

/// A style name's (bold, regular weight, italic, the other words): `Bold Italic` is (true, false,
/// true, []), `Narrow Italic` (false, true, true, ["narrow"]), `SemiBold` (false, false, false, []).
fn face_of(style: &str) -> (bool, bool, bool, Vec<String>) {
    let words: Vec<String> = style.split([' ', '-', '_']).filter(|w| !w.is_empty()).map(str::to_ascii_lowercase).collect();
    let italic = words.iter().any(|w| w == "italic" || w == "oblique");
    let bold = words.iter().any(|w| w == "bold");
    let regular = !words.iter().any(|w| WEIGHTS.contains(&w.as_str()));
    let mut rest: Vec<String> =
        words.into_iter().filter(|w| !WEIGHTS.contains(&w.as_str()) && !PLAIN.contains(&w.as_str()) && w != "italic" && w != "oblique").collect();
    rest.sort();
    (bold, regular, italic, rest)
}

/// The style of `styles` that is bold (else of regular weight) and italic (else upright), with the
/// same other words as style `like` (a Narrow face stays Narrow, a plain one plain).
fn pick_face<'a>(styles: &'a [String], bold: bool, italic: bool, like: &str) -> Option<&'a str> {
    let (.., keep) = face_of(like);
    styles
        .iter()
        .map(String::as_str)
        .filter(|s| {
            let (b, r, i, rest) = face_of(s);
            i == italic && (if bold { b } else { r }) && rest == keep
        })
        // `Regular` before `Regular Text`-like doubles: the plainest name is the family's own face.
        .min_by_key(|s| s.len())
}

/// Type › Bold and Type › Italic (Cmd+Shift+B / Cmd+Shift+I while the Type tool edits text, as in
/// page layout apps): the family's own Bold or Italic face for the text the panels act on, or back
/// to its regular weight (upright) when it already is bold (italic). No fake bold or slant: a family
/// without that face is left as it is, and the message says so (#724).
pub(crate) fn toggle_face(app: &mut VectorcraftApp, face: Face) -> Result<Value, String> {
    let (s, _) = text_style(app).ok_or("select some type first")?;
    let styles = vectorcraft_text::FontDb::global().styles(&s.font_family);
    let (bold, _, italic, _) = face_of(&s.font_style);
    let (want_bold, want_italic) = match face {
        Face::Bold => (!bold, italic),
        Face::Italic => (bold, !italic),
    };
    let Some(name) = pick_face(&styles, want_bold, want_italic, &s.font_style) else {
        let wanted = match (want_bold, want_italic) {
            (true, true) => "Bold Italic",
            (true, false) => "Bold",
            (false, true) => "Italic",
            (false, false) => "Regular",
        };
        return Err(format!("{} has no {} style", s.font_family, wanted));
    };
    let name = name.to_string();
    style(app, json!({ "style": name }));
    Ok(json!({ "style": name }))
}

/// The Character panel fields that the Highlight Font Name, Highlight Font Size (Type › Size ›
/// Other…), Highlight Kerning and Highlight Tracking commands give the keyboard focus
/// ([`highlight`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Field {
    /// The font family menu: it opens, and its search field takes the focus.
    FontName,
    FontSize,
    Kerning,
    Tracking,
}

impl Field {
    /// The id the panel draws the field with ([`show`], [`metrics_grid`]).
    fn salt(self) -> &'static str {
        match self {
            Field::FontName => "ch-font",
            Field::FontSize => "ch-size",
            Field::Kerning => "ch-kern",
            Field::Tracking => "ch-track",
        }
    }

    fn name(self) -> &'static str {
        match self {
            Field::FontName => "fontName",
            Field::FontSize => "fontSize",
            Field::Kerning => "kerning",
            Field::Tracking => "tracking",
        }
    }
}

/// `type.highlightFontName`, `type.highlightFontSize`, `type.highlightKerning` and
/// `type.highlightTracking`: show the Character panel if it is hidden (a shown one is activated,
/// so its floating window comes forward), and give `field` the keyboard focus when the panel next
/// draws it, a number field with its value selected (typing replaces it, Enter applies it).
/// Without selected type or text the Type tool edits, the panel shows, nothing takes the focus and
/// the command fails. → `{field}`.
pub(crate) fn highlight(app: &mut VectorcraftApp, field: Field) -> Result<Value, String> {
    // `window.panel` would hide a floating panel in front of its window, or an open flyout.
    if crate::panel_docking::visible(&app.ui, "character") {
        app.run("window.panel.activate", json!({"panel": "character"}))?;
    } else {
        crate::panel_docking::reveal_panel(app, "character")?;
    }
    if text_style(app).is_none() {
        app.character_focus = None;
        return Err("select some type first".into());
    }
    app.character_focus = Some(field);
    Ok(json!({ "field": field.name() }))
}

/// `type.underline` (Cmd+Shift+U): what the Underline button does, on the text the panels act on.
/// Returns whether the text is now underlined: off only when every character was underlined.
pub(crate) fn toggle_underline(app: &mut VectorcraftApp) -> Result<Value, String> {
    // The typing Real-time Drawing off left unapplied is applied before the text is read.
    text_editing_kept(app)?;
    text_style(app).ok_or("select some type first")?;
    let on = shared(app, |s| s.underline) != Some(true);
    run_format(app, json!({"underline": on}))?;
    Ok(json!(on))
}

/// `type.superscript` (Cmd+Shift+=) and `type.subscript` (Cmd+Alt+Shift+=): what the Superscript
/// or Subscript button does, on the text the panels act on. Returns the position the text now
/// has: `"normal"` only when every character had `position`, else `position`.
pub(crate) fn toggle_position(app: &mut VectorcraftApp, position: &str) -> Result<Value, String> {
    // The typing Real-time Drawing off left unapplied is applied before the text is read.
    text_editing_kept(app)?;
    text_style(app).ok_or("select some type first")?;
    let change = position_toggle(shared_position(app), position);
    let to = change["position"].clone();
    run_format(app, change)?;
    Ok(to)
}

/// `text.setRangeStyle` with `p` on the range the Type tool has selected (the whole text when
/// nothing is selected). Does nothing unless the Type tool edits text.
pub(crate) fn range_style(app: &mut VectorcraftApp, p: Value) {
    let Ok(Some((id, a, b))) = text_editing_kept(app) else { return };
    if let Some(first) = text_story(app).and_then(|story| story.first().copied()) {
        story_style(app, first, p).ok();
        return;
    }
    let mut q = p;
    q["id"] = json!(id.0);
    if b > a {
        q["start"] = json!(a);
        q["end"] = json!(b);
    }
    app.run("text.setRangeStyle", q).ok();
}

// ---------- Type tool editing glue (selection, clipboard, keys) ----------

/// The text object the Type tool is editing and its selection (clamped to the text).
pub(crate) fn text_editing(app: &VectorcraftApp) -> Option<(NodeId, usize, usize)> {
    let o = app.session.tool_options();
    let id = NodeId(o.get("editing")?.as_u64()?);
    let len = match &app.session.active()?.doc.node(id)?.kind {
        NodeKind::Text(t) => vectorcraft_text::edit::runs_len(&t.runs),
        _ => return None,
    };
    let g = |k: &str| o.get(k).and_then(Value::as_u64).map_or(0, |v| (v as usize).min(len));
    Some((id, g("start"), g("end")))
}

/// [`text_editing`] after [`end_typing`], for an edit of the text: the selection is read in the
/// text with the typing applied, which Real-time Drawing off leaves unapplied until then. When the
/// typing can't be kept, the error (also shown in the status bar), so the edit stops instead of
/// acting on a selection in the text without the typing.
pub(crate) fn text_editing_kept(app: &mut VectorcraftApp) -> Result<Option<(NodeId, usize, usize)>, String> {
    try_end_typing(app)?;
    Ok(text_editing(app))
}

/// The frames of the threaded story whose whole text the Type tool has selected after Select All,
/// in the order of the edited frame's thread as the document holds it now; `None` when its
/// selection is in one type object.
pub(crate) fn text_story(app: &VectorcraftApp) -> Option<Vec<NodeId>> {
    let o = app.session.tool_options();
    let st = app.session.active()?;
    let id = NodeId(o.get("editing")?.as_u64()?);
    if o.get("story")?.as_array()?.is_empty() {
        return None;
    }
    let ids = st.doc.story_of(id);
    (ids.len() >= 2).then_some(ids)
}

/// The type objects the panels act on with the Selection tool: the selected type objects and those
/// in selected groups, each with every frame of its threaded story (locked and hidden frames
/// included), each once, the frames of a story in thread order.
pub(crate) fn selected_stories(app: &VectorcraftApp) -> Vec<NodeId> {
    app.session.active().map_or_else(Vec::new, |st| story_frames(st).to_vec())
}

/// The last list [`selected_stories`] worked out, with the document version (its address, which
/// the held `Weak` keeps from being reused, and its revision) and the selected objects it was
/// worked out for. The Character and Paragraph panels read the list once for each field they show.
struct StoryFrames {
    doc: Weak<vectorcraft_doc::Document>,
    revision: u64,
    selection: Vec<NodeId>,
    frames: Rc<[NodeId]>,
}

thread_local! {
    static STORY_FRAMES: RefCell<Option<StoryFrames>> = const { RefCell::new(None) };
}

#[cfg(test)]
thread_local! {
    /// How many times [`build_selected_stories`] ran on this thread.
    static STORY_BUILDS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
    /// Whether [`story_frames`] builds the list on every read instead of keeping it.
    static STORIES_UNKEPT: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}

/// [`selected_stories`] of `st`: the kept list while `st`'s document, revision and selected
/// objects are the ones it was worked out for, else a new one, kept in its place.
fn story_frames(st: &DocState) -> Rc<[NodeId]> {
    #[cfg(test)]
    if STORIES_UNKEPT.get() {
        return build_selected_stories(st).into();
    }
    STORY_FRAMES.with_borrow_mut(|kept| {
        if let Some(k) = kept.as_ref()
            && k.revision == st.revision
            && k.doc.strong_count() > 0
            && std::ptr::eq(k.doc.as_ptr(), Arc::as_ptr(&st.doc))
            && k.selection == st.selection.objects
        {
            return k.frames.clone();
        }
        let frames: Rc<[NodeId]> = build_selected_stories(st).into();
        *kept = Some(StoryFrames {
            doc: Arc::downgrade(&st.doc),
            revision: st.revision,
            selection: st.selection.objects.clone(),
            frames: frames.clone(),
        });
        frames
    })
}

/// The list [`selected_stories`] describes, worked out from `st`'s selection.
fn build_selected_stories(st: &DocState) -> Vec<NodeId> {
    #[cfg(test)]
    STORY_BUILDS.set(STORY_BUILDS.get() + 1);
    let mut frames = Vec::new();
    let mut taken = HashSet::new();
    for selected in st.selection.objects.iter().filter_map(|id| st.doc.node(*id)) {
        selected.walk(&mut |child| {
            if matches!(child.kind, NodeKind::Text(_)) && !taken.contains(&child.id) {
                for id in st.doc.story_of(child.id) {
                    if taken.insert(id) {
                        frames.push(id);
                    }
                }
            }
        });
    }
    frames
}

/// The type objects of [`selected_stories`].
pub(crate) fn selected_story_texts(app: &VectorcraftApp) -> Vec<&vectorcraft_doc::TextObject> {
    let Some(st) = app.session.active() else { return Vec::new() };
    story_frames(st)
        .iter()
        .filter_map(|&id| match st.doc.node(id).map(|n| &n.kind) {
            Some(NodeKind::Text(t)) => Some(t.as_ref()),
            _ => None,
        })
        .collect()
}

/// Give the command parameters `p` the `ids` of [`selected_stories`], so a command run with the
/// Selection tool sets every frame of each selected story. `p` stays as it is when it names its
/// targets, with no type selected, and while an object of a symbol instance's art is selected,
/// which the commands refuse.
pub(crate) fn target_selected_stories(app: &VectorcraftApp, p: &mut Value) {
    if p.get("ids").is_some() || p.get("id").is_some() || app.session.active().is_none_or(|st| st.selection.symbol_part.is_some()) {
        return;
    }
    let ids = selected_stories(app);
    if let Some(params) = p.as_object_mut()
        && !ids.is_empty()
    {
        params.insert("ids".into(), json!(ids.iter().map(|id| id.0).collect::<Vec<_>>()));
    }
}

/// `text.setRangeStyle` with `p` on all the text of every frame of the story that `first` is a
/// frame of, as one undo step.
fn story_style(app: &mut VectorcraftApp, first: NodeId, mut p: Value) -> Result<Value, String> {
    end_typing(app);
    p["id"] = json!(first.0);
    p["story"] = json!(true);
    app.run("text.setRangeStyle", p)
}

/// Close the Type tool's typing session (one undo step) before another command edits the text. The
/// typing Real-time Drawing off left unapplied is applied first; when it can't be kept, the error
/// shows and the session goes on.
pub(crate) fn end_typing(app: &mut VectorcraftApp) {
    try_end_typing(app).ok();
}

/// [`end_typing`] that also returns the error when the typing can't be kept.
fn try_end_typing(app: &mut VectorcraftApp) -> Result<(), String> {
    if app.session.tool_options().get("typing").and_then(Value::as_bool) == Some(true) {
        if let Err(e) = app.keep_typing() {
            app.status(e.clone());
            return Err(e);
        }
        app.session.set_tool_option("commitTyping", &json!(true));
        app.session.commit_interaction().ok();
        app.sync_views();
    }
    Ok(())
}

static CTX: OnceLock<egui::Context> = OnceLock::new();
/// Plain text of the last text copied inside the Type tool (paste from the native menu, which
/// can't read the system clipboard).
static CLIP: Mutex<String> = Mutex::new(String::new());
static CLIP_RUNS: Mutex<Option<Value>> = Mutex::new(None);

/// Copy the Type tool's selected text (with `cut`, for a Cut, whose caller then deletes it).
fn text_copy(app: &mut VectorcraftApp, cut: bool) -> bool {
    let Some((id, a, b)) = text_editing(app) else { return false };
    let story = text_story(app);
    // An empty selection has nothing to copy, unless the story's text is in the other frames.
    if a == b && (story.is_none() || app.session.active().is_none_or(|st| st.doc.story_text(id).is_empty())) {
        return false;
    }
    // After Select All in threaded text: the whole story.
    let range = if story.is_some() { json!({"id": id.0, "story": true}) } else { json!({"id": id.0, "start": a, "end": b}) };
    let Ok(r) = app.session.execute("text.getRange", &range) else { return false };
    let runs = r["runs"].clone();
    app.session.set_tool_option("copy", &runs);
    *CLIP_RUNS.lock().unwrap_or_else(|e| e.into_inner()) = Some(runs.clone());
    let text = r["text"].as_str().unwrap_or("").to_string();
    *CLIP.lock().unwrap_or_else(|e| e.into_inner()) = text.clone();
    if let Ok(parsed_runs) = serde_json::from_value::<Vec<vectorcraft_doc::TextRun>>(runs)
        && !parsed_runs.is_empty()
    {
        let mut t = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::ZERO, "", vectorcraft_doc::CharStyle::default());
        t.runs = parsed_runs;
        let node = vectorcraft_doc::Node::new(vectorcraft_doc::NodeId(1), vectorcraft_doc::NodeKind::Text(Box::new(t)));
        let Ok(st) = app.session.doc() else { return false };
        let clip = vectorcraft_engine::cmd::clipboard::Clipboard::from_node(st, node);
        app.session.clipboard = clip;
        // The desktop clipboard must own the same styled art as the internal clipboard. An egui
        // plain-text copy would replace its formats, so let the publisher provide both text and
        // rich art. Paste on the canvas can then keep the runs after Type editing ends.
        if app.services.system_clipboard.is_some() {
            app.publish_clipboard(cut);
            return true;
        }
    }
    if let Some(ctx) = app.ui_ctx.clone().or_else(|| CTX.get().cloned()) {
        ctx.copy_text(text);
    }
    true
}

fn text_key(app: &mut VectorcraftApp, k: ToolKey, m: Mods) {
    let v = app.view_info();
    let target_before = crate::ime::target(&mut app.session, v);
    let before = crate::ime::stamp(&mut app.session, v);
    let r = app.session.tool_key(k, m, v);
    match &r {
        Err(e) => app.status(e.to_string()),
        Ok(_) => {
            if let Some(ctx) = app.ui_ctx.clone().or_else(|| CTX.get().cloned()) {
                crate::ime::note_application_edit(app, &ctx, v, target_before, before);
            }
        }
    }
}

fn text_paste(app: &mut VectorcraftApp, s: Option<String>, plain: bool) {
    let s = match s {
        Some(text) => text,
        None if app.services.system_clipboard.is_some() => app.written_clipboard_text().unwrap_or_default(),
        None => CLIP.lock().unwrap_or_else(|e| e.into_inner()).clone(),
    };
    if !s.is_empty() {
        let internal = app.type_paste_has_our_clipboard();
        let mut styled = false;
        if !plain
            && internal
            && let Some(runs) = CLIP_RUNS.lock().unwrap_or_else(|e| e.into_inner()).clone()
        {
            let clip_text: String =
                serde_json::from_value::<Vec<vectorcraft_doc::TextRun>>(runs.clone()).unwrap_or_default().into_iter().map(|r| r.text).collect();
            if clip_text == s {
                app.session.set_tool_option("copy", &runs);
                styled = true;
            }
        }
        if !styled {
            app.session.set_tool_option("copy", &json!([]));
        }
        let v = app.view_info();
        let target_before = crate::ime::target(&mut app.session, v);
        let before = crate::ime::stamp(&mut app.session, v);
        let r = app.session.tool_text(&s, v);
        match &r {
            Err(e) => app.status(e.to_string()),
            Ok(_) => {
                if let Some(ctx) = app.ui_ctx.clone().or_else(|| CTX.get().cloned()) {
                    crate::ime::note_application_edit(app, &ctx, v, target_before, before);
                }
            }
        }
    }
}

/// Edit-menu commands while the Type tool edits text act on the text (Cut/Copy/Paste/Clear;
/// Select All is the engine's `select.all`). `None` = not intercepted.
pub(crate) fn intercept_text_command(app: &mut VectorcraftApp, id: &str) -> Option<Result<Value, String>> {
    if !app.session.tool_wants_text() {
        return None;
    }
    match id {
        "edit.copy" => {
            text_copy(app, false);
        }
        "edit.cut" => {
            if text_copy(app, true) {
                text_key(app, ToolKey::Delete, Mods::default());
            }
        }
        "edit.paste" => text_paste(app, None, false),
        "edit.pasteWithoutFormatting" => text_paste(app, None, true),
        "edit.clear" => text_key(app, ToolKey::Delete, Mods::default()),
        _ => return None,
    }
    app.sync_views();
    Some(Ok(Value::Null))
}

pub(crate) enum TextInput {
    Key(ToolKey, Mods),
    Copy,
    Cut,
    Paste(Option<String>),
    Face(Face),
}

/// Takes an editing key (with modifiers), a clipboard event or Cmd+C/X/V for the Type tool into
/// `todo` (Cmd+A is left to the Select All shortcut, which selects the text being edited). Returns
/// false for an event the tool takes, which is then removed from the input.
pub(crate) fn type_input(e: &egui::Event, todo: &mut Vec<TextInput>) -> bool {
    match e {
        egui::Event::Copy => {
            todo.push(TextInput::Copy);
            false
        }
        egui::Event::Cut => {
            todo.push(TextInput::Cut);
            false
        }
        egui::Event::Paste(s) => {
            todo.push(TextInput::Paste(Some(s.clone())));
            false
        }
        egui::Event::Key { key, pressed, modifiers: m, .. } => {
            let mods = Mods { shift: m.shift, alt: m.alt, cmd: m.command, ctrl: m.ctrl && !m.command, space: false };
            let tk = match key {
                Key::ArrowLeft => Some(ToolKey::Left),
                Key::ArrowRight => Some(ToolKey::Right),
                Key::ArrowUp => Some(ToolKey::Up),
                Key::ArrowDown => Some(ToolKey::Down),
                Key::Home => Some(ToolKey::Home),
                Key::End => Some(ToolKey::End),
                Key::Backspace => Some(ToolKey::Backspace),
                Key::Delete => Some(ToolKey::Delete),
                Key::Tab if !m.command => Some(ToolKey::Tab),
                _ => None,
            };
            if let Some(tk) = tk {
                if *pressed {
                    todo.push(TextInput::Key(tk, mods));
                }
                return false;
            }
            // Type › Bold and Italic, as page layout apps have them while text is edited.
            if m.command && m.shift && !m.alt && matches!(key, Key::B | Key::I) {
                if *pressed {
                    todo.push(TextInput::Face(if *key == Key::B { Face::Bold } else { Face::Italic }));
                }
                return false;
            }
            if m.command && !m.shift && !m.alt && matches!(key, Key::C | Key::X | Key::V) {
                if *pressed {
                    todo.push(match key {
                        Key::C => TextInput::Copy,
                        Key::X => TextInput::Cut,
                        _ => TextInput::Paste(None),
                    });
                }
                return false;
            }
            true
        }
        _ => true,
    }
}

/// Keeps `ctx` for the Type tool's clipboard, which Edit › Copy and Cut also write to.
pub(crate) fn keep_ctx(ctx: &egui::Context) {
    CTX.get_or_init(|| ctx.clone());
}

/// Applies an editing key or clipboard event taken by [`type_input`] to the Type tool.
pub(crate) fn apply_type_input(app: &mut VectorcraftApp, t: TextInput) {
    match t {
        TextInput::Key(k, m) => text_key(app, k, m),
        TextInput::Copy => {
            text_copy(app, false);
        }
        TextInput::Cut => {
            if text_copy(app, true) {
                text_key(app, ToolKey::Delete, Mods::default());
            }
        }
        TextInput::Paste(s) => text_paste(app, s, false),
        TextInput::Face(f) => {
            if let Err(e) = toggle_face(app, f) {
                app.status(e);
            }
        }
    }
}

/// A compact labelled cell: short glyph label + spinner field.
fn cell(ui: &mut Ui, label: &str, tip: &str, add: impl FnOnce(&mut Ui)) {
    let t = Tokens::get(ui.ctx());
    ui.horizontal(|ui| {
        let l =
            ui.add_sized(vec2(22.0, 24.0), egui::Label::new(egui::RichText::new(label).size(11.5).strong().color(t.text))).on_hover_text(tl!(tip));
        crate::scrub::note_label(ui, l.rect);
        // The visible label names the value field beside it, also in a grid cell that draws more
        // than one widget (egui 0.37's strict accessibility check).
        ui.label_inputs_by(l.id, add);
    });
}

/// The Character panel's grid of fields, `w` wide: Font Size, Leading, Kerning and Tracking,
/// then with `more` the scales, Baseline Shift and Character Rotation, and a row with the
/// Anti-aliasing Method dropdown under Character Rotation (`s`: the style shown), and with Show East
/// Asian Options on a row with Insert Aki Left and Right and a row with Tsume, and with Show Indic
/// Options (the Middle Eastern options) on a row with Adjust Horizontal and Vertical Diacritic
/// Position. With Show Font Height Options on, a row under Font Size holds the Set Font Height
/// Reference dropdown. The Properties panel shows its first rows.
pub(crate) fn metrics_grid(app: &mut VectorcraftApp, ui: &mut Ui, id: &str, s: &CharStyle, w: f32, more: bool) {
    let fw = ((w - 66.0) / 2.0).clamp(60.0, 100.0);
    let unit = app.session.type_unit();
    egui::Grid::new(id).num_columns(2).spacing([6.0, 4.0]).show(ui, |ui| {
        cell(ui, "T", tl!("Font Size"), |ui| size_field(app, ui, "ch-size", fw));
        cell(ui, "A↕", tl!("Leading"), |ui| {
            let leading = shared_leading(app);
            let auto = shared(app, |s| s.leading.is_none()) == Some(true);
            match widgets::spin_field_auto(ui, "ch-lead", leading, Some(auto), unit, fw, 1.0, 0.1, &SIZE_PRESETS) {
                Some(SpinPick::Value(v)) => style(app, json!({"leading": v})),
                Some(SpinPick::Auto) => style(app, json!({"leading": "auto"})),
                Some(SpinPick::Optical) => {}
                None => {}
            }
        });
        ui.end_row();
        if pstate::<bool>(ui.ctx(), FONT_HEIGHT_OPTIONS) {
            cell(ui, "T↕", tl!("Set Font Height Reference"), |ui| font_height_reference(app, ui, fw));
            ui.end_row();
        }
        cell(ui, "VA", tl!("Kerning"), |ui| {
            let mode = shared(app, |s| (s.optical_kerning, s.kerning));
            let caret = text_editing(app).is_some_and(|(_, a, b)| a == b);
            let at_caret = if caret { caret_kerning(app, ui) } else { None };
            let kerning = at_caret.map(|(v, _)| v).or_else(|| mode.map(|(_, manual)| manual.unwrap_or(0.0)));
            let (automatic, optical) = kerning_methods(mode);
            match widgets::spin_kerning(
                ui,
                "ch-kern",
                kerning,
                automatic,
                optical,
                tl!("Optical"),
                at_caret.is_some_and(|(_, auto)| auto),
                fw,
                &TRACKING_PRESETS,
            ) {
                Some(SpinPick::Value(v)) => set_kerning(app, json!(v)),
                Some(SpinPick::Auto) => set_kerning(app, json!("auto")),
                Some(SpinPick::Optical) => set_kerning(app, json!("optical")),
                None => {}
            }
        });
        cell(ui, "VA↔", tl!("Tracking"), |ui| {
            if let Some(v) = widgets::spin_plain(ui, "ch-track", shared(app, |s| s.tracking), "", 0, fw, 10.0, -1000.0, &TRACKING_PRESETS) {
                style(app, json!({"tracking": v}));
            }
        });
        ui.end_row();
        if !more {
            return;
        }
        cell(ui, "IT", tl!("Vertical Scale %"), |ui| {
            if let Some(v) = widgets::spin_plain(ui, "ch-vs", shared(app, |s| s.v_scale), "%", 1, fw, 1.0, 1.0, &SCALE_PRESETS) {
                format(app, json!({"vScale": v}));
            }
        });
        cell(ui, "T↔", tl!("Horizontal Scale %"), |ui| {
            if let Some(v) = widgets::spin_plain(ui, "ch-hs", shared_effective(app, |s| s.h_scale), "%", 1, fw, 1.0, 1.0, &SCALE_PRESETS) {
                format(app, json!({"hScale": v}));
            }
        });
        ui.end_row();
        cell(ui, "Aª", tl!("Baseline Shift"), |ui| {
            if let Some(v) = widgets::spin_field(ui, "ch-bs", shared_effective(app, |s| s.baseline_shift), unit, fw, 1.0, -1296.0, &[]) {
                format(app, json!({"baselineShift": v}));
            }
        });
        cell(ui, "⟲T", tl!("Character Rotation"), |ui| {
            if let Some(v) = widgets::spin_plain(ui, "ch-rot", s.rotation, "°", 1, fw, 15.0, -360.0, &super::transform::ANGLE_PRESETS) {
                format(app, json!({"rotation": v}));
            }
        });
        ui.end_row();
        // Anti-aliasing Method, under Character Rotation.
        ui.label("");
        cell(ui, "aa", tl!("Anti-aliasing Method"), |ui| anti_alias_method(app, ui, fw));
        ui.end_row();
        // Insert Aki Left and Right, with the East Asian options: space before and after each
        // character, in thousandths of an em.
        if app.session.prefs.show_east_asian_options {
            for (field, label, key, icon) in
                [("ch-aki-left", tl!("Insert Aki Left"), "akiLeft", "↔A"), ("ch-aki-right", tl!("Insert Aki Right"), "akiRight", "A↔")]
            {
                cell(ui, icon, label, |ui| {
                    let value = shared(app, |s| if key == "akiLeft" { s.aki_left } else { s.aki_right });
                    if let Some(v) = widgets::spin_plain(ui, field, value, "", 0, fw, 10.0, 0.0, &AKI_PRESETS) {
                        // The field stops at the largest value the command takes.
                        format(app, json!({ key: v.min(vectorcraft_doc::text::MAX_AKI) }));
                    }
                });
            }
            ui.end_row();
            // Tsume: the share of the blank space beside each character's ink taken away.
            cell(ui, "→A←", tl!("Tsume"), |ui| {
                if let Some(v) = widgets::spin_plain(ui, "ch-tsume", shared(app, |s| s.tsume), "%", 1, fw, 1.0, 0.0, &TSUME_PRESETS) {
                    // The field stops at the largest value the command takes.
                    format(app, json!({ "tsume": v.min(vectorcraft_doc::text::MAX_TSUME) }));
                }
            });
            ui.end_row();
        }
        // Adjust Horizontal and Vertical Diacritic Position, with the Middle Eastern options: the
        // marks of the characters move across and up, in thousandths of an em.
        if app.session.prefs.show_indic_options {
            let max = vectorcraft_doc::text::MAX_DIACRITIC_POSITION;
            for (field, label, key, icon) in [
                ("ch-diacritic-h", tl!("Adjust Horizontal Diacritic Position"), "diacriticHorizontal", "´↔"),
                ("ch-diacritic-v", tl!("Adjust Vertical Diacritic Position"), "diacriticVertical", "´↕"),
            ] {
                cell(ui, icon, label, |ui| {
                    let value = shared(app, |s| if key == "diacriticHorizontal" { s.diacritic_horizontal } else { s.diacritic_vertical });
                    if let Some(v) = widgets::spin_plain(ui, field, value, "", 0, fw, 10.0, -max, &DIACRITIC_PRESETS) {
                        // The field stops at the largest value the command takes.
                        format(app, json!({ key: v.min(max) }));
                    }
                });
            }
            ui.end_row();
        }
    });
}

/// The Anti-aliasing Method dropdown, `width` wide: how the edges of the type objects the panel acts
/// on are drawn as pixels ([`set_anti_alias`]), blank where their methods differ.
fn anti_alias_method(app: &mut VectorcraftApp, ui: &mut Ui, width: f32) {
    // The labels of [`TypeAntiAlias::ALL`], in its order. "Sharp" is looked up under the
    // `antiAlias` context: the catalogs' plain "Sharp" row is the Contour tool's corner.
    let sharp = crate::i18n::tr_ctx(crate::i18n::current(), "antiAlias", "Sharp");
    let labels = [tl!("None"), sharp, tl!("Crisp"), tl!("Strong")];
    let current = shared_anti_alias(app);
    let shown = TypeAntiAlias::ALL.iter().zip(labels).find(|(m, _)| Some(**m) == current).map_or("", |(_, l)| l);
    if let Some(m) = widgets::dropdown_names(ui, "ch-anti-alias", shown, &labels, width).and_then(|i| TypeAntiAlias::ALL.get(i)) {
        set_anti_alias(app, *m);
    }
}

/// The anti-aliasing method of the type objects the panel acts on: the one the Type tool edits,
/// else every frame of the selected stories ([`selected_stories`]). `None` where they differ, or
/// with no type.
fn shared_anti_alias(app: &VectorcraftApp) -> Option<TypeAntiAlias> {
    let st = app.session.active()?;
    let mut acc = Shared::None;
    match text_editing(app) {
        Some((id, _, _)) => {
            if let Some(NodeKind::Text(t)) = st.doc.node(id).map(|n| &n.kind) {
                acc.add(t.anti_alias);
            }
        }
        None => {
            for t in selected_story_texts(app) {
                acc.add(t.anti_alias);
            }
        }
    }
    acc.value()
}

/// Set the anti-aliasing method `m` of the frame the Type tool edits, whatever part of its text
/// is selected, else every frame of the selected stories (`text.setFormat {antiAlias}`).
fn set_anti_alias(app: &mut VectorcraftApp, m: TypeAntiAlias) {
    let mut p = json!({"antiAlias": m.id()});
    if let Some((id, _, _)) = text_editing(app) {
        end_typing(app);
        p["ids"] = json!([id.0]);
    } else {
        target_selected_stories(app, &mut p);
    }
    app.run("text.setFormat", p).ok();
}

/// The Font Size combo (Character and Properties panels, Control bar): typed, stepped, scrubbed or
/// picked from the presets, in the type unit, blank where the selected text's sizes differ.
pub(crate) fn size_field(app: &mut VectorcraftApp, ui: &mut Ui, id: &str, width: f32) {
    size_field_named(app, ui, id, None, width);
}

/// [`size_field`] named `name` for screen readers, where no label stands beside it.
fn size_field_named(app: &mut VectorcraftApp, ui: &mut Ui, id: &str, name: Option<&str>, width: f32) {
    let size = shared_effective(app, |s| s.size);
    if let Some(v) = widgets::spin_field_named(ui, id, name, size, app.session.type_unit(), width, 1.0, 0.1, &SIZE_PRESETS) {
        style(app, json!({"size": v}));
    }
}

/// The panel state of the Character panel menu's Show Font Height Options.
const FONT_HEIGHT_OPTIONS: &str = "ch-font-height-options";

/// The font height references the Set Font Height Reference dropdown lists, with their
/// `text.setFormat` values.
const FONT_HEIGHT_REFERENCES: [(vectorcraft_doc::FontHeightReference, &str); 4] = [
    (vectorcraft_doc::FontHeightReference::EmBox, "emBox"),
    (vectorcraft_doc::FontHeightReference::CapHeight, "capHeight"),
    (vectorcraft_doc::FontHeightReference::XHeight, "xHeight"),
    (vectorcraft_doc::FontHeightReference::IcfBox, "icfBox"),
];

/// The size of the icon before each name in the Set Font Height Reference dropdown.
const FONT_HEIGHT_ICON: f32 = 16.0;

/// The Set Font Height Reference dropdown, `width` wide: the height of the font that the Font Size
/// measures, blank where the characters the panel acts on differ. Each reference shows an icon of
/// the height it measures before its name ([`paint_font_height_icon`], #6304).
fn font_height_reference(app: &mut VectorcraftApp, ui: &mut Ui, width: f32) {
    // The labels of [`FONT_HEIGHT_REFERENCES`], in its order.
    let labels = [tl!("Em Box"), tl!("Cap Height"), tl!("x-Height"), tl!("ICF Box")];
    let current = shared(app, |s| s.font_height_reference);
    let shown = FONT_HEIGHT_REFERENCES.iter().position(|(r, _)| Some(*r) == current);
    let accent = Tokens::get(ui.ctx()).accent;
    let icon = |ui: &Ui, rect: egui::Rect, i: usize, ink: egui::Color32, highlighted: bool| {
        // On the highlighted row the selection fill is accent-tinted, so the measure takes the
        // name's colour there to keep its contrast.
        let mark = if highlighted { ink } else { accent };
        if let Some((r, _)) = FONT_HEIGHT_REFERENCES.get(i) {
            paint_font_height_icon(ui.painter(), rect, *r, ink, mark);
        }
    };
    let picked = widgets::dropdown_icon_names(ui, "ch-font-height", shown, &labels, width, FONT_HEIGHT_ICON, icon);
    if let Some((_, key)) = picked.and_then(|i| FONT_HEIGHT_REFERENCES.get(i)) {
        format(app, json!({"fontHeightReference": key}));
    }
}

/// Paints the icon of font height reference `r` into the square `rect` (#6304): a letter drawn in
/// `ink` on a baseline, and in `mark` the height the reference measures. Em Box frames the whole
/// square around an "A"; Cap Height puts a bar from the baseline to the top of a capital "A"
/// beside it; x-Height a bar from the baseline to the top of a lowercase "x"; ICF Box frames a
/// square inset in the faint em square around an ideograph-like cross, as the ideographic
/// character face sits inside the em box. The drawings are VectorCraft's own.
fn paint_font_height_icon(
    painter: &egui::Painter,
    rect: egui::Rect,
    r: vectorcraft_doc::FontHeightReference,
    ink: egui::Color32,
    mark: egui::Color32,
) {
    use vectorcraft_doc::FontHeightReference as R;
    // A point at (x, y) in the unit square mapped onto `rect`.
    let p = |x: f32, y: f32| rect.lerp_inside(vec2(x, y));
    let glyph = egui::Stroke::new(1.3, ink);
    let measure = egui::Stroke::new(1.2, mark);
    let line = |a: (f32, f32), b: (f32, f32), stroke: egui::Stroke| painter.line_segment([p(a.0, a.1), p(b.0, b.1)], stroke);
    let frame = |min: f32, max: f32, stroke: egui::Stroke| {
        painter.rect_stroke(egui::Rect::from_min_max(p(min, min), p(max, max)), 0.0, stroke, egui::StrokeKind::Middle);
    };
    // A capital A from `left` to `right`, its apex at `top` and its feet on `base`.
    let capital = |left: f32, right: f32, top: f32, base: f32| {
        let mid = (left + right) / 2.0;
        painter.add(egui::Shape::line(vec![p(left, base), p(mid, top), p(right, base)], glyph));
        let bar = top + (base - top) * 0.62;
        let inset = (right - left) * 0.5 * 0.62;
        line((mid - inset, bar), (mid + inset, bar), glyph);
    };
    // A vertical measure from `top` to `base` at `x`, with ticks at its ends.
    let height_bar = |x: f32, top: f32, base: f32| {
        line((x, top), (x, base), measure);
        line((x - 0.1, top), (x + 0.1, top), measure);
        line((x - 0.1, base), (x + 0.1, base), measure);
    };
    let (base, cap_top, x_top) = (0.86, 0.16, 0.46);
    match r {
        R::EmBox => {
            frame(0.06, 0.94, measure);
            capital(0.26, 0.74, 0.26, 0.76);
        }
        R::CapHeight => {
            capital(0.06, 0.6, cap_top, base);
            height_bar(0.82, cap_top, base);
        }
        R::XHeight => {
            line((0.1, x_top), (0.54, base), glyph);
            line((0.54, x_top), (0.1, base), glyph);
            height_bar(0.82, x_top, base);
        }
        R::IcfBox => {
            frame(0.06, 0.94, egui::Stroke::new(1.0, ink.gamma_multiply(0.4)));
            frame(0.2, 0.8, measure);
            line((0.33, 0.5), (0.67, 0.5), glyph);
            line((0.5, 0.31), (0.5, 0.69), glyph);
        }
    }
}

/// The font family menu and the font style dropdown of style `s` (Character and Properties panels,
/// Control bar), with their `ids` and `widths`. The mouse wheel over the closed family field steps
/// the text through the families.
pub(crate) fn font_pickers(app: &mut VectorcraftApp, ui: &mut Ui, s: &CharStyle, ids: (&str, &str), widths: (f32, f32)) {
    let wheel_owner = match ids.0 {
        "ch-font" => Some(crate::font_menu::WheelOwner::Character),
        "font" => Some(crate::font_menu::WheelOwner::Properties),
        "cb-font" => Some(crate::font_menu::WheelOwner::Control),
        _ => None,
    };
    font_pickers_owned(app, ui, s, ids, widths, wheel_owner, (None, None));
}

fn font_pickers_owned(
    app: &mut VectorcraftApp,
    ui: &mut Ui,
    s: &CharStyle,
    ids: (&str, &str),
    widths: (f32, f32),
    wheel_owner: Option<crate::font_menu::WheelOwner>,
    a11y: (Option<&str>, Option<&str>),
) {
    crate::font_menu::sync_wheel_target(app, ui.ctx(), ui.ctx().viewport_id());
    let sample = crate::font_menu::sample_text(app);
    let look = crate::font_menu::MenuLook { wheel: true, wheel_owner, name: a11y.0, ..crate::font_menu::MenuLook::of(app) };
    if let Some(pick) = crate::font_menu::font_menu(ui, ids.0, &s.font_family, widths.0, sample.as_deref(), look) {
        crate::font_menu::apply(app, ui.ctx(), pick);
    }
    let styles = vectorcraft_text::FontDb::global().styles(&s.font_family);
    let names: Vec<&str> = styles.iter().map(String::as_str).collect();
    if let Some(name) = widgets::dropdown_names_named(ui, ids.1, a11y.1, &s.font_style, &names, widths.1).and_then(|i| names.get(i)) {
        style(app, json!({"style": name}));
    }
}

/// The Variable Font button, `width` wide, shown when the font of style `s` is a variable font: it
/// opens the font's axis sliders ([`axis_sliders`]).
pub(crate) fn variable_font(app: &mut VectorcraftApp, ui: &mut Ui, s: &CharStyle, width: f32) {
    let Some(face) = vectorcraft_text::FontDb::global().face_version(&s.font_family, &s.font_style, s.font_version.as_deref()) else { return };
    if face.axes().iter().all(|a| a.hidden) {
        return;
    }
    let resp = widgets::flat_button(ui, tl!("Variable Font"), width);
    widgets::popover(&resp, resp.clicked(), |ui| {
        ui.set_width(240.0);
        axis_sliders(app, ui, &face);
    });
}

/// One slider and field per axis of `face`'s variable font (the axes it asks to hide left out),
/// named as the font names it: each sets that axis of the text the panel acts on
/// (`text.setFormat {fontAxes}`, or `text.setRangeStyle` while the Type tool edits text), one undo
/// step per drag. A blank field: the text's settings of that axis differ.
pub(crate) fn axis_sliders(app: &mut VectorcraftApp, ui: &mut Ui, face: &vectorcraft_text::FontFace) {
    let t = Tokens::get(ui.ctx());
    let db = vectorcraft_text::FontDb::global();
    for axis in face.axes().into_iter().filter(|a| !a.hidden) {
        let tag = String::from_utf8_lossy(&axis.tag).into_owned();
        // Each character style's setting: its own, else its face's (a named instance's, or the default).
        let setting = |s: &CharStyle| {
            s.font_axes.get(&tag).copied().or_else(|| {
                let face = db.face_version(&s.font_family, &s.font_style, s.font_version.as_deref())?;
                face.axis_value(axis.tag).map(f64::from)
            })
        };
        let value = shared(app, setting).flatten();
        let (min, max) = (f64::from(axis.min.min(axis.max)), f64::from(axis.max.max(axis.min)));
        ui.horizontal(|ui| {
            let label = widgets::dim_name(ui, &axis.name);
            crate::scrub::note_label(ui, label.rect);
            ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                if let Some(v) = widgets::spin_plain(ui, ("ch-axis-field", axis.tag), value, "", 1, 72.0, 1.0, min, &[]) {
                    axes_cmd(app, json!({ &tag: v.clamp(min, max) }), widgets::Live::Released);
                }
            });
        });
        let at = value.map_or(0.0, |v| if max > min { ((v - min) / (max - min)) as f32 } else { 0.0 });
        // A mixed value leaves the field blank and the slider without a value.
        let shown = value.map(|v| widgets::SliderValue::field(v, min..=max, "", 1));
        let (picked, phase) =
            widgets::color_slider_valued(ui, ("ch-axis", axis.tag), &axis.name, shown, at, ui.available_width(), &|_| t.button_border);
        if let Some(p) = picked {
            let v = ((min + f64::from(p) * (max - min)) * 10.0).round() / 10.0;
            axes_cmd(app, json!({ &tag: v }), phase);
        }
    }
}

/// Set Variable Font settings `axes` on the text the panel acts on, live while a slider drags.
fn axes_cmd(app: &mut VectorcraftApp, axes: Value, phase: widgets::Live) {
    match text_editing_kept(app) {
        // The typing can't be kept (the error shows): nothing is set.
        Err(_) => {}
        Ok(Some((id, a, b))) => {
            let mut q = json!({"id": id.0, "fontAxes": axes});
            // After Select All in threaded text: every frame of the story.
            if let Some(first) = text_story(app).and_then(|story| story.first().copied()) {
                q["id"] = json!(first.0);
                q["story"] = json!(true);
            } else if b > a {
                q["start"] = json!(a);
                q["end"] = json!(b);
            }
            super::live_run(app, "Character", "text.setRangeStyle", q, phase);
        }
        Ok(None) => {
            let mut p = json!({ "fontAxes": axes });
            target_selected_stories(app, &mut p);
            super::live_run(app, "Character", "text.setFormat", p, phase);
        }
    }
}

/// The Control bar's type controls while type is selected or edited: the Character link (the
/// Character panel in a popover), the font family and style menus and the Font Size combo. They
/// show whole, with `reserve` left after them, or not at all: it returns false when type is selected
/// or edited and the row has no room for them.
pub(crate) fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui, reserve: f32) -> bool {
    let Some((s, _)) = text_style(app) else { return true };
    if ui.available_width() < control_bar_width(ui) + reserve {
        return false;
    }
    let link = ui.link(control_bar_link_text(ui)).on_hover_text(tl!("Character options"));
    widgets::popover(&link, link.clicked(), |ui| {
        ui.set_width(260.0);
        show_owned(app, ui, crate::font_menu::WheelOwner::ControlPopover(link.id));
    });
    let [family, style, size] = CONTROL_BAR_WIDTHS;
    font_pickers(app, ui, &s, ("cb-font", "cb-font-style"), (family, style));
    size_field(app, ui, "cb-font-size", size);
    ui.add_space(4.0);
    crate::chrome::group_separator(ui);
    true
}

/// The Control bar's widths of the font family menu, the font style dropdown and the Font Size combo.
const CONTROL_BAR_WIDTHS: [f32; 3] = [150.0, 96.0, 96.0];

/// The text of the Control bar's Character link, as [`control_bar`] draws it.
fn control_bar_link_text(ui: &Ui) -> egui::RichText {
    egui::RichText::new(tl!("Character:")).size(12.0).color(Tokens::get(ui.ctx()).text).underline()
}

/// The room [`control_bar`]'s link, menus and Font Size combo take in the Control bar's row, with
/// the spacing after each.
fn control_bar_width(ui: &Ui) -> f32 {
    let spacing = ui.spacing().item_spacing.x;
    widgets::text_width(ui, control_bar_link_text(ui)) + CONTROL_BAR_WIDTHS.iter().sum::<f32>() + 4.0 * spacing
}

/// The Contextual Task Bar's widths of the font family menu, the font style dropdown and the
/// Font Size combo.
pub(crate) const TASK_BAR_WIDTHS: [f32; 3] = [140.0, 90.0, 76.0];

/// The smallest share of [`TASK_BAR_WIDTHS`] the Contextual Task Bar's type controls narrow to.
const TASK_BAR_MIN_SCALE: f32 = 0.4;

/// The gaps between the Contextual Task Bar's type controls.
fn task_bar_gaps() -> f32 {
    6.0 * (TASK_BAR_WIDTHS.len() - 1) as f32
}

/// The narrowest room the Contextual Task Bar's type controls fit in, with their spacing.
pub(crate) fn task_bar_min_room() -> f32 {
    TASK_BAR_MIN_SCALE * TASK_BAR_WIDTHS.iter().sum::<f32>() + task_bar_gaps()
}

/// The Contextual Task Bar's type controls while type is selected or edited: the font family and
/// style menus and the Font Size combo, as the Control bar has them, named for screen readers.
/// They narrow, down to 40% of their widths, to fit in `room` points with their spacing.
pub(crate) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, room: f32) {
    let Some((s, _)) = text_style(app) else { return };
    let k = ((room - task_bar_gaps()) / TASK_BAR_WIDTHS.iter().sum::<f32>()).clamp(TASK_BAR_MIN_SCALE, 1.0);
    let [family, style, size] = TASK_BAR_WIDTHS.map(|w| w * k);
    let owner = Some(crate::font_menu::WheelOwner::TaskBar);
    font_pickers_owned(app, ui, &s, ("tb-font", "tb-font-style"), (family, style), owner, (Some(tl!("Font Family")), Some(tl!("Style"))));
    size_field_named(app, ui, "tb-font-size", Some(tl!("Font Size")), size);
}

/// The panel state key of the panel menu's Show Snap to Glyph Options.
const SNAP_TO_GLYPH_OPTIONS: &str = "ch-snap-to-glyph-options";
/// Set when Show Snap to Glyph Options is chosen: the next frame scrolls the panel to the options,
/// which come after every character attribute (#5273).
const SNAP_TO_GLYPH_REVEAL: &str = "ch-snap-to-glyph-reveal";

pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
    show_owned(app, ui, crate::font_menu::WheelOwner::Character);
}

fn show_owned(app: &mut VectorcraftApp, ui: &mut Ui, owner: crate::font_menu::WheelOwner) {
    attributes(app, ui, owner);
    // Drawing over type needs no type selected, so the options show without one too.
    if pstate::<bool>(ui.ctx(), SNAP_TO_GLYPH_OPTIONS) {
        snap_to_glyph_options(app, ui);
    }
}

/// The Snap to Glyph options (Show Snap to Glyph Options): View › Snap to Glyph itself, then which
/// guides it gives, each a checkbox running `view.snapToGlyph.options` (dimmed while Snap to Glyph
/// is off). Shown from the panel menu, the panel scrolls to them (#5273).
fn snap_to_glyph_options(app: &mut VectorcraftApp, ui: &mut Ui) {
    ui.add_space(4.0);
    ui.separator();
    let top = ui.cursor().min;
    let (o, enabled) = (app.session.prefs.glyph_snap, app.ui.view.snap_to_glyph);
    // A UI command that takes no params: it can't refuse.
    if widgets::check(ui, "Snap to Glyph", enabled, true) {
        app.run("view.snapToGlyph", json!({})).ok();
    }
    egui::Grid::new("ch-snap-to-glyph").num_columns(2).show(ui, |ui| {
        for (i, (label, key, on)) in [
            ("Baseline", "baseline", o.baseline),
            ("x-height", "xHeight", o.x_height),
            ("Glyph Bounds", "bounds", o.bounds),
            ("Proximity Guides", "proximity", o.proximity),
            ("Angular Guides", "angular", o.angular),
            ("Anchor Point", "anchors", o.anchors),
        ]
        .into_iter()
        .enumerate()
        {
            // A known key and a bool: the command can't refuse it.
            if widgets::check(ui, label, on, enabled) {
                app.run("view.snapToGlyph.options", json!({ key: !on })).ok();
            }
            if i % 2 == 1 {
                ui.end_row();
            }
        }
    });
    if pstate::<bool>(ui.ctx(), SNAP_TO_GLYPH_REVEAL) {
        set_pstate(ui.ctx(), SNAP_TO_GLYPH_REVEAL, false);
        ui.scroll_to_rect(egui::Rect::from_min_max(top, ui.min_rect().max), Some(egui::Align::BOTTOM));
    }
}

/// The character attributes of the type selected (an empty state without any).
fn attributes(app: &mut VectorcraftApp, ui: &mut Ui, owner: crate::font_menu::WheelOwner) {
    let Some((s, _)) = text_style(app) else {
        app.character_focus = None;
        super::empty_state(ui, "type", tl!("No text selected"), tl!("Select a text object to edit its character attributes."));
        return;
    };
    let w = ui.available_width();
    // The field a Highlight command asked for takes the focus as it is drawn. If no field took it
    // (a sizing pass), the next frame tries again.
    if let Some(f) = app.character_focus {
        widgets::arm_field_focus(ui.ctx(), f.salt());
    }
    font_pickers_owned(app, ui, &s, ("ch-font", "ch-style"), (w - 4.0, w - 4.0), Some(owner), (None, None));
    variable_font(app, ui, &s, w - 4.0);
    ui.add_space(2.0);
    let hidden = pstate::<bool>(ui.ctx(), "ch-hide-options");
    metrics_grid(app, ui, "ch-grid", &s, w, !hidden);
    if app.character_focus.is_some() && !widgets::disarm_field_focus(ui.ctx()) {
        app.character_focus = None;
    }
    if hidden {
        return;
    }
    ui.add_space(4.0);
    ui.horizontal(|ui| {
        // On only when every character the panel acts on has it; a mixed selection turns it on.
        let all_caps = shared(app, |s| s.all_caps) == Some(true);
        let small = shared(app, |s| s.small_caps.is_some()) == Some(true);
        let position = shared_position(app);
        let underline = shared(app, |s| s.underline) == Some(true);
        let strike = shared(app, |s| s.strikethrough) == Some(true);
        for (kind, tip, on, change) in [
            (Glyph::AllCaps, tl!("All Caps"), all_caps, json!({"allCaps": !all_caps})),
            (Glyph::SmallCaps, tl!("Small Caps"), small, json!({"smallCaps": !small})),
            (Glyph::Super, tl!("Superscript"), position == "superscript", position_toggle(position, "superscript")),
            (Glyph::Sub, tl!("Subscript"), position == "subscript", position_toggle(position, "subscript")),
            (Glyph::Underline, tl!("Underline"), underline, json!({"underline": !underline})),
            (Glyph::Strike, tl!("Strikethrough"), strike, json!({"strikethrough": !strike})),
        ] {
            if style_toggle(ui, kind, tip, on) {
                format(app, change);
            }
        }
    });
    // Language: the characters are shaped in it, so that the font uses that language's forms.
    ui.add_space(4.0);
    let names: Vec<&str> = LANGUAGES.iter().map(|(n, _, _)| *n).collect();
    // Mixed: blank; a tag from a file that is not in the list: as it is.
    let current = shared(app, |s| s.language.clone())
        .map_or_else(String::new, |l| char_language_name(l.as_deref()).map_or_else(|| l.unwrap_or_default(), str::to_string));
    widgets::label_row(ui, tl!("Language:"), 64.0, |ui| {
        if let Some(name) = widgets::dropdown(ui, "ch-language", &current, &names, w - 72.0).and_then(|i| names.get(i)) {
            format(app, json!({"language": name}));
        }
    });
}

/// The position kind (`normal`, `superscript` or `subscript`) that every character a Superscript
/// or Subscript toggle changes has, else `""`: at a Type tool caret with no characters selected
/// every character of the text (of each frame of a threaded story), as the toggle changes all of
/// it there ([`run_format`], [`range_style`]), else the characters [`shared`] reads. Superscripts
/// in different proportions count as superscript.
fn shared_position(app: &VectorcraftApp) -> &'static str {
    let Some((id, _, _)) = text_editing(app).filter(|&(_, a, b)| b <= a) else {
        return shared(app, |s| s.position.id()).unwrap_or("");
    };
    let Some(st) = app.session.active() else { return "" };
    let mut acc = Shared::None;
    for frame in text_story(app).unwrap_or_else(|| vec![id]) {
        if let Some(NodeKind::Text(t)) = st.doc.node(frame).map(|n| &n.kind) {
            each_paragraph_run(t, None, |_, style, _| acc.add(style.position.id()));
        }
    }
    acc.value().unwrap_or("")
}

/// The `text.setFormat` params of the Superscript or Subscript toggle `p` for text whose
/// position is `position`: `normal` when `p` is on, else `p`, which turns the other one off.
fn position_toggle(position: &str, p: &str) -> Value {
    json!({"position": if position == p { "normal" } else { p }})
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum Glyph {
    AllCaps,
    SmallCaps,
    Super,
    Sub,
    Underline,
    Strike,
}

/// A drawn "T" style toggle (All Caps, Small Caps, Superscript, Subscript, Underline, Strikethrough).
fn style_toggle(ui: &mut Ui, g: Glyph, tip: &str, on: bool) -> bool {
    let t = Tokens::get(ui.ctx());
    let (r, resp) = ui.allocate_exact_size(vec2(30.0, 26.0), egui::Sense::click());
    if on {
        ui.painter().rect_filled(r, 3, t.tool_active);
    } else if resp.hovered() {
        ui.painter().rect_filled(r, 3, t.hover);
    }
    let col = t.text_strong;
    let big = egui::FontId::proportional(15.0);
    let small = egui::FontId::proportional(10.5);
    let c = r.center();
    let p = ui.painter();
    match g {
        Glyph::AllCaps => {
            p.text(c - vec2(5.0, 0.0), egui::Align2::CENTER_CENTER, "T", big.clone(), col);
            p.text(c + vec2(5.0, 0.0), egui::Align2::CENTER_CENTER, "T", big, col);
        }
        Glyph::SmallCaps => {
            p.text(c - vec2(4.0, 0.0), egui::Align2::CENTER_CENTER, "T", big, col);
            p.text(c + vec2(6.0, 2.0), egui::Align2::CENTER_CENTER, "T", small, col);
        }
        Glyph::Super => {
            p.text(c - vec2(3.0, 0.0), egui::Align2::CENTER_CENTER, "T", big, col);
            p.text(c + vec2(6.0, -5.0), egui::Align2::CENTER_CENTER, "1", small, col);
        }
        Glyph::Sub => {
            p.text(c - vec2(3.0, 0.0), egui::Align2::CENTER_CENTER, "T", big, col);
            p.text(c + vec2(6.0, 5.0), egui::Align2::CENTER_CENTER, "1", small, col);
        }
        Glyph::Underline => {
            p.text(c - vec2(0.0, 1.0), egui::Align2::CENTER_CENTER, "T", big, col);
            p.line_segment([c + vec2(-5.0, 7.0), c + vec2(5.0, 7.0)], egui::Stroke::new(1.2, col));
        }
        Glyph::Strike => {
            p.text(c, egui::Align2::CENTER_CENTER, "T", big, col);
            p.line_segment([c + vec2(-6.0, 1.0), c + vec2(6.0, 1.0)], egui::Stroke::new(1.2, col));
        }
    }
    let resp = resp.on_hover_text(tl!(tip));
    resp.clicked()
}

/// The Character Direction submenu: Default, Left to Right and Right to Left set the characters the
/// panel acts on ([`char_cmd`]) as the bidi algorithm sets them, or left to right or right to left
/// inside their paragraph. The direction those characters share is checked, and none is checked
/// when they differ. At a caret in text the Type tool edits, with no characters selected, the items
/// are disabled.
fn char_direction_items(app: &mut VectorcraftApp, ui: &mut Ui) {
    use vectorcraft_doc::ParaDirection;
    let direction = shared(app, |s| s.char_direction);
    let enabled = text_editing(app).is_none_or(|(_, a, b)| b > a);
    for (label, d, key) in [
        (tl!("Default"), None, "default"),
        (tl!("Left to Right"), Some(ParaDirection::LeftToRight), "leftToRight"),
        (tl!("Right to Left"), Some(ParaDirection::RightToLeft), "rightToLeft"),
    ] {
        if menu_item(ui, label, enabled, direction == Some(d)) {
            format(app, json!({"charDirection": key}));
        }
    }
}

/// The numeral systems Character panel menu › Digits lists after Default, with their English
/// labels, translated in the `digits` context (Hindi, Bengali, Tamil… are also languages): the
/// Arabic-script ones, then the Indic scripts' own digits from Devanagari on.
pub(crate) const DIGITS: [(&str, vectorcraft_doc::Digits); 12] = {
    use vectorcraft_doc::Digits;
    [
        ("Arabic", Digits::Arabic),
        ("Hindi", Digits::Hindi),
        ("Farsi", Digits::Farsi),
        ("Devanagari", Digits::Devanagari),
        ("Bengali", Digits::Bengali),
        ("Gurmukhi", Digits::Gurmukhi),
        ("Gujarati", Digits::Gujarati),
        ("Odia", Digits::Odia),
        ("Tamil", Digits::Tamil),
        ("Telugu", Digits::Telugu),
        ("Kannada", Digits::Kannada),
        ("Malayalam", Digits::Malayalam),
    ]
};

/// Character panel menu › Digits; `digits`: the selected characters' (`None` when they differ).
fn digits_items(app: &mut VectorcraftApp, ui: &mut Ui, digits: Option<vectorcraft_doc::Digits>) {
    use vectorcraft_doc::Digits;
    let mut item = |ui: &mut Ui, label: &str, d: Digits| {
        if menu_item(ui, label, true, digits == Some(d)) {
            format(app, json!({"digits": d.id()}));
        }
    };
    item(ui, tl!("Default"), Digits::Default);
    for (label, d) in DIGITS {
        if d == Digits::Devanagari {
            ui.separator();
        }
        item(ui, crate::i18n::tr_ctx(crate::i18n::current(), "digits", label), d);
    }
}

pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) {
    let has = text_style(app).is_some();
    let hidden: bool = pstate(ui.ctx(), "ch-hide-options");
    if menu_item(ui, if hidden { tl!("Show Options") } else { tl!("Hide Options") }, true, false) {
        set_pstate(ui.ctx(), "ch-hide-options", !hidden);
    }
    let glyph = pstate::<bool>(ui.ctx(), SNAP_TO_GLYPH_OPTIONS);
    if menu_item(ui, if glyph { tl!("Hide Snap to Glyph Options") } else { tl!("Show Snap to Glyph Options") }, true, false) {
        set_pstate(ui.ctx(), SNAP_TO_GLYPH_OPTIONS, !glyph);
        set_pstate(ui.ctx(), SNAP_TO_GLYPH_REVEAL, !glyph);
    }
    // Show Font Height Options shows the Set Font Height Reference dropdown under Font Size.
    let heights: bool = pstate(ui.ctx(), FONT_HEIGHT_OPTIONS);
    if menu_item(ui, if heights { tl!("Hide Font Height Options") } else { tl!("Show Font Height Options") }, true, false) {
        set_pstate(ui.ctx(), FONT_HEIGHT_OPTIONS, !heights);
    }
    ui.separator();
    // A check item is checked when every character the panel acts on has it; choosing it with a
    // mixed selection turns it on.
    for (label, key, on) in [
        (tl!("All Caps"), "allCaps", shared(app, |s| s.all_caps) == Some(true)),
        (tl!("Underline"), "underline", shared(app, |s| s.underline) == Some(true)),
        (tl!("Strikethrough"), "strikethrough", shared(app, |s| s.strikethrough) == Some(true)),
    ] {
        if menu_item(ui, label, has, on) {
            format(app, json!({key: !on}));
        }
    }
    let small = shared(app, |s| s.small_caps.is_some()) == Some(true);
    let position = shared_position(app);
    for (label, on, change) in [
        (tl!("Small Caps"), small, json!({"smallCaps": !small})),
        (tl!("Superscript"), position == "superscript", position_toggle(position, "superscript")),
        (tl!("Subscript"), position == "subscript", position_toggle(position, "subscript")),
    ] {
        if menu_item(ui, label, has, on) {
            format(app, change);
        }
    }
    ui.separator();
    // Character Alignment: where characters smaller than the largest on their line line up, with
    // the East Asian options.
    if app.session.prefs.show_east_asian_options {
        let align = shared(app, |s| s.char_align);
        ui.add_enabled_ui(has, |ui| {
            // Indented like the items beside it (their check column).
            ui.menu_button(format!("   {}", tl!("Character Alignment")), |ui| {
                use vectorcraft_doc::CharAlign;
                for (label, a, key) in [
                    (tl!("Roman Baseline"), CharAlign::RomanBaseline, "romanBaseline"),
                    (tl!("Em Box Top/Right"), CharAlign::EmBoxTop, "emBoxTop"),
                    (tl!("Em Box Center"), CharAlign::EmBoxCenter, "emBoxCenter"),
                    (tl!("Em Box Bottom/Left"), CharAlign::EmBoxBottom, "emBoxBottom"),
                    (tl!("ICF Top/Right"), CharAlign::IcfTop, "icfTop"),
                    (tl!("ICF Bottom/Left"), CharAlign::IcfBottom, "icfBottom"),
                ] {
                    if menu_item(ui, label, true, align == Some(a)) {
                        format(app, json!({"charAlign": key}));
                    }
                }
            });
        });
        // Proportional Metrics: full-width glyphs on the font's proportional widths (`palt`, `vpal`).
        let proportional = shared(app, |s| s.proportional_metrics) == Some(true);
        if menu_item(ui, tl!("Proportional Metrics"), has, proportional) {
            format(app, json!({"proportionalMetrics": !proportional}));
        }
        // Tate-chu-yoko: the selected characters stand side by side across one em of a vertical column.
        let tcy = shared(app, |s| s.tate_chu_yoko) == Some(true);
        if menu_item(ui, tl!("Tate-chu-yoko"), has, tcy) {
            format(app, json!({"tateChuYoko": !tcy}));
        }
        // Tate-chu-yoko Settings…: the Up/Down and Left/Right that move a tate-chu-yoko block.
        if menu_item(ui, tl!("Tate-chu-yoko Settings…"), has, false)
            && let Err(e) = app.run("ui.tateChuYokoSettings", json!({}))
        {
            app.status(e);
        }
        // Warichu: the selected characters set smaller and stacked on lines inside their line.
        // Checked when every selected character has it; a mixed selection turns it on.
        let warichu = shared(app, |s| s.warichu) == Some(true);
        if menu_item(ui, tl!("Warichu"), has, warichu) {
            format(app, json!({"warichu": !warichu}));
        }
        // Warichu Settings…: the Lines, Line Gap, Scale and Alignment of a warichu block.
        if menu_item(ui, tl!("Warichu Settings…"), has, false)
            && let Err(e) = app.run("ui.warichuSettings", json!({}))
        {
            app.status(e);
        }
        // Standard Vertical Roman Alignment: the selected half-width characters stand upright in
        // vertical type instead of being rotated. Checked when every selected character has it; a
        // mixed selection turns it on.
        let roman = shared(app, |s| s.standard_vertical_roman) == Some(true);
        if menu_item(ui, tl!("Standard Vertical Roman Alignment"), has, roman) {
            format(app, json!({"standardVerticalRoman": !roman}));
        }
        ui.separator();
    }
    // Digits: the numeral system the selected characters' digits are drawn in, with the Middle
    // Eastern (Indic) options, as Paragraph Direction is in the Paragraph panel.
    if app.session.prefs.show_indic_options {
        let digits = shared(app, |s| s.digits);
        ui.add_enabled_ui(has, |ui| {
            ui.menu_button(format!("   {}", tl!("Digits")), |ui| widgets::menu_scroll(ui, |ui| digits_items(app, ui, digits)));
        });
        ui.add_enabled_ui(has, |ui| {
            ui.menu_button(format!("   {}", tl!("Character Direction")), |ui| char_direction_items(app, ui));
        });
        // A mixed selection is unchecked; choosing it enables kashidas for the whole range.
        let kashidas = shared(app, |s| s.kashidas) == Some(true);
        let selected_characters = text_editing(app).is_none_or(|(_, start, end)| end > start);
        if menu_item(ui, tl!("Kashidas"), has && selected_characters, kashidas) {
            format(app, json!({"kashidas": !kashidas}));
        }
        ui.separator();
    }
    // No Break: the selected characters stay on one line.
    let no_break = shared(app, |s| s.no_break) == Some(true);
    if menu_item(ui, tl!("No Break"), has, no_break) {
        format(app, json!({"noBreak": !no_break}));
    }
    // Fractional Widths: the whole type object's spacing, on unless turned off. Not a character
    // range, so a selection inside the text sets the object the Type tool is editing.
    let fractional = fractional_widths_on(app);
    if menu_item(ui, tl!("Fractional Widths"), has, fractional) {
        let mut p = json!({});
        if let Some((id, _, _)) = text_editing(app) {
            p["id"] = json!(id.0);
        }
        app.run("type.fractionalWidths", p).ok();
    }
    // System Layout: whole-point spacing for every text object in the document. It does not need
    // a type selection; a document is enough.
    let open = app.session.active().is_some();
    let system = app.session.active().is_some_and(|st| st.doc.setup.system_layout);
    if menu_item(ui, tl!("System Layout"), open, system) {
        app.run("type.systemLayout", json!({})).ok();
    }
    ui.separator();
    // The installed fonts are always listed; this picks up fonts installed since the app started.
    #[cfg(not(target_arch = "wasm32"))]
    if menu_item(ui, tl!("Refresh Font List"), true, false)
        && let Ok(r) = app.run("text.rescanFonts", json!({}))
    {
        app.status(format!("{} font families available", r["families"]));
    }
    if menu_item(ui, tl!("Reset Panel"), has, false) {
        reset_panel(app);
    }
}

/// Whether Fractional Widths is on for the type the panel shows: the object being edited, else
/// the first selected text object. On when there is no type (the item is disabled then).
fn fractional_widths_on(app: &VectorcraftApp) -> bool {
    if let Some((id, _, _)) = text_editing(app)
        && let Some(NodeKind::Text(t)) = app.session.active().and_then(|d| d.doc.node(id)).map(|n| &n.kind)
    {
        return t.fractional_widths;
    }
    first_selected_text(app).is_none_or(|t| t.fractional_widths)
}

/// Reset Panel, in one undo step: the type objects the panel acts on take the Sharp anti-aliasing
/// method, and the characters the panel acts on ([`char_cmd`]) take tracking 0, Auto leading and
/// kerning, no baseline shift, 100% scales, no rotation, no underline or strikethrough, All Caps
/// and Small Caps off, the normal position (neither superscript nor subscript), Roman Baseline
/// character alignment, Proportional Metrics, Tate-chu-yoko, Warichu, Standard Vertical Roman Alignment and
/// No Break off, Tate-chu-yoko Settings Up/Down and Left/Right 0, the default Warichu Settings (2 lines, no
/// line gap, 50%, Auto alignment), Insert Aki Left and Right 0, Tsume 0, the Default character direction,
/// Kashidas on, the Default digits, Adjust Horizontal and Vertical Diacritic Position 0 and the Em Box
/// font height reference, whether or not Show East Asian
/// Options, Show Indic Options and Show Font Height Options are on. Inside an undo group that is
/// already open, the reset is part of that group's step.
fn reset_panel(app: &mut VectorcraftApp) {
    // Typing in progress stays an undo step of its own.
    end_typing(app);
    let open = app.session.active().is_some_and(|st| st.undo_group.is_some());
    if !open {
        app.session.begin_named_undo_group(Some("Reset Panel".into()));
    }
    let d = CharStyle::default();
    style(app, json!({"tracking": 0, "leading": "auto"}));
    format(
        app,
        json!({
            "kerning": "auto", "baselineShift": 0, "hScale": 100, "vScale": 100, "rotation": 0, "underline": false, "strikethrough": false,
            "allCaps": false, "smallCaps": d.small_caps.is_some(), "position": d.position.id(), "charAlign": d.char_align,
            "proportionalMetrics": d.proportional_metrics, "tateChuYoko": d.tate_chu_yoko,
            "tcyUpDown": d.tcy_up_down, "tcyLeftRight": d.tcy_left_right, "akiLeft": d.aki_left, "akiRight": d.aki_right,
            "tsume": d.tsume, "warichu": d.warichu, "warichuLines": d.warichu_lines, "warichuGap": d.warichu_gap, "warichuScale": d.warichu_scale,
            "warichuAlign": d.warichu_align,
            "standardVerticalRoman": d.standard_vertical_roman, "noBreak": d.no_break, "charDirection": "default", "kashidas": d.kashidas,
            "digits": d.digits, "diacriticHorizontal": d.diacritic_horizontal, "diacriticVertical": d.diacritic_vertical,
            "fontHeightReference": d.font_height_reference
        }),
    );
    set_anti_alias(app, TypeAntiAlias::Sharp);
    // Closes the active document's undo group only, so an undo group open in another document
    // stays open.
    if !open && let Some(st) = app.session.active_mut() {
        st.undo_group = None;
    }
}

#[cfg(test)]
mod tests;