Repository Public
1# Grid engine23The worksheet grid is one custom AppKit view, `GridView`, in `Packages/SheetUI/Sources/SheetUI/Grid/`.4It draws only what is visible, with CoreGraphics and CoreText, and handles scrolling, selection,5resizing, autofill, in-cell editing and hit testing itself. There is no `NSTableView`, no6`NSScrollView` and no per-cell view or layer.78| File | Lines | Role |9|---|---|---|10| `Grid/AxisLayout.swift` | 74 | index ⇄ offset mapping for rows and columns |11| `Grid/GridView.swift` | 657 | geometry, scrolling, zoom, drawing of quadrants, overlays, headers, editor placement, autofit |12| `Grid/GridView+Events.swift` | 486 | hit testing, mouse, context menu, keyboard, responder actions |13| `Grid/GridView+Accessibility.swift` | 297 | accessibility table and cell elements (see [accessibility.md](../development/accessibility.md)) |14| `Grid/CellPainter.swift` | 356 | paints a rectangular block of cells; shared by the screen and by printing |15| `Grid/PrintRenderer.swift` | 292 | pagination, PDF export, print view |16| `Session/Providers.swift` | 219 | protocols through which the grid obtains display text, conditional-format effects, validation, object renderers |17| `Chrome/GridHost.swift` | 112 | `NSViewRepresentable` that hosts the grid in the SwiftUI window, and the formula field |1819Source: `wc -l` on the files, 2026-11-21.2021Related documents: [overview.md](overview.md) (threading, extension points),22[calculation-graph.md](calculation-graph.md) (the engine lock the painter takes),23[chart-engine.md](chart-engine.md) (objects drawn on top of the cells),24[../design/design-system.md](../design/design-system.md) (palette tokens).2526## Structure2728<!-- diagram: grid-engine-structure -->29```mermaid30flowchart TD31 Session["WorkbookSession<br/>selection, edit state, zoom, revision"] --> Grid["GridView<br/>one layer-backed NSView"]32 Grid --> Layout["AxisLayout x 2<br/>rows and columns"]33 Grid --> Painter["CellPainter<br/>one paint call per quadrant"]34 Grid --> Overlays["Overlays<br/>selection, spill, tables, fill handle, references"]35 Grid --> Headers["Headers and corner"]36 Grid --> Editor["NSTextField editor<br/>the only subview besides two scrollers"]37 Painter --> Display["CellDisplayProvider<br/>number formats"]38 Painter --> Effects["CellEffectsProvider<br/>conditional formats"]39 Grid --> Objects["ObjectRenderer per kind<br/>charts, figures, pivots"]40 Print["PrintRenderer and SheetPrintView"] --> Painter41```42SVG fallback: 4344`GridView` is `@MainActor`, flipped (origin top-left), opaque, layer-backed with45`layerContentsRedrawPolicy = .onSetNeedsDisplay`. Its only subviews are the horizontal and vertical46`NSScroller` (overlay style) and one hidden `NSTextField` used as the in-cell editor.4748The view never reads the model on its own initiative: it registers one listener on the49`WorkbookSession` (`session.addListener`), and every session change calls `sessionChanged()`, which50refreshes the layout if needed, honours a pending `scrollTarget`, clamps the scroll position,51synchronises the editor, sets `needsDisplay` and posts accessibility notifications.5253## AxisLayout: virtualization5455A sheet always has 1,048,576 rows and 16,384 columns (`Limits.maxRows`, `Limits.maxCols` in56`SheetCore/Model/Address.swift`). `AxisLayout` makes that affordable: it stores a default size plus a57sorted array of the indices that have a custom size (hidden rows and columns are custom entries of58size 0, and rows hidden by a filter are merged in the same way), and a prefix array `deltaBefore`59holding the cumulated difference from the default.6061| Query | Method | Cost |62|---|---|---|63| size of item `i` | binary search in the custom indices | O(log k) |64| offset of the leading edge of item `i` | `i × default + deltaBefore[lowerBound(i)]` | O(log k) |65| item containing an offset | binary search over `0 ..< count` using `offset` | O(log n · log k) |66| next visible item | linear step over hidden items | O(hidden run) |6768`k` = number of rows (or columns) with a custom size, `n` = 1,048,576 or 16,384.69Source: `Grid/AxisLayout.swift`.7071The two layouts are rebuilt only when the pair *(sheet id, `session.contentRevision`)* changes72(`refreshLayout`), and immediately during a resize drag. Building is O(k log k).7374All geometry derives from the layouts, the scroll position and the zoom factor `z`:7576```77xFor(col) = headerW + offset(col) × z for frozen columns78 = headerW + (offset(col) − scrollX) × z otherwise79```8081and symmetrically for rows. `scrollX` / `scrollY` are sheet points *past the frozen area*. The row82header width adapts to the number of digits of the last visible row number; the header height is8324 points. Zoom is clamped to 25 %–400 % (`setZoom`); ⌘/⌃ + scroll wheel and the pinch gesture change84it.8586The scrollers do not represent the full 1,048,576-row extent, which would make the knob useless:87`extent()` uses *max(used range + 200 rows, last visible row + 60)* rows and *max(used range + 3088columns, last visible column + 12)* columns, so the scrollable extent grows as the user moves89outwards.9091## Drawing a frame9293`draw(_:)` repaints the whole view each time (`dirtyRect` is ignored). The sequence is:94951. Resolve the `GridPalette` for the effective appearance (light/dark) and the system Increase96 Contrast option; fill the background.972. Compute the visible row and column ranges from the layouts.983. Fetch conditional-format effects for the visible range from the `CellEffectsProvider`, cached99 under the key *sheet id | content revision | visible range* (skipped when the sheet has no100 conditional format).1014. Take `session.engine.lock`, paint the quadrants, release the lock.1025. Draw embedded objects, clipped to the main quadrant.1036. Draw overlays, clipped per quadrant.1047. Draw the frozen-pane lines, then the headers and the corner on top of everything.1058. Record the elapsed time in `lastDrawDuration` and increment `drawCount`.106107### Frozen quadrants108109With `frozenRows = fr` and `frozenCols = fc`, the cell area is split into up to four rectangles, each110painted by one `CellPainter.paint` call with its own clip rectangle and origin:111112<!-- diagram: grid-engine-quadrants -->113```mermaid114flowchart LR115 Corner["Frozen corner<br/>rows 0..fr-1, cols 0..fc-1<br/>never scrolls<br/>painted 4th"] --> Top["Frozen rows<br/>rows 0..fr-1, visible cols<br/>scrolls horizontally<br/>painted 2nd"]116 Left["Frozen columns<br/>visible rows, cols 0..fc-1<br/>scrolls vertically<br/>painted 3rd"] --> Main["Main quadrant<br/>visible rows and cols<br/>scrolls both ways<br/>painted 1st"]117 Corner --> Left118 Top --> Main119```120SVG fallback: 121122The same decomposition is reused for overlays by `inQuadrants(_:_:clip:_:)`: a range (a selection, a123spill area, a table) is intersected with each quadrant's cell range and drawn clipped to that124quadrant, so an outline that spans the frozen boundary is drawn in two or four pieces and the125scrolled part slides under the frozen part. Rectangles are intersected with the view bounds126(±10 pt) to stay finite for whole-row and whole-column selections.127128Embedded objects (charts, figures, pivot tables) live in the main quadrant only: they are clipped to129it, and hit testing ignores them over the frozen area.130131### CellPainter passes132133`CellPainter.paint(in:rowRange:colRange:origin:clip:)` works in six passes over the block:1341351. **Gridlines** — one device-pixel-wide filled rectangle per visible row and column edge (not136 stroked paths), when both the painter option and the sheet's `showGridlines` are on.1372. **Collection** — builds the list of items to draw. When the sheet has no row or column default138 style, only *stored* cells in the visible range are enumerated (`sheet.cells.forEach(in:)`), plus139 cells that have a conditional-format effect but no stored cell; an empty area costs nothing beyond140 its gridlines. When row/column default styles exist, every visible cell is visited. Merged ranges141 intersecting the block are added once, as one item covering the whole merge, and their member142 cells are skipped.1433. **Fills and data bars** — a merged cell is first erased with the background (to hide the144 gridlines under it), then the fill of the conditional-format effect or of the style is painted,145 then the data bar (rounded rectangle, 55 % alpha, inset 2 pt).1464. **Text** — see the next section.1475. **Borders** — filled rectangles per edge; thickness 1 (thin), 2 (medium family), 3 (thick,148 double) logical pixels scaled by zoom, hair = one device pixel; dashed and dotted styles are drawn149 as segments (5/3 or 2/2); `double` is two one-pixel lines. In dark mode a pure black border is150 drawn in `#D6DAE8` so that it stays visible.1516. **Comment markers** — a red (`#E5484D`) triangle in the top-right corner of cells with a note.152153Fonts are cached per painter in a dictionary keyed by *(name, scaled size, bold, italic)*. Shaped154lines are cached in a process-wide `LineCache` keyed by *(text, font identity, colour, underline)*155holding the `CTLine` and its typographic width; the cache is emptied when it exceeds 30,000 entries.156157### Text layout and overflow rules158159Display text comes from the `CellDisplayProvider` (the app installs `FormatDisplayProvider`, which160calls the SheetFormat engine: `NumberFormat.cached(format).render(...)`). With *Show Formulas* on,161the text is the formula in the session's locale syntax.162163Horizontal alignment `general` resolves to right for numbers, centre for booleans and errors, left164for text (and left for everything when formulas are shown). Insets are 4 pt × zoom for text and1652.5 pt × zoom for numbers; indent is 8 pt × zoom per level.166167| Situation | What is drawn |168|---|---|169| Text fits | one `CTLine`, clipped to the cell |170| **Number** wider than the cell | re-rendered with `maxChars` = available width ÷ width of `0` (General format shortens decimals, then switches to scientific notation); if it still does not fit, a run of `#` fills the cell. A number never overflows into neighbours |171| **Text** wider than the cell, not merged, not wrapped | overflows into adjacent **empty** cells: to the right unless right-aligned, to the left when right-aligned or centred. The scan stops at the first neighbour that has content or belongs to a merge, at most 20 columns past the painted block, and as soon as the text fits |172| Text in a merged cell | clipped to the merge |173| `wrap` on, value is text or contains a line break | laid out by AppKit (`NSAttributedString.draw(with:)`, word wrapping) inside the cell, honouring vertical alignment; no overflow |174| Icon-set effect | an SF Symbol is drawn at the left edge and the text is shifted |175| Hyperlink cell without explicit colour | link colour and single underline |176| Strikethrough | a line at half the x-height |177178Source: `CellPainter.paint`, pass 4.179180Not rendered (the attributes are stored in `CellStyle` and round-trip through the file formats, but181the painter does not use them): text **rotation**, **shrink to fit**, horizontal alignment `fill`182and `distributed` (drawn as left), `centerContinuous` (drawn as centred in its own cell, not across183the selection), vertical `justify`/`distributed` (drawn as centre), double and accounting underlines184(drawn as single), diagonal borders (not modelled at all). The `*x` fill character of accounting185number formats is reported by SheetFormat but not expanded. See186[../compatibility/excel.md](../compatibility/excel.md).187188### Overlays189190Drawn after the cells, in this order (`drawOverlays`): selection fill (even-odd fill so that the191active cell stays clear), outline of the spill area of the active cell (anchor or member), table192outlines, selection borders (2 px for the last range, 1 px for the others; 3/2 px under Increase193Contrast), the dropdown arrow of a list validation next to the active cell (`GridView.dropdownItems`;194clicking the arrow opens a menu of at most 500 items, and choosing one enters it in the cell), the fill handle195(7 × 7 pt square at the bottom-right of a single selection), the dashed outline of an autofill drag,196the dashed "marching" outline of the clipboard source (static, not animated), and the coloured197rectangles of the references of the formula being edited (`ORIX.referenceColors`, 9 % fill plus1981.5 px outline, the same colours as in the formula bar).199200### Headers201202Column letters and row numbers are drawn last, each strip clipped so that scrolled headers slide203under the frozen ones. A header is highlighted when any selected range intersects its column or row.204A column letter is omitted when it does not fit; the corner shows a small triangle (click = select205everything).206207## The editor208209One `NSTextField` is reused for all in-cell editing. `syncEditor()` shows it when the session is in210edit mode, with the cell's font scaled by the zoom, the palette colours and a 2 px accent border;211`positionEditor()` places it over the cell (or the whole merge) and widens it to the text width, up212to the right edge of the view. When the edited cell is on another sheet (pointing at references on213another sheet while typing a formula) the editor is parked off-screen.214215Editing state lives in `WorkbookSession`, not in the view: the field's delegate forwards every216change to `session.userEdited(_:)`, and commands to `handleEditorCommand`, which is shared with the217formula bar:218219| Key in the editor | Effect |220|---|---|221| Return / Shift-Return | commit, move down / up |222| Control-Return | commit and fill the whole selection with the entry |223| Option-Return | insert a line break |224| Tab / Shift-Tab | commit, move right / left |225| Escape | cancel |226| Arrow keys | in *quick* edit mode (started by typing): commit and move; in full edit mode (F2, double-click, formula bar): move the caret |227228Source: `GridView.handleEditorCommand`.229230A commit can be refused (the formula does not parse, or a blocking validation rule rejects the231entry): `commitEdit` returns `false` and the editor stays open with `session.editError` set.232233While a formula is being edited, a click or drag in the grid inserts a reference instead of moving234the selection (`session.pointReference`, drag state `.point`).235236## Hit testing237238`hit(_:)` maps a point to one of six targets, tested in this order:239240| Target | Rule |241|---|---|242| `corner` | inside the header corner |243| `colHeader(c, resize:)` | in the column header strip; `resize` within 4 pt of a column's right edge (or of the left edge, which resizes the previous visible column) |244| `rowHeader(r, resize:)` | in the row header strip; `resize` within 3 pt of the bottom (or top) edge |245| `object(o, resize:)` | inside an object's rectangle grown by 4 pt, topmost first, only outside the frozen area; `resize` on the 16 pt handle of the selected object |246| `fillHandle` | 11 × 11 pt around the bottom-right corner of a single, non-whole-row/column selection, when not editing |247| `cell(ref)` | everything else |248249Source: `GridView+Events.swift`, `hit(_:)`.250251Mouse handling is a small state machine (`DragState`): select, select rows, select columns, resize252column, resize row, fill, point (reference picking), move object, resize object. Resizes and object253moves mutate `sheet.meta` directly during the drag for immediate feedback, then on mouse-up restore254the initial value and re-apply the final one through the session so that the change is one undoable255step; resizing a column that is part of a whole-column selection resizes all selected columns.256Double-click on a resize edge autofits (`autofitColumn` measures at most 20,000 cells of the column257and caps the width at 600 pt; `autofitRow` uses wrapped height for wrapped cells). While dragging258outside the cell area, a 40 ms timer autoscrolls by 28 pt ÷ zoom per tick.259260Command-click on a cell with a hyperlink opens it: `#Sheet!A1` targets are handled internally;261`http`, `https` and `mailto` URLs are handed to `NSWorkspace.shared.open`; every other scheme is262ignored.263264Keyboard handling is described, with its differences from Excel, in265[../compatibility/excel.md](../compatibility/excel.md).266267## Why CoreGraphics and CoreText, and not Metal268269The decision is recorded in [../research/technology-evaluation.md](../research/technology-evaluation.md)270("Rendering — AppKit + CoreGraphics/CoreText for the grid; Metal not used"): a Metal text renderer271needs its own glyph atlas and shaping, and the CoreGraphics path is also what produces vector PDF, so272the same painter serves the screen and the printer.273274The repository contains no recorded repaint benchmark (`docs/benchmarks/` only holds the engine275benchmark). The view measures every frame itself (`GridView.lastDrawDuration`), and two things use276that value: the preview executables print it, and the app test `testLargeSheetStaysResponsive`277(`App/Tests/AppIntegrationTests.swift`) asserts a worst case under 50 ms over 20 repaints of a27850,000-row sheet scrolled to its end. The figures below were measured for this document.279280**Measurement 1 — the SheetUI preview**, release build, demo workbook (two sheets, about 50 cells,281frozen rows, one spill, one overflowing text), 1280 × 800 window, last frame before the screenshot:282283| Run | Light | Dark |284|---|---|---|285| 1 | 1.47 ms | 1.36 ms |286| 2 | 1.42 ms | 1.51 ms |287| 3 | 1.43 ms | 1.71 ms |288289At 2560 × 1440 (one run, light): 1.62 ms.290291Source: `swift run -c release sheet-preview --shot <png> [--dark] [--size WxH]` in `Packages/SheetUI`,292run on 2026-11-21 on an Apple M5 Max (48 GB), macOS 27.0 (26A5425a), Swift 6.4.2. The program prints293`grid draw: … ms`.294295**Measurement 2 — dense sheets**, release build, a `GridView` in an off-screen window rendered with296`cacheDisplay(in:to:)`; 60 frames while paging down 40 rows per frame ("scrolling", new text on every297frame) and 60 frames of the same view ("static"). The sheet holds 50,000 × 40 cells (four numeric298columns out of five, one text column).299300| Content | Window (points) | Appearance | Scrolling, median | Scrolling, worst | Static, median | Static, worst |301|---|---|---|---|---|---|---|302| empty sheet | 1280 × 800 | light | 1.08 ms | 1.58 ms | 1.49 ms | 25.76 ms |303| dense, General format | 1280 × 800 | light | 3.81 ms | 6.03 ms | 4.18 ms | 10.12 ms |304| dense, General format | 1280 × 800 | dark | 2.72 ms | 6.31 ms | 2.41 ms | 3.76 ms |305| dense, `#,##0.00`, fill and bottom border on every cell, 2 × 2 frozen panes | 1280 × 800 | light | 3.76 ms | 6.13 ms | 3.66 ms | 5.06 ms |306| empty sheet | 2560 × 1440 | light | 2.90 ms | 3.99 ms | 2.94 ms | 3.38 ms |307| dense, General format | 2560 × 1440 | light | 9.31 ms | 16.02 ms | 8.97 ms | 11.52 ms |308| dense, General format | 2560 × 1440 | dark | 9.46 ms | 17.12 ms | 10.55 ms | 18.22 ms |309| dense, `#,##0.00`, fill and bottom border on every cell, 2 × 2 frozen panes | 2560 × 1440 | light | 16.01 ms | 20.41 ms | 15.69 ms | 22.24 ms |310311Source: a scratch Swift program written for this document (not in the repository) that links312`SheetUI`, creates the workbook, hosts `GridView` in an `NSWindow` that is never shown, and reads313`lastDrawDuration`; single run on 2026-11-21, same machine and toolchain as above. One run only: the31425.76 ms outlier on the empty sheet is a single frame and was not investigated.315316How to read these numbers:317318- They time `draw(_:)` only (model access, text shaping, CoreGraphics calls into a bitmap). They do319 not include the window server's compositing, and an off-screen bitmap is not the on-screen path, so320 on-screen figures may differ.321- At 1280 × 800 a full repaint stays under the 8.3 ms of a 120 Hz frame in every case measured.322- At 2560 × 1440 with every visible cell filled, the median is 9–16 ms: above the 120 Hz frame budget323 and, for the styled case, at the 16.7 ms of a 60 Hz frame. The statement in the technology324 evaluation ("a few milliseconds … far below a 120 Hz frame") therefore holds for a typical window325 but not for a large, fully populated one. The cost grows with the number of visible cells because326 every frame repaints everything; there is no dirty-rectangle or scroll-blit optimisation.327328No Metal prototype exists in the repository, so there is no measured comparison between the two329approaches.330331## Printing and PDF reuse332333Printing does not have a second renderer. `PrintLayout` computes the pages of one sheet:334335- paper size and orientation, margins, scale (10–400 %) or fit-to-width/height (never enlarges, floor336 10 %) from `SheetMeta.print`;337- the area is the print area; when no print area is set, it is the used range extended to cover every338 embedded object of the sheet (a chart placed beside or below the data is therefore printed);339- rows and columns are split into bands that fit the printable area minus the headings (36 × 18 pt340 when "print headings" is on) and minus the repeated title rows/columns; manual page breaks force a341 split; pages are ordered down, then over.342343`PrintRenderer.draw(page:layout:totalPages:fileName:in:)` then calls the **same `CellPainter`** with344the light palette, a slightly darker gridline colour, no background fill, and the page's row and345column ranges — up to four paint calls per page (body, repeated rows, repeated columns, their346corner), mirroring the frozen quadrants. Conditional-format effects are requested for the page range.347Embedded objects whose origin falls on the page are drawn by their `ObjectRenderer` in the same348context (charts therefore stay vector; see [chart-engine.md](chart-engine.md)). Headers and footers349support the Excel codes `&L &C &R &P &N &D &T &F &A &&`; font and style codes are ignored.350351Two consumers share that function:352353- `PrintRenderer.pdfData(session:sheets:fileName:)` writes pages into a `CGContext` PDF consumer354 (File ▸ Export To ▸ PDF);355- `SheetPrintView`, the view given to `NSPrintOperation`, stacks the pages vertically and draws each356 one with the same call, so the system print preview shows what the PDF export produces.357358The app test `testPrintingProducesPaginatedVectorPDF` checks that 150 rows × 6 columns paginate to 5359Letter pages and that the PDF contains font resources (text is not rasterised).360361Limits: an object is drawn only on the page where its top-left corner falls and is clipped at the362page edge; it is not split across pages. Print settings are per sheet; "all sheets" export skips363hidden sheets.364365## Extension points used by the grid366367All are registered on the process-wide `Workspace.shared` (`Session/Providers.swift`); the app fills368them at launch in `Features.registerAll()`.369370| Hook | Used for | Registered by (in this repository) |371|---|---|---|372| `displayProvider: CellDisplayProvider` | value → display text and colour | the app (`FormatDisplayProvider`) |373| `effectsProvider: CellEffectsProvider` | conditional-format fill, colour, bold/italic/strike, data bar, icon | FeatureAudit |374| `validator: InputValidator` | entry validation and dropdown items | FeatureAudit |375| `objectRenderers[kind]: ObjectRenderer` | drawing and opening embedded objects | FeatureCharts (charts, figures), FeatureData (pivot tables) |376| `formulaAssist` | completion and signature hints while typing a formula | FeatureAudit |377378Source: `grep` for the assignments in `Packages/Feature*/Sources`, 2026-11-21.379380Without a registered renderer an object is drawn as a rounded card showing its name.381382## Known limits383384- Full repaint on every change; cost proportional to the number of visible cells (see the385 measurements).386- `effects(...)` of the conditional-format provider is called on the main thread before drawing. The387 grid caches the result only for an unchanged *(sheet, revision, visible range)*, so while a sheet388 with conditional formats scrolls the provider is asked again on every frame (the protocol requires389 providers to be fast and to cache internally).390- With row or column default styles, every visible cell is visited even when empty.391- The clipboard outline is static; there is no animation anywhere in the grid.392- Column and row headers, objects and the fill handle are not accessibility elements393 ([accessibility.md](../development/accessibility.md)).394- Rotation, shrink-to-fit and the alignment variants listed above are not rendered.395