| 1 | #if os(macOS) |
| 2 | import AppKit |
| 3 | import SwiftUI |
| 4 | import XCTest |
| 5 | import RastrilloApple |
| 6 | @testable import SheetsKit |
| 7 | |
| 8 | final class SheetNativeInteractionTests: XCTestCase { |
| 9 | @MainActor func testTypingEntersCellAndFailedCommitIsMarkedNotBlocking() async throws { |
| 10 | let model = SheetModel(client: NativeHTTP(origin: URL(string: "http://127.0.0.1:1")!)) |
| 11 | model.page = SheetPage(Sheet: SheetSummary(ID: 1, Title: "Fixture", TabID: 1, TabName: "Sheet 1"), Rows: 4, Cols: 3, Truncated: false, MayWrite: true, MayComment: true, MayShare: false, FillSwatches: [], InkSwatches: [], NumberFormats: [], Warned: nil) |
| 12 | let host = NSHostingView(rootView: SheetGrid(model: model).background(Color.white).preferredColorScheme(.light)) |
| 13 | let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 640, height: 400), styleMask: [.titled], backing: .buffered, defer: false) |
| 14 | window.contentView = host |
| 15 | NSApp.setActivationPolicy(.regular) |
| 16 | window.makeKeyAndOrderFront(nil) |
| 17 | host.layoutSubtreeIfNeeded() |
| 18 | window.displayIfNeeded() |
| 19 | NSApp.activate() |
| 20 | defer { window.orderOut(nil) } |
| 21 | try await Task.sleep(for: .milliseconds(300)) |
| 22 | for type in [NSEvent.EventType.leftMouseDown, .leftMouseUp] { |
| 23 | let event = NSEvent.mouseEvent(with: type, location: NSPoint(x: 100, y: 350), modifierFlags: [], timestamp: 0, windowNumber: window.windowNumber, context: nil, eventNumber: 1, clickCount: 1, pressure: 1)! |
| 24 | window.sendEvent(event) |
| 25 | } |
| 26 | try await Task.sleep(for: .milliseconds(100)) |
| 27 | key("h", code: 4, window: window) |
| 28 | try await Task.sleep(for: .milliseconds(150)) |
| 29 | XCTAssertEqual(model.draft, "h") |
| 30 | XCTAssertTrue(window.firstResponder is NSTextView, "Typing must transfer focus into a native cell text field") |
| 31 | key("e", code: 14, window: window) |
| 32 | try await Task.sleep(for: .milliseconds(100)) |
| 33 | XCTAssertEqual(model.draft, "he", "The initial character must not be selected and overwritten") |
| 34 | if ProcessInfo.processInfo.environment["OFICINA_CAPTURE_FIXTURES"] == "1", |
| 35 | let bitmap = host.bitmapImageRepForCachingDisplay(in: host.bounds) { |
| 36 | host.cacheDisplay(in: host.bounds, to: bitmap) |
| 37 | try bitmap.representation(using: .png, properties: [:])?.write(to: URL(fileURLWithPath: "/tmp/oficina-sheets-grid-fixture.png")) |
| 38 | } |
| 39 | // The server is unreachable. Tab still commits at once and moves on; |
| 40 | // the failure marks A1 and blocks nothing. |
| 41 | key("\t", code: 48, window: window) |
| 42 | try await Task.sleep(for: .milliseconds(500)) |
| 43 | XCTAssertEqual(model.selection.start, Coordinate(r: 0, c: 1)) |
| 44 | XCTAssertEqual(model.displayCell(Coordinate(r: 0, c: 0))?.display, "he") |
| 45 | XCTAssertEqual(model.editState(Coordinate(r: 0, c: 0)), .failed) |
| 46 | XCTAssertFalse(model.dirty) |
| 47 | key("x", code: 7, window: window) |
| 48 | try await Task.sleep(for: .milliseconds(150)) |
| 49 | XCTAssertEqual(model.draft, "x", "a failed edit elsewhere must not stop typing") |
| 50 | XCTAssertTrue(window.firstResponder is NSTextView) |
| 51 | key("\u{1b}", code: 53, window: window) |
| 52 | try await Task.sleep(for: .milliseconds(100)) |
| 53 | XCTAssertFalse(model.dirty) |
| 54 | XCTAssertEqual(model.selection.start, Coordinate(r: 0, c: 1)) |
| 55 | model.revertWrites() |
| 56 | XCTAssertFalse(model.hasUnconfirmedChanges) |
| 57 | // Column B header then row 2 header select complete ranges. |
| 58 | click(NSPoint(x: 200, y: 375), window: window) |
| 59 | try await Task.sleep(for: .milliseconds(100)) |
| 60 | XCTAssertEqual(model.selection.start, Coordinate(r: 0, c: 1)) |
| 61 | XCTAssertEqual(model.selection.end, Coordinate(r: 3, c: 1)) |
| 62 | click(NSPoint(x: 24, y: 320), window: window) |
| 63 | try await Task.sleep(for: .milliseconds(100)) |
| 64 | XCTAssertEqual(model.selection.start, Coordinate(r: 1, c: 0)) |
| 65 | XCTAssertEqual(model.selection.end, Coordinate(r: 1, c: 2)) |
| 66 | } |
| 67 | @MainActor func testRapidTypingDuringFocusTransfer() async throws { |
| 68 | for delay in [0, 1, 5, 10, 25, 50] { |
| 69 | let model = SheetModel(client: NativeHTTP(origin: URL(string: "http://127.0.0.1:1")!)) |
| 70 | model.page = SheetPage(Sheet: SheetSummary(ID: 1, Title: "Fixture", TabID: 1, TabName: "Sheet 1"), Rows: 4, Cols: 3, Truncated: false, MayWrite: true, MayComment: true, MayShare: false, FillSwatches: [], InkSwatches: [], NumberFormats: [], Warned: nil) |
| 71 | let host = NSHostingView(rootView: SheetGrid(model: model)) |
| 72 | let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 640, height: 400), styleMask: [.titled], backing: .buffered, defer: false) |
| 73 | window.contentView = host; NSApp.setActivationPolicy(.regular); window.makeKeyAndOrderFront(nil); NSApp.activate() |
| 74 | defer { window.orderOut(nil) } |
| 75 | try await Task.sleep(for: .milliseconds(200)) |
| 76 | click(NSPoint(x: 100, y: 350), window: window) |
| 77 | try await Task.sleep(for: .milliseconds(100)) |
| 78 | key("h", code: 4, window: window) |
| 79 | if delay > 0 { try await Task.sleep(for: .milliseconds(delay)) } |
| 80 | key("e", code: 14, window: window) |
| 81 | try await Task.sleep(for: .milliseconds(200)) |
| 82 | XCTAssertEqual(model.draft, "he", "Typing during focus handoff (\(delay)ms)") |
| 83 | } |
| 84 | } |
| 85 | func testResizePreviewUsesOriginalSizeAndServerBounds() { |
| 86 | var preview = SheetResizePreview(axis: "col", index: 0, original: 110) |
| 87 | preview.update(translation: 30) |
| 88 | XCTAssertEqual(preview.size, 140) |
| 89 | preview.update(translation: 40) |
| 90 | XCTAssertEqual(preview.size, 150) |
| 91 | preview.update(translation: -1000) |
| 92 | XCTAssertEqual(preview.size, 16) |
| 93 | preview.update(translation: 5000) |
| 94 | XCTAssertEqual(preview.size, 2000) |
| 95 | } |
| 96 | @MainActor func testDragResizeWaitsForReleaseAndRollsBackOnFailure() async throws { |
| 97 | for axis in ["col", "row"] { |
| 98 | for succeeds in [false, true] { |
| 99 | let server = try ResizeFixtureServer() |
| 100 | let origin = try await server.start() |
| 101 | defer { server.stop() } |
| 102 | let model = SheetModel(client: NativeHTTP(origin: succeeds ? origin : URL(string: "http://127.0.0.1:1")!)) |
| 103 | model.page = SheetPage(Sheet: SheetSummary(ID: 1, Title: "Fixture", TabID: 1, TabName: "Sheet 1"), Rows: 4, Cols: 3, Truncated: false, MayWrite: true, MayComment: true, MayShare: false, FillSwatches: [], InkSwatches: [], NumberFormats: [], Warned: nil) |
| 104 | let host = NSHostingView(rootView: SheetGrid(model: model)) |
| 105 | let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 640, height: 400), styleMask: [.titled], backing: .buffered, defer: false) |
| 106 | window.contentView = host; NSApp.setActivationPolicy(.regular); window.makeKeyAndOrderFront(nil); NSApp.activate() |
| 107 | defer { window.orderOut(nil) } |
| 108 | try await Task.sleep(for: .milliseconds(200)) |
| 109 | func handles(_ view: NSView) -> [SheetResizeHandle.Handle] { |
| 110 | (view as? SheetResizeHandle.Handle).map { [$0] } ?? view.subviews.flatMap(handles) |
| 111 | } |
| 112 | let handle = try XCTUnwrap(handles(host).first { $0.actions?.vertical == (axis == "row") }) |
| 113 | let start = handle.convert(NSPoint(x: handle.bounds.midX, y: handle.bounds.midY), to: nil) |
| 114 | let end = NSPoint(x: start.x + (axis == "col" ? 40 : 0), y: start.y - (axis == "row" ? 40 : 0)) |
| 115 | func send(_ type: NSEvent.EventType, _ point: NSPoint) { |
| 116 | window.sendEvent(NSEvent.mouseEvent(with: type, location: point, modifierFlags: [], timestamp: ProcessInfo.processInfo.systemUptime, windowNumber: window.windowNumber, context: nil, eventNumber: 1, clickCount: 1, pressure: 1)!) |
| 117 | } |
| 118 | // Cancel one drag first: no save, and geometry must return to its original position. |
| 119 | send(.leftMouseDown, start) |
| 120 | send(.leftMouseDragged, end) |
| 121 | try await Task.sleep(for: .milliseconds(100)) |
| 122 | let preview = handle.convert(NSPoint(x: handle.bounds.midX, y: handle.bounds.midY), to: nil) |
| 123 | XCTAssertEqual(axis == "col" ? preview.x - start.x : start.y - preview.y, 40, accuracy: 1) |
| 124 | handle.keyDown(with: NSEvent.keyEvent(with: .keyDown, location: .zero, modifierFlags: [], timestamp: 0, windowNumber: window.windowNumber, context: nil, characters: "\u{1b}", charactersIgnoringModifiers: "\u{1b}", isARepeat: false, keyCode: 53)!) |
| 125 | send(.leftMouseUp, end) |
| 126 | try await Task.sleep(for: .milliseconds(100)) |
| 127 | XCTAssertEqual(server.requests.count, 0) |
| 128 | XCTAssertEqual(handle.convert(NSPoint(x: handle.bounds.midX, y: handle.bounds.midY), to: nil), start) |
| 129 | send(.leftMouseDown, start) |
| 130 | try await Task.sleep(for: .milliseconds(50)) |
| 131 | for step in 1...5 { |
| 132 | send(.leftMouseDragged, NSPoint(x: start.x + (end.x - start.x) * Double(step) / 5, y: start.y + (end.y - start.y) * Double(step) / 5)) |
| 133 | try await Task.sleep(for: .milliseconds(30)) |
| 134 | } |
| 135 | try await Task.sleep(for: .milliseconds(150)) |
| 136 | XCTAssertFalse(model.busy) |
| 137 | XCTAssertEqual(server.requests.count, 0) |
| 138 | XCTAssertEqual(model.error, "", "Dragging must not send intermediate requests") |
| 139 | send(.leftMouseUp, end) |
| 140 | try await Task.sleep(for: .milliseconds(300)) |
| 141 | if succeeds { |
| 142 | XCTAssertEqual(model.error, "") |
| 143 | XCTAssertEqual(server.requests, [[axis: 0, "size": axis == "col" ? 150 : 72]]) |
| 144 | XCTAssertEqual(axis == "col" ? model.sizes.cols?["0"] : model.sizes.rows?["0"], axis == "col" ? 150 : 72) |
| 145 | } else { |
| 146 | XCTAssertFalse(model.error.isEmpty, "Releasing the \(axis) handle must attempt persistence") |
| 147 | XCTAssertNil(model.sizes.cols?["0"]) |
| 148 | XCTAssertNil(model.sizes.rows?["0"]) |
| 149 | XCTAssertEqual(handle.convert(NSPoint(x: handle.bounds.midX, y: handle.bounds.midY), to: nil), start) |
| 150 | } |
| 151 | XCTAssertFalse(model.busy) |
| 152 | } |
| 153 | } |
| 154 | } |
| 155 | @MainActor private func click(_ point: NSPoint, window: NSWindow) { |
| 156 | for type in [NSEvent.EventType.leftMouseDown, .leftMouseUp] { |
| 157 | let event = NSEvent.mouseEvent(with: type, location: point, modifierFlags: [], timestamp: 0, windowNumber: window.windowNumber, context: nil, eventNumber: 1, clickCount: 1, pressure: 1)! |
| 158 | window.sendEvent(event) |
| 159 | } |
| 160 | } |
| 161 | /// Through NSApp, as the system delivers it, so local monitors see it. |
| 162 | @MainActor private func key(_ text: String, code: UInt16, window: NSWindow) { |
| 163 | let event = NSEvent.keyEvent(with: .keyDown, location: .zero, modifierFlags: [], timestamp: 0, windowNumber: window.windowNumber, context: nil, characters: text, charactersIgnoringModifiers: text, isARepeat: false, keyCode: code)! |
| 164 | NSApp.sendEvent(event) |
| 165 | } |
| 166 | } |
| 167 | #endif |
| 168 | |