SPB Git

Repository Public

grid-engine.md 23.8 KB

# Grid engine

The worksheet grid is one custom AppKit view, GridView, in Packages/SheetUI/Sources/SheetUI/Grid/. It draws only what is visible, with CoreGraphics and CoreText, and handles scrolling, selection, resizing, autofill, in-cell editing and hit testing itself. There is no NSTableView, no NSScrollView and no per-cell view or layer.

File Lines Role
Grid/AxisLayout.swift 74 index ⇄ offset mapping for rows and columns
Grid/GridView.swift 657 geometry, scrolling, zoom, drawing of quadrants, overlays, headers, editor placement, autofit
Grid/GridView+Events.swift 486 hit testing, mouse, context menu, keyboard, responder actions
Grid/GridView+Accessibility.swift 297 accessibility table and cell elements (see accessibility.md)
Grid/CellPainter.swift 356 paints a rectangular block of cells; shared by the screen and by printing
Grid/PrintRenderer.swift 292 pagination, PDF export, print view
Session/Providers.swift 219 protocols through which the grid obtains display text, conditional-format effects, validation, object renderers
Chrome/GridHost.swift 112 NSViewRepresentable that hosts the grid in the SwiftUI window, and the formula field

Source: wc -l on the files, 2026-11-21.

Related documents: overview.md (threading, extension points), calculation-graph.md (the engine lock the painter takes), chart-engine.md (objects drawn on top of the cells), ../design/design-system.md (palette tokens).

# Structure

flowchart TD
    Session["WorkbookSession<br/>selection, edit state, zoom, revision"] --> Grid["GridView<br/>one layer-backed NSView"]
    Grid --> Layout["AxisLayout x 2<br/>rows and columns"]
    Grid --> Painter["CellPainter<br/>one paint call per quadrant"]
    Grid --> Overlays["Overlays<br/>selection, spill, tables, fill handle, references"]
    Grid --> Headers["Headers and corner"]
    Grid --> Editor["NSTextField editor<br/>the only subview besides two scrollers"]
    Painter --> Display["CellDisplayProvider<br/>number formats"]
    Painter --> Effects["CellEffectsProvider<br/>conditional formats"]
    Grid --> Objects["ObjectRenderer per kind<br/>charts, figures, pivots"]
    Print["PrintRenderer and SheetPrintView"] --> Painter

SVG fallback: Structure of the grid engine

GridView is @MainActor, flipped (origin top-left), opaque, layer-backed with layerContentsRedrawPolicy = .onSetNeedsDisplay. Its only subviews are the horizontal and vertical NSScroller (overlay style) and one hidden NSTextField used as the in-cell editor.

The view never reads the model on its own initiative: it registers one listener on the WorkbookSession (session.addListener), and every session change calls sessionChanged(), which refreshes the layout if needed, honours a pending scrollTarget, clamps the scroll position, synchronises the editor, sets needsDisplay and posts accessibility notifications.

# AxisLayout: virtualization

A sheet always has 1,048,576 rows and 16,384 columns (Limits.maxRows, Limits.maxCols in SheetCore/Model/Address.swift). AxisLayout makes that affordable: it stores a default size plus a sorted array of the indices that have a custom size (hidden rows and columns are custom entries of size 0, and rows hidden by a filter are merged in the same way), and a prefix array deltaBefore holding the cumulated difference from the default.

Query Method Cost
size of item i binary search in the custom indices O(log k)
offset of the leading edge of item i i × default + deltaBefore[lowerBound(i)] O(log k)
item containing an offset binary search over 0 ..< count using offset O(log n · log k)
next visible item linear step over hidden items O(hidden run)

k = number of rows (or columns) with a custom size, n = 1,048,576 or 16,384. Source: Grid/AxisLayout.swift.

The two layouts are rebuilt only when the pair (sheet id, session.contentRevision) changes (refreshLayout), and immediately during a resize drag. Building is O(k log k).

