GitCorner

Code

ossartcraftgridcraft๐ŸŒ
1687a9c05b0c
use gridcraft_engine::model::{ObjKind, ObjRef};

use super::editor::validation_arrow;
use super::geo::Geo;
use super::keyboard::keyboard;
use super::menus::set_fill_tag;
use super::selection::select_ranges;
use super::tables::{is_filter_button, table_headings};
use super::{
    CellRef, Color32, CursorIcon, Drag, EditState, MAX_COLS, MAX_ROWS, Painter, Pos2, RangeRef, Rect, Sheet, SheetApp, Stroke, Tokens, Workbook,
    json, pos2, vec2,
};

// ------------------------------------------------------------------ interaction

struct InteractionInput<'a> {
    ui: &'a mut egui::Ui,
    response: &'a egui::Response,
    geo: &'a Geo,
    sheet: &'a Sheet,
    workbook: &'a Workbook,
    context: egui::Context,
    press_origin: Option<Pos2>,
    any_pointer_down: bool,
    modifiers: egui::Modifiers,
    position: Option<Pos2>,
    primary_clicked: bool,
    in_cells: bool,
    in_column_header: bool,
    in_row_header: bool,
    in_corner: bool,
    selection: gridcraft_engine::Selection,
    current_rect: Rect,
    handle: Rect,
    handle_panes: Vec<Rect>,
    border_panes: Vec<Rect>,
    freeze_columns: Rect,
    freeze_rows: Rect,
}

impl InteractionInput<'_> {
    fn on_handle(&self, p: Pos2) -> bool {
        self.handle.contains(p) && self.handle_panes.iter().any(|r| r.contains(p))
    }

    fn on_current_border(&self, p: Pos2) -> bool {
        on_border(self.current_rect, p) && self.border_panes.iter().any(|r| r.contains(p))
    }
}

pub(super) fn interact(app: &mut SheetApp, ui: &mut egui::Ui, resp: &egui::Response, geo: &Geo, sh: &Sheet, wb: &Workbook) {
    // Text selection and editing must not also move the object or edit worksheet cells.
    if app.text_box_editor.is_some() || app.grid.hf_edit.is_some() {
        return;
    }
    let ctx = ui.ctx().clone();
    // Enter/Space synthesize egui clicks; only real pointer clicks use sheet coordinates.
    let primary_clicked = resp.clicked_by(egui::PointerButton::Primary);
    let pointer = ctx.input(|i| i.pointer.clone());
    let mods = ctx.input(|i| i.modifiers);
    // Hit-testing works in logical coordinates (see `Geo::rtl`).
    let pos = pointer.interact_pos().or(pointer.hover_pos()).map(|p| geo.mirror_pos(p));
    let in_cells = pos.is_some_and(|p| geo.in_cells(p));
    let in_col_header = pos.is_some_and(|p| p.y < geo.cells.top() && p.y >= geo.head_top() && p.x >= geo.cells.left());
    let in_row_header = pos.is_some_and(|p| p.x < geo.cells.left() && p.x >= geo.head_left() && p.y >= geo.cells.top());
    let in_corner = pos.is_some_and(|p| p.x < geo.cells.left() && p.y < geo.cells.top() && p.x >= geo.head_left() && p.y >= geo.head_top());
    // Insert โ€บ Controls places a control; a click works a form control (Ctrl or Cmd+click, or a
    // right-click, selects it instead).
    if app.editor.is_none() && crate::control_ui::place(app, ui, resp, geo, sh) {
        return;
    }
    if app.editor.is_none() && app.session.draw_tool.is_empty() && crate::form_controls::interact(app, &ctx, resp, geo, sh) {
        keyboard(app, &ctx, resp, geo, sh);
        return;
    }
    let sel = app.session.active().map(|d| d.selection.clone()).unwrap_or_default();
    let cur_rect = geo.range_rect(sh, sel.current());
    let handle = Rect::from_center_size(cur_rect.right_bottom(), vec2(9.0, 9.0));
    // The fill handle and the move border only react in the panes where they are painted, not
    // over the frozen rows/columns that a scrolled selection lies under.
    let handle_panes = geo.range_panes(RangeRef::cell(sel.current().end));
    let border_panes = geo.range_panes(sel.current());
    let (freeze_cols, freeze_rows) = freeze_handles(geo);
    let input = InteractionInput {
        ui,
        response: resp,
        geo,
        sheet: sh,
        workbook: wb,
        context: ctx.clone(),
        press_origin: pointer.press_origin(),
        any_pointer_down: pointer.any_down(),
        modifiers: mods,
        position: pos,
        primary_clicked,
        in_cells,
        in_column_header: in_col_header,
        in_row_header,
        in_corner,
        selection: sel.clone(),
        current_rect: cur_rect,
        handle,
        handle_panes,
        border_panes,
        freeze_columns: freeze_cols,
        freeze_rows,
    };
    if handle_draw_tool(app, &input) {
        return;
    }
    // A plain click on a slicer value tile toggles it (Ctrl/Cmd for multi-select); the clear
    // button resets it. Runs before the generic object select/drag so tiles stay clickable, but
    // only when the slicer is what the press lands on: a form control over a tile (Ctrl or
    // Cmd+clicked, or clicked while selected, so `form_controls::interact` left the click) and a
    // selected object's handle keep the generic path, which selects, moves or resizes them.
    if primary_clicked
        && !resp.drag_started()
        && let Some(p) = pos
        && object_under(app, geo, sh, p).is_some_and(|(o, _, handle)| o.kind == ObjKind::Slicer && handle.is_none())
        && let Some((id, act)) = crate::chartview::slicer_click(geo, sh, wb, wb.active_sheet(), p)
    {
        app.selected_object = Some(ObjRef::new(ObjKind::Slicer, id));
        match act {
            crate::chartview::SlicerAction::Toggle(value) => {
                let _ = app.run("slicer.toggle", json!({"slicer": id, "value": value, "multi": mods.command || mods.ctrl}));
            }
            crate::chartview::SlicerAction::Clear => {
                let _ = app.run("slicer.clear", json!({"slicer": id}));
            }
        }
        return;
    }
    // Objects (charts, pictures, shapes, slicers) take clicks first. Only the primary button moves
    // them: a right-click that wobbles into a drag still opens the object's menu (#2067).
    let primary_drag = resp.drag_started_by(egui::PointerButton::Primary);
    if primary_drag || primary_clicked {
        // A drag is recognised only after the pointer has moved, so grab the object where the press began.
        let at = if primary_drag { pointer.press_origin().map(|p| geo.mirror_pos(p)).or(pos) } else { pos };
        if primary_drag
            && let Some(p) = at
            && let Some((obj, rect)) = crate::chartview::selected_rotate(app, geo, sh, p)
        {
            app.grid.drag = Drag::Rotate { obj, rect, stepped: false };
            return;
        }
        // The selected object's handles reach a little outside it, so they win over hit-testing.
        // Only they resize: a press anywhere on another object selects and moves it, as the
        // hover cursor shows.
        let under = at.and_then(|p| object_under(app, geo, sh, p));
        let handle = under.and_then(|(.., h)| h);
        if let Some(p) = at
            && let Some((obj, _, _)) = under
        {
            app.selected_object = Some(obj);
            if resp.double_clicked() && app.open_object(obj) != crate::objects::OpenAction::Select {
                return;
            }
            if primary_drag && let Some(a) = sh.object_anchor(obj) {
                app.grid.drag = Drag::Object { obj, start: p, orig: (a.cell, a.dx, a.dy, a.width, a.height), handle, stepped: false };
                // The first recognised drag frame already holds movement away from the press.
                if let Some(now) = pos {
                    drag_object(app, geo, sh, now);
                }
            }
            return;
        }
        // A corner of the selected chart's values outline drags the block the chart plots
        // (#4389); a click on it keeps the chart selected.
        if let Some(p) = at
            && app.editor.is_none()
            && let Some((chart, orig, corner)) = crate::chartview::chart_data_handle(app, geo, sh, p)
        {
            if primary_drag {
                app.grid.drag = Drag::ChartData { chart, orig, corner, to: None };
                if let Some(now) = pos {
                    drag_chart_data(app, geo, sh, now);
                }
            }
            return;
        }
        app.selected_object = None;
    }
    // A right-click on a chart, picture, shape, slicer or form control opens the object's menu, not
    // the cell's under it; a right press that wobbles into a drag counts too (#2067). On a form
    // control it selects the control without running it.
    let secondary_drag = resp.drag_started_by(egui::PointerButton::Secondary);
    if (resp.secondary_clicked() || secondary_drag)
        && let Some(p) = if secondary_drag { pointer.press_origin().map(|p| geo.mirror_pos(p)).or(pos) } else { pos }
        && let Some((obj, _)) = crate::chartview::hit(app, geo, sh, p)
    {
        app.selected_object = Some(obj);
        if obj.kind == ObjKind::Control {
            app.grid.focused_control = None;
        }
        app.grid.object_menu = Some((geo.mirror_pos(p), obj.kind.name(), obj.id));
        return;
    }

    if handle_header_autofit(app, &input) {
        return;
    }

    // Double-click the fill handle: a double-click is also a click, so run it before the handle press returns.
    if resp.double_clicked()
        && let Some(p) = pos
        && input.on_handle(p)
    {
        // Fill down as far as the neighbouring column goes.
        let src = sel.current();
        let neighbour = if src.start.col > 0 { src.start.col - 1 } else { src.end.col + 1 };
        let cap = src.end.row.saturating_add(1_000_000).min(MAX_ROWS - 1);
        let last = if src.end.row < cap { sh.last_contiguous_nonempty(neighbour, src.end.row + 1, cap) } else { src.end.row };
        if last > src.end.row {
            let target = RangeRef::new(src.start, CellRef::new(last, src.end.col));
            let _ = app.run("edit.autoFill", json!({"source": src.a1(), "target": target.a1()}));
        }
        app.grid.drag = Drag::None;
        app.grid.drag_select = false;
        resp.request_focus();
        return;
    }

    // Press: choose the interaction mode before pointer movement is applied.
    if resp.drag_started() || (primary_clicked && app.grid.drag == Drag::None) {
        handle_press(app, &input);
        return;
    }

    handle_dragging(app, &input);

    handle_release(app, &input);

    handle_context_menu_and_keyboard(app, &input);
}

