| 1 | #if os(macOS) |
| 2 | import AppKit |
| 3 | import SwiftUI |
| 4 | import XCTest |
| 5 | import RastrilloApple |
| 6 | @testable import SheetsKit |
| 7 | |
| 8 | /// Review #72, the column windowing: the grid is laid out from exact column |
| 9 | /// widths and row heights (SheetGridMetrics), and the editor, clicks and |
| 10 | /// scrolling all use the same numbers. A LazyHStack estimated the widths of |
| 11 | /// columns it had not built, so after scrolling right a click selected a cell |
| 12 | /// columns away from the one under the pointer, and the editor opened off |
| 13 | /// screen. These scroll, click where the geometry says a cell is, and type. |
| 14 | final class GridGeometryTests: XCTestCase { |
| 15 | /// 60 columns of 40, 300 and 110 points, and rows of 60 and 32. |
| 16 | @MainActor private func mixedModel() -> SheetModel { |
| 17 | let model = fixtureModel(SheetServerFixture(), rows: 120, cols: 60) |
| 18 | var cols: [String: Double] = [:], rows: [String: Double] = [:] |
| 19 | for c in 0..<60 where c % 3 != 2 { cols[String(c)] = c % 3 == 0 ? 40 : 300 } |
| 20 | for r in stride(from: 0, to: 120, by: 4) { rows[String(r)] = 60 } |
| 21 | model.sizes = Sizes(cols: cols, rows: rows) |
| 22 | return model |
| 23 | } |
| 24 | @MainActor private func metrics(_ model: SheetModel) -> SheetGridMetrics { |
| 25 | SheetGridMetrics(sizes: model.sizes, resizing: nil, rows: model.rows, cols: model.cols) |
| 26 | } |
| 27 | @MainActor private func open(_ model: SheetModel) async throws -> (NSWindow, NSView, NSScrollView) { |
| 28 | let host = NSHostingView(rootView: SheetGrid(model: model)) |
| 29 | let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 640, height: 400), styleMask: [.titled], backing: .buffered, defer: false) |
| 30 | window.contentView = host; NSApp.setActivationPolicy(.regular); window.makeKeyAndOrderFront(nil); NSApp.activate() |
| 31 | try await Task.sleep(for: .milliseconds(300)) |
| 32 | func scrolls(_ v: NSView) -> [NSScrollView] { ((v as? NSScrollView).map { [$0] } ?? []) + v.subviews.flatMap(scrolls) } |
| 33 | let scroll = try XCTUnwrap(scrolls(host).first) |
| 34 | return (window, host, scroll) |
| 35 | } |
| 36 | @MainActor private func wheel(_ window: NSWindow, dx: Int32, dy: Int32 = 0) { |
| 37 | let event = CGEvent(scrollWheelEvent2Source: nil, units: .pixel, wheelCount: 2, wheel1: dy, wheel2: dx, wheel3: 0)! |
| 38 | let screen = window.convertPoint(toScreen: NSPoint(x: 320, y: 200)) |
| 39 | event.location = CGPoint(x: screen.x, y: (NSScreen.screens.first?.frame.height ?? 0) - screen.y) |
| 40 | window.sendEvent(NSEvent(cgEvent: event)!) |
| 41 | } |
| 42 | /// A content rect (the grid's coordinates) in window coordinates, now. |
| 43 | @MainActor private func onScreen(_ frame: CGRect, _ scroll: NSScrollView, _ window: NSWindow) -> CGRect { |
| 44 | let visible = scroll.contentView.bounds |
| 45 | let height = window.contentView!.bounds.height |
| 46 | return CGRect(x: frame.minX - visible.minX, y: height - (frame.maxY - visible.minY), width: frame.width, height: frame.height) |
| 47 | } |
| 48 | @MainActor private func click(_ point: CGPoint, _ window: NSWindow) { |
| 49 | for type in [NSEvent.EventType.leftMouseDown, .leftMouseUp] { |
| 50 | window.sendEvent(NSEvent.mouseEvent(with: type, location: point, modifierFlags: [], timestamp: 0, windowNumber: window.windowNumber, context: nil, eventNumber: 1, clickCount: 1, pressure: 1)!) |
| 51 | } |
| 52 | } |
| 53 | @MainActor private func key(_ text: String, _ code: UInt16, _ window: NSWindow) { |
| 54 | NSApp.sendEvent(NSEvent.keyEvent(with: .keyDown, location: .zero, modifierFlags: [], timestamp: 0, windowNumber: window.windowNumber, context: nil, characters: text, charactersIgnoringModifiers: text, isARepeat: false, keyCode: code)!) |
| 55 | } |
| 56 | @MainActor private func editorRect(_ host: NSView) -> CGRect? { |
| 57 | func find(_ v: NSView) -> NSView? { v is SheetCellEditor.CellTextField ? v : v.subviews.lazy.compactMap(find).first } |
| 58 | return find(host).map { $0.convert($0.bounds, to: nil) } |
| 59 | } |
| 60 | /// The editor's field sits inside its cell (inset by its padding) and on screen. |
| 61 | @MainActor private func assertEditor(at cell: CGRect, _ host: NSView, _ scroll: NSScrollView, file: StaticString = #filePath, line: UInt = #line) { |
| 62 | guard let field = editorRect(host) else { return XCTFail("no editor", file: file, line: line) } |
| 63 | XCTAssertTrue(cell.insetBy(dx: -1, dy: -1).contains(field), "editor \(field) is not in its cell \(cell)", file: file, line: line) |
| 64 | XCTAssertTrue(scroll.frame.contains(field), "editor \(field) is off screen", file: file, line: line) |
| 65 | } |
| 66 | |
| 67 | @MainActor func testTheContentIsExactlyAsWideAndTallAsTheCells() async throws { |
| 68 | let model = mixedModel() |
| 69 | let (window, _, scroll) = try await open(model) |
| 70 | defer { window.orderOut(nil) } |
| 71 | let m = metrics(model) |
| 72 | let document = try XCTUnwrap(scroll.documentView).frame.size |
| 73 | // Plus room for always-shown scroll bars, when they are. |
| 74 | let bar = SheetGridScroller.legacyBar |
| 75 | XCTAssertEqual(document.width, SheetGridMetrics.rowHeader + m.cellsWidth + bar, accuracy: 0.5) |
| 76 | XCTAssertEqual(document.height, SheetGridMetrics.colHeader + m.cellsHeight + bar, accuracy: 0.5) |
| 77 | XCTAssertEqual(scroll.contentView.bounds.origin, .zero, "mixed widths opened pre-scrolled") |
| 78 | } |
| 79 | |
| 80 | @MainActor func testClickAfterScrollingRightSelectsTheCellUnderThePointer() async throws { |
| 81 | let model = mixedModel() |
| 82 | let (window, host, scroll) = try await open(model) |
| 83 | defer { window.orderOut(nil) } |
| 84 | let m = metrics(model) |
| 85 | for distance: Int32 in [-4000, -3000] { |
| 86 | wheel(window, dx: distance) |
| 87 | try await Task.sleep(for: .milliseconds(300)) |
| 88 | let visible = scroll.contentView.bounds |
| 89 | XCTAssertGreaterThan(visible.minX, 1000, "the grid scrolled right") |
| 90 | // A cell fully in view, by the exact geometry. |
| 91 | let row = 6 |
| 92 | let col = try XCTUnwrap((0..<60).first { c in |
| 93 | let f = m.frame(Coordinate(r: row, c: c)) |
| 94 | return f.minX >= visible.minX + 10 && f.maxX <= visible.maxX - 10 |
| 95 | }) |
| 96 | let target = Coordinate(r: row, c: col) |
| 97 | let cell = onScreen(m.frame(target), scroll, window) |
| 98 | click(CGPoint(x: cell.midX, y: cell.midY), window) |
| 99 | try await Task.sleep(for: .milliseconds(150)) |
| 100 | XCTAssertEqual(model.selection.start, target, "the click selected a different cell from the one under it") |
| 101 | key("q", 12, window) |
| 102 | try await Task.sleep(for: .milliseconds(200)) |
| 103 | XCTAssertEqual(model.draft, "q") |
| 104 | assertEditor(at: cell, host, scroll) |
| 105 | key("\u{1b}", 53, window) |
| 106 | try await Task.sleep(for: .milliseconds(100)) |
| 107 | } |
| 108 | } |
| 109 | |
| 110 | @MainActor func testTypingOnAFarCellScrollsExactlyToIt() async throws { |
| 111 | let model = mixedModel() |
| 112 | let (window, host, scroll) = try await open(model) |
| 113 | defer { window.orderOut(nil) } |
| 114 | let m = metrics(model) |
| 115 | // Including the last cell, BH120: with always-shown scroll bars it |
| 116 | // stopped one bar short, under both bars. |
| 117 | for target in [Coordinate(r: 90, c: 50), Coordinate(r: 3, c: 1), Coordinate(r: 61, c: 33), Coordinate(r: 119, c: 59)] { |
| 118 | model.select(target) |
| 119 | key("z", 6, window) |
| 120 | try await Task.sleep(for: .milliseconds(400)) |
| 121 | let frame = m.frame(target) |
| 122 | let visible = scroll.contentView.bounds |
| 123 | let clear = CGRect(x: visible.minX, y: visible.minY + SheetGridMetrics.colHeader, |
| 124 | width: visible.width, height: visible.height - SheetGridMetrics.colHeader) |
| 125 | XCTAssertTrue(clear.insetBy(dx: -1, dy: -1).contains(frame), "\(target.ref) at \(frame) not in view \(visible)") |
| 126 | XCTAssertEqual(model.draft, "z") |
| 127 | assertEditor(at: onScreen(frame, scroll, window), host, scroll) |
| 128 | key("\u{1b}", 53, window) |
| 129 | try await Task.sleep(for: .milliseconds(100)) |
| 130 | } |
| 131 | } |
| 132 | |
| 133 | /// Review #72 delta 2, finding 3: an open editor scrolled up under the |
| 134 | /// pinned column header is clipped by it, not drawn over it. |
| 135 | @MainActor func testTheEditorStaysBelowThePinnedHeader() async throws { |
| 136 | let model = fixtureModel(SheetServerFixture(), rows: 60, cols: 10) |
| 137 | let (window, host, scroll) = try await open(model) |
| 138 | defer { window.orderOut(nil) } |
| 139 | model.select(Coordinate(r: 1, c: 1)) |
| 140 | key("w", 13, window) |
| 141 | try await Task.sleep(for: .milliseconds(200)) |
| 142 | XCTAssertNotNil(editorRect(host)) |
| 143 | wheel(window, dx: 0, dy: -50) |
| 144 | try await Task.sleep(for: .milliseconds(300)) |
| 145 | XCTAssertGreaterThan(scroll.contentView.bounds.minY, 20) |
| 146 | let bitmap = try XCTUnwrap(host.bitmapImageRepForCachingDisplay(in: host.bounds)) |
| 147 | host.cacheDisplay(in: host.bounds, to: bitmap) |
| 148 | let scale = Double(bitmap.pixelsWide) / host.bounds.width |
| 149 | func colour(_ x: Double, _ yFromTop: Double) -> NSColor? { |
| 150 | bitmap.colorAt(x: Int(x * scale), y: Int(yFromTop * scale))?.usingColorSpace(.sRGB) |
| 151 | } |
| 152 | let visible = scroll.contentView.bounds |
| 153 | // Column B's header strip, above where the editor would draw, against |
| 154 | // column D's, which has no editor anywhere near it. |
| 155 | let m = metrics(model) |
| 156 | let b = m.frame(Coordinate(r: 1, c: 1)), d = m.frame(Coordinate(r: 1, c: 3)) |
| 157 | let underB = try XCTUnwrap(colour(b.midX - visible.minX, 20)) |
| 158 | let underD = try XCTUnwrap(colour(d.midX - visible.minX, 20)) |
| 159 | XCTAssertEqual(underB.redComponent, underD.redComponent, accuracy: 0.03, "the editor drew over the pinned header") |
| 160 | XCTAssertEqual(underB.blueComponent, underD.blueComponent, accuracy: 0.03, "the editor drew over the pinned header") |
| 161 | } |
| 162 | |
| 163 | @MainActor func testTheLeastScrollThatShowsACell() { |
| 164 | let visible = CGRect(x: 1000, y: 500, width: 600, height: 400) |
| 165 | XCTAssertNil(SheetGridScroller.offset(showing: CGRect(x: 1100, y: 600, width: 100, height: 30), in: visible)) |
| 166 | XCTAssertEqual(SheetGridScroller.offset(showing: CGRect(x: 3000, y: 600, width: 100, height: 30), in: visible), |
| 167 | CGPoint(x: 2500, y: 500), "far right: its right edge at the view's, not the grid's last column") |
| 168 | XCTAssertEqual(SheetGridScroller.offset(showing: CGRect(x: 200, y: 510, width: 100, height: 30), in: visible), |
| 169 | CGPoint(x: 200, y: 478), "up and left: clear of the pinned column header") |
| 170 | } |
| 171 | } |
| 172 | #endif |
| 173 | |
| 174 | #if os(macOS) |
| 175 | /// Review #72 (58b4cb0), finding 4: scrolling crosses a window block every |
| 176 | /// few rows or columns, and each crossing rebuilt every visible cell's body. |
| 177 | final class GridScrollTests: XCTestCase { |
| 178 | @MainActor func testScrollStepsStayCheap() async throws { |
| 179 | let model = fixtureModel(SheetServerFixture(), rows: 1000, cols: 200) |
| 180 | for r in 0..<60 { for c in 0..<20 { model.cells[Coordinate(r: r, c: c)] = Cell(r: r, c: c, raw: "\(r)·\(c)", display: "\(r)·\(c)") } } |
| 181 | let host = NSHostingView(rootView: SheetGrid(model: model)) |
| 182 | let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 1200, height: 800), styleMask: [.titled], backing: .buffered, defer: false) |
| 183 | window.contentView = host; NSApp.setActivationPolicy(.regular); window.makeKeyAndOrderFront(nil); NSApp.activate() |
| 184 | defer { window.orderOut(nil) } |
| 185 | try await Task.sleep(for: .milliseconds(300)) |
| 186 | func scrolls(_ v: NSView) -> [NSScrollView] { ((v as? NSScrollView).map { [$0] } ?? []) + v.subviews.flatMap(scrolls) } |
| 187 | let scroll = try XCTUnwrap(scrolls(host).first) |
| 188 | var report: [String] = [] |
| 189 | for (name, dx, dy) in [("vertical", 0.0, 32.0), ("horizontal", 55.0, 0.0), ("diagonal", 55.0, 32.0)] { |
| 190 | scroll.contentView.scroll(to: .zero); scroll.reflectScrolledClipView(scroll.contentView) |
| 191 | try await Task.sleep(for: .milliseconds(200)) |
| 192 | var steps: [Double] = [] |
| 193 | for step in 1...120 { |
| 194 | let start = ProcessInfo.processInfo.systemUptime |
| 195 | scroll.contentView.scroll(to: NSPoint(x: dx * Double(step), y: dy * Double(step))) |
| 196 | scroll.reflectScrolledClipView(scroll.contentView) |
| 197 | host.layoutSubtreeIfNeeded(); window.displayIfNeeded() |
| 198 | var spent = ProcessInfo.processInfo.systemUptime - start |
| 199 | // The window update the scroll set off renders on the next turn. |
| 200 | await Task.yield(); await Task.yield() |
| 201 | let again = ProcessInfo.processInfo.systemUptime |
| 202 | host.layoutSubtreeIfNeeded(); window.displayIfNeeded() |
| 203 | spent += ProcessInfo.processInfo.systemUptime - again |
| 204 | steps.append(spent * 1000) |
| 205 | } |
| 206 | let mean = steps.reduce(0, +) / Double(steps.count) |
| 207 | let worst = steps.max() ?? 0 |
| 208 | report.append("\(name) mean \(String(format: "%.1f", mean)) worst \(String(format: "%.0f", worst)) ms") |
| 209 | // Was 113 / 117 / 154 ms worst at 58b4cb0 on this host; a busy |
| 210 | // machine adds a little, so the bound is loose. |
| 211 | XCTAssertLessThan(worst, 130, "\(name): a scroll step took \(worst) ms") |
| 212 | } |
| 213 | print("MEASURE scroll steps, 1000x200, 1200x800: " + report.joined(separator: "; ")) |
| 214 | } |
| 215 | } |
| 216 | #endif |
| 217 | |