All geometry derives from the layouts, the scroll position and the zoom factor z:

text
xFor(col) = headerW + offset(col) × z                 for frozen columns
          = headerW + (offset(col) − scrollX) × z     otherwise

and symmetrically for rows. scrollX / scrollY are sheet points past the frozen area. The row header width adapts to the number of digits of the last visible row number; the header height is 24 points. Zoom is clamped to 25 %–400 % (setZoom); ⌘/⌃ + scroll wheel and the pinch gesture change it.

The scrollers do not represent the full 1,048,576-row extent, which would make the knob useless: extent() uses max(used range + 200 rows, last visible row + 60) rows and max(used range + 30 columns, last visible column + 12) columns, so the scrollable extent grows as the user moves outwards.

# Drawing a frame

draw(_:) repaints the whole view each time (dirtyRect is ignored). The sequence is:

  1. Resolve the GridPalette for the effective appearance (light/dark) and the system Increase Contrast option; fill the background.
  2. Compute the visible row and column ranges from the layouts.
  3. Fetch conditional-format effects for the visible range from the CellEffectsProvider, cached under the key sheet id | content revision | visible range (skipped when the sheet has no conditional format).
  4. Take session.engine.lock, paint the quadrants, release the lock.
  5. Draw embedded objects, clipped to the main quadrant.
  6. Draw overlays, clipped per quadrant.
  7. Draw the frozen-pane lines, then the headers and the corner on top of everything.
  8. Record the elapsed time in lastDrawDuration and increment drawCount.

# Frozen quadrants

With frozenRows = fr and frozenCols = fc, the cell area is split into up to four rectangles, each painted by one CellPainter.paint call with its own clip rectangle and origin:

flowchart LR
    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"]
    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"]
    Corner --> Left
    Top --> Main

SVG fallback: The four frozen quadrants and their paint order

The same decomposition is reused for overlays by inQuadrants(_:_:clip:_:): a range (a selection, a spill area, a table) is intersected with each quadrant's cell range and drawn clipped to that quadrant, so an outline that spans the frozen boundary is drawn in two or four pieces and the scrolled part slides under the frozen part. Rectangles are intersected with the view bounds (±10 pt) to stay finite for whole-row and whole-column selections.

Embedded objects (charts, figures, pivot tables) live in the main quadrant only: they are clipped to it, and hit testing ignores them over the frozen area.

# CellPainter passes