fn handle_draw_tool(app: &mut SheetApp, input: &InteractionInput<'_>) -> bool {
    let (in_cells, pos, resp, geo, sh, primary_clicked) =
        (input.in_cells, input.position, input.response, input.geo, input.sheet, input.primary_clicked);
    let ctx = input.context.clone();
    if !app.session.draw_tool.is_empty() && in_cells {
        ctx.set_cursor_icon(CursorIcon::Crosshair);
        if app.session.draw_tool == "pen" {
            if let Some(p) = pos
                && resp.dragged()
            {
                // Through the cell under the pointer, so frozen panes and pages map right.
                let c = geo.cell_at(sh, p);
                let sx = sh.col_left(c.col) as f32 + (p.x - geo.x(sh, c.col)) / geo.z;
                let sy = sh.row_top(c.row) as f32 + (p.y - geo.y(sh, c.row)) / geo.z;
                app.grid.ink.push([sx, sy]);
            }
            if !app.grid.ink.is_empty() {
                // Live preview.
                let pts: Vec<Pos2> = app
                    .grid
                    .ink
                    .iter()
                    .map(|q| {
                        let (col, row) = (sh.col_at(q[0].max(0.0) as f64), sh.row_at(q[1].max(0.0) as f64));
                        geo.mirror_pos(pos2(
                            geo.x(sh, col) + (q[0] - sh.col_left(col) as f32) * geo.z,
                            geo.y(sh, row) + (q[1] - sh.row_top(row) as f32) * geo.z,
                        ))
                    })
                    .collect();
                // The line under the pointer is the ink the stroke will commit (#1786).
                let theme = app.session.active().map(|d| d.wb.theme.clone()).unwrap_or_default();
                let (color, width) = pen_ink(&app.session.draw_color, app.session.draw_width, &theme);
                input.ui.painter().add(egui::epaint::PathShape::line(pts, egui::epaint::PathStroke::new(width * geo.z, color)));
            }
            if resp.drag_stopped() && app.grid.ink.len() >= 2 {
                let pts: Vec<[f32; 2]> = std::mem::take(&mut app.grid.ink);
                let _ = app.run("draw.stroke", json!({"points": pts}));
            }
            return true;
        }
        if app.session.draw_tool == "eraser" && (primary_clicked || resp.dragged()) {
            if let Some(p) = pos
                && let Some((ObjRef { kind: ObjKind::Shape, id }, _)) = crate::chartview::hit(app, geo, sh, p)
                && sh.shapes.iter().any(|s| s.id == id && s.kind == gridcraft_engine::model::ShapeKind::Ink)
            {
                let _ = app.run("object.delete", json!({"kind": "shape", "id": id}));
            }
            return true;
        }
    }
    false
}

/// The colour and width (points) of the ink a pen stroke commits, as `draw.stroke` stores it (the
/// pen's colour, pen blue by default; its width, 2 pt by default, kept to 0.5โ€“40 pt and stored
/// whole) and as Ink shapes paint it (a highlighter, over 8 pt, is translucent).
pub(crate) fn pen_ink(color: &str, width: f32, theme: &gridcraft_engine::model::Theme) -> (Color32, f32) {
    let pen_blue = gridcraft_engine::model::Color::rgb(0x1F, 0x5F, 0xC9);
    let line = gridcraft_engine::model::Color::from_hex(color).unwrap_or(pen_blue);
    let width = if width <= 0.0 { 2.0 } else { width }.clamp(0.5, 40.0).round().max(1.0);
    let color = line.resolve(theme).map(crate::theme::color32).unwrap_or(Color32::from_rgb(0x1F, 0x5F, 0xC9));
    (crate::chartview::ink_color(color, width), width)
}

fn handle_header_autofit(app: &mut SheetApp, input: &InteractionInput<'_>) -> bool {
    let (geo, sh, sel, pos) = (input.geo, input.sheet, &input.selection, input.position);
    let (in_col_header, in_row_header) = (input.in_column_header, input.in_row_header);
    let resp = input.response;
    if !resp.double_clicked() {
        return false;
    }
    let Some(p) = pos else { return false };

    let unhide = if in_col_header {
        hidden_col_edge(geo, sh, p.x).map(|col| ("home.unhideColumns", json!({"cols": RangeRef::cols(col, col).a1()})))
    } else if in_row_header {
        hidden_row_edge(geo, sh, p.y).map(|row| ("home.unhideRows", json!({"rows": RangeRef::rows(row, row).a1()})))
    } else {
        None
    };
    let autofit = if unhide.is_some() {
        unhide
    } else if in_col_header {
        col_edge(geo, sh, p.x).map(|(col, _)| {
            let selected = sel.ranges.iter().any(|r| r.is_full_cols() && col >= r.start.col && col <= r.end.col);
            ("home.autofitColumnWidth", if selected { json!({}) } else { json!({"cols": RangeRef::cols(col, col).a1()}) })
        })
    } else if in_row_header {
        row_edge(geo, sh, p.y).map(|(row, _)| {
            let selected = sel.ranges.iter().any(|r| r.is_full_rows() && row >= r.start.row && row <= r.end.row);
            ("home.autofitRowHeight", if selected { json!({}) } else { json!({"rows": RangeRef::rows(row, row).a1()}) })
        })
    } else {
        None
    };
    if let Some((command, params)) = autofit {
        app.grid.drag = Drag::None;
        app.grid.drag_select = false;
        app.run_or_alert(command, params);
        resp.request_focus();
        return true;
    }
    false
}

fn handle_column_header_press(app: &mut SheetApp, input: &InteractionInput<'_>, p: Pos2) {
    let (geo, sh, wb, sel) = (input.geo, input.sheet, input.workbook, &input.selection);
    let mods = input.modifiers;
    let resp = input.response;
    let in_col_header = input.in_column_header;
    if in_col_header {
        if let Some((c, x)) = col_edge(geo, sh, p.x) {
            begin_resize(app);
            app.grid.drag = Drag::ResizeCol { col: c, start: p.x, orig: sh.col_width(c).max(0.0) * 0.0 + (x - geo.x(sh, c)) / geo.z, to: None };
            return;
        }
        let c = geo.col_at(sh, p.x);
        // A Table heading's filter button, while the header names stand in for the letters.
        if let Some(h) = table_headings(geo, sh, sel.active).into_iter().find(|h| h.col == c && h.button.is_some_and(|b| b.contains(p))) {
            app.grid.filter_menu = Some((c, h.header_row, geo.mirror_pos(p)));
            return;
        }
        if point_header(app, wb, sh, RangeRef::cols(c, c), mods.shift, mods.command) {
            point_header_first_move(app, input);
            return;
        }
        // An armed Format Painter paints the columns dragged over instead of moving them.
        if resp.drag_started()
            && !mods.any()
            && app.session.format_painter.is_none()
            && sel.ranges.len() == 1
            && sel.current().is_full_cols()
            && sel.current().contains(CellRef::new(0, c))
        {
            app.grid.drag = Drag::MoveCols { source: sel.current(), before: None };
            return;
        }
        let range = if mods.shift { RangeRef::cols(sel.anchor.col.min(c), sel.anchor.col.max(c)) } else { RangeRef::cols(c, c) };
        note_selecting_press(app);
        select_ranges(app, range, mods.command, CellRef::new(geo.row_at(sh, geo.cells.top() + 1.0), c));
        app.grid.drag = Drag::Cols(if mods.shift { sel.anchor.col } else { c });
    }
}

