GitCorner

Code

ossartcraftwordcraft🌐
6ef13b2cc8a6
use super::buttons::DROPDOWN;
use super::tooltip::{keytip_badge, show_hint};
use super::{Color32, CornerRadius, Rect, Response, Sense, Stroke, Tokens, Ui, icons, pos2, regular, vec2};

/// Word's standard colour grid (theme colours + tints, standard colours). Returns a picked hex.
pub fn color_grid(ui: &mut Ui, theme: &[wordcraft_doc::Rgb]) -> Option<String> {
    let mut picked = None;
    ui.label(egui::RichText::new(tl!("Theme Colors")).small().weak());
    let base: Vec<wordcraft_doc::Rgb> = theme.iter().take(10).copied().collect();
    let tint = |c: wordcraft_doc::Rgb, k: f32| {
        let f = |v: u8| if k >= 0.0 { (v as f32 + (255.0 - v as f32) * k) as u8 } else { (v as f32 * (1.0 + k)) as u8 };
        wordcraft_doc::Rgb(f(c.0), f(c.1), f(c.2))
    };
    let order = [1usize, 0, 3, 2, 4, 5, 6, 7, 8, 9];
    for k in [0.0f32, 0.8, 0.6, 0.4, -0.25, -0.5] {
        ui.horizontal(|ui| {
            ui.spacing_mut().item_spacing = vec2(3.0, if k == 0.0 { 6.0 } else { 0.0 });
            for i in order {
                let Some(c) = base.get(i).copied() else { continue };
                let c = tint(c, k);
                if swatch(ui, c) {
                    picked = Some(c.hex());
                }
            }
        });
    }
    ui.add_space(4.0);
    ui.label(egui::RichText::new(tl!("Standard Colors")).small().weak());
    ui.horizontal(|ui| {
        ui.spacing_mut().item_spacing = vec2(3.0, 0.0);
        for hex in ["C00000", "FF0000", "FFC000", "FFFF00", "92D050", "00B050", "00B0F0", "0070C0", "002060", "7030A0"] {
            if let Some(c) = wordcraft_doc::Rgb::parse(hex)
                && swatch(ui, c)
            {
                picked = Some(hex.to_string());
            }
        }
    });
    picked
}

fn hover_key() -> egui::Id {
    egui::Id::unique("wc_pick_hover")
}

/// Records the list entry or colour the pointer is over in this pass (one per pass; the last
/// drawn wins). [`take_hover`] reads it.
pub(crate) fn note_hover(ctx: &egui::Context, value: String) {
    let pass = ctx.cumulative_pass_nr();
    ctx.data_mut(|d| d.insert_temp(hover_key(), (pass, value)));
}

/// The entry noted by [`note_hover`] in this pass, if any; it is read once. Callers take before
/// drawing a list too, to drop what another widget noted.
pub(crate) fn take_hover(ctx: &egui::Context) -> Option<String> {
    let pass = ctx.cumulative_pass_nr();
    let seen = ctx.data_mut(|d| d.remove_temp::<(u64, String)>(hover_key()));
    seen.filter(|(p, _)| *p == pass).map(|(_, v)| v)
}

fn current_key() -> egui::Id {
    egui::Id::unique("wc_pick_current")
}

/// The colour (hex, or a name the menu uses) a palette marks as the one in effect; `None` marks
/// nothing. The caller sets it before drawing a menu and clears it after.
pub(crate) fn set_current_pick(ctx: &egui::Context, current: Option<String>) {
    ctx.data_mut(|d| match current {
        Some(c) => {
            d.insert_temp(current_key(), c);
        }
        None => d.remove::<String>(current_key()),
    });
}

pub(crate) fn current_pick(ctx: &egui::Context) -> Option<String> {
    ctx.data(|d| d.get_temp::<String>(current_key()))
}

pub(crate) fn swatch(ui: &mut Ui, c: wordcraft_doc::Rgb) -> bool {
    let (r, resp) = ui.allocate_exact_size(vec2(15.0, 15.0), Sense::click());
    ui.painter().rect_filled(r, 0.0, Color32::from_rgb(c.0, c.1, c.2));
    let t = Tokens::get(ui.ctx());
    ui.painter().rect_stroke(
        r,
        0.0,
        Stroke::new(if resp.hovered() { 1.5 } else { 0.5 }, if resp.hovered() { t.accent } else { t.border_strong }),
        egui::StrokeKind::Inside,
    );
    if resp.hovered() {
        note_hover(ui.ctx(), c.hex());
    }
    if current_pick(ui.ctx()).is_some_and(|cur| cur.eq_ignore_ascii_case(&c.hex())) {
        ui.painter().rect_stroke(r.expand(1.0), 0.0, Stroke::new(2.0, t.accent), egui::StrokeKind::Outside);
    }
    resp.on_hover_text(format!("#{}", c.hex())).clicked()
}

/// A ribbon-style text field with a dropdown list. Returns a chosen/typed value; Enter commits
/// the typed text as is (the font size box relies on that: "1" must not become "10").
pub fn combo(
    ui: &mut Ui,
    id: &str,
    width: f32,
    current: &str,
    items: &[String],
    preview: Option<&dyn Fn(&mut Ui, &str) -> Response>,
) -> Option<String> {
    combo_impl(ui, ComboOptions { id, width, current, items, recent: &[], preview, search: false, tip: "", shown_as: None })
}