CellPainter.paint(in:rowRange:colRange:origin:clip:) works in six passes over the block:

  1. Gridlines — one device-pixel-wide filled rectangle per visible row and column edge (not stroked paths), when both the painter option and the sheet's showGridlines are on.
  2. Collection — builds the list of items to draw. When the sheet has no row or column default style, only stored cells in the visible range are enumerated (sheet.cells.forEach(in:)), plus cells that have a conditional-format effect but no stored cell; an empty area costs nothing beyond its gridlines. When row/column default styles exist, every visible cell is visited. Merged ranges intersecting the block are added once, as one item covering the whole merge, and their member cells are skipped.
  3. Fills and data bars — a merged cell is first erased with the background (to hide the gridlines under it), then the fill of the conditional-format effect or of the style is painted, then the data bar (rounded rectangle, 55 % alpha, inset 2 pt).
  4. Text — see the next section.
  5. Borders — filled rectangles per edge; thickness 1 (thin), 2 (medium family), 3 (thick, double) logical pixels scaled by zoom, hair = one device pixel; dashed and dotted styles are drawn as segments (5/3 or 2/2); double is two one-pixel lines. In dark mode a pure black border is drawn in #D6DAE8 so that it stays visible.
  6. Comment markers — a red (#E5484D) triangle in the top-right corner of cells with a note.

Fonts are cached per painter in a dictionary keyed by (name, scaled size, bold, italic). Shaped lines are cached in a process-wide LineCache keyed by (text, font identity, colour, underline) holding the CTLine and its typographic width; the cache is emptied when it exceeds 30,000 entries.

# Text layout and overflow rules

Display text comes from the CellDisplayProvider (the app installs FormatDisplayProvider, which calls the SheetFormat engine: NumberFormat.cached(format).render(...)). With Show Formulas on, the text is the formula in the session's locale syntax.

Horizontal alignment general resolves to right for numbers, centre for booleans and errors, left for text (and left for everything when formulas are shown). Insets are 4 pt × zoom for text and 2.5 pt × zoom for numbers; indent is 8 pt × zoom per level.

Situation What is drawn
Text fits one CTLine, clipped to the cell
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
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
Text in a merged cell clipped to the merge
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
Icon-set effect an SF Symbol is drawn at the left edge and the text is shifted
Hyperlink cell without explicit colour link colour and single underline
Strikethrough a line at half the x-height

Source: CellPainter.paint, pass 4.

Not rendered (the attributes are stored in CellStyle and round-trip through the file formats, but the painter does not use them): text rotation, shrink to fit, horizontal alignment fill and distributed (drawn as left), centerContinuous (drawn as centred in its own cell, not across the selection), vertical justify/distributed (drawn as centre), double and accounting underlines (drawn as single), diagonal borders (not modelled at all). The *x fill character of accounting number formats is reported by SheetFormat but not expanded. See ../compatibility/excel.md.

# Overlays

Drawn after the cells, in this order (drawOverlays): selection fill (even-odd fill so that the active cell stays clear), outline of the spill area of the active cell (anchor or member), table outlines, selection borders (2 px for the last range, 1 px for the others; 3/2 px under Increase Contrast), the dropdown arrow of a list validation next to the active cell (GridView.dropdownItems; clicking the arrow opens a menu of at most 500 items, and choosing one enters it in the cell), the fill handle (7 × 7 pt square at the bottom-right of a single selection), the dashed outline of an autofill drag, the dashed "marching" outline of the clipboard source (static, not animated), and the coloured rectangles of the references of the formula being edited (ORIX.referenceColors, 9 % fill plus 1.5 px outline, the same colours as in the formula bar).

# Headers

Column letters and row numbers are drawn last, each strip clipped so that scrolled headers slide under the frozen ones. A header is highlighted when any selected range intersects its column or row. A column letter is omitted when it does not fit; the corner shows a small triangle (click = select everything).

# The editor

One NSTextField is reused for all in-cell editing. syncEditor() shows it when the session is in edit mode, with the cell's font scaled by the zoom, the palette colours and a 2 px accent border; positionEditor() places it over the cell (or the whole merge) and widens it to the text width, up to the right edge of the view. When the edited cell is on another sheet (pointing at references on another sheet while typing a formula) the editor is parked off-screen.

Editing state lives in WorkbookSession, not in the view: the field's delegate forwards every change to session.userEdited(_:), and commands to handleEditorCommand, which is shared with the formula bar:

Key in the editor Effect
Return / Shift-Return commit, move down / up
Control-Return commit and fill the whole selection with the entry
Option-Return insert a line break
Tab / Shift-Tab commit, move right / left
Escape cancel
Arrow keys in quick edit mode (started by typing): commit and move; in full edit mode (F2, double-click, formula bar): move the caret

Source: GridView.handleEditorCommand.

A commit can be refused (the formula does not parse, or a blocking validation rule rejects the entry): commitEdit returns false and the editor stays open with session.editError set.

While a formula is being edited, a click or drag in the grid inserts a reference instead of moving the selection (session.pointReference, drag state .point).

# Hit testing

hit(_:) maps a point to one of six targets, tested in this order:

Target Rule
corner inside the header corner
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)
rowHeader(r, resize:) in the row header strip; resize within 3 pt of the bottom (or top) edge
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
fillHandle 11 × 11 pt around the bottom-right corner of a single, non-whole-row/column selection, when not editing
cell(ref) everything else

Source: GridView+Events.swift, hit(_:).