fn handle_row_header_press(app: &mut SheetApp, input: &InteractionInput<'_>, p: Pos2) {
    let (geo, sh, wb, sel) = (input.geo, input.sheet, input.workbook, &input.selection);
    let mods = input.modifiers;
    let in_row_header = input.in_row_header;
    if in_row_header {
        if let Some((r, y)) = row_edge(geo, sh, p.y) {
            begin_resize(app);
            app.grid.drag = Drag::ResizeRow { row: r, start: p.y, orig: (y - geo.y(sh, r)) / geo.z, to: None };
            return;
        }
        let r = geo.row_at(sh, p.y);
        if point_header(app, wb, sh, RangeRef::rows(r, r), mods.shift, mods.command) {
            point_header_first_move(app, input);
            return;
        }
        let range = if mods.shift { RangeRef::rows(sel.anchor.row.min(r), sel.anchor.row.max(r)) } else { RangeRef::rows(r, r) };
        note_selecting_press(app);
        select_ranges(app, range, mods.command, CellRef::new(r, geo.col_at(sh, geo.cells.left() + 1.0)));
        app.grid.drag = Drag::Rows(if mods.shift { sel.anchor.row } else { r });
    }
}

fn handle_press(app: &mut SheetApp, input: &InteractionInput<'_>) {
    let (geo, sh, wb, resp) = (input.geo, input.sheet, input.workbook, input.response);
    let (pos, mods, sel) = (input.position, input.modifiers, &input.selection);
    let (primary_clicked, in_cells, in_col_header, in_row_header, in_corner) =
        (input.primary_clicked, input.in_cells, input.in_column_header, input.in_row_header, input.in_corner);
    let (freeze_cols, freeze_rows) = (input.freeze_columns, input.freeze_rows);
    let on_handle = |p| input.on_handle(p);
    let on_cur_border = |p| input.on_current_border(p);
    let pointer = input.press_origin;

    // Where the press began (a drag is only recognised after the pointer has moved).
    let Some(p) = pointer.map(|p| geo.mirror_pos(p)).or(pos) else { return };
    // The outline band's โˆ’ / + and level buttons act on release, like buttons.
    if let Some(action) = crate::outline::hit(geo, sh, p) {
        if primary_clicked {
            let (command, params) = action.command();
            app.run_or_alert(command, params);
        }
        return;
    }
    // Freeze handles sit on the header edges (and the corner's edges when nothing is frozen).
    if freeze_cols.contains(p) || freeze_rows.contains(p) {
        app.grid.drag = Drag::Freeze { cols: freeze_cols.contains(p), to: None };
        return;
    }
    if in_corner {
        note_selecting_press(app);
        let _ = app.session.run("selection.set", json!({"range": RangeRef::all().a1()}));
        return;
    }
    if in_col_header {
        handle_column_header_press(app, input, p);
        return;
    }
    if in_row_header {
        handle_row_header_press(app, input, p);
        return;
    }
    if !in_cells {
        return;
    }
    let c = geo.cell_at(sh, p);
    // Data validation list arrow next to the active cell.
    if let Some(r) = validation_arrow(sh, geo, sel.active)
        && r.contains(p)
    {
        app.grid.list_picker = Some(sel.active);
        return;
    }
    // Filter dropdown buttons.
    if is_filter_button(sh, geo, p) {
        app.grid.filter_menu = Some((c.col, c.row, geo.mirror_pos(p)));
        return;
    }
    // A dialog's formula box in point mode (New Formatting Rule) takes the reference; the
    // selection, which the dialog acts on, stays.
    if let Some(d) = app.dialog.as_mut().filter(|d| d.picks_references()) {
        d.pick_reference(c, &sh.name, false);
        app.grid.drag = Drag::Select;
        app.grid.drag_select = true;
        if resp.drag_started()
            && let Some(p) = pos
        {
            select_to_pointer(app, geo, sh, wb, p);
        }
        return;
    }
    // Point mode while editing a formula: clicking inserts a reference.
    if let Some(ed) = app.editor.as_mut()
        && ed.can_point()
    {
        let anchor = if mods.shift && ed.point_at_caret() {
            ed.point_anchor.filter(|(sheet, _)| *sheet == wb.active_sheet()).map(|(_, cell)| cell).unwrap_or(c)
        } else {
            c
        };
        let range = RangeRef::new(anchor, c);
        let text = if range.is_single() { c.a1() } else { range.a1() };
        let sheet_name = (ed.sheet != wb.active_sheet()).then(|| sh.name.clone());
        let r = match sheet_name {
            Some(n) => format!("{}!{text}", gridcraft_engine::formula::quote_sheet(&n)),
            None => text,
        };
        if mods.command && !mods.shift {
            ed.append_ref(&r);
        } else {
            ed.insert_ref(&r);
        }
        ed.request_focus = true;
        ed.point_cell = Some(c);
        ed.point_anchor = Some((wb.active_sheet(), anchor));
        app.grid.drag = Drag::Select;
        app.grid.drag_select = true;
        if resp.drag_started()
            && let Some(p) = pos
        {
            select_to_pointer(app, geo, sh, wb, p);
        }
        return;
    }
    if app.editor.is_some() && !app.commit_edit(0, 0, false, false) {
        return;
    }
    if on_handle(p) {
        app.grid.drag = Drag::Fill { target: None, menu: resp.drag_started_by(egui::PointerButton::Secondary) };
        return;
    }
    if on_cur_border(p) && resp.drag_started() {
        app.grid.drag = Drag::Move { grab: c, to: None };
        return;
    }
    let now = crate::now_ms();
    // While a reference box picks, a click only picks: a second click on a cell does not edit it,
    // and a link is not followed nor a checkbox toggled.
    let ref_box_picks = app.dialog.as_ref().is_some_and(|d| d.ref_box_picks());
    let acts = primary_clicked && !ref_box_picks;
    if !ref_box_picks && handle_cell_double_click(app, input, c, now) {
        return;
    }
    app.grid.last_click = Some((c, now));
    if mods.shift {
        note_selecting_press(app);
        let _ = app.session.run("selection.set", json!({"range": RangeRef::new(sel.anchor, c).a1(), "active": sel.active.a1()}));
        if let Some(d) = app.session.active_mut() {
            d.selection.anchor = sel.anchor;
        }
    } else if mods.command {
        // Ctrl+click (without Alt) on a hyperlink's text follows it instead of adding the cell to the selection.
        if let Some(h) = sh.hyperlinks.get(&c).cloned()
            && acts
            && !mods.alt
            && p.x < geo.cell_rect(sh, c).left() + geo.cell_rect(sh, c).width() * 0.8
        {
            follow_link(app, &h.target);
        } else {
            note_selecting_press(app);
            select_ranges(app, RangeRef::cell(c), true, c);
        }
    } else {
        note_selecting_press(app);
        let _ = app.session.run("selection.set", json!({"cell": c.a1()}));
        if acts && wb.styles.get(sh.style_id(c)).num_fmt.as_str() == "checkbox" {
            let _ = app.run("cell.toggleCheckbox", json!({"cell": c.a1()}));
        }
        // A click on a hyperlink's text follows it (like Excel); elsewhere in the cell selects.
        if let Some(h) = sh.hyperlinks.get(&c).cloned()
            && acts
            && !mods.any()
        {
            let r = geo.cell_rect(sh, c);
            if p.x < r.left() + r.width() * 0.8 {
                follow_link(app, &h.target);
            }
        }
    }
    app.grid.drag = Drag::Select;
    app.grid.drag_select = true;
    if resp.drag_started()
        && let Some(p) = pos
    {
        // The first recognised drag already includes movement away from the press.
        select_to_pointer(app, geo, sh, wb, p);
    }
}

/// Tells the open dialog that a press on the grid selects: the reference box being picked into
/// takes the selection even when the press leaves it as it was (a click on the cell already
/// selected), as a deliberate pick.
fn note_selecting_press(app: &mut SheetApp) {
    if let Some(d) = app.dialog.as_mut() {
        d.note_selecting_press();
    }
}

fn handle_cell_double_click(app: &mut SheetApp, input: &InteractionInput<'_>, c: CellRef, now: f64) -> bool {
    let (sh, mods) = (input.sheet, input.modifiers);
    if let Some((last, at)) = app.grid.last_click
        && last == c
        && now - at < 450.0
        && !mods.shift
    {
        app.grid.last_click = None;
        // A PivotTable's value cell shows its source records on a new sheet (Excel's Show
        // Details); its labels and headers still edit.
        if sh.pivots.iter().any(|pt| pt.last_range.is_some_and(|r| r.contains(c))) {
            let not_a_value_cell =
                gridcraft_engine::EngineError::Disabled("pivot.showDetails".into(), gridcraft_engine::pivot::NOT_A_VALUE_CELL.into()).to_string();
            match app.run("pivot.showDetails", json!({"cell": c.a1()})) {
                Ok(_) => return true,
                Err(e) if e == not_a_value_cell => {}
                Err(e) => {
                    app.message = Some(("GridCraft".into(), crate::clean_error(&e)));
                    return true;
                }
            }
        }
        // Following a hyperlink requires a single click in Excel; double-click edits.
        app.begin_edit(None, false);
        return true;
    }
    false
}

/// What a press at `p` lands on, for slicer tiles and the generic object handling alike, so the
/// z-order decides once: the selected object's handle (handles reach a little past the frame and
/// win over hit-testing), else the topmost object under `p` and its rect.
fn object_under(app: &SheetApp, geo: &Geo, sh: &Sheet, p: Pos2) -> Option<(ObjRef, Rect, Option<crate::objects::Handle>)> {
    crate::chartview::selected_handle(app, geo, sh, p)
        .map(|(o, r, h)| (o, r, Some(h)))
        .or_else(|| crate::chartview::hit(app, geo, sh, p).map(|(o, r)| (o, r, None)))
}

