#if os(macOS) import AppKit import SwiftUI import XCTest import RastrilloApple @testable import SheetsKit /// Review #72, the column windowing: the grid is laid out from exact column /// widths and row heights (SheetGridMetrics), and the editor, clicks and /// scrolling all use the same numbers. A LazyHStack estimated the widths of /// columns it had not built, so after scrolling right a click selected a cell /// columns away from the one under the pointer, and the editor opened off /// screen. These scroll, click where the geometry says a cell is, and type. final class GridGeometryTests: XCTestCase { /// 60 columns of 40, 300 and 110 points, and rows of 60 and 32. @MainActor private func mixedModel() -> SheetModel { let model = fixtureModel(SheetServerFixture(), rows: 120, cols: 60) var cols: [String: Double] = [:], rows: [String: Double] = [:] for c in 0..<60 where c % 3 != 2 { cols[String(c)] = c % 3 == 0 ? 40 : 300 } for r in stride(from: 0, to: 120, by: 4) { rows[String(r)] = 60 } model.sizes = Sizes(cols: cols, rows: rows) return model } @MainActor private func metrics(_ model: SheetModel) -> SheetGridMetrics { SheetGridMetrics(sizes: model.sizes, resizing: nil, rows: model.rows, cols: model.cols) } @MainActor private func open(_ model: SheetModel) async throws -> (NSWindow, NSView, NSScrollView) { let host = NSHostingView(rootView: SheetGrid(model: model)) let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 640, height: 400), styleMask: [.titled], backing: .buffered, defer: false) window.contentView = host; NSApp.setActivationPolicy(.regular); window.makeKeyAndOrderFront(nil); NSApp.activate() try await Task.sleep(for: .milliseconds(300)) func scrolls(_ v: NSView) -> [NSScrollView] { ((v as? NSScrollView).map { [$0] } ?? []) + v.subviews.flatMap(scrolls) } let scroll = try XCTUnwrap(scrolls(host).first) return (window, host, scroll) } @MainActor private func wheel(_ window: NSWindow, dx: Int32, dy: Int32 = 0) { let event = CGEvent(scrollWheelEvent2Source: nil, units: .pixel, wheelCount: 2, wheel1: dy, wheel2: dx, wheel3: 0)! let screen = window.convertPoint(toScreen: NSPoint(x: 320, y: 200)) event.location = CGPoint(x: screen.x, y: (NSScreen.screens.first?.frame.height ?? 0) - screen.y) window.sendEvent(NSEvent(cgEvent: event)!) } /// A content rect (the grid's coordinates) in window coordinates, now. @MainActor private func onScreen(_ frame: CGRect, _ scroll: NSScrollView, _ window: NSWindow) -> CGRect { let visible = scroll.contentView.bounds let height = window.contentView!.bounds.height return CGRect(x: frame.minX - visible.minX, y: height - (frame.maxY - visible.minY), width: frame.width, height: frame.height) } @MainActor private func click(_ point: CGPoint, _ window: NSWindow) { for type in [NSEvent.EventType.leftMouseDown, .leftMouseUp] { window.sendEvent(NSEvent.mouseEvent(with: type, location: point, modifierFlags: [], timestamp: 0, windowNumber: window.windowNumber, context: nil, eventNumber: 1, clickCount: 1, pressure: 1)!) } } @MainActor private func key(_ text: String, _ code: UInt16, _ window: NSWindow) { NSApp.sendEvent(NSEvent.keyEvent(with: .keyDown, location: .zero, modifierFlags: [], timestamp: 0, windowNumber: window.windowNumber, context: nil, characters: text, charactersIgnoringModifiers: text, isARepeat: false, keyCode: code)!) } @MainActor private func editorRect(_ host: NSView) -> CGRect? { func find(_ v: NSView) -> NSView? { v is SheetCellEditor.CellTextField ? v : v.subviews.lazy.compactMap(find).first } return find(host).map { $0.convert($0.bounds, to: nil) } } /// The editor's field sits inside its cell (inset by its padding) and on screen. @MainActor private func assertEditor(at cell: CGRect, _ host: NSView, _ scroll: NSScrollView, file: StaticString = #filePath, line: UInt = #line) { guard let field = editorRect(host) else { return XCTFail("no editor", file: file, line: line) } XCTAssertTrue(cell.insetBy(dx: -1, dy: -1).contains(field), "editor \(field) is not in its cell \(cell)", file: file, line: line) XCTAssertTrue(scroll.frame.contains(field), "editor \(field) is off screen", file: file, line: line) } @MainActor func testTheContentIsExactlyAsWideAndTallAsTheCells() async throws { let model = mixedModel() let (window, _, scroll) = try await open(model) defer { window.orderOut(nil) } let m = metrics(model) let document = try XCTUnwrap(scroll.documentView).frame.size // Plus room for always-shown scroll bars, when they are. let bar = SheetGridScroller.legacyBar XCTAssertEqual(document.width, SheetGridMetrics.rowHeader + m.cellsWidth + bar, accuracy: 0.5) XCTAssertEqual(document.height, SheetGridMetrics.colHeader + m.cellsHeight + bar, accuracy: 0.5) XCTAssertEqual(scroll.contentView.bounds.origin, .zero, "mixed widths opened pre-scrolled") } @MainActor func testClickAfterScrollingRightSelectsTheCellUnderThePointer() async throws { let model = mixedModel() let (window, host, scroll) = try await open(model) defer { window.orderOut(nil) } let m = metrics(model) for distance: Int32 in [-4000, -3000] { wheel(window, dx: distance) try await Task.sleep(for: .milliseconds(300)) let visible = scroll.contentView.bounds XCTAssertGreaterThan(visible.minX, 1000, "the grid scrolled right") // A cell fully in view, by the exact geometry. let row = 6 let col = try XCTUnwrap((0..<60).first { c in let f = m.frame(Coordinate(r: row, c: c)) return f.minX >= visible.minX + 10 && f.maxX <= visible.maxX - 10 }) let target = Coordinate(r: row, c: col) let cell = onScreen(m.frame(target), scroll, window) click(CGPoint(x: cell.midX, y: cell.midY), window) try await Task.sleep(for: .milliseconds(150)) XCTAssertEqual(model.selection.start, target, "the click selected a different cell from the one under it") key("q", 12, window) try await Task.sleep(for: .milliseconds(200)) XCTAssertEqual(model.draft, "q") assertEditor(at: cell, host, scroll) key("\u{1b}", 53, window) try await Task.sleep(for: .milliseconds(100)) } } @MainActor func testTypingOnAFarCellScrollsExactlyToIt() async throws { let model = mixedModel() let (window, host, scroll) = try await open(model) defer { window.orderOut(nil) } let m = metrics(model) // Including the last cell, BH120: with always-shown scroll bars it // stopped one bar short, under both bars. for target in [Coordinate(r: 90, c: 50), Coordinate(r: 3, c: 1), Coordinate(r: 61, c: 33), Coordinate(r: 119, c: 59)] { model.select(target) key("z", 6, window) try await Task.sleep(for: .milliseconds(400)) let frame = m.frame(target) let visible = scroll.contentView.bounds let clear = CGRect(x: visible.minX, y: visible.minY + SheetGridMetrics.colHeader, width: visible.width, height: visible.height - SheetGridMetrics.colHeader) XCTAssertTrue(clear.insetBy(dx: -1, dy: -1).contains(frame), "\(target.ref) at \(frame) not in view \(visible)") XCTAssertEqual(model.draft, "z") assertEditor(at: onScreen(frame, scroll, window), host, scroll) key("\u{1b}", 53, window) try await Task.sleep(for: .milliseconds(100)) } } /// Review #72 delta 2, finding 3: an open editor scrolled up under the /// pinned column header is clipped by it, not drawn over it. @MainActor func testTheEditorStaysBelowThePinnedHeader() async throws { let model = fixtureModel(SheetServerFixture(), rows: 60, cols: 10) let (window, host, scroll) = try await open(model) defer { window.orderOut(nil) } model.select(Coordinate(r: 1, c: 1)) key("w", 13, window) try await Task.sleep(for: .milliseconds(200)) XCTAssertNotNil(editorRect(host)) wheel(window, dx: 0, dy: -50) try await Task.sleep(for: .milliseconds(300)) XCTAssertGreaterThan(scroll.contentView.bounds.minY, 20) let bitmap = try XCTUnwrap(host.bitmapImageRepForCachingDisplay(in: host.bounds)) host.cacheDisplay(in: host.bounds, to: bitmap) let scale = Double(bitmap.pixelsWide) / host.bounds.width func colour(_ x: Double, _ yFromTop: Double) -> NSColor? { bitmap.colorAt(x: Int(x * scale), y: Int(yFromTop * scale))?.usingColorSpace(.sRGB) } let visible = scroll.contentView.bounds // Column B's header strip, above where the editor would draw, against // column D's, which has no editor anywhere near it. let m = metrics(model) let b = m.frame(Coordinate(r: 1, c: 1)), d = m.frame(Coordinate(r: 1, c: 3)) let underB = try XCTUnwrap(colour(b.midX - visible.minX, 20)) let underD = try XCTUnwrap(colour(d.midX - visible.minX, 20)) XCTAssertEqual(underB.redComponent, underD.redComponent, accuracy: 0.03, "the editor drew over the pinned header") XCTAssertEqual(underB.blueComponent, underD.blueComponent, accuracy: 0.03, "the editor drew over the pinned header") } @MainActor func testTheLeastScrollThatShowsACell() { let visible = CGRect(x: 1000, y: 500, width: 600, height: 400) XCTAssertNil(SheetGridScroller.offset(showing: CGRect(x: 1100, y: 600, width: 100, height: 30), in: visible)) XCTAssertEqual(SheetGridScroller.offset(showing: CGRect(x: 3000, y: 600, width: 100, height: 30), in: visible), CGPoint(x: 2500, y: 500), "far right: its right edge at the view's, not the grid's last column") XCTAssertEqual(SheetGridScroller.offset(showing: CGRect(x: 200, y: 510, width: 100, height: 30), in: visible), CGPoint(x: 200, y: 478), "up and left: clear of the pinned column header") } } #endif #if os(macOS) /// Review #72 (58b4cb0), finding 4: scrolling crosses a window block every /// few rows or columns, and each crossing rebuilt every visible cell's body. final class GridScrollTests: XCTestCase { @MainActor func testScrollStepsStayCheap() async throws { let model = fixtureModel(SheetServerFixture(), rows: 1000, cols: 200) 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)") } } let host = NSHostingView(rootView: SheetGrid(model: model)) let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 1200, height: 800), styleMask: [.titled], backing: .buffered, defer: false) window.contentView = host; NSApp.setActivationPolicy(.regular); window.makeKeyAndOrderFront(nil); NSApp.activate() defer { window.orderOut(nil) } try await Task.sleep(for: .milliseconds(300)) func scrolls(_ v: NSView) -> [NSScrollView] { ((v as? NSScrollView).map { [$0] } ?? []) + v.subviews.flatMap(scrolls) } let scroll = try XCTUnwrap(scrolls(host).first) var report: [String] = [] for (name, dx, dy) in [("vertical", 0.0, 32.0), ("horizontal", 55.0, 0.0), ("diagonal", 55.0, 32.0)] { scroll.contentView.scroll(to: .zero); scroll.reflectScrolledClipView(scroll.contentView) try await Task.sleep(for: .milliseconds(200)) var steps: [Double] = [] for step in 1...120 { let start = ProcessInfo.processInfo.systemUptime scroll.contentView.scroll(to: NSPoint(x: dx * Double(step), y: dy * Double(step))) scroll.reflectScrolledClipView(scroll.contentView) host.layoutSubtreeIfNeeded(); window.displayIfNeeded() var spent = ProcessInfo.processInfo.systemUptime - start // The window update the scroll set off renders on the next turn. await Task.yield(); await Task.yield() let again = ProcessInfo.processInfo.systemUptime host.layoutSubtreeIfNeeded(); window.displayIfNeeded() spent += ProcessInfo.processInfo.systemUptime - again steps.append(spent * 1000) } let mean = steps.reduce(0, +) / Double(steps.count) let worst = steps.max() ?? 0 report.append("\(name) mean \(String(format: "%.1f", mean)) worst \(String(format: "%.0f", worst)) ms") // Was 113 / 117 / 154 ms worst at 58b4cb0 on this host; a busy // machine adds a little, so the bound is loose. XCTAssertLessThan(worst, 130, "\(name): a scroll step took \(worst) ms") } print("MEASURE scroll steps, 1000x200, 1200x800: " + report.joined(separator: "; ")) } } #endif