Mouse handling is a small state machine (DragState): select, select rows, select columns, resize column, resize row, fill, point (reference picking), move object, resize object. Resizes and object moves mutate sheet.meta directly during the drag for immediate feedback, then on mouse-up restore the initial value and re-apply the final one through the session so that the change is one undoable step; resizing a column that is part of a whole-column selection resizes all selected columns. Double-click on a resize edge autofits (autofitColumn measures at most 20,000 cells of the column and caps the width at 600 pt; autofitRow uses wrapped height for wrapped cells). While dragging outside the cell area, a 40 ms timer autoscrolls by 28 pt ÷ zoom per tick.

Command-click on a cell with a hyperlink opens it: #Sheet!A1 targets are handled internally; http, https and mailto URLs are handed to NSWorkspace.shared.open; every other scheme is ignored.

Keyboard handling is described, with its differences from Excel, in ../compatibility/excel.md.

# Why CoreGraphics and CoreText, and not Metal

The decision is recorded in ../research/technology-evaluation.md ("Rendering — AppKit + CoreGraphics/CoreText for the grid; Metal not used"): a Metal text renderer needs its own glyph atlas and shaping, and the CoreGraphics path is also what produces vector PDF, so the same painter serves the screen and the printer.

The repository contains no recorded repaint benchmark (docs/benchmarks/ only holds the engine benchmark). The view measures every frame itself (GridView.lastDrawDuration), and two things use that value: the preview executables print it, and the app test testLargeSheetStaysResponsive (App/Tests/AppIntegrationTests.swift) asserts a worst case under 50 ms over 20 repaints of a 50,000-row sheet scrolled to its end. The figures below were measured for this document.

Measurement 1 — the SheetUI preview, release build, demo workbook (two sheets, about 50 cells, frozen rows, one spill, one overflowing text), 1280 × 800 window, last frame before the screenshot:

Run Light Dark
1 1.47 ms 1.36 ms
2 1.42 ms 1.51 ms
3 1.43 ms 1.71 ms

At 2560 × 1440 (one run, light): 1.62 ms.

Source: swift run -c release sheet-preview --shot <png> [--dark] [--size WxH] in Packages/SheetUI, run on 2026-11-21 on an Apple M5 Max (48 GB), macOS 27.0 (26A5425a), Swift 6.4.2. The program prints grid draw: … ms.

Measurement 2 — dense sheets, release build, a GridView in an off-screen window rendered with cacheDisplay(in:to:); 60 frames while paging down 40 rows per frame ("scrolling", new text on every frame) and 60 frames of the same view ("static"). The sheet holds 50,000 × 40 cells (four numeric columns out of five, one text column).

Content Window (points) Appearance Scrolling, median Scrolling, worst Static, median Static, worst
empty sheet 1280 × 800 light 1.08 ms 1.58 ms 1.49 ms 25.76 ms
dense, General format 1280 × 800 light 3.81 ms 6.03 ms 4.18 ms 10.12 ms
dense, General format 1280 × 800 dark 2.72 ms 6.31 ms 2.41 ms 3.76 ms
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
empty sheet 2560 × 1440 light 2.90 ms 3.99 ms 2.94 ms 3.38 ms
dense, General format 2560 × 1440 light 9.31 ms 16.02 ms 8.97 ms 11.52 ms
dense, General format 2560 × 1440 dark 9.46 ms 17.12 ms 10.55 ms 18.22 ms
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

Source: a scratch Swift program written for this document (not in the repository) that links SheetUI, creates the workbook, hosts GridView in an NSWindow that is never shown, and reads lastDrawDuration; single run on 2026-11-21, same machine and toolchain as above. One run only: the 25.76 ms outlier on the empty sheet is a single frame and was not investigated.

