diff --git a/.claude/rules/data-grid.md b/.claude/rules/data-grid.md index 17072747ce..ba1f3bab0b 100644 --- a/.claude/rules/data-grid.md +++ b/.claude/rules/data-grid.md @@ -15,6 +15,7 @@ Three layers, knowledge pointing one way: an owner's adapter, then `DataGridMode ## Model - **`DataGridModel` holds the grid's state** and outlives every mount: column set, row order, selection, sort, value filter, column layout, display formats, find and the edit session. Its owner holds it strongly; the data tab keeps one per tab on `MainContentCoordinator`. +- **The data tab hands its grid a `DataTabGridPresentation` named by the tab**, applied through `applyGridPresentation(_:)`. `onChange` runs the closure of the body from before a tab switch, so a closure that captured the model wrote the incoming tab's configuration into the outgoing tab's model. - **An owner talks to the model, never to the view.** It implements `DataGridDataSource` and `DataGridActions` in an adapter class and calls `reloadRows()` when its rows were replaced or `apply(_ delta:)` when they changed. The model keeps the selection by identity and sends the mounted view one `DataGridChange`. - **Rows are `RowID`, columns are `DataGridColumnID`.** `DataGridRowOrder` maps display rows, and `DataGridColumnSet` is the only converter between data index, display position and pane. A bare `Int` is a display position, valid only inside one call: capture the IDs before a popover, a sheet or an `await`. - **Every edit is one `model.commit(_:actionName:)`** of `DataGridCellEdit`s, taken by IDs when the gesture began. A command over many cells is one call, so one undo step. @@ -42,7 +43,7 @@ Three layers, knowledge pointing one way: an owner's adapter, then `DataGridMode - **Wrap Text is per grid, and off is the fixed-pitch table.** `model.wrapsText` is the store's flag on a grid that offers `.wrapText`. The controller answers `tableView(_:heightOfRow:)` only while it is on (`responds(to:)`, then the delegates are assigned again and the tables reloaded), so a grid that never wraps runs none of this. `tableView.rowHeight` stays the one-line height in both modes. - **A wrapped row's height comes from `display.lineCounts`**, a line count per `RowID` over every column, capped at `DataGridWrapLayout.maximumLines`. It clears with the display cache and whenever `DataGridWrapGeometry` moves (a width, the column set, a font, the Row height, Show Invisible Characters). A row with no count is one line. Rows AppKit shows or holds ready are measured on the main actor as the viewport moves, the prewarm fills the rest, and every count that changes an answer is followed by `noteHeightOfRows` on both panes inside a kept place, never by a reload. - **In a tall row everything but the value sits on the first line**: the row number, the accessory, the checkbox, a placeholder and the edit field. `DataGridWrapLayout` breaks the value and the renderer draws it, from the text the formatter left with every line break as one LF. -- **Every column stays attached.** Never hide an off-screen column with `NSTableColumn.isHidden`: each write costs O(attached columns). Columns come from each pane's pool, keyed by `DataGridColumnID`, so a re-run of the same result does not flicker (#951). +- **Every column stays attached.** Never hide an off-screen column with `NSTableColumn.isHidden`: each write costs O(attached columns). Columns come from each pane's pool, keyed by `DataGridColumnID`, so a re-run of the same result does not flicker (#951). A pooled column's `dataCell` is a plain `NSCell`: the default text field cell tiles the table on every attach, which made attaching n columns O(n²). - **Resolve a table column through `DataGridPane.slot(atTableIndex:columns:)` and `tableIndex(forDisplayPosition:columns:)`**, never a fixed index into `tableColumns`: the row-number column sits first and the frozen pane holds a subset. - **`gridStyleMask` stays empty.** AppKit's vertical grid lines keep a subview per column (518 ms a layout at 500 columns). `DataGridBodyChrome` draws the separators in each row, and the stripes and separators past the last row. - **Selection takes the theme.** `drawSelection(in:)` fills the whole row in a row selection and the selected columns' span in a cell range: `dataGrid.selection` when emphasized, else `dataGrid.inactiveSelection`. The active cell is an inner stroke in `dataGrid.focusBorder`, 2 pt with focus and 1 pt without, in the selected text color over an emphasized fill. No outline goes round a range. @@ -52,7 +53,7 @@ Three layers, knowledge pointing one way: an owner's adapter, then `DataGridMode ## Header -- **AppKit's header behavior in the theme's colors.** `DataGridHeaderView` is a `ThemeTableHeaderView` and every column a `ThemeTableHeaderCell` (`.claude/rules/theme.md`); it adds `menu(for:)` and a `viewWillDraw` that repaints the body on each step of a column drag. AppKit draws the title and the primary sort arrow; the controller sets each header cell's `accessibilitySortDirection`, which AppKit leaves unknown. +- **AppKit's header behavior in the theme's colors.** `DataGridHeaderView` is a `ThemeTableHeaderView` and every column a `ThemeTableHeaderCell` (`.claude/rules/theme.md`); it adds `menu(for:)`, a `viewWillDraw` that repaints the body on each step of a column drag, and a `resetCursorRects` that adds AppKit's divider rects for the columns on screen only, since AppKit's own pass adds one for every column on every scroll step. AppKit draws the title and the primary sort arrow; the controller sets each header cell's `accessibilitySortDirection`, which AppKit leaves unknown. - **The model's sort is the source.** `tableView.sortDescriptors` is written from `store.sortState` under `isApplyingSortDescriptors`, because an assignment inside the callback fires it again. A plain click keeps only the clicked key and flips it on a repeat; an Option-click keeps the key AppKit appended (`HeaderSortCycle`). Shift-click reaches no sort callback, and Command-click selects the column. - **Header text is the column name.** The type, the comment and, while several keys sort, the sort order go in `headerToolTip`; an active value filter adds a funnel symbol attachment to the title, in the header text color. diff --git a/apple/.swiftlint.yml b/apple/.swiftlint.yml index 75f9a2dd45..7af0fa2114 100644 --- a/apple/.swiftlint.yml +++ b/apple/.swiftlint.yml @@ -256,6 +256,15 @@ custom_rules: excluded_match_kinds: [comment, doccomment] message: "Declare an FSEvents callback as a `nonisolated private static let` of type FSEventStreamCallback and pass that." severity: error + # The app builds in the Swift 6 mode, where a main-actor @objc getter checks its executor on every call. The editor + # package builds in the Swift 5 mode, so the scope names the app folder alone. + flipped_view_getter_isolation: + name: "Flipped View Getter Isolation" + regex: '^(?![^\n]*\bnonisolated\b)[^\n]*\boverride\b[^\n]*\bvar\s+isFlipped\b' + included: ['.*/apple/TablePro/'] + excluded_match_kinds: [comment, doccomment] + message: "isFlipped is a constant AppKit asks in every coordinate conversion: declare it nonisolated." + severity: error date_formatter_locale: name: "Fixed-Format Date Formatter Locale" regex: 'DateFormatter\(\)(?:(?!\.locale\s*=|DateFormatter\(\))[\s\S]){0,800}?\.dateFormat\s*=\s*"(?!(?:[^\n]*\n){0,8}[^\n]*\.locale\s*=)' diff --git a/apple/TablePro/Views/DataGrid/Cells/DataGridBodyChrome.swift b/apple/TablePro/Views/DataGrid/Cells/DataGridBodyChrome.swift index 0ec73c5095..c9f124c99c 100644 --- a/apple/TablePro/Views/DataGrid/Cells/DataGridBodyChrome.swift +++ b/apple/TablePro/Views/DataGrid/Cells/DataGridBodyChrome.swift @@ -89,11 +89,18 @@ enum DataGridBodyChrome { return row.isMultiple(of: 2) ? resolved[.gridBackground] : resolved[.gridAlternateRow] } - // Opaque whatever the stripe is, because a frozen pane row covers the scrolling rows beneath it. + // Opaque whatever the stripe is, because a frozen pane row covers the scrolling rows beneath it. An even row's + // stripe is the grid background, which is always opaque (`ThemeSlot.requiresOpaque`), so it fills once. static func fillRowBackground(_ rect: NSRect, row: Int, of tableView: NSTableView, scope: ThemeScope) { + let stripe = stripeColor(forRow: row, of: tableView, scope: scope) + if let stripe, row.isMultiple(of: 2) { + stripe.setFill() + rect.fill() + return + } tableView.backgroundColor.setFill() rect.fill() - guard let stripe = stripeColor(forRow: row, of: tableView, scope: scope) else { return } + guard let stripe else { return } stripe.setFill() rect.fill(using: .sourceOver) } diff --git a/apple/TablePro/Views/DataGrid/DataGridContainerView.swift b/apple/TablePro/Views/DataGrid/DataGridContainerView.swift index 29f0e5199d..d0563d8050 100644 --- a/apple/TablePro/Views/DataGrid/DataGridContainerView.swift +++ b/apple/TablePro/Views/DataGrid/DataGridContainerView.swift @@ -56,7 +56,7 @@ final class DataGridContainerView: NSView { fatalError("init(coder:) has not been implemented") } - override var isFlipped: Bool { true } + override nonisolated var isFlipped: Bool { true } override func setFrameSize(_ newSize: NSSize) { super.setFrameSize(newSize) diff --git a/apple/TablePro/Views/DataGrid/DataGridHeaderView.swift b/apple/TablePro/Views/DataGrid/DataGridHeaderView.swift index 1e0e5c8d5c..0ab2713d40 100644 --- a/apple/TablePro/Views/DataGrid/DataGridHeaderView.swift +++ b/apple/TablePro/Views/DataGrid/DataGridHeaderView.swift @@ -34,4 +34,85 @@ final class DataGridHeaderView: ThemeTableHeaderView { bodyFollowsColumnDrag = isDragging controller?.headerGeometryDidStep(in: paneKind) } + + // Every scroll step drops the cursor rects, and AppKit's pass adds one for every column, asking for the visible + // columns again for each: 75 M instructions a step at 500 columns (measured on macOS 27). + override func resetCursorRects() { + guard let tableView, tableView.userInterfaceLayoutDirection == .leftToRight else { + super.resetCursorRects() + return + } + for resize in DataGridHeaderCursor.resizeRects(in: self, of: tableView) { + addCursorRect(resize.rect, cursor: resize.cursor) + } + } +} + +// AppKit's own divider geometry and cursors, measured on macOS 27, for the columns the header shows. +@MainActor +enum DataGridHeaderCursor { + struct Resize: Equatable { + let rect: NSRect + let cursor: NSCursor + } + + static let width: CGFloat = 5 + static let leadingInset: CGFloat = 3 + // The last divider has nothing after it, so AppKit gives it a wider target. + static let lastWidth: CGFloat = 9 + static let lastLeadingInset: CGFloat = 5 + + static func resizeRects(in header: NSTableHeaderView, of tableView: NSTableView) -> [Resize] { + guard tableView.allowsColumnResizing else { return [] } + let visible = header.visibleRect + guard visible.width > 0 else { return [] } + let columns = tableView.tableColumns + let shown = tableView.columnIndexes(in: NSRect(x: visible.minX, y: tableView.bounds.minY, width: visible.width, height: 1)) + guard let first = shown.first, let last = shown.last, last < columns.count else { return [] } + // The divider before the first shown column reaches into view. + return (max(first - 1, 0)...last).compactMap { index in + let column = columns[index] + guard !column.isHidden, column.resizingMask.contains(.userResizingMask) else { return nil } + let header = header.headerRect(ofColumn: index) + let isLast = index == columns.count - 1 + let rect = NSRect( + x: header.maxX - (isLast ? lastLeadingInset : leadingInset), + y: header.minY, + width: isLast ? lastWidth : width, + height: header.height + ) + return Resize(rect: rect, cursor: cursor(for: column)) + } + } + + private enum Direction { + case left + case right + case both + } + + static func cursor(for column: NSTableColumn) -> NSCursor { + if column.width <= column.minWidth { + return resize(.right) + } + if column.width >= column.maxWidth { + return resize(.left) + } + return resize(.both) + } + + private static func resize(_ direction: Direction) -> NSCursor { + if #available(macOS 15.0, *) { + switch direction { + case .left: return .columnResize(directions: .left) + case .right: return .columnResize(directions: .right) + case .both: return .columnResize(directions: .all) + } + } + switch direction { + case .left: return .resizeLeft + case .right: return .resizeRight + case .both: return .resizeLeftRight + } + } } diff --git a/apple/TablePro/Views/DataGrid/DataGridPane.swift b/apple/TablePro/Views/DataGrid/DataGridPane.swift index 29cc00195f..e9c2db7a01 100644 --- a/apple/TablePro/Views/DataGrid/DataGridPane.swift +++ b/apple/TablePro/Views/DataGrid/DataGridPane.swift @@ -107,6 +107,7 @@ final class DataGridPane { let identifier = NSUserInterfaceItemIdentifier("DataGrid.column.\(id.stringValue)") let column = NSTableColumn(identifier: identifier) column.headerCell = ThemeTableHeaderCell() + column.dataCell = Self.undrawnDataCell() column.minWidth = DataGridMetrics.dataColumnMinWidth column.maxWidth = DataGridMetrics.dataColumnMaxWidth column.resizingMask = .userResizingMask @@ -119,6 +120,7 @@ final class DataGridPane { if let rowNumberColumn { return rowNumberColumn } let column = NSTableColumn(identifier: Self.rowNumberIdentifier) column.headerCell = ThemeTableHeaderCell() + column.dataCell = Self.undrawnDataCell() column.title = "#" column.isEditable = false column.resizingMask = [] @@ -129,6 +131,12 @@ final class DataGridPane { return column } + // A view-based table never draws it, and the default text field cell tiles the table on every attach, which made + // attaching n columns O(n²) (measured on macOS 27). One per column, since a cell belongs to one control view. + private static func undrawnDataCell() -> NSCell { + NSCell() + } + func forgetColumns(except kept: Set) { for (id, column) in columnsByID where !kept.contains(id) { columnsByID.removeValue(forKey: id) diff --git a/apple/TablePro/Views/DataGrid/DataGridRowView.swift b/apple/TablePro/Views/DataGrid/DataGridRowView.swift index 98250d144f..4a832807bc 100644 --- a/apple/TablePro/Views/DataGrid/DataGridRowView.swift +++ b/apple/TablePro/Views/DataGrid/DataGridRowView.swift @@ -86,6 +86,12 @@ final class DataGridRowView: NSTableRowView { // MARK: - Drawing + // drawBackground(in:) fills with an opaque color whenever both are set. Saying so spares AppKit a color lookup per + // row and the layer its blending. + override var isOpaque: Bool { + controller != nil && gridTable != nil + } + override func drawBackground(in dirtyRect: NSRect) { guard let controller, let gridTable else { super.drawBackground(in: dirtyRect) @@ -145,7 +151,7 @@ final class DataGridRowView: NSTableRowView { final class DataGridRowContentView: NSView { weak var rowView: DataGridRowView? - override var isFlipped: Bool { true } + override nonisolated var isFlipped: Bool { true } override var allowsVibrancy: Bool { false } override func isAccessibilityElement() -> Bool { false } diff --git a/apple/TablePro/Views/DataGrid/DataGridViewController+Changes.swift b/apple/TablePro/Views/DataGrid/DataGridViewController+Changes.swift index 6e491b0802..22161bf0d7 100644 --- a/apple/TablePro/Views/DataGrid/DataGridViewController+Changes.swift +++ b/apple/TablePro/Views/DataGrid/DataGridViewController+Changes.swift @@ -92,14 +92,13 @@ extension DataGridViewController { // Only an accessory that came or went can move a width, and a wider column can leave the frozen pane with an open editor. private func columnMetadataDidChange() { let changed = presenter.refreshColumnPresentations() - if changed.isEmpty { - refreshHeaders() - } else { + if !changed.isEmpty { suspendFieldEditing(unmounting: true) reconcileColumns(widening: changed) resumeFieldEditing() followRowChangesWithPopovers() } + refreshHeaders() redrawVisibleRows() } diff --git a/apple/TablePro/Views/DataGrid/DataGridViewController+Columns.swift b/apple/TablePro/Views/DataGrid/DataGridViewController+Columns.swift index 9bcc0883e8..6645465939 100644 --- a/apple/TablePro/Views/DataGrid/DataGridViewController+Columns.swift +++ b/apple/TablePro/Views/DataGrid/DataGridViewController+Columns.swift @@ -7,7 +7,8 @@ import AppKit extension DataGridViewController { // Builds both panes' column lists from the model. Never culls a column with isHidden: each write costs - // O(attached columns), and seconds at 500 columns with mounted views (probe section 5). + // O(attached columns), and seconds at 500 columns with mounted views (probe section 5). Leaves the header text + // to the caller, which refreshes it once after the sort indicators. func reconcileColumns(widening changedPresentations: IndexSet = []) { isRebuildingColumns = true defer { isRebuildingColumns = false } @@ -53,7 +54,6 @@ extension DataGridViewController { main.forgetColumns(except: ids) savedWidthIDs = nextSaved updateFrozenPane() - refreshHeaders() } // A width saved before accessories reserved room, and never set by the user, is measured again. diff --git a/apple/TablePro/Views/DataGrid/DataGridViewController.swift b/apple/TablePro/Views/DataGrid/DataGridViewController.swift index 1a7f3ac4d9..d924116f9a 100644 --- a/apple/TablePro/Views/DataGrid/DataGridViewController.swift +++ b/apple/TablePro/Views/DataGrid/DataGridViewController.swift @@ -315,6 +315,7 @@ final class DataGridViewController: NSViewController, DataGridMountedView { } if previous.defaultSortDirection != settings.defaultSortDirection { reconcileColumns() + refreshHeaders() } if previous.dateFormat != settings.dateFormat || previous.nullDisplay != settings.nullDisplay diff --git a/apple/TablePro/Views/DataGrid/Editing/DataGridEditingCellView.swift b/apple/TablePro/Views/DataGrid/Editing/DataGridEditingCellView.swift index 42f71de486..90eb00e283 100644 --- a/apple/TablePro/Views/DataGrid/Editing/DataGridEditingCellView.swift +++ b/apple/TablePro/Views/DataGrid/Editing/DataGridEditingCellView.swift @@ -80,7 +80,7 @@ final class DataGridEditingCellView: NSTableCellView { layoutField() } - override var isFlipped: Bool { true } + override nonisolated var isFlipped: Bool { true } // A selected row's emphasized style would turn the text white on the field's own white background. override var backgroundStyle: NSView.BackgroundStyle { diff --git a/apple/TablePro/Views/ERDiagram/ERDiagramSceneView.swift b/apple/TablePro/Views/ERDiagram/ERDiagramSceneView.swift index c763591438..d3aeb50ccc 100644 --- a/apple/TablePro/Views/ERDiagram/ERDiagramSceneView.swift +++ b/apple/TablePro/Views/ERDiagram/ERDiagramSceneView.swift @@ -118,7 +118,7 @@ final class ERDiagramSceneView: NSView, NSMenuItemValidation { return baked } - override var isFlipped: Bool { true } + override nonisolated var isFlipped: Bool { true } override var isOpaque: Bool { false } diff --git a/apple/TablePro/Views/Main/Child/DataTabGrid.swift b/apple/TablePro/Views/Main/Child/DataTabGrid.swift new file mode 100644 index 0000000000..0f7097e4e5 --- /dev/null +++ b/apple/TablePro/Views/Main/Child/DataTabGrid.swift @@ -0,0 +1,35 @@ +// +// DataTabGrid.swift +// TablePro +// + +import SwiftUI + +// The data tab's grid. onChange runs the closure of the body from before a tab switch, so it reads only the +// presentation it is handed, which names its tab. Configuration is applied outside the update pass, since the model +// publishes when it changes. +struct DataTabGrid: View { + let coordinator: MainContentCoordinator + let model: DataGridModel + let presentation: DataTabGridPresentation + + var body: some View { + DataGridView(model: model) + .id(presentation.tabId) + .frame(maxHeight: .infinity, alignment: .top) + .onAppear { + coordinator.applyGridPresentation(presentation) + focusIfRequested() + } + .onChange(of: presentation) { coordinator.applyGridPresentation($0) } + } + + // An explicit open asks for the keyboard; the grid is in its window once this turn ends. + private func focusIfRequested() { + guard coordinator.consumePendingGridFocus() else { return } + let model = model + Task { @MainActor in + model.focus() + } + } +} diff --git a/apple/TablePro/Views/Main/Child/MainEditorContentView.swift b/apple/TablePro/Views/Main/Child/MainEditorContentView.swift index d6e71b3a62..6c434624e2 100644 --- a/apple/TablePro/Views/Main/Child/MainEditorContentView.swift +++ b/apple/TablePro/Views/Main/Child/MainEditorContentView.swift @@ -824,24 +824,12 @@ struct MainEditorContentView: View { .frame(maxWidth: .infinity, maxHeight: .infinity) } - // Configuration is applied outside the update pass: the model publishes when it changes. - @ViewBuilder private func dataGridView(tab: QueryTab) -> some View { - let model = displayedGridModel(for: tab) - let configuration = coordinator.gridConfiguration(for: tab) - let highlightRules = coordinator.highlightRules(for: tab) - DataGridView(model: model) - .id(tab.id) - .frame(maxHeight: .infinity, alignment: .top) - .onAppear { - model.configuration = configuration - focusGridIfRequested(model) - } - .onChange(of: configuration) { model.configuration = $0 } - .onChange(of: highlightRules) { _ in - model.display.cache.clearHighlights() - model.repaintAllRows() - } + DataTabGrid( + coordinator: coordinator, + model: displayedGridModel(for: tab), + presentation: coordinator.gridPresentation(for: tab) + ) } private func displayedGridModel(for tab: QueryTab) -> DataGridModel { @@ -850,14 +838,6 @@ struct MainEditorContentView: View { return model } - // An explicit open asks for the keyboard; the grid is in its window once this turn ends. - private func focusGridIfRequested(_ model: DataGridModel) { - guard coordinator.consumePendingGridFocus() else { return } - Task { @MainActor in - model.focus() - } - } - private func resolvedTableRows(for tab: QueryTab) -> TableRows { coordinator.tabSessionRegistry.existingTableRows(for: tab.id) ?? TableRows() } diff --git a/apple/TablePro/Views/Main/EditorTabItemView.swift b/apple/TablePro/Views/Main/EditorTabItemView.swift index d57b8bce71..35cb1607bd 100644 --- a/apple/TablePro/Views/Main/EditorTabItemView.swift +++ b/apple/TablePro/Views/Main/EditorTabItemView.swift @@ -62,7 +62,7 @@ internal final class EditorTabItemView: NSView { fatalError("EditorTabItemView does not support NSCoder init") } - override internal var isFlipped: Bool { true } + override nonisolated internal var isFlipped: Bool { true } override internal var mouseDownCanMoveWindow: Bool { false } // HIG: people expect to act on a tab in an inactive window without bringing it forward first. diff --git a/apple/TablePro/Views/Main/EditorTabStripView.swift b/apple/TablePro/Views/Main/EditorTabStripView.swift index 4cee0fcf35..6d5e851380 100644 --- a/apple/TablePro/Views/Main/EditorTabStripView.swift +++ b/apple/TablePro/Views/Main/EditorTabStripView.swift @@ -47,7 +47,7 @@ internal final class EditorTabStripView: NSView { fatalError("EditorTabStripView does not support NSCoder init") } - override internal var isFlipped: Bool { true } + override nonisolated internal var isFlipped: Bool { true } private func configure() { addSubview(track) @@ -815,7 +815,7 @@ internal enum EditorTabDragEnding { } internal final class EditorTabDocumentView: NSView { - override internal var isFlipped: Bool { true } + override nonisolated internal var isFlipped: Bool { true } override internal var mouseDownCanMoveWindow: Bool { false } } @@ -840,7 +840,7 @@ internal final class EditorTabScrollView: NSScrollView { @MainActor internal final class EditorTabTrackView: NSView { - override internal var isFlipped: Bool { true } + override nonisolated internal var isFlipped: Bool { true } override internal var mouseDownCanMoveWindow: Bool { false } override internal func draw(_ dirtyRect: NSRect) { diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+GridModels.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+GridModels.swift index fc2e9bfb07..f68603b8fc 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+GridModels.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+GridModels.swift @@ -20,6 +20,15 @@ struct DataTabGridEntry { let store: QueryTabGridStateStore var lastUsed: Int var displayInputs: DataTabDisplayInputs? + // Every switch hands over a new presentation, so only rules that differ from these repaint. + var appliedHighlightRules: [HighlightRule] +} + +// What the data tab's body computes for a tab's grid, named by the tab so it never reaches another tab's model. +struct DataTabGridPresentation: Equatable { + let tabId: UUID + let configuration: DataGridConfiguration + let highlightRules: [HighlightRule] } // What decided a model's formatted text, which nothing invalidates while the grid is unmounted. @@ -41,7 +50,8 @@ extension MainContentCoordinator { return model } let store = QueryTabGridStateStore(tabId: tabId, coordinator: self) - let configuration = tabManager.tabs.first { $0.id == tabId }.map(gridConfiguration(for:)) ?? DataGridConfiguration() + let tab = tabManager.tabs.first { $0.id == tabId } + let configuration = tab.map(gridConfiguration(for:)) ?? DataGridConfiguration() let model = DataGridModel(store: store, configuration: configuration, selectionSummary: selectionSummary) let adapter = DataTabGridAdapter(tabId: tabId, coordinator: self) adapter.attach(model) @@ -52,7 +62,8 @@ extension MainContentCoordinator { adapter: adapter, store: store, lastUsed: displayStateClock, - displayInputs: currentDisplayInputs + displayInputs: currentDisplayInputs, + appliedHighlightRules: tab.map(highlightRules(for:)) ?? [] ) model.reloadRows() return model @@ -187,6 +198,19 @@ extension MainContentCoordinator { return configuration } + func gridPresentation(for tab: QueryTab) -> DataTabGridPresentation { + DataTabGridPresentation(tabId: tab.id, configuration: gridConfiguration(for: tab), highlightRules: highlightRules(for: tab)) + } + + func applyGridPresentation(_ presentation: DataTabGridPresentation) { + guard let entry = dataGridEntries[presentation.tabId] else { return } + entry.model.configuration = presentation.configuration + guard entry.appliedHighlightRules != presentation.highlightRules else { return } + dataGridEntries[presentation.tabId]?.appliedHighlightRules = presentation.highlightRules + entry.model.display.cache.clearHighlights() + entry.model.repaintAllRows() + } + private func gridCommands(for tab: QueryTab, isSelected: Bool, isEditable: Bool) -> Set { var commands: Set = [ .hideColumns, .showRowsAsJSON, .exportResults, .shareResult, .navigateForeignKey, diff --git a/apple/TablePro/Views/QueryPlan/QueryPlanDiagramCanvasView.swift b/apple/TablePro/Views/QueryPlan/QueryPlanDiagramCanvasView.swift index 231234f869..ab4b27e334 100644 --- a/apple/TablePro/Views/QueryPlan/QueryPlanDiagramCanvasView.swift +++ b/apple/TablePro/Views/QueryPlan/QueryPlanDiagramCanvasView.swift @@ -29,7 +29,7 @@ final class QueryPlanDiagramCanvasView: NSView { private var popover: NSPopover? private var popoverNodeId: UUID? - override var isFlipped: Bool { true } + override nonisolated var isFlipped: Bool { true } /// Taking focus on a click is what puts the plan's scroll view on the responder chain, so View > /// Zoom In and Edit > Copy act on the plan instead of on the editor above it. diff --git a/apple/TableProTests/Views/DataGrid/DataGridBodyChromeTests.swift b/apple/TableProTests/Views/DataGrid/DataGridBodyChromeTests.swift index 5abaf3b1ef..2eeef1aec1 100644 --- a/apple/TableProTests/Views/DataGrid/DataGridBodyChromeTests.swift +++ b/apple/TableProTests/Views/DataGrid/DataGridBodyChromeTests.swift @@ -235,6 +235,101 @@ struct DataGridBodyChromeTests { #expect(DataGridBodyChrome.stripeColor(forRow: 1, of: tableView, scope: .live) == resolved[.gridAlternateRow]) } + // MARK: - Opaque rows + + @Test("A row view with its controller and table says it is opaque, and with either missing it does not") + func rowViewOpacityFollowsItsDrawingPath() throws { + let grid = makeGrid(columns: ["id", "name"]) + defer { grid.close() } + let rowView = try #require(grid.main.rowView(atRow: 0, makeIfNecessary: true) as? DataGridRowView) + let controller = rowView.controller + let table = rowView.gridTable + defer { + rowView.controller = controller + rowView.gridTable = table + } + #expect(rowView.isOpaque) + + rowView.gridTable = nil + #expect(!rowView.isOpaque) + + rowView.gridTable = table + rowView.controller = nil + #expect(!rowView.isOpaque) + #expect(!DataGridRowView(frame: .zero).isOpaque) + } + + @Test("A row's background has full alpha in both appearances, on a translucent stripe and under a row tint") + func rowBackgroundIsOpaque() throws { + let grid = makeGrid(columns: ["id", "name"]) + defer { grid.close() } + grid.main.usesAlternatingRowBackgroundColors = true + grid.owner.visualStates[.existing(1)] = RowVisualState(isDeleted: true, isInserted: false, modifiedColumns: []) + for name in [NSAppearance.Name.aqua, .darkAqua] { + let appearance = try #require(NSAppearance(named: name)) + for row in 0..<3 { + let rowView = try #require(grid.main.rowView(atRow: row, makeIfNecessary: true) as? DataGridRowView) + let bounds = rowView.bounds + let rep = try bitmap(width: bounds.width, height: bounds.height) + try drawFlipped(into: rep, height: bounds.height, appearance: appearance) { + rowView.drawBackground(in: bounds) + } + for x in [1, rep.pixelsWide / 2, rep.pixelsWide - 2] { + let alpha = try #require(rep.colorAt(x: x, y: rep.pixelsHigh / 2)).alphaComponent + #expect(alpha == 1, "row \(row), \(name.rawValue), x \(x)") + } + } + } + } + + @Test("Even and odd rows fill the pixels of the fill they replace, also over a table background left stale") + func rowFillMatchesTheTwoStepFill() throws { + let themed = ThemeScope.fixed(try ThemeTestFixture.theme(.light, [ + .gridBackground: "#10203080", + .gridAlternateRow: "#C0402060", + ])) + let table = NSTableView() + table.usesAlternatingRowBackgroundColors = true + let rect = NSRect(x: 0, y: 0, width: 4, height: 4) + for scope in [ThemeScope.live, themed] { + for name in [NSAppearance.Name.aqua, .darkAqua] { + let appearance = try #require(NSAppearance(named: name)) + for isStale in [false, true] { + DataGridBodyChrome.applyThemeColors(to: table, scope: scope) + if isStale { + table.backgroundColor = .systemRed + } + for row in 0..<2 { + let expected = try bitmap(width: rect.width, height: rect.height) + try drawFlipped(into: expected, height: rect.height, appearance: appearance) { + twoStepFill(rect, row: row, of: table, scope: scope) + } + let drawn = try bitmap(width: rect.width, height: rect.height) + try drawFlipped(into: drawn, height: rect.height, appearance: appearance) { + DataGridBodyChrome.fillRowBackground(rect, row: row, of: table, scope: scope) + } + #expect(pixel(of: drawn) == pixel(of: expected), "row \(row), \(name.rawValue), stale \(isStale)") + } + } + } + } + } + + // The fill rows drew before: the table's background, then the stripe blended over it. + private func twoStepFill(_ rect: NSRect, row: Int, of table: NSTableView, scope: ThemeScope) { + table.backgroundColor.setFill() + rect.fill() + guard let stripe = DataGridBodyChrome.stripeColor(forRow: row, of: table, scope: scope) else { return } + stripe.setFill() + rect.fill(using: .sourceOver) + } + + private func pixel(of rep: NSBitmapImageRep) -> [Int] { + var samples = [Int](repeating: 0, count: 4) + rep.getPixel(&samples, atX: rep.pixelsWide / 2, y: rep.pixelsHigh / 2) + return samples + } + private func singleBlend(over background: NSColor, of row: Int, appearance: NSAppearance) -> NSColor? { guard let rep = NSBitmapImageRep( bitmapDataPlanes: nil, diff --git a/apple/TableProTests/Views/DataGrid/DataGridColumnMetadataTests.swift b/apple/TableProTests/Views/DataGrid/DataGridColumnMetadataTests.swift index 06091ae16b..8611b172be 100644 --- a/apple/TableProTests/Views/DataGrid/DataGridColumnMetadataTests.swift +++ b/apple/TableProTests/Views/DataGrid/DataGridColumnMetadataTests.swift @@ -116,6 +116,25 @@ struct DataGridColumnMetadataTests { #expect(grid.model.display.cache.box(forID: .existing(0)) != nil) } + @Test("Metadata that gives a column an accessory still reaches the column's header") + func accessoryMetadataReachesTheHeader() throws { + var configuration = DataGridConfiguration() + configuration.isEditable = true + let grid = HostedDataGrid(rows: GridFixtureRows.people, configuration: configuration) + defer { grid.close() } + let column = try #require(grid.tableColumn(named: "name")) + let showsComments = AppSettingsManager.shared.general.showObjectComments + + grid.model.apply(grid.owner.tableRows.updateDisplayMetadata( + columnEnumValues: ["name": ["ann", "bob"]], + columnComments: ["name": "Given name"] + )) + + #expect(grid.controller.presenter.presentation(forDataIndex: 1).accessory != .none) + #expect(column.headerToolTip?.contains("Given name") == showsComments) + #expect(column.headerCell.accessibilityLabel()?.contains("Given name") == showsComments) + } + @Test("A comment arriving after the rows reaches the column's header") func commentsReachTheHeader() throws { let grid = HostedDataGrid(rows: GridFixtureRows.people) diff --git a/apple/TableProTests/Views/DataGrid/DataGridHeaderCursorTests.swift b/apple/TableProTests/Views/DataGrid/DataGridHeaderCursorTests.swift new file mode 100644 index 0000000000..9037b6f993 --- /dev/null +++ b/apple/TableProTests/Views/DataGrid/DataGridHeaderCursorTests.swift @@ -0,0 +1,146 @@ +// +// DataGridHeaderCursorTests.swift +// TableProTests +// + +import AppKit +@testable import TablePro +import Testing + +// Records what AppKit's own pass adds instead of installing it, so the grid's rects can be compared with it. +@MainActor +private final class RecordingHeaderView: NSTableHeaderView { + private var recorded: [DataGridHeaderCursor.Resize] = [] + + override func addCursorRect(_ rect: NSRect, cursor object: NSCursor) { + recorded.append(DataGridHeaderCursor.Resize(rect: rect, cursor: object)) + } + + func stockRects() -> [DataGridHeaderCursor.Resize] { + recorded = [] + resetCursorRects() + return recorded + } +} + +@MainActor +private final class HeaderHost { + let table = NSTableView(frame: .zero) + let header = RecordingHeaderView(frame: NSRect(x: 0, y: 0, width: 0, height: 28)) + let scrollView = NSScrollView(frame: NSRect(x: 0, y: 0, width: 600, height: 300)) + let window: NSWindow + let columns: [NSTableColumn] + + // The first column is fixed, as the grid's row numbers are. + init(columns count: Int) { + table.headerView = header + table.columnAutoresizingStyle = .noColumnAutoresizing + table.intercellSpacing = NSSize(width: 1, height: 0) + columns = (0..