fn handle_context_menu_and_keyboard(app: &mut SheetApp, input: &InteractionInput<'_>) {
    let (geo, sh, sel, pos) = (input.geo, input.sheet, &input.selection, input.position);
    let resp = input.response;
    let primary_clicked = input.primary_clicked;
    let (in_cells, in_col_header, in_row_header) = (input.in_cells, input.in_column_header, input.in_row_header);
    let ctx = input.context.clone();
    // Right-click: context menu.
    if resp.secondary_clicked()
        && let Some(p) = pos
    {
        if in_cells && !sel.contains(geo.cell_at(sh, p)) {
            let _ = app.session.run("selection.set", json!({"cell": geo.cell_at(sh, p).a1()}));
        }
        if in_col_header || in_row_header {
            let (rows, idx) = if in_row_header { (true, geo.row_at(sh, p.y)) } else { (false, geo.col_at(sh, p.x)) };
            let inside = sel.ranges.iter().any(|r| {
                if rows {
                    r.is_full_rows() && idx >= r.start.row && idx <= r.end.row
                } else {
                    r.is_full_cols() && idx >= r.start.col && idx <= r.end.col
                }
            });
            if !inside {
                let range = if rows { RangeRef::rows(idx, idx) } else { RangeRef::cols(idx, idx) };
                let _ = app.session.run("selection.set", json!({"range": range.a1()}));
            }
            app.grid.header_menu = Some((geo.mirror_pos(p), rows));
        } else {
            app.grid.context_menu = Some(geo.mirror_pos(p));
            app.grid.context_menu_frame = input.ui.ctx().cumulative_frame_nr();
        }
    }

    if primary_clicked || resp.drag_started() {
        resp.request_focus();
    }
    keyboard(app, &ctx, resp, geo, sh);
}

/// Whether Esc was pressed this frame, with any modifiers; every Esc press is then spent, so the
/// grid's own Esc doesn't also drop a pending copy or Format Painter.
fn spend_escape(ctx: &egui::Context) -> bool {
    ctx.input_mut(|i| {
        let pressed = i.key_pressed(egui::Key::Escape);
        if pressed {
            i.events.retain(|e| !matches!(e, egui::Event::Key { key: egui::Key::Escape, pressed: true, .. }));
        }
        pressed
    })
}

fn handle_dragging(app: &mut SheetApp, input: &InteractionInput<'_>) {
    let (geo, sh, wb, sel, pos) = (input.geo, input.sheet, input.workbook, &input.selection, input.position);
    let resp = input.response;
    // Esc during a header-boundary drag cancels it: undo the preview, ignore the release. egui
    // aborts the drag on Esc, so `resp.dragged()` is already false in this frame. The key is
    // spent on the drag, so the grid's Esc doesn't also drop a pending copy or Format Painter.
    // Esc during a drag of a chart's values outline drops it: the chart keeps its data, whatever
    // modifiers are held (egui ends the drag on any Esc, so the release must not apply it).
    if matches!(app.grid.drag, Drag::ChartData { .. }) && spend_escape(&input.context) {
        app.grid.drag = Drag::None;
    }
    if matches!(app.grid.drag, Drag::ResizeCol { .. } | Drag::ResizeRow { .. }) && spend_escape(&input.context) {
        // Undo back to where the drag began, but never past it into an earlier edit.
        let steps = resize_steps(app);
        if steps > 0 {
            let _ = app.session.run("edit.undo", json!({"steps": steps}));
        }
        // Undo pushes the cancelled preview onto the redo stack; put back what the drag began with.
        if let Some(d) = app.session.active_mut() {
            d.redo = std::mem::take(&mut app.grid.resize_redo);
        }
        app.grid.drag = Drag::None;
        app.grid.resize_base = None;
    }
    if resp.dragged()
        && let Some(p) = pos
    {
        // Auto-scroll near edges.
        let edge = 24.0;
        let mut auto = egui::Vec2::ZERO;
        if p.y > geo.cells.bottom() - edge {
            auto.y = 20.0;
        }
        if p.y < geo.cells.top() + edge * 0.5 && !matches!(app.grid.drag, Drag::ResizeRow { .. }) {
            auto.y = -20.0;
        }
        if p.x > geo.cells.right() - edge {
            auto.x = 30.0;
        }
        if p.x < geo.cells.left() + edge * 0.5 && !matches!(app.grid.drag, Drag::ResizeCol { .. }) {
            auto.x = -30.0;
        }
        let pc = CellRef::new(
            geo.row_at(sh, p.y.clamp(geo.cells.top() + 1.0, geo.cells.bottom() - 1.0)),
            geo.col_at(sh, p.x.clamp(geo.cells.left() + 1.0, geo.cells.right() - 1.0)),
        );
        match app.grid.drag.clone() {
            Drag::Select => {
                select_to_pointer(app, geo, sh, wb, p);
                scroll_by(app, auto);
            }
            Drag::Rows(anchor) => {
                let r = geo.row_at(sh, p.y);
                let _ =
                    app.session.run("selection.set", json!({"range": RangeRef::rows(anchor.min(r), anchor.max(r)).a1(), "active": sel.active.a1()}));
                scroll_by(app, vec2(0.0, auto.y));
            }
            Drag::Cols(anchor) => {
                let c = geo.col_at(sh, p.x);
                let _ =
                    app.session.run("selection.set", json!({"range": RangeRef::cols(anchor.min(c), anchor.max(c)).a1(), "active": sel.active.a1()}));
                scroll_by(app, vec2(auto.x, 0.0));
            }
            drag @ (Drag::PointRows(_) | Drag::PointCols(_)) => {
                point_header_to(app, geo, sh, wb, &drag, p);
                scroll_by(app, if matches!(drag, Drag::PointRows(_)) { vec2(0.0, auto.y) } else { vec2(auto.x, 0.0) });
            }
            Drag::MoveCols { source, .. } => {
                let col = geo.col_at(sh, p.x.clamp(geo.cells.left() + 1.0, geo.cells.right() - 1.0));
                let midpoint = geo.x(sh, col) + sh.col_width(col) * geo.z * 0.5;
                let before = (col + u32::from(p.x >= midpoint)).min(MAX_COLS - 1);
                let before = (!(source.start.col..=source.end.col + 1).contains(&before)).then_some(before);
                app.grid.drag = Drag::MoveCols { source, before };
                scroll_by(app, vec2(auto.x, 0.0));
            }
            Drag::ResizeCol { col, start, orig, to } => {
                let w = nan_safe_size(orig + (p.x - start) / geo.z);
                app.toast = Some((column_width_tip(app.ui.language, w), crate::now_ms()));
                // Preview on the dragged column only; the release applies it to the selection. A
                // rejected size leaves the last shown preview (and `to`) as it was.
                let ok = app.session.run("home.columnWidth", json!({"cols": RangeRef::cols(col, col).a1(), "width": w.round()})).is_ok();
                coalesce_resize_undo(app);
                app.grid.drag = Drag::ResizeCol { col, start, orig, to: if ok { Some(w) } else { to } };
            }
            Drag::ResizeRow { row, start, orig, to } => {
                let h = nan_safe_size(orig + (p.y - start) / geo.z);
                app.toast = Some((row_height_tip(app.ui.language, h), crate::now_ms()));
                let ok = app.session.run("home.rowHeight", json!({"rows": format!("{}:{}", row + 1, row + 1), "height": h.round()})).is_ok();
                coalesce_resize_undo(app);
                app.grid.drag = Drag::ResizeRow { row, start, orig, to: if ok { Some(h) } else { to } };
            }
            Drag::Freeze { cols, .. } => {
                app.grid.drag = Drag::Freeze { cols, to: Some(freeze_boundary(geo, sh, p, cols)) };
            }
            Drag::Fill { menu, .. } => {
                let src = sel.current();
                let target = fill_target(src, pc);
                app.grid.drag = Drag::Fill { target: Some(target), menu };
                scroll_by(app, auto);
            }
            Drag::Move { grab, .. } => {
                let src = sel.current();
                let dr = pc.row as i64 - grab.row as i64;
                let dc = pc.col as i64 - grab.col as i64;
                app.grid.drag = Drag::Move { grab, to: Some(src.start.offset_clamped(dr, dc)) };
                scroll_by(app, auto);
            }
            Drag::Object { .. } => drag_object(app, geo, sh, p),
            Drag::Rotate { obj, rect, .. } => rotate_object(app, obj, rect, p, input.modifiers.shift),
            Drag::ChartData { .. } => {
                drag_chart_data(app, geo, sh, p);
                scroll_by(app, auto);
            }
            Drag::None => {}
        }
    }
}

