Files
gridcraft/crates/ui-egui/src/grid.rs
T
Pranav f6a0556b9e Objects: one selection for every floating object, eight resize handles, and objects that follow edits (#470)
* Objects: one selection for charts, pictures, shapes and slicers, with eight resize handles

The sheet tracked the selected object as a bare id in `selected_chart`, so
only charts and text boxes drew a selection frame, only the bottom-right
corner resized, and the kind of the selected object had to be guessed from
the id. The selection is now `SheetApp::selected_object: Option<ObjRef>`,
with `selected_chart()` kept for the Chart Design tab and the Format Chart
pane.

- Model: `ObjKind` (chart, image, shape, slicer) and `ObjRef { kind, id }`;
  `Sheet` helpers find, move and remove an object by `ObjRef` and walk every
  object's anchor in a fixed order. `next_object_id` saturates instead of
  overflowing on an id at `u32::MAX` read from a file.
- Commands: `object.delete`, `object.move` and `object.setAnchorMode` accept
  the four kinds through one parameter check, refuse an unknown kind or id
  instead of succeeding silently, and clamp hostile offsets. `object.delete`
  replies with the deleted object. Arrange and the Selection Pane include
  slicers, which stack above the other objects.
- Sheet: the selected object of any kind draws a frame with eight handles
  over every object. Each handle resizes only its own edges, which never
  cross; the body moves the object, and the first drag frame already applies
  the pointer's movement. The pointer shows the handle's resize cursor or a
  move cursor, with the diagonals swapped on a right-to-left sheet, where the
  frame moves with its object.
- Keys: Escape drops the object selection; Delete and Backspace keep
  deleting the selected object (#213). A selection whose object disappears
  (undo, redo, delete, sheet switch) is cleared.
- Double-click: `open_object` routes by kind (a text box edits in place, a
  chart opens Format Chart).
- Control protocol: `ui.inspect` reports `selectedObject {kind, id}` and
  keeps `selectedChart`; `ui.object.select` selects any object and replies
  with its rect. The snapshot example takes `--object <id>`.

Tests: engine tests for every kind by kind and id, the Selection Pane and
hostile parameters; UI tests for selecting each kind (a slicer over a chart
takes the click), all eight handles on four kinds, cursors, Delete,
Backspace and Escape, undo and redo, double-click routing, and resizing on a
right-to-left sheet. Existing tests use the new selection API.

* Objects: every kind follows edits; chart series follow cut-moves and sheet deletes

Structural edits and sorts kept three hand-indexed lists (charts, images,
shapes) in step in two places, and slicers were left out of both, so a
slicer stayed put when rows were inserted above it. Chart series were
rewritten for inserted and deleted lines and for sheet renames, but not for
cut-moves or sheet deletes, which left them pointing at the old cells.

- Inserting and deleting rows and columns and sorting walk
  `Sheet::object_anchors` and `object_anchors_mut`, one fixed order over
  every kind, so slicers now follow their cells by their anchor mode like
  the other objects, and a new kind cannot be forgotten in one of the
  passes.
- `rewrite_cell_links` is the one place that rewrites the references
  floating objects hold (chart series values, categories and names,
  and the source block a chart was made from).
  `rewrite_all_formulas` calls it, which covers inserting and deleting
  lines and cells and cut-moves on one sheet or across sheets; renaming and
  deleting a sheet call it too, so a series into a deleted sheet becomes
  #REF!, as a formula does.
- Copying a sheet gives its charts, pictures, shapes and slicers fresh ids,
  keeping ids unique across the workbook, which object selection and the
  `{kind, id}` commands rely on.

Tests: every kind through row and column inserts and deletes, an absolute
shape, a sort and undo; a slicer through inserted rows; chart series
through a cut-move, a sheet rename, a sheet delete and undo; ids after a
sheet copy.

* Objects: bubble sizes follow edits like the other series references

`rewrite_cell_links` rewrote a chart series' values, categories and name
but not its bubble sizes, so inserting or deleting lines, a cut-move or a
sheet rename left a bubble chart's sizes pointing at the old cells. They
are now rewritten with the rest.

Test: bubble sizes through an inserted row, a cut-move and a sheet rename.

* Objects: a resize handle under the headers leaves the press to them

A selected object's handles reach a few points outside it, and a press
was matched against them before any check of where it landed, so a press
on the column or row header beside an object at the sheet's edge resized
the object instead of selecting the column or row. The cursor already
ignored handles outside the cells.

`chartview::selected_handle` finds the selected object's handle under a
point only over the cell area, as `hit` does, and not while objects are
hidden; the press and the cursor both use it.

Test: presses within a handle's reach over the column header and the row
header neither move nor resize the object.

* Objects: each drag of an object is its own undo step

A drag merges its frames into one undo step by dropping a new step whose
label matches the one before it. Its first frame did the same, so a second
drag of an object (a move after a move, or a resize after a move) merged
into the first drag's "Move Object" step, and one undo took back both.

`Drag::Object` records whether the drag has made its step; only the later
frames of the same drag merge into it.

Test: a move and then a resize of a picture take two undos to reverse,
the first restoring the moved picture.

* Objects: the parity and gap docs no longer list chart resizing as missing

gaps.md (§4), target-app-parity.md (the Essentials tier's work, the
Mainstream chart row, the interaction discount and the Essentials chart
task) and chart-parity.md (the element table and the work list) still
described charts as impossible to resize (#190). Charts move and resize
from eight handles like every floating object, so those statements now
say so; the 2026-10-10 revision rows and the 10-10 re-check stay as
history. Scores and the 40-60 h chart estimate are unchanged (resizing
was 1-2 h, within the rounding).

* Objects: one chart evidence paragraph in gaps.md; trendlines are not missing

gaps.md §4 carried two evidence paragraphs, an older one saying PRs #158
and #161 were open and a newer one saying all 2-D kinds survive XLSX round
trip, both repeating the resize, smooth-line, Switch Row/Column and
trendline statements. It is one paragraph with the current status again.

The Mainstream chart row in target-app-parity.md listed trendlines as
missing; they are read, written and drawn (`Series::trendlines`, the XLSX
chart reader and writer, `chart.addElement`), as chart-parity.md records.
The row now says so and keeps "no axis options". No score change.

* Objects: only the selected object's handles resize; a press elsewhere on an object moves it

A primary drag looked for a handle under the press on whatever object it
grabbed, so pressing near the edge or corner of an object that was not
selected started a resize, while the pointer over that spot showed the
Move cursor (handles are only shown, and only offered by the cursor, on
the selected object). The press now takes its handle from
`chartview::selected_handle`, the same lookup the cursor uses; a press on
any other object selects and moves it.

Test: dragging an unselected shape by its bottom-right corner shows the
Move cursor, then selects and moves the shape without resizing it.

* Docs: ui.object.select says what it replies when it clears the selection

* Objects: a test pins that both anchor accessors visit the same objects in the same order

Sorting and row or column edits read every anchor through
`object_anchors`, compute the new ones and write them back through
`object_anchors_mut` in step. Nothing checked that the two accessors
visit the same objects in the same order; a kind of floating object
reaching only one of them would have paired objects with other objects'
anchors silently.

Test: two objects of every kind are inserted in a mixed order, each
anchor is marked with its position through the mutable accessor, the
marks are read back through the shared one in the same sequence, the
count matches the per-kind collections, and the mark is found on the
object `object_anchor` names by kind and id. The test's constructor
matches on `ObjKind` exhaustively, so a new kind does not compile until
the test covers it.

* Objects: sorting keeps the size of a "move and size" picture whose lines swap places

A picture anchored to move and size with cells and spanning two rows
(or columns) was re-fitted between its top-left and bottom-right lines
after a sort. When the sort put the bottom line above the top one, the
fitted extent was negative and the picture collapsed to a zero height
or width. It now keeps its old size on that axis and travels with its
top-left line, like a "move only" picture.

Tests: for a sort by rows and one by columns, "move and size" and
"move only" pictures inside one line travel with it (the first
re-fitted to the same line, the second at its own size), an absolute
picture stays while the cells move under it, a two-line picture whose
lines swap keeps its size, and undo restores every anchor.

* Objects: a copied sheet's objects get free ids even when a file used the largest id

`Workbook::next_object_id` returned one more than the largest id in use,
saturating at `u32::MAX`. A workbook read from a file can carry an object
with that id; every later insert (a chart, picture, shape, table or
slicer) then got `u32::MAX` again, and so did each object of a copied
sheet, whose ids also came from a saturating counter. Lookups and
selection take the first object with an id, and `object.delete` removes
every one.

`Workbook::free_object_ids(count)` now returns distinct unused ids: those
above the largest in use while they last, then the lowest free ones from
1. `next_object_id` takes the first of them, and the sheet copy takes one
per copied object (and refuses if the id space were ever exhausted). The
model test that recorded the saturation now checks the free ids instead,
and a new one covers a file that used the largest ids: the free ids come
from below, 100,000 of them distinct and in order.

Test: object_ids_stay_unique_when_a_file_used_the_largest_id gives a
shape id u32::MAX, inserts two shapes and copies the sheet; every shape id
is distinct across both sheets. It fails without the fix (both new shapes
get 4294967295).

* Objects: main's chart data table compiles with the object selection and the model's object test

Two leftovers of the merge of origin/main (25881a8e), neither a textual
conflict: `Chart` gained a `data_table` field, which the `push_object`
helper of the model's object test did not set (it is `None`, as in
`insert.chart`); and chart_data_table.rs set the `selected_chart` field
this branch replaced by `selected_object`. The test selects its chart as
a floating object, as the branch's other tests do.

* Objects: object.move and chart.set keep a size a file made larger than 10,000

`object.move` clamped `width` and `height` to 10,000 points, the most it
gives a new size, while the XLSX reader accepts anchors far past that.
A resize of a picture a file made 12,000 wide passed 11,990 through the
clamp and jumped to 10,000; `chart.set`, whose Format Chart pane sends
the unchanged dimension back with the edited one, clamped the same way.

Each dimension is now capped at 10,000 or the object's current size,
whichever is larger (`size_cap`): such an object keeps its size when it
is moved, shrinks by what a resize asks and never grows further, and a
hostile size is still capped. The params doc of `object.move` and the
control protocol notes say so.

Tests: an_oversized_imported_object_keeps_its_size_when_moved_and_shrinks_only_by_a_resize
makes a picture 12,000 by 300, writes and reads it back as a file, then
moves it without a size (12,000 stays), asks 12,010 (stays 12,000),
11,990 (11,990, no jump) and 50,000 by 50,000 (11,990 by 10,000).
chart_set_keeps_a_chart_size_a_file_made_larger_than_the_limit does the
same through `chart.set`. Both fail without the fix (width 10,000).

* Objects: dragging an object's body sends its position only, not its size

`drag_object` sent `width` and `height` with every step of a body drag,
so moving a picture a file made 12,000 wide shrank it to the 10,000 that
`object.move` gives a new size. Only a handle drag sends a size now; a
body move leaves the engine's size alone.

Tests (real input): dragging_the_body_of_an_oversized_imported_object_keeps_its_size
reopens the workbook with a 12,000 by 60 picture, drags its body by
30 by 25 and checks the size is untouched, the picture moved with the
pointer and the journaled `object.move` carries no width or height; it
fails without the fix (the journaled command carries both, and without
the engine's cap the picture is 10,000 wide).
a_handle_drag_on_an_oversized_imported_object_resizes_by_the_drag_only
moves the left handle 10 px right: the picture is 10 points narrower in
the window and keeps a width near 12,000, with no jump to the limit.

* Objects: the Format Chart Size fields show a chart's real size and send only the edited dimension

The Width and Height fields ranged 40 to 4,000 and sent both values on
every edit. egui clamps an existing value into a field's range, so a
chart a file made 12,000 wide showed "Width 4000", and typing a new
height sent that 4,000 as the width: the chart shrank although only its
height changed, and the cap `chart.set` keeps for an existing size
cannot help once the pane itself sends 4,000. Each field's range now
reaches the larger of 4,000 and the chart's current size, so the field
shows the real size, and a commit sends only the dimension that differs
from the chart's (`chart.set` reads `width` and `height` independently).

Test (real input): the_size_fields_keep_an_oversized_imported_chart_width_when_the_height_changes
reopens a workbook with a 12,000-wide chart, opens Format Chart Area's
Size section, checks the Width field shows 12000 and types 201 as the
height: the width stays 12,000, the height is 201 and the journaled
chart.set carries no width. Without the fix the field shows
"Width 4000".
2026-11-02 09:30:13 +01:00

343 lines
15 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! The worksheet grid: virtualised painting of only the visible cells, frozen panes,
//! headers, selection, fill handle, column/row resizing, text overflow, borders, conditional
//! formats, tables, comments, filters, sparklines, floating charts/pictures/shapes and the
//! in-cell editor.
use std::sync::Arc;
use egui::{Align2, Color32, CursorIcon, FontId, Painter, Pos2, Rect, Sense, Stroke, StrokeKind, pos2, vec2};
use gridcraft_engine::cf::{CfCache, CfLook};
use gridcraft_engine::core::{CellRef, MAX_COLS, MAX_ROWS, RangeRef, Value, col_to_letters};
use gridcraft_engine::model::{BorderLine, BorderStyle, Color, HAlign, LineIndex, PatternType, Sheet, Style, Underline, VAlign, Workbook};
use serde_json::json;
use crate::SheetApp;
use crate::editor::EditState;
use crate::theme::{self, Tokens};
/// A painted pane: its row span, column span and screen rectangle.
pub(crate) type PaneQuad = ((u32, u32), (u32, u32), Rect);
/// Cached Page Break Preview ranges, keyed by (doc uid, revision, sheet).
type PagesCache = ((u64, u64, usize), Vec<(RangeRef, u32)>);
/// Cached Show Details cells, keyed by (doc uid, revision, sheet, pivot).
type DetailsCache = ((u64, u64, usize, usize), Option<std::collections::HashSet<(u32, u32)>>);
mod cell_paint;
mod cursor;
mod editor;
mod geo;
mod interact;
mod keyboard;
mod menus;
mod quadrant;
mod selection;
mod show;
mod tables;
pub(crate) use cell_paint::paint_border;
#[cfg(test)]
pub(crate) use cell_paint::{cell_text_y, rotated_text_pos, wrapped_cell_text_y};
#[cfg(test)]
use cell_paint::{center_across_end, display_text, look, numfmt_color, painted_halign};
pub use editor::validation_arrow;
#[cfg(test)]
use editor::{editor_slack, editor_width, list_picker_height};
pub use geo::Geo;
pub use interact::{follow_link, freeze_handles, point_move};
pub(crate) use quadrant::{QuadrantPaint, paint_quadrant};
pub use selection::selection_fill;
pub(crate) use selection::{SelectionPaintInput, paint_selection};
pub(crate) use show::horizontal_scrollbar;
pub use show::show;
#[cfg(test)]
use tables::filter_table_range;
pub use tables::{TableHeading, filter_button_rect, heading_table, table_headings};
pub const COL_HEADER_H: f32 = 21.0;
/// Sheet units are 96-dpi pixels (as in XLSX); on screen one unit is drawn at this many points,
/// which matches desktop spreadsheet density (a default 20 px row is 16 pt tall).
pub const DISPLAY_SCALE: f32 = 0.8;
/// The zoom percentages a Ctrl+wheel notch steps between: four per doubling (about 20% apart),
/// so 25, 50, 100, 200 and 400 are on it. Excel steps 15 points a notch instead; the status bar's
/// Zoom In / Zoom Out buttons keep their 10% steps.
pub const WHEEL_ZOOM_LADDER: [u16; 22] = [10, 12, 15, 18, 21, 25, 30, 35, 42, 50, 60, 70, 85, 100, 120, 140, 170, 200, 240, 280, 340, 400];
/// Seconds without Ctrl+wheel input after which part of a notch turned so far is forgotten.
const WHEEL_ZOOM_IDLE: f64 = 0.75;
/// The zoom one Ctrl+wheel notch goes to from `zoom`: the next step on [`WHEEL_ZOOM_LADDER`] in
/// that direction, skipping a step less than 5% away (121% out goes to 100%, not 120%), but never
/// 100% or the 10% / 400% limits (99% or 101% towards 100% goes to 100%).
pub fn wheel_zoom_step(zoom: u16, zoom_in: bool) -> u16 {
let zoom = zoom.clamp(10, 400);
let z = u32::from(zoom);
let far = |l: u32| if zoom_in { l * 100 >= z * 105 } else { l * 105 <= z * 100 };
let mut ahead = WHEEL_ZOOM_LADDER.iter().copied().filter(|&l| if zoom_in { l > zoom } else { l < zoom }).collect::<Vec<_>>();
if !zoom_in {
ahead.reverse();
}
let limit = ahead.last().copied().unwrap_or(zoom);
ahead.into_iter().find(|&l| l == 100 || far(u32::from(l))).unwrap_or(limit)
}
/// One frame of the zoom gliding from `from` to `to` percent: the share `t` (0–1) of the way,
/// measured as a ratio so zooming in and out feel alike, and at least one percent, so it arrives.
pub fn zoom_glide_step(from: u16, to: u16, t: f32) -> u16 {
let (f, g) = (f32::from(from.max(1)), f32::from(to.max(1)));
let next = (f * (g / f).powf(t.clamp(0.0, 1.0))).round();
let next = if next.is_finite() { next.clamp(f32::from(from.min(to)), f32::from(from.max(to))) as u16 } else { to };
match (next == from, from.cmp(&to)) {
(true, std::cmp::Ordering::Less) => from + 1,
(true, std::cmp::Ordering::Greater) => from - 1,
_ => next,
}
}
#[derive(Clone, Debug, Default, PartialEq)]
pub enum Drag {
#[default]
None,
Select,
Rows(u32),
Cols(u32),
/// Reordering one contiguous whole-column selection by its header.
MoveCols {
source: RangeRef,
before: Option<u32>,
},
ResizeCol {
col: u32,
start: f32,
orig: f32,
},
ResizeRow {
row: u32,
start: f32,
orig: f32,
},
/// Dragging the fill handle; `menu` when the right button drags it (the fill menu opens on release).
Fill {
target: Option<RangeRef>,
menu: bool,
},
/// Dragging a freeze handle: `cols` for the column bar, `to` the line count it would freeze.
Freeze {
cols: bool,
to: Option<u32>,
},
/// Moving the selection by its border (cut & paste).
Move {
grab: CellRef,
to: Option<CellRef>,
},
/// Moving a floating object, or resizing it from one of its eight handles.
Object {
obj: gridcraft_engine::model::ObjRef,
start: Pos2,
orig: (CellRef, f32, f32, f32, f32),
handle: Option<crate::objects::Handle>,
/// This drag has made its undo step; later frames merge into it, and never into the
/// step of an earlier drag.
stepped: bool,
},
}
/// The fill a left-drag of the handle just made, which the Auto Fill Options button can redo
/// another way. It only applies while nothing else changed the workbook (`revision`) and the
/// filled cells are still selected.
#[derive(Clone, Debug, PartialEq)]
pub struct FillTag {
pub src: RangeRef,
pub target: RangeRef,
pub uid: u64,
pub sheet: usize,
pub revision: u64,
pub undo_len: usize,
}
/// Trace Precedents, Trace Dependents and Trace Error arrows: they stay on the cells they were
/// traced from while the selection moves. They go away when anything but a zoom changes the
/// workbook (`revision`): Excel removes them on edits to the traced formula and on inserted,
/// deleted or moved cells, this also on a new value in a precedent.
pub struct Trace {
pub uid: u64,
pub revision: u64,
pub arrows: Vec<TraceArrow>,
}
/// One trace arrow, from a cell or range (boxed) to a cell, each on its sheet. An arrow is drawn
/// on a sheet that holds both its ends.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct TraceArrow {
pub from: (usize, RangeRef),
pub to: (usize, RangeRef),
/// A link between two cells showing the error Trace Error follows, drawn in the error colour.
pub error: bool,
}
impl Trace {
/// The arrows of a trace of the active cell, from the command's result: `{"sheet", "range"}`
/// precedents (Trace Precedents), `{"sheet", "cell"}` dependents (Trace Dependents), or
/// `{"arrows": [{"from", "to", "kind"}]}` (Trace Error). Ends on a sheet the workbook no
/// longer has are left out.
pub fn new(app: &SheetApp, result: serde_json::Value) -> Option<Trace> {
let d = app.session.active()?;
let traced = (d.wb.active_sheet(), RangeRef::new(d.selection.active, d.selection.active));
let end = |v: &serde_json::Value| {
let sheet = match v["sheet"].as_str() {
Some(name) => d.wb.sheet_index(name)?,
None => traced.0,
};
Some((sheet, RangeRef::parse(v["range"].as_str().or(v["cell"].as_str())?)?))
};
let arrows = match result.get("arrows").and_then(|a| a.as_array()) {
Some(list) => {
list.iter().filter_map(|a| Some(TraceArrow { from: end(&a["from"])?, to: end(&a["to"])?, error: a["kind"] == "error" })).collect()
}
None => result
.as_array()
.into_iter()
.flatten()
.filter_map(|it| {
let (from, to) = if it.get("range").is_some() { (end(it)?, traced) } else { (traced, end(it)?) };
Some(TraceArrow { from, to, error: false })
})
.collect(),
};
Some(Trace { uid: d.uid, revision: d.revision, arrows })
}
/// The active document's uid and revision, to hand [`Trace::keep_through_zoom`] after a zoom.
pub fn key(app: &SheetApp) -> Option<(u64, u64)> {
app.session.active().map(|d| (d.uid, d.revision))
}
/// Zooming changes the workbook (its revision) but moves no cell: arrows that were shown
/// before a zoom stay after it, as in Excel (#3097). `before` is [`Trace::key`] from then.
pub fn keep_through_zoom(app: &mut SheetApp, before: Option<(u64, u64)>) {
let now = Trace::key(app);
if let Some(t) = app.grid.trace.as_mut()
&& before == Some((t.uid, t.revision))
&& let Some((uid, revision)) = now
&& uid == t.uid
{
t.revision = revision;
}
}
}
#[derive(Default)]
pub struct GridState {
pub drag: Drag,
pub ensure_visible: bool,
/// With `ensure_visible`: scroll to the moving end of the selection instead of the active cell
/// (Shift/Ctrl+Shift+arrows keep the active cell on the anchor while the far corner moves).
pub reveal_moving_end: bool,
/// With `ensure_visible`: the cell an arrow or paging key moved from (the moving end when
/// extending), set only by those keys. A move from the scrolled rows or columns into the
/// frozen ones scrolls them back to their top or left.
pub reveal_from: Option<CellRef>,
pub last_title: Option<String>,
pub drag_select: bool,
pub rect: Option<Rect>,
pub cells_rect: Option<Rect>,
/// Column and row of the clicked header cell, and where to open the menu.
pub filter_menu: Option<(u32, u32, Pos2)>,
pub context_menu: Option<Pos2>,
/// The frame a right-click opened `context_menu` in: that click's own press doesn't close it.
pub context_menu_frame: u64,
/// After a right-drag of the fill handle: the source, the dragged range and where to open the menu.
pub fill_menu: Option<(RangeRef, RangeRef, Pos2)>,
/// After a left-drag of the fill handle: the Auto Fill Options button beside the filled cells.
pub fill_tag: Option<FillTag>,
/// The right-clicked chart, picture, shape or slicer: where to open its menu, its kind and id.
pub object_menu: Option<(Pos2, &'static str, u32)>,
pub marching_phase: f32,
/// The selection outline on its way to a new selection.
pub glide: crate::selection_glide::SelectionGlide,
pub last_click: Option<(CellRef, f64)>,
pub hover_cell: Option<CellRef>,
pub last_autosave: f64,
pub last_border: String,
pub last_fill: String,
pub last_font_color: String,
pub trace: Option<Trace>,
pub renaming_tab: Option<usize>,
pub rename_text: String,
pub list_picker: Option<CellRef>,
/// Open task pane: comments, watch, selection, formatChart.
pub pane: Option<String>,
/// Ink stroke being drawn (sheet points).
pub ink: Vec<[f32; 2]>,
/// Page ranges for Page Break Preview, cached per (doc uid, revision, sheet).
pub pages: Option<PagesCache>,
/// The PivotTable Fields pane's `pivot.fields` answer, cached per (doc uid, revision, pivot):
/// it scans the whole source list, far too slow to repeat every frame (#2113).
pub pivot_fields: Option<((u64, u64, String), serde_json::Value)>,
/// The cells of a PivotTable report where the cell menu offers Show Details, relative to the
/// report's top-left and cached per (doc uid, revision, sheet, pivot): finding them computes
/// the whole report. `None` when the report can't be computed or is out of date: every cell
/// of it offers Show Details, and running it says why.
pub show_details_cells: Option<DetailsCache>,
pub header_menu: Option<(Pos2, bool)>,
/// Page Layout view pagination, cached per (doc uid, revision, sheet, rows, columns).
pub paper: Option<crate::paper_view::PaperCache>,
/// Header or footer being edited in place (Page Layout view).
pub hf_edit: Option<crate::paper_view::HfEdit>,
/// A page margin being dragged on a ruler (Page Layout view); committed on release.
pub ruler_drag: Option<crate::paper_view::RulerDrag>,
/// Insert › Header & Footer: start editing the first page's header once Page Layout view is up.
pub hf_start: bool,
/// The grid geometry of the last frame (hit-testing for agents and tests).
pub geo: Option<Geo>,
/// The horizontal scrollbar's track in the sheet tab bar (hit-testing for tests).
pub hscroll: Option<Rect>,
/// The handle between the sheet tabs and the horizontal scrollbar (hit-testing for tests).
pub tab_split: Option<Rect>,
/// The share of the tab bar each workbook's tabs (and New sheet) take after the handle was
/// dragged, by document uid. A workbook without one gives its tabs up to 60%.
pub tab_shares: std::collections::HashMap<u64, f32>,
/// Ctrl+wheel zoom in progress (see [`WheelZoom`]).
pub wheel_zoom: Option<WheelZoom>,
/// A one-finger touch drag in progress: it pans the sheet instead of selecting.
pub touch_pan: bool,
/// What the macro step editor shows on the grid (Check, debugging).
pub macro_overlay: Option<crate::macro_editor::MacroOverlay>,
}
/// Ctrl+wheel zoom for one (doc uid, sheet). egui eases a notch in over several frames and
/// fine-grained wheels send parts of one, so the turning is counted in notches, and each whole
/// notch steps [`WHEEL_ZOOM_LADDER`]. With animations on the zoom then glides to that step.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct WheelZoom {
pub place: (u64, usize),
/// Turned so far towards the next step, in notches (+ in, − out).
pub notches: f32,
/// When `notches` last changed.
pub time: f64,
/// The step the zoom is gliding to, and the percentage set last on the way.
pub glide: Option<(u16, u16)>,
}
impl WheelZoom {
/// The state for `place` showing `zoom` percent: fresh for another document or sheet, and
/// without its glide if the zoom was changed some other way since the glide set it.
fn at(app: &SheetApp, place: (u64, usize), zoom: u16, now: f64) -> WheelZoom {
let mut w = app.grid.wheel_zoom.filter(|w| w.place == place).unwrap_or(WheelZoom { place, notches: 0.0, time: now, glide: None });
if w.glide.is_some_and(|(_, shown)| shown != zoom) {
w.glide = None;
}
w
}
}
/// Row and column heading labels grow with the zoom as the cells do, as in Excel (at 400% the
/// labels are four times their 100% size), and never get smaller than a readable 8.5 points.
pub(crate) fn heading_font_size(zoom: f32) -> f32 {
(11.5 * (zoom / DISPLAY_SCALE)).max(8.5)
}
#[cfg(test)]
mod tests;