/// [`combo`] whose field and arrow show the hover hint `tip` (already translated).
pub fn combo_hint(
    ui: &mut Ui,
    id: &str,
    width: f32,
    current: &str,
    items: &[String],
    preview: Option<&dyn Fn(&mut Ui, &str) -> Response>,
    tip: &str,
) -> Option<String> {
    combo_impl(ui, ComboOptions { id, width, current, items, recent: &[], preview, search: false, tip, shown_as: None })
}

/// What [`font_combo`] returns when its list's last entry, Add Font…, is chosen (#582): the
/// caller runs `font.add`, which shows a file picker. Not a family name anyone can type.
pub const ADD_FONT: &str = "\u{1}font.add";

/// What [`font_combo`] returns when "Load System Installed Fonts…" is chosen on web: the
/// caller runs `font.loadSystem`.
pub const LOAD_SYSTEM_FONTS: &str = "\u{1}font.loadSystem";

/// The font box: a [`combo`] where typing lists the matching families under the field (#359).
/// Its list ends with Add Font… ([`ADD_FONT`]).
/// Up/Down move the highlight, Enter or a click applies the highlighted family ("arial" applies
/// "Arial"), Escape restores the current font. Text matching no family is applied as typed, as
/// Word allows fonts that are not installed.
pub fn font_combo(
    ui: &mut Ui,
    id: &str,
    width: f32,
    current: &str,
    items: &[String],
    preview: Option<&dyn Fn(&mut Ui, &str) -> Response>,
) -> Option<String> {
    combo_impl(ui, ComboOptions { id, width, current, items, recent: &[], preview, search: true, tip: tl!("Font"), shown_as: None })
}

/// [`font_combo`] with the `recent` families (most recent first) in a Recently Used Fonts
/// section above the list, then All Fonts, as in Word (#2068). The sections show when nothing is
/// typed; a query lists its matches only. Up/Down walk the recent entries, then the list; the
/// headings are skipped. A recent font that is no longer installed stays listed and is applied as
/// typed.
pub fn font_combo_with_recent(
    ui: &mut Ui,
    id: &str,
    width: f32,
    current: &str,
    items: &[String],
    recent: &[String],
    preview: Option<&dyn Fn(&mut Ui, &str) -> Response>,
) -> Option<String> {
    combo_impl(ui, ComboOptions { id, width, current, items, recent, preview, search: true, tip: tl!("Font"), shown_as: None })
}

/// [`font_combo_with_recent`] with a hover hint `tip` (already translated). With `shown_as`
/// (the families drawn instead of a `current` font that isn't installed) the box carries a
/// warning mark saying so.
pub struct FontComboOptions<'a> {
    pub id: &'a str,
    pub width: f32,
    pub current: &'a str,
    pub items: &'a [String],
    pub recent: &'a [String],
    pub preview: Option<&'a dyn Fn(&mut Ui, &str) -> Response>,
    pub tip: &'a str,
    pub shown_as: Option<&'a str>,
}

pub fn font_combo_with_recent_hint(ui: &mut Ui, options: FontComboOptions<'_>) -> Option<String> {
    combo_impl(
        ui,
        ComboOptions {
            search: true,
            id: options.id,
            width: options.width,
            current: options.current,
            items: options.items,
            recent: options.recent,
            preview: options.preview,
            tip: options.tip,
            shown_as: options.shown_as,
        },
    )
}

/// The hover note for a font that isn't installed, `shown_as` drawn instead.
fn missing_font_tip(font: &str, shown_as: &str) -> String {
    crate::i18n::fmt(
        tl!(
            "{font} isn't installed on this computer, so its text is shown in {shown}. Line breaks and page count can differ from where the document was made. If you have the font file, add it with Add Font… at the end of this list."
        ),
        &[("font", font), ("shown", shown_as)],
    )
}

struct ComboOptions<'a> {
    id: &'a str,
    width: f32,
    current: &'a str,
    items: &'a [String],
    recent: &'a [String],
    preview: Option<&'a dyn Fn(&mut Ui, &str) -> Response>,
    search: bool,
    tip: &'a str,
    /// See [`FontComboOptions::shown_as`].
    shown_as: Option<&'a str>,
}

/// The arrow's box next to a combo's field: its corner radii and the rectangle it paints, reaching
/// one border width under the field on the side the two meet (the field is left of the arrow in a
/// left-to-right row, right of it in a right-to-left one).
fn arrow_box_shape(rtl: bool, arrow: Rect, r: CornerRadius) -> (CornerRadius, Rect) {
    if rtl {
        (CornerRadius { nw: r.nw, sw: r.sw, ne: 0, se: 0 }, Rect::from_min_max(arrow.min, pos2(arrow.max.x + ARROW_BORDER, arrow.max.y)))
    } else {
        (CornerRadius { nw: 0, sw: 0, ne: r.ne, se: r.se }, Rect::from_min_max(pos2(arrow.min.x - ARROW_BORDER, arrow.min.y), arrow.max))
    }
}