fn handle_release(app: &mut SheetApp, input: &InteractionInput<'_>) {
    let (geo, sh, wb, sel, pos, mods, resp) =
        (input.geo, input.sheet, input.workbook, &input.selection, input.position, input.modifiers, input.response);
    let ctx = input.context.clone();
    if resp.drag_stopped() || (!input.any_pointer_down && app.grid.drag != Drag::None && !resp.dragged()) {
        match std::mem::take(&mut app.grid.drag) {
            Drag::Select => {
                if resp.drag_stopped()
                    && let Some(p) = pos
                {
                    select_to_pointer(app, geo, sh, wb, p);
                }
                format_painter_apply(app);
            }
            // Whole rows or columns clicked or dragged over by their headers.
            Drag::Rows(_) | Drag::Cols(_) => format_painter_apply(app),
            // The release may be the first frame to report the pointer's last position.
            drag @ (Drag::PointRows(_) | Drag::PointCols(_)) => {
                if resp.drag_stopped()
                    && let Some(p) = pos
                {
                    point_header_to(app, geo, sh, wb, &drag, p);
                }
            }
            // Esc mid-drag lands here too (egui ends the drag on Esc): no menu, and the key is
            // spent on the drag so the grid's Esc doesn't also drop the copy.
            Drag::Fill { target: Some(t), menu: true } => {
                if let Some(p) = pos
                    && t != sel.current()
                    && !ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape))
                {
                    app.grid.fill_menu = Some((sel.current(), t, geo.mirror_pos(p)));
                }
            }
            Drag::Fill { target: Some(t), menu: false } => {
                let src = sel.current();
                if t != src {
                    // Ctrl (Cmd on macOS) swaps copying and extending, as in Excel.
                    let mode = if mods.command { "alternate" } else { "series" };
                    match app.run("edit.autoFill", json!({"source": src.a1(), "target": t.a1(), "mode": mode})) {
                        Ok(_) => set_fill_tag(app, src, t),
                        Err(e) => app.message = Some(("GridCraft".into(), crate::clean_error(&e))),
                    }
                }
            }
            Drag::Freeze { cols, to: Some(to) } => {
                let (rows_now, cols_now) = (geo.fr, geo.fc);
                let (rows, cols) = if cols { (rows_now, to) } else { (to, cols_now) };
                if (rows, cols) != (rows_now, cols_now) {
                    // A1 (nothing left frozen) unfreezes.
                    app.run_or_alert("view.freezePanes", json!({"cell": CellRef::new(rows, cols).a1()}));
                }
            }
            Drag::Move { to: Some(to), .. } => {
                let src = sel.current();
                // Dropping on cells that hold data asks first, as in Excel.
                if to != src.start {
                    crate::macro_ui::call(app, "GridCraft", "range.move", json!({"range": src.a1(), "to": to.a1()}));
                }
            }
            Drag::ResizeCol { col, to: Some(w), .. } => {
                // The preview already sized the dragged column; the other selected ones follow now.
                let cols = resize_targets(&sel.ranges, col, true);
                if cols != RangeRef::cols(col, col).a1() {
                    let _ = app.session.run("home.columnWidth", json!({"cols": cols, "width": w.round()}));
                    coalesce_resize_undo(app);
                }
            }
            Drag::ResizeRow { row, to: Some(h), .. } => {
                let rows = resize_targets(&sel.ranges, row, false);
                if rows != format!("{}:{}", row + 1, row + 1) {
                    let _ = app.session.run("home.rowHeight", json!({"rows": rows, "height": h.round()}));
                    coalesce_resize_undo(app);
                }
            }
            // The release may be the first frame to report the pointer's last position, so the
            // block is taken from there. (Esc already dropped a cancelled drag, and so did a
            // change to the chart's data; one in the release's own frame is caught here.)
            Drag::ChartData { chart, orig, corner, to } => {
                let to = if resp.drag_stopped()
                    && let Some(p) = pos
                {
                    Some(chart_data_target(geo, sh, orig, corner, p))
                } else {
                    to
                };
                if let Some(to) = to.filter(|to| *to != orig)
                    && chart_still_plots(app, chart, orig)
                {
                    app.run_or_alert("chart.setValuesRange", json!({"chart": chart, "range": to.a1()}));
                }
            }
            Drag::MoveCols { source, before: Some(before) } => {
                if let Err(e) = app.run("sheet.moveColumns", json!({"cols": source.a1(), "before": before})) {
                    app.message = Some(("GridCraft".into(), crate::clean_error(&e)));
                }
            }
            _ => {}
        }
        app.grid.drag_select = false;
    }
}

/// An armed Format Painter pastes onto the cells just clicked or dragged over (not while
/// pointing a formula reference, which also drags a Select).
fn format_painter_apply(app: &mut SheetApp) {
    if app.session.format_painter.is_some()
        && !app.editor.as_ref().is_some_and(|ed| ed.can_point())
        && !app.dialog.as_ref().is_some_and(|d| d.picks_references())
    {
        let dest = app.session.active().map(|d| d.selection.current().a1());
        if let Some(dest) = dest
            && let Err(e) = app.run("edit.formatPainter", json!({"apply": dest}))
        {
            app.message = Some(("GridCraft".into(), crate::clean_error(&e)));
        }
    }
}

/// Point mode on a header: inserts a whole-row or whole-column reference instead of selecting,
/// and dragging on from there extends it.
fn point_header(app: &mut SheetApp, wb: &Workbook, sh: &Sheet, range: RangeRef, extend: bool, add: bool) -> bool {
    let Some(ed) = app.editor.as_mut().filter(|ed| ed.can_point()) else { return false };
    let edit_sheet = ed.sheet;
    let active_sheet = wb.active_sheet();
    let pressed = range;
    let range = if extend {
        ed.point
            .and_then(|point| crate::editor::formula_refs(&ed.text).into_iter().find(|(start, end, ..)| (*start, *end) == point))
            .and_then(|(_, _, previous, previous_sheet, _)| {
                let previous_sheet = previous_sheet.as_deref().map(|name| wb.sheet_index(name)).unwrap_or(Some(edit_sheet));
                if previous_sheet != Some(active_sheet) {
                    return None;
                }
                if range.is_full_cols() && previous.is_full_cols() {
                    Some(RangeRef::cols(previous.start.col.min(range.start.col), previous.end.col.max(range.end.col)))
                } else if range.is_full_rows() && previous.is_full_rows() {
                    Some(RangeRef::rows(previous.start.row.min(range.start.row), previous.end.row.max(range.end.row)))
                } else {
                    None
                }
            })
            .unwrap_or(range)
    } else {
        range
    };
    let reference = header_reference(ed, wb, sh, range);
    if add {
        ed.append_ref(&reference);
    } else {
        ed.insert_ref(&reference);
    }
    ed.point_anchor = None;
    ed.point_cell = Some(range.start);
    ed.request_focus = true;
    // The drag keeps the end of the reference the press didn't land on.
    app.grid.drag = if range.is_full_cols() {
        Drag::PointCols(if range.start.col == pressed.start.col { range.end.col } else { range.start.col })
    } else {
        Drag::PointRows(if range.start.row == pressed.start.row { range.end.row } else { range.start.row })
    };
    true
}

fn header_reference(ed: &EditState, wb: &Workbook, sh: &Sheet, range: RangeRef) -> String {
    let reference = range.a1();
    if ed.sheet != wb.active_sheet() { format!("{}!{reference}", gridcraft_engine::formula::quote_sheet(&sh.name)) } else { reference }
}

/// The frame that starts a drag reports no `dragged()`, so its movement is applied here.
fn point_header_first_move(app: &mut SheetApp, input: &InteractionInput<'_>) {
    if input.response.drag_started()
        && let Some(p) = input.position
    {
        let drag = app.grid.drag.clone();
        point_header_to(app, input.geo, input.sheet, input.workbook, &drag, p);
    }
}

/// Point mode dragged over the headers: the pointed reference runs from the anchor to the pointer.
fn point_header_to(app: &mut SheetApp, geo: &Geo, sh: &Sheet, wb: &Workbook, drag: &Drag, p: Pos2) {
    // The pointer's end moves with Shift+arrow next; the opposite corner keeps it a whole column or row.
    let (range, pointer, opposite) = match *drag {
        Drag::PointCols(anchor) => {
            let col = geo.col_at(sh, p.x.clamp(geo.cells.left() + 1.0, geo.cells.right() - 1.0));
            let range = RangeRef::cols(anchor.min(col), anchor.max(col));
            (range, CellRef::new(range.start.row, col), CellRef::new(range.end.row, anchor))
        }
        Drag::PointRows(anchor) => {
            let row = geo.row_at(sh, p.y.clamp(geo.cells.top() + 1.0, geo.cells.bottom() - 1.0));
            let range = RangeRef::rows(anchor.min(row), anchor.max(row));
            (range, CellRef::new(row, range.start.col), CellRef::new(anchor, range.end.col))
        }
        _ => return,
    };
    let Some(ed) = app.editor.as_mut().filter(|ed| ed.point_at_caret()) else { return };
    let reference = header_reference(ed, wb, sh, range);
    ed.insert_ref(&reference);
    ed.point_cell = Some(pointer);
    ed.point_anchor = Some((wb.active_sheet(), opposite));
}