How to read these numbers:

  • They time draw(_:) only (model access, text shaping, CoreGraphics calls into a bitmap). They do not include the window server's compositing, and an off-screen bitmap is not the on-screen path, so on-screen figures may differ.
  • At 1280 × 800 a full repaint stays under the 8.3 ms of a 120 Hz frame in every case measured.
  • At 2560 × 1440 with every visible cell filled, the median is 9–16 ms: above the 120 Hz frame budget and, for the styled case, at the 16.7 ms of a 60 Hz frame. The statement in the technology evaluation ("a few milliseconds … far below a 120 Hz frame") therefore holds for a typical window but not for a large, fully populated one. The cost grows with the number of visible cells because every frame repaints everything; there is no dirty-rectangle or scroll-blit optimisation.

No Metal prototype exists in the repository, so there is no measured comparison between the two approaches.

# Printing and PDF reuse

Printing does not have a second renderer. PrintLayout computes the pages of one sheet:

  • paper size and orientation, margins, scale (10–400 %) or fit-to-width/height (never enlarges, floor 10 %) from SheetMeta.print;
  • the area is the print area; when no print area is set, it is the used range extended to cover every embedded object of the sheet (a chart placed beside or below the data is therefore printed);
  • rows and columns are split into bands that fit the printable area minus the headings (36 × 18 pt when "print headings" is on) and minus the repeated title rows/columns; manual page breaks force a split; pages are ordered down, then over.

PrintRenderer.draw(page:layout:totalPages:fileName:in:) then calls the same CellPainter with the light palette, a slightly darker gridline colour, no background fill, and the page's row and column ranges — up to four paint calls per page (body, repeated rows, repeated columns, their corner), mirroring the frozen quadrants. Conditional-format effects are requested for the page range. Embedded objects whose origin falls on the page are drawn by their ObjectRenderer in the same context (charts therefore stay vector; see chart-engine.md). Headers and footers support the Excel codes &L &C &R &P &N &D &T &F &A &&; font and style codes are ignored.

Two consumers share that function:

  • PrintRenderer.pdfData(session:sheets:fileName:) writes pages into a CGContext PDF consumer (File ▸ Export To ▸ PDF);
  • SheetPrintView, the view given to NSPrintOperation, stacks the pages vertically and draws each one with the same call, so the system print preview shows what the PDF export produces.

The app test testPrintingProducesPaginatedVectorPDF checks that 150 rows × 6 columns paginate to 5 Letter pages and that the PDF contains font resources (text is not rasterised).

Limits: an object is drawn only on the page where its top-left corner falls and is clipped at the page edge; it is not split across pages. Print settings are per sheet; "all sheets" export skips hidden sheets.

# Extension points used by the grid

All are registered on the process-wide Workspace.shared (Session/Providers.swift); the app fills them at launch in Features.registerAll().

Hook Used for Registered by (in this repository)
displayProvider: CellDisplayProvider value → display text and colour the app (FormatDisplayProvider)
effectsProvider: CellEffectsProvider conditional-format fill, colour, bold/italic/strike, data bar, icon FeatureAudit
validator: InputValidator entry validation and dropdown items FeatureAudit
objectRenderers[kind]: ObjectRenderer drawing and opening embedded objects FeatureCharts (charts, figures), FeatureData (pivot tables)
formulaAssist completion and signature hints while typing a formula FeatureAudit

Source: grep for the assignments in Packages/Feature*/Sources, 2026-11-21.

Without a registered renderer an object is drawn as a rounded card showing its name.

# Known limits

  • Full repaint on every change; cost proportional to the number of visible cells (see the measurements).
  • effects(...) of the conditional-format provider is called on the main thread before drawing. The grid caches the result only for an unchanged (sheet, revision, visible range), so while a sheet with conditional formats scrolls the provider is asked again on every frame (the protocol requires providers to be fast and to cache internally).
  • With row or column default styles, every visible cell is visited even when empty.
  • The clipboard outline is static; there is no animation anywhere in the grid.
  • Column and row headers, objects and the fill handle are not accessibility elements (accessibility.md).
  • Rotation, shrink-to-fit and the alignment variants listed above are not rendered.
Files main
Menu

Theme