/// Indices of the `items` matching `query`, ignoring case: exact matches, then the names starting
/// with it, then those containing it, each group in list order. A blank query matches everything.
pub fn font_matches(query: &str, items: &[String]) -> Vec<usize> {
    let q = query.trim().to_lowercase();
    if q.is_empty() {
        return (0..items.len()).collect();
    }
    let (mut exact, mut prefix, mut inner) = (Vec::new(), Vec::new(), Vec::new());
    for (i, it) in items.iter().enumerate() {
        let name = it.to_lowercase();
        if name == q {
            exact.push(i);
        } else if name.starts_with(&q) {
            prefix.push(i);
        } else if name.contains(&q) {
            inner.push(i);
        }
    }
    exact.extend(prefix);
    exact.extend(inner);
    exact
}

/// Width of a combo arrow's border, the field's own (the theme's input border is 1 pt).
const ARROW_BORDER: f32 = 1.0;

/// A searching combo's state between frames.
#[derive(Clone, Default)]
struct ComboSearch {
    /// The match list is showing (opened via the arrow button or typing in the field).
    open: bool,
    /// Whether the user has typed or modified the search query.
    typed: bool,
    /// The query `matches` were computed for, and the list length then.
    query: String,
    items_len: usize,
    matches: std::sync::Arc<Vec<usize>>,
    /// Index among the entries: the recent families shown, then `matches`.
    highlight: Option<usize>,
    /// Up or Down moved the highlight since the query last changed.
    moved: bool,
    /// Rows the list drew last frame; 0 while it is hidden.
    rows: usize,
    /// Where the list was drawn last frame, its scroll offset and visible height.
    popup: Option<Rect>,
    offset: f32,
    view_h: f32,
}

/// Selects all characters in the text edit widget with `id`.
///
/// Requires that `text` matches the widget's current content, since only its character
/// count (`text.chars().count()`) is used to define the character selection range `0..len`.
fn select_all_text(ctx: &egui::Context, id: egui::Id, text: &str) {
    if let Some(mut state) = egui::TextEdit::load_state(ctx, id) {
        let all = egui::text::CCursorRange::two(egui::text::CCursor::new(0), egui::text::CCursor::new(text.chars().count()));
        state.cursor.set_char_range(Some(all));
        state.store(ctx, id);
    }
}

/// Squares the inner corners between the text edit field and the dropdown arrow button.
///
/// Zeroes the right corners (`ne`, `se`) in left-to-right layouts or the left corners
/// (`nw`, `sw`) in right-to-left (`rtl`) layouts across all widget visual states
/// (`noninteractive`, `inactive`, `hovered`, `active`, `open`) so the text box and arrow button
/// appear as a unified single border control.
fn square_inner_corners(ui: &mut Ui, rtl: bool) {
    let w = &mut ui.visuals_mut().widgets;
    for v in [&mut w.noninteractive, &mut w.inactive, &mut w.hovered, &mut w.active, &mut w.open] {
        let (a, b) = if rtl { (&mut v.corner_radius.nw, &mut v.corner_radius.sw) } else { (&mut v.corner_radius.ne, &mut v.corner_radius.se) };
        *a = 0;
        *b = 0;
    }
}

/// Consumes Up and Down arrow key events to step through the combo list.
///
/// Only consumes key events when the combo list is `open` and the text edit field `has_focus`.
/// Returns `+1` when ArrowDown was pressed, `-1` when ArrowUp was pressed, or `0` if neither
/// was pressed or if the preconditions were not met.
fn consume_arrow_steps(ui: &mut Ui, open: bool, has_focus: bool) -> i32 {
    let mut step = 0i32;
    if open && has_focus {
        ui.input_mut(|i| {
            if i.consume_key(egui::Modifiers::NONE, egui::Key::ArrowDown) {
                step += 1;
            }
            if i.consume_key(egui::Modifiers::NONE, egui::Key::ArrowUp) {
                step -= 1;
            }
        });
    }
    step
}

/// Handles open/close state transitions, focus, and text selection for searchable combos.
///
/// - `resp`: the text edit field's interaction response.
/// - `aresp`: the dropdown arrow button's interaction response.
/// - `te_id`: the text edit widget ID used to inspect and manipulate focus and selection.
/// - `text`: the current text string in the edit field.
/// - `reveal`: set to `true` when opening or changing search query to scroll the list/highlight into view.
///
/// Clicking the dropdown arrow (`aresp.clicked()`) toggles `s.open`; when opening, it requests focus
/// on `te_id`, resets `typed` and `moved`, sets `*reveal = true`, and selects all text with
/// [`select_all_text`].
/// Changing the text (`resp.changed()`) opens the dropdown with `s.typed = true`, clears `s.highlight`,
/// clears `s.moved`, and sets `*reveal = true`.
/// Gaining focus while closed (`resp.gained_focus() && !was_open`, from an initial click in the field
/// or Tab navigation) selects all text for immediate replacement typing without opening the 420px
/// dropdown popup; subsequent clicks inside the already-focused field and regaining focus while already
/// open (e.g. after interacting with the popup scrollbar) preserve caret placement and query text without
/// re-selecting all.
fn handle_search_interactions(
    ui: &mut Ui,
    s: &mut ComboSearch,
    resp: &egui::Response,
    aresp: &egui::Response,
    te_id: egui::Id,
    text: &str,
    reveal: &mut bool,
) {
    let was_open = s.open;
    if aresp.clicked() {
        if was_open {
            s.open = false;
        } else {
            s.open = true;
            s.typed = false;
            s.moved = false;
            *reveal = true;
            ui.memory_mut(|m| m.request_focus(te_id));
            select_all_text(ui.ctx(), te_id, text);
        }
    } else if resp.changed() {
        s.open = true;
        s.typed = true;
        s.highlight = None;
        s.moved = false;
        *reveal = true;
    } else if resp.gained_focus() && !was_open {
        select_all_text(ui.ctx(), te_id, text);
    }
}