fn select_to_pointer(app: &mut SheetApp, geo: &Geo, sh: &Sheet, wb: &Workbook, p: Pos2) {
    let cell = CellRef::new(
        geo.row_at(sh, p.y.clamp(geo.cells.top() + 1.0, geo.cells.bottom() - 1.0)),
        geo.col_at(sh, p.x.clamp(geo.cells.left() + 1.0, geo.cells.right() - 1.0)),
    );
    if let Some(d) = app.dialog.as_mut().filter(|d| d.picks_references()) {
        d.pick_reference(cell, &sh.name, true);
    } else if let Some(ed) = app.editor.as_mut()
        && ed.point.is_some()
    {
        if let Some(start) = ed.point_anchor.filter(|(sheet, _)| *sheet == wb.active_sheet()).map(|(_, cell)| cell).or(ed.point_cell) {
            let range = RangeRef::new(start, cell);
            let text = if range.is_single() { range.start.a1() } else { range.a1() };
            let text = if ed.sheet != wb.active_sheet() { format!("{}!{text}", gridcraft_engine::formula::quote_sheet(&sh.name)) } else { text };
            ed.insert_ref(&text);
            ed.point_cell = Some(cell);
            ed.point_anchor = Some((wb.active_sheet(), start));
        }
    } else if let Some(d) = app.session.active() {
        // Read the current anchor: starting a drag may have just replaced the selection.
        let anchor = d.selection.anchor;
        let active = d.selection.active;
        let mut ranges: Vec<String> = d.selection.ranges.iter().map(|r| r.a1()).collect();
        ranges.pop();
        ranges.push(RangeRef::new(anchor, cell).a1());
        let _ = app.session.run("selection.set", json!({"range": ranges.join(","), "active": active.a1()}));
        if let Some(d) = app.session.active_mut() {
            d.selection.anchor = anchor;
        }
    }
}

/// A drag size in points: NaN or negative becomes 0 (a hidden line).
fn nan_safe_size(v: f32) -> f32 {
    if v.is_nan() { 0.0 } else { v.max(0.0) }
}

/// The lines a header-boundary drag resizes on release: every selected whole line when the
/// dragged one is part of the selection (Ctrl-selected areas included), otherwise only it.
fn resize_targets(ranges: &[RangeRef], index: u32, cols: bool) -> String {
    let whole = |r: &RangeRef| if cols { r.is_full_cols() } else { r.is_full_rows() };
    let span = |r: &RangeRef| if cols { (r.start.col, r.end.col) } else { (r.start.row, r.end.row) };
    let name = |r: &RangeRef| {
        let (a, b) = span(r);
        if cols { RangeRef::cols(a, b).a1() } else { format!("{}:{}", a + 1, b + 1) }
    };
    if ranges.iter().any(|r| whole(r) && (span(r).0..=span(r).1).contains(&index)) {
        ranges.iter().filter(|r| whole(r)).map(name).collect::<Vec<_>>().join(",")
    } else if cols {
        RangeRef::cols(index, index).a1()
    } else {
        format!("{}:{}", index + 1, index + 1)
    }
}

fn coalesce_last_undo(app: &mut SheetApp) {
    // Merge consecutive drag steps into one undo entry.
    if let Some(d) = app.session.active_mut()
        && d.undo.len() >= 2
    {
        let n = d.undo.len();
        if d.undo[n - 1].label == d.undo[n - 2].label {
            d.undo.remove(n - 1);
        }
    }
}

/// Starts a header resize drag: remembers the workbook and the redo stack it began with.
fn begin_resize(app: &mut SheetApp) {
    app.grid.resize_base = app.session.active().map(|d| d.wb.clone());
    app.grid.resize_redo = app.session.active().map(|d| d.redo.clone()).unwrap_or_default();
}

/// Undo entries a header resize drag has pushed so far: those from the first one that snapshots
/// the workbook the drag started from (`resize_base`). A failed command pushes none.
fn resize_steps(app: &SheetApp) -> usize {
    let (Some(base), Some(d)) = (&app.grid.resize_base, app.session.active()) else { return 0 };
    d.undo.iter().position(|e| std::sync::Arc::ptr_eq(&e.wb, base)).map_or(0, |first| d.undo.len() - first)
}

/// Like [`coalesce_last_undo`] for a resize drag: merges only the drag's own entries, so an
/// earlier edit with the same label ("Column width") stays a separate undo step.
fn coalesce_resize_undo(app: &mut SheetApp) {
    if resize_steps(app) >= 2
        && let Some(d) = app.session.active_mut()
    {
        d.undo.pop();
    }
}

fn scroll_by(app: &mut SheetApp, d: egui::Vec2) {
    if d != egui::Vec2::ZERO
        && let Some(v) = app.view_mut()
    {
        v.scroll = (v.scroll + d).max(egui::Vec2::ZERO);
    }
}

/// The tip while a column border is dragged to `width` pixels: the width in characters, then in
/// pixels (`Width: 8.43 (64 pixels)`).
pub(crate) fn column_width_tip(lang: crate::i18n::Language, width: f32) -> String {
    let chars = format!("{:.2}", gridcraft_engine::cmd::format::points_to_chars(f64::from(width)));
    lang.tr_fill("Width: {chars} ({pixels} pixels)", &[("chars", &chars), ("pixels", &width.round().to_string())])
}

/// The tip while a row border is dragged to `height` pixels: the height in points, then in pixels
/// (`Height: 15.00 (20 pixels)`).
pub(crate) fn row_height_tip(lang: crate::i18n::Language, height: f32) -> String {
    let points = format!("{:.2}", height * 0.75);
    lang.tr_fill("Height: {points} ({pixels} pixels)", &[("points", &points), ("pixels", &height.round().to_string())])
}

fn fill_target(src: RangeRef, pc: CellRef) -> RangeRef {
    let below = pc.row as i64 - src.end.row as i64;
    let above = src.start.row as i64 - pc.row as i64;
    let right = pc.col as i64 - src.end.col as i64;
    let left = src.start.col as i64 - pc.col as i64;
    let vert = below.max(above);
    let horiz = right.max(left);
    if vert <= 0 && horiz <= 0 {
        return src;
    }
    if vert >= horiz {
        if below > 0 {
            RangeRef::new(src.start, CellRef::new(pc.row, src.end.col))
        } else {
            RangeRef::new(CellRef::new(pc.row, src.start.col), src.end)
        }
    } else if right > 0 {
        RangeRef::new(src.start, CellRef::new(src.end.row, pc.col))
    } else {
        RangeRef::new(CellRef::new(src.start.row, pc.col), src.end)
    }
}

pub(super) fn on_border(r: Rect, p: Pos2) -> bool {
    let outer = r.expand(3.0);
    let inner = r.shrink(3.0);
    outer.contains(p) && !inner.contains(p)
}

/// The freeze handles, as in Excel for the web: a bar in the upper part of the column-header strip
/// on the frozen columns' right edge, and one in the left part of the row-header strip on the
/// frozen rows' bottom edge. With nothing frozen they sit on the corner's edges. The rest of the
/// header edge keeps resizing the column or row.
pub fn freeze_handles(geo: &Geo) -> (Rect, Rect) {
    let x = geo.cells.left() + geo.frozen_w;
    let y = geo.cells.top() + geo.frozen_h;
    let cols = Rect::from_min_max(pos2(x - 3.0, geo.head_top()), pos2(x + 3.0, geo.head_top() + geo.header_h * 0.4));
    let rows = Rect::from_min_max(pos2(geo.head_left(), y - 3.0), pos2(geo.head_left() + geo.header_w * 0.4, y + 3.0));
    (cols, rows)
}

/// How many columns (or rows) a freeze handle dropped at `p` freezes: the line boundary nearest
/// the pointer, limited so the frozen pane leaves room for the scrolling one.
fn freeze_boundary(geo: &Geo, sh: &Sheet, p: Pos2, cols: bool) -> u32 {
    if cols {
        if p.x <= geo.cells.left() {
            return 0;
        }
        let c = geo.col_at(sh, p.x);
        let (l, r) = (geo.x(sh, c), geo.x_end(sh, c));
        let b = if p.x - l > r - p.x { c.saturating_add(1) } else { c };
        let room = geo.ci.at((((geo.cells.width() - 40.0) / geo.z).max(0.0)) as f64);
        b.min(room).min(MAX_COLS - 1)
    } else {
        if p.y <= geo.cells.top() {
            return 0;
        }
        let rr = geo.row_at(sh, p.y);
        let (t, b2) = (geo.y(sh, rr), geo.y_end(sh, rr));
        let b = if p.y - t > b2 - p.y { rr.saturating_add(1) } else { rr };
        let room = geo.ri.at((((geo.cells.height() - 40.0) / geo.z).max(0.0)) as f64);
        b.min(room).min(MAX_ROWS - 1)
    }
}

/// Paints the freeze handles and, while one is dragged, where the freeze line will go.
pub(super) fn paint_freeze_handles(p: &Painter, geo: &Geo, sh: &Sheet, drag: &Drag, t: &Tokens) {
    let (cols, rows) = freeze_handles(geo);
    let bar = Color32::from_gray(150);
    p.rect_filled(Rect::from_center_size(cols.center(), vec2(3.0, cols.height())), 1.0, bar);
    p.rect_filled(Rect::from_center_size(rows.center(), vec2(rows.width(), 3.0)), 1.0, bar);
    if let Drag::Freeze { cols, to: Some(to) } = *drag {
        let stroke = Stroke::new(2.0, t.accent);
        if cols {
            let x = geo.cells.left() + sh.col_left(to) as f32 * geo.z;
            p.line_segment([pos2(x, geo.head_top()), pos2(x, geo.cells.bottom())], stroke);
        } else {
            let y = geo.cells.top() + sh.row_top(to) as f32 * geo.z;
            p.line_segment([pos2(geo.head_left(), y), pos2(geo.cells.right(), y)], stroke);
        }
    }
}

