From d96c96e82c6f383ad55ecdc520f1a25287f216d9 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Mon, 23 Nov 2026 11:59:18 +0700 Subject: [PATCH 1/4] perf(grid): attach columns in linear time and cut per-scroll header and row work --- apple/.swiftlint.yml | 9 + .../DataGrid/Cells/DataGridBodyChrome.swift | 11 +- .../DataGrid/DataGridContainerView.swift | 2 +- .../Views/DataGrid/DataGridHeaderView.swift | 81 ++++++++ .../Views/DataGrid/DataGridPane.swift | 8 + .../Views/DataGrid/DataGridRowView.swift | 8 +- .../DataGridViewController+Changes.swift | 5 +- .../DataGridViewController+Columns.swift | 4 +- .../DataGrid/DataGridViewController.swift | 1 + .../Editing/DataGridEditingCellView.swift | 2 +- .../Views/ERDiagram/ERDiagramSceneView.swift | 2 +- .../Views/Main/Child/DataTabGrid.swift | 35 ++++ .../Main/Child/MainEditorContentView.swift | 30 +-- .../Views/Main/EditorTabItemView.swift | 2 +- .../Views/Main/EditorTabStripView.swift | 6 +- .../MainContentCoordinator+GridModels.swift | 28 ++- .../QueryPlanDiagramCanvasView.swift | 2 +- .../DataGrid/DataGridBodyChromeTests.swift | 95 +++++++++ .../DataGridColumnMetadataTests.swift | 19 ++ .../DataGrid/DataGridHeaderCursorTests.swift | 146 +++++++++++++ .../Views/DataGrid/DataGridPaneTests.swift | 65 ++++++ .../Main/DataTabGridPresentationTests.swift | 196 ++++++++++++++++++ 22 files changed, 714 insertions(+), 43 deletions(-) create mode 100644 apple/TablePro/Views/Main/Child/DataTabGrid.swift create mode 100644 apple/TableProTests/Views/DataGrid/DataGridHeaderCursorTests.swift create mode 100644 apple/TableProTests/Views/Main/DataTabGridPresentationTests.swift 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..