/// Refreshes the filtered list matches and updates keyboard navigation position.
///
/// Operates in one of two modes:
/// - When `s.typed` is `false` (the combo is opened without active typing), resets `s.matches` to
///   the full list of `items` in original order, clears `s.query`, and if `s.moved` is `false`,
///   initializes `s.highlight` to the position of `current` in `recent_shown` or in `items`
///   (offset by `recent_shown.len()`), leaving `s.highlight = None` if `current` is not in either list.
/// - When `s.typed` is `true`, filters `items` matching `text` using [`font_matches`], stores the
///   active `text` in `s.query`, and if `s.moved` is `false`, highlights the first match if any.
///
/// Finally, if `step != 0`, marks `s.moved = true`, adjusts `s.highlight` by `step` (+1 for Down, -1 for Up),
/// and clamps `s.highlight` to the valid range across `recent_shown` and `s.matches`.
fn update_search_matches(s: &mut ComboSearch, text: &str, items: &[String], recent_shown: &[String], current: &str, step: i32) {
    if !s.typed {
        if !s.query.is_empty() || s.matches.len() != items.len() || s.items_len != items.len() {
            s.matches = std::sync::Arc::new((0..items.len()).collect());
            s.query.clear();
            s.items_len = items.len();
        }
        if !s.moved {
            if let Some(pos) = recent_shown.iter().position(|r| r == current) {
                s.highlight = Some(pos);
            } else if let Some(pos) = s.matches.iter().position(|&i| items.get(i).is_some_and(|it| it == current)) {
                s.highlight = Some(recent_shown.len().saturating_add(pos));
            } else {
                s.highlight = None;
            }
        }
    } else if s.query != text || s.items_len != items.len() {
        s.matches = std::sync::Arc::new(font_matches(text, items));
        s.query = text.to_string();
        s.items_len = items.len();
        if !s.moved {
            s.highlight = if s.matches.is_empty() { None } else { Some(0) };
        }
    }
    let total_len = recent_shown.len().saturating_add(s.matches.len());
    if total_len > 0 {
        let last = total_len.saturating_sub(1);
        if step != 0 {
            s.moved = true;
            s.highlight = match (s.highlight, step) {
                (Some(cur), 1..) => Some(cur.saturating_add(step as usize).min(last)),
                (Some(cur), ..=-1) => Some(cur.saturating_sub((-step) as usize)),
                (Some(cur), 0) => Some(cur),
                (None, 1..) => Some(0),
                (None, ..=-1) => Some(last),
                (None, 0) => None,
            };
        }
    } else {
        s.highlight = None;
    }
}

/// Returns the font name at the current highlight index in the combined recent and matched lists.
///
/// If the user has neither typed a query nor moved the highlight via arrow keys (`!s.typed && !s.moved`),
/// or if no item is currently highlighted (`s.highlight` is `None`), the edit field's current `text` is
/// returned as-is so an unchanged or uninstalled font is not replaced. When the text edit box has been
/// cleared (`text.trim().is_empty()`) and the user has not explicitly moved the highlight via arrow keys
/// (`!s.moved`), `text` is returned as-is.
fn pick_highlighted_font(s: &ComboSearch, text: &str, items: &[String], recent_shown: &[String]) -> String {
    if !s.typed && !s.moved {
        return text.to_string();
    }
    let Some(hl) = s.highlight else {
        return text.to_string();
    };
    let picked = recent_shown.get(hl).or_else(|| hl.checked_sub(recent_shown.len()).and_then(|k| s.matches.get(k)).and_then(|&i| items.get(i)));
    match picked {
        Some(name) if !text.trim().is_empty() || s.moved => name.clone(),
        _ => text.to_string(),
    }
}

/// The warning mark at the right end of the field `resp` when its font `current` isn't installed
/// and is drawn in `shown_as`, with its note as the field's description (the note is a hover
/// hint: a screen reader reads it here). Returns the note, for the field's hover.
fn missing_font_mark(ui: &Ui, resp: &egui::Response, current: &str, shown_as: Option<&str>, t: &Tokens) -> Vec<String> {
    let Some(shown) = shown_as else { return Vec::new() };
    let r = Rect::from_center_size(pos2(resp.rect.right() - 9.0, resp.rect.center().y), vec2(12.0, 12.0));
    icons::paint(ui.painter(), r, "fontMissing", t.icon, t.accent);
    let note = missing_font_tip(current, shown);
    ui.ctx().accesskit_node_builder(resp.id, |n| n.set_description(note.as_str()));
    vec![note]
}