pub(super) fn col_edge(geo: &Geo, sh: &Sheet, x: f32) -> Option<(u32, f32)> {
    let c = geo.col_at(sh, x);
    for cc in [c, c.saturating_sub(1)] {
        let edge = geo.x(sh, cc) + sh.col_width(cc) * geo.z;
        if (x - edge).abs() <= 4.0 {
            return Some((cc, edge));
        }
    }
    None
}

pub(super) fn row_edge(geo: &Geo, sh: &Sheet, y: f32) -> Option<(u32, f32)> {
    let r = geo.row_at(sh, y);
    for rr in [r, r.saturating_sub(1)] {
        let edge = geo.y(sh, rr) + sh.row_height(rr) * geo.z;
        if (y - edge).abs() <= 3.0 {
            return Some((rr, edge));
        }
    }
    None
}

/// The hidden column whose (zero-width) edge is at `x`: only just right of the boundary, as the
/// edge just left of it belongs to the visible column there.
pub(super) fn hidden_col_edge(geo: &Geo, sh: &Sheet, x: f32) -> Option<u32> {
    col_edge(geo, sh, x).map(|(c, _)| c).filter(|&c| sh.col_width(c) <= 0.0)
}

pub(super) fn hidden_row_edge(geo: &Geo, sh: &Sheet, y: f32) -> Option<u32> {
    row_edge(geo, sh, y).map(|(r, _)| r).filter(|&r| sh.row_height(r) <= 0.0)
}

/// Arrow-key nudge of a selected object, sheet points (Ctrl/Alt: fine).
const NUDGE: f32 = 6.0;

/// Arrow keys aimed at the selected object rather than the cells: they nudge it.
pub(super) fn object_key(app: &mut SheetApp, sh: &Sheet, key: egui::Key, m: egui::Modifiers) -> bool {
    use egui::Key;
    let Some(o) = app.selected_object else { return false };
    let step = if m.ctrl || m.alt { 1.0 } else { NUDGE };
    // Arrows follow the screen: a right-to-left sheet is mirrored.
    let sx = if sh.right_to_left { -step } else { step };
    let d = match key {
        Key::ArrowLeft => vec2(-sx, 0.0),
        Key::ArrowRight => vec2(sx, 0.0),
        Key::ArrowUp => vec2(0.0, -step),
        Key::ArrowDown => vec2(0.0, step),
        _ => return false,
    };
    // On Windows and Linux egui sets `command` with `ctrl`: only the Mac Command key opts out.
    if m.shift || m.mac_cmd {
        return false;
    }
    let Some(a) = sh.object_anchor(o) else { return false };
    let x0 = (sh.col_left(a.cell.col) as f32 + a.dx + d.x).max(0.0);
    let y0 = (sh.row_top(a.cell.row) as f32 + a.dy + d.y).max(0.0);
    let nc = CellRef::new(sh.row_at(f64::from(y0)), sh.col_at(f64::from(x0)));
    let params =
        json!({"kind": o.kind.name(), "id": o.id, "at": nc.a1(), "dx": x0 - sh.col_left(nc.col) as f32, "dy": y0 - sh.row_top(nc.row) as f32});
    app.run_or_alert("object.move", params);
    true
}

/// Turns the dragged shape so its rotation handle points at `p`; the drag is one undo step.
fn rotate_object(app: &mut SheetApp, obj: ObjRef, rect: Rect, p: Pos2, snap: bool) {
    let deg = crate::frame::angle_to(rect, p, snap);
    let revision = app.session.active().map(|d| d.revision);
    let _ = app.session.run("object.move", json!({"kind": obj.kind.name(), "id": obj.id, "rotation": deg}));
    let Drag::Rotate { stepped, .. } = app.grid.drag else { return };
    if stepped {
        coalesce_last_undo(app);
    } else if app.session.active().map(|d| d.revision) != revision
        && let Drag::Rotate { stepped, .. } = &mut app.grid.drag
    {
        *stepped = true;
    }
}

/// Moves the dragged object, or resizes it from the grabbed handle, to follow the pointer at `p`
/// (logical coordinates). The whole drag coalesces into one undo step of its own.
fn drag_object(app: &mut SheetApp, geo: &Geo, sh: &Sheet, p: Pos2) {
    let Drag::Object { obj, start, orig, handle, stepped } = app.grid.drag.clone() else { return };
    let d = (p - start) / geo.z;
    let (cell, dx, dy, w, h) = orig;
    let x0 = sh.col_left(cell.col) as f32 + dx;
    let y0 = sh.row_top(cell.row) as f32 + dy;
    let frame_deg = crate::chartview::frame_of(sh, obj).0;
    let [x0, y0, x1, y1] = match handle {
        Some(hd) if frame_deg != 0.0 => {
            let fh = crate::frame::Handle { x: hd.sides().0, y: hd.sides().1 };
            let r0 = Rect::from_min_max(pos2(x0, y0), pos2(x0 + w, y0 + h));
            let min = crate::objects::min_size(sh, obj);
            let r = crate::frame::resized_turned_by_min(r0, frame_deg, fh, d, min, false);
            let (nx, ny) = (r.min.x.max(0.0), r.min.y.max(0.0));
            [nx, ny, r.max.x.max(nx + min.x), r.max.y.max(ny + min.y)]
        }
        Some(hd) => crate::objects::resized([x0, y0, x0 + w, y0 + h], hd, d, crate::objects::min_size(sh, obj)),
        None => {
            let (x0, y0) = ((x0 + d.x).max(0.0), (y0 + d.y).max(0.0));
            [x0, y0, x0 + w, y0 + h]
        }
    };
    // Re-anchor at the cell under the new top-left.
    let nc = CellRef::new(sh.row_at(y0 as f64), sh.col_at(x0 as f64));
    let mut params = json!({
        "kind": obj.kind.name(), "id": obj.id, "at": nc.a1(),
        "dx": x0 - sh.col_left(nc.col) as f32, "dy": y0 - sh.row_top(nc.row) as f32,
    });
    // Only a handle changes the size. A body move sends none, so the engine keeps whatever the
    // object has: a file can make it larger than `object.move` accepts for a new size, and
    // moving it must not shrink it to that limit.
    if handle.is_some()
        && let Some(p) = params.as_object_mut()
    {
        p.insert("width".into(), json!(x1 - x0));
        p.insert("height".into(), json!(y1 - y0));
    }
    let revision = app.session.active().map(|d| d.revision);
    let _ = app.session.run("object.move", params);
    if stepped {
        coalesce_last_undo(app);
    } else if app.session.active().map(|d| d.revision) != revision
        && let Drag::Object { stepped, .. } = &mut app.grid.drag
    {
        // The first step of this drag stays apart from an earlier drag's step of the same name.
        *stepped = true;
    }
}

/// Previews the selected chart's values block with the grabbed corner dragged to `p` (logical
/// coordinates); the opposite corner stays. The release gives the chart the block
/// (`chart.setValuesRange`).
fn drag_chart_data(app: &mut SheetApp, geo: &Geo, sh: &Sheet, p: Pos2) {
    let Drag::ChartData { chart, orig, corner, .. } = app.grid.drag else { return };
    // The chart's data changed under the drag: drop it, as Esc does, rather than preview a
    // block the release would put over that change.
    if !chart_still_plots(app, chart, orig) {
        app.grid.drag = Drag::None;
        return;
    }
    app.grid.drag = Drag::ChartData { chart, orig, corner, to: Some(chart_data_target(geo, sh, orig, corner, p)) };
}

/// Whether chart `chart` on the active sheet still plots the values block `orig` its drag
/// started from. A command run between frames (the control channel, a macro) may have changed
/// or removed it, and the dragged block would then overwrite that change. Read from the session,
/// not the frame's workbook, which predates such a command.
fn chart_still_plots(app: &SheetApp, chart: u32, orig: RangeRef) -> bool {
    let Some(wb) = app.session.active().map(|d| &d.wb) else { return false };
    let si = wb.active_sheet();
    wb.sheet(si)
        .and_then(|sh| sh.charts.iter().find(|ch| ch.id == chart))
        .and_then(|ch| gridcraft_engine::chart_data::chart_data(wb, si, ch))
        .is_some_and(|data| data.sheet == si && data.values == orig)
}

/// The values block `orig` with its `corner` dragged to `p`. Each edge the corner moves snaps
/// to the gridline nearest the pointer, so every row and column changes over at its own middle
/// whatever its height or width, and a release where the press was (on the corner's own
/// gridlines) changes nothing. The block may flip past its fixed edges, as a selection does; a
/// moving edge dropped on its fixed edge keeps one row or column.
fn chart_data_target(geo: &Geo, sh: &Sheet, orig: RangeRef, corner: crate::objects::Handle, p: Pos2) -> RangeRef {
    let (sx, sy) = corner.sides();
    let (x, y) = (p.x.clamp(geo.cells.left() + 1.0, geo.cells.right() - 1.0), p.y.clamp(geo.cells.top() + 1.0, geo.cells.bottom() - 1.0));
    // Gridline `k` is the top (left) edge of row (column) `k`; the last one closes the sheet.
    let row = geo.row_at(sh, y);
    let row_line = nearest_line(geo.y(sh, row), sh.row_height(row) * geo.z, row, y, MAX_ROWS);
    let col = geo.col_at(sh, x);
    let col_line = nearest_line(geo.x(sh, col), sh.col_width(col) * geo.z, col, x, MAX_COLS);
    let (r0, r1) = between_lines(if sy < 0 { orig.end.row.saturating_add(1) } else { orig.start.row }, row_line, sy);
    let (c0, c1) = between_lines(if sx < 0 { orig.end.col.saturating_add(1) } else { orig.start.col }, col_line, sx);
    RangeRef::new(CellRef::new(r0, c0), CellRef::new(r1, c1))
}

/// The gridline nearest `v` for line `index`, which starts at `start` and is `size` long: its
/// own start, or the next line's past its middle (never past `last`).
fn nearest_line(start: f32, size: f32, index: u32, v: f32, last: u32) -> u32 {
    if v - start < size / 2.0 { index } else { index.saturating_add(1).min(last) }
}

/// The rows (columns) from gridline `fixed` to gridline `moving`. A moving edge on the fixed one
/// keeps one line on its own side: after it for a bottom or right edge (`dir` > 0), before it
/// for a top or left edge.
fn between_lines(fixed: u32, moving: u32, dir: i8) -> (u32, u32) {
    let moving = match (moving == fixed, dir > 0) {
        (false, _) => moving,
        (true, true) => fixed.saturating_add(1),
        (true, false) => fixed.saturating_sub(1),
    };
    (fixed.min(moving), fixed.max(moving).saturating_sub(1))
}

/// A click on a hyperlink. References select; web and e-mail addresses ask first (the dialog's
/// OK calls `Session::open_confirmed_link`, since `link.open` refuses them for programmatic
/// callers, #2181); every other kind is refused with a message. The decision is the engine's
/// ([`gridcraft_engine::links::classify`]), the same one `link.open` applies.
pub fn follow_link(app: &mut SheetApp, target: &str) {
    use gridcraft_engine::links::{LinkKind, classify};
    match classify(target) {
        LinkKind::Internal(r) => {
            let _ = app.session.run("edit.goTo", json!({"reference": r.trim_start_matches('#')}));
            app.grid.ensure_visible = true;
        }
        LinkKind::External(url) => app.open_dialog("openLink", json!({"url": url})),
        LinkKind::Refused(why) => app.message = Some(("Hyperlink".into(), why)),
    }
}

/// Moves the pointed cell one step, or with `jump` (Ctrl+arrow) to the edge of its data region;
/// `extend` (Shift) moves the far end of the pointed range instead. Keeps the pointed cell visible.
pub fn point_move(app: &mut SheetApp, ed: &mut EditState, dr: i64, dc: i64, extend: bool, jump: bool) {
    let Some(d) = app.session.active() else { return };
    let Some(sheet) = d.wb.active() else { return };
    let from = ed.point_cell.unwrap_or(ed.cell);
    let to = if jump { gridcraft_engine::selection::jump(sheet, from, dr.signum(), dc.signum()) } else { from.offset_clamped(dr, dc) };
    let anchor = if extend {
        // The anchor is the corner opposite the moving end: the written range is normalized, so
        // after extending up or left its first cell is the moving end, not the anchor.
        let pointed = ed.point.and_then(|(s, e)| ed.text.get(s..e)).and_then(RangeRef::parse);
        let inferred_anchor = pointed
            .map(|r| {
                CellRef::new(
                    if from.row == r.start.row { r.end.row } else { r.start.row },
                    if from.col == r.start.col { r.end.col } else { r.start.col },
                )
            })
            .unwrap_or(from);
        ed.point_anchor.filter(|(sheet, _)| *sheet == d.wb.active_sheet()).map(|(_, cell)| cell).unwrap_or(inferred_anchor)
    } else {
        to
    };
    let text = if extend { RangeRef::new(anchor, to).a1() } else { to.a1() };
    let text = if ed.sheet != d.wb.active_sheet() { format!("{}!{text}", gridcraft_engine::formula::quote_sheet(&sheet.name)) } else { text };
    let sheet = d.wb.active_sheet();
    ed.insert_ref(&text);
    ed.point_cell = Some(to);
    ed.point_anchor = Some((sheet, anchor));
    app.grid.ensure_visible = true;
}

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

    #[test]
    fn a_chart_data_edge_snaps_to_the_nearest_gridline_of_any_size() {
        // Row 5 starts at 100 and is 20 tall: before its middle the line is its own, past it the next.
        assert_eq!(nearest_line(100.0, 20.0, 5, 109.0, MAX_ROWS), 5);
        assert_eq!(nearest_line(100.0, 20.0, 5, 111.0, MAX_ROWS), 6);
        // A 100-tall row changes over at 50 into it, not at the grabbed row's middle.
        assert_eq!(nearest_line(100.0, 100.0, 5, 149.0, MAX_ROWS), 5);
        assert_eq!(nearest_line(100.0, 100.0, 5, 151.0, MAX_ROWS), 6);
        assert_eq!(nearest_line(0.0, 20.0, MAX_ROWS - 1, 19.0, MAX_ROWS), MAX_ROWS);
        // A1:A5 (lines 0 and 5) by its bottom edge: on line 5 it stays, on 8 it grows, on 2 it shrinks.
        assert_eq!(between_lines(0, 5, 1), (0, 4));
        assert_eq!(between_lines(0, 8, 1), (0, 7));
        assert_eq!(between_lines(0, 2, 1), (0, 1));
        // Dropped on its fixed edge it keeps one row; past it the block flips.
        assert_eq!(between_lines(4, 4, 1), (4, 4));
        assert_eq!(between_lines(4, 2, 1), (2, 3));
        // By its top edge (fixed line 5, below A5).
        assert_eq!(between_lines(5, 0, -1), (0, 4));
        assert_eq!(between_lines(5, 5, -1), (4, 4));
        assert_eq!(between_lines(5, 7, -1), (5, 6));
    }

    #[test]
    fn resize_targets_follow_the_selection_only_when_the_dragged_line_is_in_it() {
        let sel = [RangeRef::cols(0, 0), RangeRef::cols(2, 3)];
        assert_eq!(resize_targets(&sel, 3, true), "A:A,C:D");
        assert_eq!(resize_targets(&sel, 1, true), "B:B");
        assert_eq!(resize_targets(&[RangeRef::rows(1, 2)], 2, false), "2:3");
        assert_eq!(resize_targets(&[RangeRef::rows(1, 2)], 5, false), "6:6");
        assert_eq!(resize_targets(&[], 0, true), "A:A");
    }

    #[test]
    fn drag_sizes_are_nan_safe() {
        assert_eq!(nan_safe_size(f32::NAN), 0.0);
        assert_eq!(nan_safe_size(-4.0), 0.0);
        assert_eq!(nan_safe_size(12.5), 12.5);
    }
}

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

    #[test]
    fn resize_tips_follow_the_interface_language() {
        use crate::i18n::Language;
        assert_eq!(column_width_tip(Language::En, 64.0), "Width: 8.43 (64 pixels)");
        assert_eq!(row_height_tip(Language::En, 20.0), "Height: 15.00 (20 pixels)");
        let de = Language::De;
        assert_eq!(column_width_tip(de, 64.0), de.tr("Width: {chars} ({pixels} pixels)").replace("{chars}", "8.43").replace("{pixels}", "64"));
        assert_eq!(row_height_tip(de, 20.0), de.tr("Height: {points} ({pixels} pixels)").replace("{points}", "15.00").replace("{pixels}", "20"));
        assert!(!column_width_tip(de, 64.0).starts_with("Width"));
    }

    #[test]
    fn the_pen_preview_is_the_ink_the_stroke_commits() {
        // #1786: the preview was always blue at 2 pt, whatever the pen.
        let theme = gridcraft_engine::model::Theme::default();
        assert_eq!(pen_ink("#C00000", 3.0, &theme), (Color32::from_rgb(0xC0, 0, 0), 3.0));
        assert_eq!(pen_ink("", 0.0, &theme), (Color32::from_rgb(0x1F, 0x5F, 0xC9), 2.0), "no pen chosen yet: pen blue, 2 pt");
        assert_eq!(pen_ink("not a colour", 0.2, &theme), (Color32::from_rgb(0x1F, 0x5F, 0xC9), 1.0));
        // A highlighter is wide and translucent, as the committed ink is painted.
        let (c, w) = pen_ink("#FFFF00", 12.0, &theme);
        assert_eq!((c, w), (Color32::from_rgb(0xFF, 0xFF, 0).gamma_multiply(0.45), 12.0));
    }
}