/// Draws an editable or searchable combo box: keeps temporary text and search state, supports
/// keyboard selection, popup rows with recent and preview sections, an arrow and hint, and
/// returns the chosen or committed text.
fn combo_impl(ui: &mut Ui, options: ComboOptions<'_>) -> Option<String> {
    let ComboOptions { id, width, current, items, recent, preview, search, tip, shown_as } = options;
    let mut out = None;
    let edit_id = ui.scope_id().with(("combo_text", id));
    let te_id = ui.scope_id().with(("combo_edit", id));
    let search_id = ui.scope_id().with(("combo_search", id));
    let mut text = ui.data_mut(|d| d.get_temp::<String>(edit_id)).unwrap_or_else(|| current.to_string());
    let mut s: ComboSearch = if search { ui.data_mut(|d| d.get_temp(search_id)).unwrap_or_default() } else { ComboSearch::default() };
    let mut focused = false;
    let mut cancelled = false;
    let t = Tokens::get(ui.ctx());
    ui.horizontal(|ui| {
        ui.spacing_mut().item_spacing = vec2(0.0, 0.0);
        // The field and its arrow share one outline: rounded on the outside, square where they
        // meet. The field's frame takes the widget visuals' radius in every state. In a row that
        // runs right to left the arrow comes after the field on its left, so the corners and the
        // arrow's underlap are the mirror image.
        let rtl = ui.layout().prefer_right_to_left();
        let r = ui.visuals().widgets.inactive.corner_radius;
        square_inner_corners(ui, rtl);
        // Up/Down move the list's highlight: take them before the text field moves its cursor.
        let step = consume_arrow_steps(ui, s.open, ui.memory(|m| m.has_focus(te_id)));
        // A font that isn't installed: room at the field's right end for the warning mark.
        let mark = shown_as.filter(|_| !current.is_empty());
        let right = if mark.is_some() { 18 } else { 4 };
        let te = egui::TextEdit::singleline(&mut text).id(te_id).desired_width(width - 16.0).font(regular(12.0)).margin(egui::Margin {
            left: 4,
            right,
            top: 3,
            bottom: 3,
        });
        // The arrow's box is painted here, under the field, once its size is known.
        let arrow_bg = ui.painter().add(egui::Shape::Noop);
        let resp = ui.add(te);
        let (ar, aresp) = ui.allocate_exact_size(vec2(16.0, resp.rect.height()), Sense::click());
        // The field says what it is: without a name a screen reader has only "edit" to say
        // (#3172). The arrow says whose options it opens, as the split buttons' arrow does.
        if !tip.is_empty() {
            resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::TextInput, ui.is_enabled(), tip));
        }
        let notes = missing_font_mark(ui, &resp, current, mark, &t);
        keytip_badge(ui, resp.rect, "combo", id);
        focused = resp.has_focus();
        let enter = resp.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter));
        let mut reveal = step != 0;
        if search {
            handle_search_interactions(ui, &mut s, &resp, &aresp, te_id, &text, &mut reveal);
        }
        // The recent section keeps its order while the list stays open: a pick moves the family to
        // the top for the next time the list opens, not under the pointer.
        let frozen_id = search_id.with("recent_frozen");
        let menu_recent: Vec<String> = ui.data(|d| d.get_temp(frozen_id)).unwrap_or_else(|| recent.to_vec());
        // The recent section shows while nothing is typed; a query lists its matches only.
        let recent_shown: &[String] = if !s.typed || text.trim().is_empty() { &menu_recent } else { &[] };
        let mut regain_focus = false;
        let list_id = search_id.with("list");
        if s.open {
            egui::Popup::open_id(ui.ctx(), list_id);
            update_search_matches(&mut s, &text, items, recent_shown, current, step);
            if enter {
                out = Some(pick_highlighted_font(&s, &text, items, recent_shown));
                s.open = false;
            } else if ui.input(|i| i.key_pressed(egui::Key::Escape) || i.key_pressed(egui::Key::Tab)) {
                s.open = false;
                cancelled = true;
                ui.memory_mut(|m| m.surrender_focus(te_id));
            } else if !focused && !aresp.clicked() {
                let over = ui.input(|i| i.pointer.latest_pos()).is_some_and(|p| s.popup.is_some_and(|r| r.contains(p)));
                if over {
                    regain_focus = true;
                } else {
                    s.open = false;
                }
            }
        } else if enter {
            out = Some(text.clone());
        }
        if !s.open {
            egui::Popup::close_id(ui.ctx(), list_id);
        }
        if !tip.is_empty() {
            let arrow_name = crate::i18n::fmt(tl!("{name} options"), &[("name", tip)]);
            aresp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), &arrow_name));
        }
        // It reaches one border width under the field, so the field's right border is the only line
        // between them: two borders side by side read as a double-width divider.
        let (ar_radius, under) = arrow_box_shape(rtl, ar, r);
        let fill = if aresp.hovered() { t.hover } else { t.input };
        let arrow_box = egui::epaint::RectShape::new(under, ar_radius, fill, Stroke::new(ARROW_BORDER, t.input_border), egui::StrokeKind::Inside);
        ui.painter().set(arrow_bg, arrow_box);
        // Not while typing: the family list drops from the field's bottom edge and the hint would cover it.
        // A field only focused by Tab, with nothing typed, still gets its (delayed) keyboard hint.
        let typing = focused && text != current;
        if !tip.is_empty() && !typing && !s.open {
            show_hint(&resp, tip, &notes);
            show_hint(&aresp, tip, &notes);
        }
        icons::paint(ui.painter(), Rect::from_center_size(ar.center(), vec2(DROPDOWN, DROPDOWN)), "dropdown", t.icon, t.accent);
        if !search {
            let close = egui::PopupCloseBehavior::CloseOnClick;
            let mut menu_field = aresp.clone();
            menu_field.rect = resp.rect.union(ar);
            let menu = craft_ui::combo::Menu::new(ui, &menu_field).close_behavior(close).height(420.0);
            let row_h = if preview.is_some() { COMBO_PREVIEW_ROW_H } else { ui.spacing().interact_size.y };
            let item = |k: usize| items.get(k);
            let row = |k: usize| section_row(k, &[], &item);
            let total = section_rows(0, items.len());
            let list = |ui: &mut Ui, range: std::ops::Range<usize>, ()| {
                let picked =
                    draw_rows(ui, RowDrawOptions { width, current, range, row: &row, highlight: None, preview, row_height: row_h, recent_rows: 0 });
                if picked.is_some() {
                    ui.close();
                }
                picked
            };
            let picked = menu.show_rows_with_header(|_| (), row_h, |()| total, list).flatten();
            if let Some(v) = picked {
                out = Some(v);
            }
        }
        ui.data_mut(|d| {
            if s.open {
                d.insert_temp(frozen_id, menu_recent.clone());
            } else {
                d.remove::<Vec<String>>(frozen_id);
            }
        });
        let n = section_rows(recent_shown.len(), s.matches.len());
        if s.open && n > 0 {
            let matches = s.matches.clone();
            let scroll = reveal.then_some((s.offset, s.view_h));
            let lit = s.highlight.map(|hl| highlight_row(hl, recent_shown.len()));
            // A list of a new length is sized again (an area keeps its last size, so a list that
            // once held one match stayed one row tall). That pass draws nothing, so it is
            // discarded and the frame drawn again, as egui does for its own sizing passes.
            let list_id = search_id.with("list");
            let resize = n != s.rows;
            if resize || egui::AreaState::load(ui.ctx(), list_id).is_none() {
                ui.ctx().request_discard("font list resized");
            }
            s.rows = n;
            let area = egui::Area::new(list_id).order(egui::Order::Tooltip).fixed_pos(resp.rect.left_bottom()).sizing_pass(resize);
            let shown = area.show(ui.ctx(), |ui| {
                egui::Frame::popup(ui.style())
                    .show(ui, |ui| {
                        let item = |k: usize| matches.get(k).and_then(|&i| items.get(i));
                        let row = |k: usize| section_row(k, recent_shown, &item);
                        let (mut picked, offset, view_h) = list_rows(
                            ui,
                            RowListOptions { width, current, n, row: &row, highlight: lit, scroll, preview, recent_rows: recent_shown.len() },
                        );
                        if !s.typed {
                            ui.separator();
                            if ui.button(tl!("Add Font…")).clicked() {
                                picked = Some(ADD_FONT.to_string());
                            }
                            #[cfg(target_arch = "wasm32")]
                            if ui.button(tl!("Load System Installed Fonts…")).clicked() {
                                picked = Some(LOAD_SYSTEM_FONTS.to_string());
                            }
                        }
                        (picked, offset, view_h)
                    })
                    .inner
            });
            s.popup = Some(shown.response.rect);
            let (picked, offset, view_h) = shown.inner;
            (s.offset, s.view_h) = (offset, view_h);
            if let Some(v) = picked {
                out = Some(v);
                s.open = false;
                regain_focus = false;
                ui.memory_mut(|m| m.surrender_focus(te_id));
            }
        } else {
            s.popup = None;
            s.rows = 0;
        }
        if regain_focus && s.open {
            ui.memory_mut(|m| m.request_focus(te_id));
        }
    });
    let keep = (focused || s.open) && out.is_none() && !cancelled;
    ui.data_mut(|d| {
        if keep {
            d.insert_temp(edit_id, text);
        } else {
            d.remove::<String>(edit_id);
        }
        if search {
            d.insert_temp(search_id, s);
        }
    });
    out
}

/// Height of a row drawn by a combo's preview closure (`Previews::font_preview_fn`'s entries).
pub const COMBO_PREVIEW_ROW_H: f32 = 24.0;

/// A combo's scrolling list. Only the rows in view are built: the font menu lists every installed
/// family and each preview loads that font, so building all rows loaded every font on the system
/// (gigabytes on large font collections) and froze the app (#121).
pub fn combo_list(ui: &mut Ui, width: f32, current: &str, items: &[String], preview: Option<&dyn Fn(&mut Ui, &str) -> Response>) -> Option<String> {
    list_rows(
        ui,
        RowListOptions {
            width,
            current,
            n: items.len(),
            row: &|k| items.get(k).map(Row::Item),
            highlight: None,
            scroll: None,
            preview,
            recent_rows: 0,
        },
    )
    .0
}

/// A row of a combo's list: a dim section heading nothing picks, or an entry.
pub(super) enum Row<'a> {
    Heading(&'a str),
    Item(&'a String),
}

/// Rows in a list of `n` entries headed by `recent` recent ones: the two headings and the recent
/// entries come on top when there are any.
pub(super) fn section_rows(recent: usize, n: usize) -> usize {
    if recent == 0 { n } else { n.saturating_add(recent).saturating_add(2) }
}

/// Row `k` of a list headed by the `recent` families: Recently Used Fonts, those families, All
/// Fonts, then `item(0..)`. Without recent families the rows are the items.
pub(super) fn section_row<'a>(k: usize, recent: &'a [String], item: &dyn Fn(usize) -> Option<&'a String>) -> Option<Row<'a>> {
    if recent.is_empty() {
        return item(k).map(Row::Item);
    }
    if k == 0 {
        return Some(Row::Heading(tl!("Recently Used Fonts")));
    }
    if let Some(r) = recent.get(k.saturating_sub(1)) {
        return Some(Row::Item(r));
    }
    if k == recent.len().saturating_add(1) {
        return Some(Row::Heading(tl!("All Fonts")));
    }
    item(k.saturating_sub(recent.len()).saturating_sub(2)).map(Row::Item)
}

/// The row of entry `entry` in a list headed by `recent` recent families ([`section_row`]).
pub(super) fn highlight_row(entry: usize, recent: usize) -> usize {
    if recent == 0 {
        entry
    } else if entry < recent {
        entry.saturating_add(1)
    } else {
        entry.saturating_add(2)
    }
}

/// A section heading's row of `size`: dim text, a rule across the list above it after the
/// first row, nothing to click. The row asks for no more than `size`: the list's width is its
/// entries' (a sizing pass offers an unbounded width).
fn heading_row(ui: &mut Ui, text: &str, size: egui::Vec2, rule: bool) {
    let weak = ui.visuals().weak_text_color();
    let line = ui.visuals().widgets.noninteractive.bg_stroke;
    if rule {
        ui.painter().hline(ui.max_rect().x_range(), ui.cursor().top(), line);
    }
    ui.allocate_ui_with_layout(size, egui::Layout::left_to_right(egui::Align::Center), |ui| {
        ui.set_min_size(size);
        ui.add_space(6.0);
        ui.add(egui::Label::new(egui::RichText::new(text).small().color(weak)).selectable(false));
    });
}

/// The rows `range` of a combo's list, in `ui`'s scroll area. Returns the clicked item.
struct RowDrawOptions<'rows, 'text> {
    width: f32,
    current: &'text str,
    range: std::ops::Range<usize>,
    row: &'rows dyn Fn(usize) -> Option<Row<'text>>,
    highlight: Option<usize>,
    preview: Option<&'rows dyn Fn(&mut Ui, &str) -> Response>,
    row_height: f32,
    /// How many recent families head the list (0 without the section).
    recent_rows: usize,
}

fn draw_rows(ui: &mut Ui, options: RowDrawOptions<'_, '_>) -> Option<String> {
    let RowDrawOptions { width, current, range, row, highlight, preview, row_height: row_h, recent_rows } = options;
    let mut out = None;
    let tokens = Tokens::get(ui.ctx());
    let (fill, accent) = (tokens.checked, tokens.accent);
    ui.set_min_width(width + 60.0);
    // A family in Recently Used is marked there only: marked again under All Fonts it would look as
    // if two were chosen.
    let current_is_recent = (1..=recent_rows).any(|k| matches!(row(k), Some(Row::Item(r)) if r == current));
    for k in range {
        let it = match row(k) {
            Some(Row::Item(it)) => it,
            Some(Row::Heading(h)) => {
                heading_row(ui, h, vec2(width + 60.0, row_h), k > 0);
                continue;
            }
            None => continue,
        };
        let lit = highlight == Some(k);
        let clicked = match preview {
            Some(p) => {
                if lit {
                    let r = Rect::from_min_size(ui.cursor().min, vec2(ui.available_width(), row_h));
                    ui.painter().rect_filled(r, 3.0, fill);
                }
                let in_all_fonts = recent_rows > 0 && k > recent_rows.saturating_add(1);
                if it == current && !(in_all_fonts && current_is_recent) {
                    let r = Rect::from_min_size(ui.cursor().min, vec2(ui.available_width(), row_h));
                    ui.painter().rect_filled(r, 3.0, fill);
                    ui.painter().rect_filled(Rect::from_min_size(r.min, vec2(3.0, row_h)), 1.5, accent);
                }
                let resp = p(ui, it);
                if resp.hovered() {
                    note_hover(ui.ctx(), it.clone());
                }
                resp.clicked()
            }
            None => {
                let resp = ui.selectable_label(if highlight.is_some() { lit } else { it == current }, it.as_str());
                if resp.hovered() {
                    note_hover(ui.ctx(), it.clone());
                }
                resp.clicked()
            }
        };
        if clicked {
            out = Some(it.clone());
        }
    }
    out
}

/// The rows of [`combo_list`], virtualised, for `n` rows fetched by index. With a `highlight`
/// that row is marked instead of `current`; `scroll` (last frame's offset and visible height)
/// scrolls the highlight into view. Returns the clicked item, the scroll offset and the height.
struct RowListOptions<'rows, 'text> {
    width: f32,
    current: &'text str,
    n: usize,
    row: &'rows dyn Fn(usize) -> Option<Row<'text>>,
    highlight: Option<usize>,
    scroll: Option<(f32, f32)>,
    preview: Option<&'rows dyn Fn(&mut Ui, &str) -> Response>,
    recent_rows: usize,
}

fn list_rows(ui: &mut Ui, options: RowListOptions<'_, '_>) -> (Option<String>, f32, f32) {
    let RowListOptions { width, current, n, row, highlight, scroll, preview, recent_rows } = options;
    let mut out = None;
    let row_h = if preview.is_some() { COMBO_PREVIEW_ROW_H } else { ui.spacing().interact_size.y };
    let desired_h = (n as f32 * (row_h + ui.spacing().item_spacing.y)).min(420.0);
    ui.set_min_height(desired_h);
    let mut area = egui::ScrollArea::vertical().max_height(desired_h);
    if let (Some(h), Some((offset, view_h))) = (highlight, scroll) {
        let top = h as f32 * (row_h + ui.spacing().item_spacing.y);
        let bottom = top + row_h;
        let offset = if view_h <= 0.0 {
            // No list was visible for the previous query. Start at the first row, including
            // its heading, rather than scrolling to the first selectable entry below it.
            0.0
        } else if top < offset {
            top
        } else if bottom > offset + view_h {
            bottom - view_h
        } else {
            offset
        };
        area = area.vertical_scroll_offset(offset.max(0.0));
    }
    let shown = area.show_rows(ui, row_h, n, |ui, range| {
        if let Some(v) = draw_rows(ui, RowDrawOptions { width, current, range, row, highlight, preview, row_height: row_h, recent_rows }) {
            out = Some(v);
        }
    });
    (out, shown.state.clamped_offset().y, shown.inner_rect.height())
}

/// How a drawn button looks this frame. Hover fades in over egui's animation time and the
/// pressed state blends in while the pointer is down, as on egui's own buttons. Framed buttons
/// take egui's widget visuals (fill, stroke, text colour, expansion) so they match `ui.button`;
/// frameless ones take the ribbon's hover/pressed tokens, like [`small`] and [`big`]. With
/// animation effects off (egui's animation time is zero) both states show at once.
pub struct DrawnState {
    pub fill: Color32,
    pub stroke: Stroke,
    pub text: Color32,
    pub expansion: f32,
}

pub fn drawn_state(ui: &Ui, resp: &Response, framed: bool) -> DrawnState {
    let pressed = resp.is_pointer_button_down_on();
    let h = ui.ctx().animate_bool_responsive(resp.id.with("hover"), resp.hovered() || pressed);
    let p = ui.ctx().animate_bool_with_time(resp.id.with("press"), pressed, ui.style().animation_time.min(0.06));
    if framed {
        let w = &ui.visuals().widgets;
        let mix = |a: Color32, b: Color32, c: Color32| a.lerp_to_gamma(b, h).lerp_to_gamma(c, p);
        let num = |a: f32, b: f32, c: f32| egui::lerp(egui::lerp(a..=b, h)..=c, p);
        DrawnState {
            fill: mix(w.inactive.weak_bg_fill, w.hovered.weak_bg_fill, w.active.weak_bg_fill),
            stroke: Stroke::new(
                num(w.inactive.bg_stroke.width, w.hovered.bg_stroke.width, w.active.bg_stroke.width),
                mix(w.inactive.bg_stroke.color, w.hovered.bg_stroke.color, w.active.bg_stroke.color),
            ),
            text: mix(w.inactive.fg_stroke.color, w.hovered.fg_stroke.color, w.active.fg_stroke.color),
            expansion: num(w.inactive.expansion, w.hovered.expansion, w.active.expansion),
        }
    } else {
        let t = Tokens::get(ui.ctx());
        DrawnState {
            fill: Color32::TRANSPARENT.lerp_to_gamma(t.hover, h).lerp_to_gamma(t.pressed, p),
            stroke: Stroke::NONE,
            text: t.text,
            expansion: 0.0,
        }
    }
}

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

    /// The arrow's box fuses with its field on the side they meet: in a left-to-right row the
    /// arrow is right of the field (rounded on the right, painted one border under the field's
    /// right edge), in a right-to-left row it is left of it (rounded on the left, under the
    /// field's left edge).
    #[test]
    fn the_arrow_box_is_rounded_away_from_its_field() {
        let arrow = Rect::from_min_max(pos2(100.0, 0.0), pos2(116.0, 20.0));
        let r = CornerRadius::same(4);
        let (ltr, under) = arrow_box_shape(false, arrow, r);
        assert_eq!((ltr.nw, ltr.sw, ltr.ne, ltr.se), (0, 0, 4, 4));
        assert_eq!((under.min.x, under.max.x), (100.0 - ARROW_BORDER, 116.0));
        let (rtl, under) = arrow_box_shape(true, arrow, r);
        assert_eq!((rtl.nw, rtl.sw, rtl.ne, rtl.se), (4, 4, 0, 0));
        assert_eq!((under.min.x, under.max.x), (100.0, 116.0 + ARROW_BORDER));
    }
}