#if os(macOS) import AppKit import Carbon import SwiftUI import XCTest import RastrilloApple @testable import SheetsKit /// Paul, 2026-11-26: "the first character typed focusses the cell and doesn't /// actually type into it." Two causes: a save in flight disabled the field (so /// keys typed meanwhile reached no responder), and the grid read keys as /// characters, which a dead key or an input method does not produce. final class FirstKeystrokeTests: XCTestCase { /// Records what reaches the cell's field editor. In `inputMethod` mode it /// stands in for an input method: it takes the key without inserting it, /// and the test then composes exactly as the system would. final class RecordingFieldEditor: NSTextView { var keys: [NSEvent] = [] var inputMethod = false override func keyDown(with event: NSEvent) { keys.append(event) if !inputMethod { super.keyDown(with: event) } } } @MainActor final class FieldEditorDelegate: NSObject, NSWindowDelegate { let editor: RecordingFieldEditor = { let editor = RecordingFieldEditor() editor.isFieldEditor = true return editor }() func windowWillReturnFieldEditor(_ sender: NSWindow, to client: Any?) -> Any? { client is SheetCellEditor.CellTextField ? editor : nil } } @MainActor private func host(_ model: SheetModel, delegate: NSWindowDelegate? = nil) async throws -> (NSWindow, NSView) { 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.delegate = delegate window.contentView = host; NSApp.setActivationPolicy(.regular); window.makeKeyAndOrderFront(nil); NSApp.activate() try await Task.sleep(for: .milliseconds(200)) // A2: below the header row and A1. click(NSPoint(x: 100, y: 400 - 32 - 32 - 16), window: window) try await Task.sleep(for: .milliseconds(100)) return (window, host) } @MainActor private func click(_ point: NSPoint, window: NSWindow, count: Int = 1) { 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: count, pressure: 1)!) } } @MainActor private func key(_ text: String, ignoring: String? = nil, code: UInt16, modifiers: NSEvent.ModifierFlags = [], window: NSWindow) { NSApp.sendEvent(NSEvent.keyEvent(with: .keyDown, location: .zero, modifierFlags: modifiers, timestamp: ProcessInfo.processInfo.systemUptime, windowNumber: window.windowNumber, context: nil, characters: text, charactersIgnoringModifiers: ignoring ?? text, isARepeat: false, keyCode: code)!) } @MainActor private func editors(_ view: NSView) -> [NSTextField] { ((view as? SheetCellEditor.CellTextField).map { [$0] } ?? []) + view.subviews.flatMap(editors) } @MainActor func testTypingReplacesAndReturnKeeps() async throws { let server = SheetServerFixture() let model = fixtureModel(server) let a2 = Coordinate(r: 1, c: 0) model.cells[a2] = Cell(r: 1, c: 0, raw: "old", display: "old") let (window, _) = try await host(model) defer { window.orderOut(nil) } XCTAssertEqual(model.selection.start, a2) key("n", code: 45, window: window) try await Task.sleep(for: .milliseconds(150)) XCTAssertEqual(model.draft, "n", "typing on a selected cell replaces it") key("\u{1b}", code: 53, window: window) try await Task.sleep(for: .milliseconds(100)) XCTAssertEqual(model.draft, "old") // Return edits without replacing; so does F2. key("\r", code: 36, window: window) try await Task.sleep(for: .milliseconds(150)) XCTAssertTrue(window.firstResponder is NSTextView) key("!", code: 18, modifiers: [.shift], window: window) try await Task.sleep(for: .milliseconds(100)) XCTAssertEqual(model.draft, "old!") key("\u{1b}", code: 53, window: window) try await Task.sleep(for: .milliseconds(100)) let f2 = String(UnicodeScalar(UInt16(NSF2FunctionKey))!) key(f2, code: 120, modifiers: [.function], window: window) try await Task.sleep(for: .milliseconds(150)) XCTAssertTrue(window.firstResponder is NSTextView) XCTAssertEqual(model.draft, "old") } /// A dead key has no characters; the grid used to drop it, so ´ then e /// gave "e". Now the raw events reach the field editor in order, where the /// system composes them; the composition then lands in the draft. @MainActor func testDeadKeyReachesTheFieldAndComposes() async throws { let delegate = FieldEditorDelegate() let model = fixtureModel(SheetServerFixture()) let (window, _) = try await host(model, delegate: delegate) defer { window.orderOut(nil) } delegate.editor.inputMethod = true // Option-E is ´ on a US layout: no characters until the next key. key("", ignoring: "e", code: 14, modifiers: [.option], window: window) key("e", code: 14, window: window) try await Task.sleep(for: .milliseconds(200)) XCTAssertTrue(window.firstResponder === delegate.editor, "the cell's field must have focus") XCTAssertEqual(delegate.editor.keys.map(\.keyCode), [14, 14], "both keys, in order, reach the text input") XCTAssertEqual(delegate.editor.keys.first?.modifierFlags.contains(.option), true) XCTAssertEqual(delegate.editor.keys.first?.characters, "", "the dead key arrives as a dead key") // What the keyboard layout does with that pair: delegate.editor.setMarkedText("´", selectedRange: NSRange(location: 1, length: 0), replacementRange: NSRange(location: NSNotFound, length: 0)) delegate.editor.insertText("é", replacementRange: NSRange(location: NSNotFound, length: 0)) try await Task.sleep(for: .milliseconds(50)) XCTAssertEqual(model.draft, "é") } /// An input method (Japanese) must see the first key too, or "ka" becomes /// "kあ" instead of "か". @MainActor func testInputMethodSeesTheFirstKey() async throws { let delegate = FieldEditorDelegate() let model = fixtureModel(SheetServerFixture()) let (window, _) = try await host(model, delegate: delegate) defer { window.orderOut(nil) } delegate.editor.inputMethod = true key("k", code: 40, window: window) key("a", code: 0, window: window) try await Task.sleep(for: .milliseconds(200)) XCTAssertEqual(delegate.editor.keys.compactMap(\.characters), ["k", "a"]) XCTAssertEqual(model.draft, "", "nothing is inserted behind the input method's back") let none = NSRange(location: NSNotFound, length: 0) delegate.editor.setMarkedText("k", selectedRange: NSRange(location: 1, length: 0), replacementRange: none) delegate.editor.setMarkedText("か", selectedRange: NSRange(location: 1, length: 0), replacementRange: none) delegate.editor.insertText("か", replacementRange: none) try await Task.sleep(for: .milliseconds(50)) XCTAssertEqual(model.draft, "か") delegate.editor.inputMethod = false key("\r", code: 36, window: window) try await Task.sleep(for: .milliseconds(100)) XCTAssertEqual(model.displayCell(Coordinate(r: 1, c: 0))?.display, "か") XCTAssertEqual(model.selection.start, Coordinate(r: 2, c: 0)) } /// Typing straight on after Return, while the server has not answered. /// The field used to be disabled for the save: grey, and the next key went /// nowhere. @MainActor func testTypingDuringASaveIsNotLost() async throws { let server = SheetServerFixture() server.hold() let model = fixtureModel(server) let (window, host) = try await host(model) defer { window.orderOut(nil) } key("h", code: 4, window: window) try await Task.sleep(for: .milliseconds(100)) key("\r", code: 36, window: window) key("x", code: 7, window: window) key("y", code: 16, window: window) try await Task.sleep(for: .milliseconds(200)) XCTAssertEqual(server.heldCount, 1, "the first save is still waiting for the server") XCTAssertEqual(model.selection.start, Coordinate(r: 2, c: 0)) XCTAssertEqual(model.draft, "xy") XCTAssertTrue(editors(host).allSatisfy(\.isEnabled), "no field greys while a save is in flight") XCTAssertEqual(model.displayCell(Coordinate(r: 1, c: 0))?.display, "h") server.release(stopHolding: true) key("\r", code: 36, window: window) await model.settle() XCTAssertEqual(server.value(1, 0), "h") XCTAssertEqual(server.value(2, 0), "xy") } /// Return to the cell looking committed (editor gone, value painted). /// Before this change it was the server's round trip plus ~20 ms, grey /// throughout (measured on main 26d271a: 172 ms median at 150 ms latency). @MainActor func testReturnLooksCommittedWithinAFrame() async throws { var samples: [Double] = [] for _ in 0..<5 { let server = SheetServerFixture() server.hold() // the server never answers during the measurement let model = fixtureModel(server) let (window, host) = try await host(model) key("h", code: 4, window: window) try await Task.sleep(for: .milliseconds(120)) let start = ProcessInfo.processInfo.systemUptime key("\r", code: 36, window: window) while ProcessInfo.processInfo.systemUptime - start < 2 { host.layoutSubtreeIfNeeded(); window.displayIfNeeded() if editors(host).isEmpty, model.displayCell(Coordinate(r: 1, c: 0))?.display == "h" { break } try await Task.sleep(for: .milliseconds(1)) } samples.append((ProcessInfo.processInfo.systemUptime - start) * 1000) server.release(stopHolding: true) window.orderOut(nil) } let median = samples.sorted()[samples.count / 2] print("MEASURE return->committed with the server not answering: median \(String(format: "%.1f", median)) ms, all \(samples.map { String(format: "%.1f", $0) })") XCTAssertLessThan(median, 50) } /// Review #72, finding 2: a selected cell scrolled out of the lazy grid /// has no field. Typing must bring it into view and type into it, and /// must never empty the draft for a field that does not exist (the next /// click would commit that empty draft over the cell). @MainActor func testTypingOnACellScrolledOutOfViewBringsItBack() async throws { let server = SheetServerFixture() let model = fixtureModel(server, rows: 120, cols: 4) let far = Coordinate(r: 100, c: 0) model.cells[far] = Cell(r: 100, c: 0, raw: "keep me", display: "keep me") let (window, host) = try await host(model) defer { window.orderOut(nil) } model.select(far) key("x", code: 7, window: window) XCTAssertEqual(model.draft, "keep me", "the draft changes only once the cell's field has the keys") try await Task.sleep(for: .milliseconds(400)) XCTAssertFalse(editors(host).isEmpty, "the cell was scrolled into view and opened") XCTAssertEqual(model.draft, "x") key("\r", code: 36, window: window) await model.settle() XCTAssertEqual(server.value(100, 0), "x") } /// Review #72, finding 4: a layout's own dead key (Spanish ´, German ^) /// needs no Option and its key-down may carry no characters at all. The /// layouts are read with UCKeyTranslate, not selected, so the machine's /// keyboard is left alone: find each layout's unmodified dead keys, check /// they compose, and check such a key-down starts typing whatever AppKit /// puts in its character fields. @MainActor func testLayoutDeadKeysWithoutOptionStartTyping() throws { for id in ["com.apple.keylayout.Spanish-ISO", "com.apple.keylayout.German"] { let filter = [kTISPropertyInputSourceID as String: id] as CFDictionary guard let list = TISCreateInputSourceList(filter, true)?.takeRetainedValue() as? [TISInputSource], let source = list.first, let raw = TISGetInputSourceProperty(source, kTISPropertyUnicodeKeyLayoutData) else { XCTFail("\(id) is not installed"); continue } let data = Unmanaged.fromOpaque(raw).takeUnretainedValue() as Data var deadKeys: [(UInt16, String)] = [] data.withUnsafeBytes { buffer in let layout = buffer.bindMemory(to: UCKeyboardLayout.self).baseAddress! func translate(_ code: UInt16, _ state: inout UInt32) -> String { var chars = [UniChar](repeating: 0, count: 4); var length = 0 UCKeyTranslate(layout, code, UInt16(kUCKeyActionDown), 0, UInt32(LMGetKbdType()), 0, &state, 4, &length, &chars) return String(utf16CodeUnits: chars, count: length) } for code in UInt16(0).. NSEvent { NSEvent.keyEvent(with: .keyDown, location: .zero, modifierFlags: [], timestamp: 0, windowNumber: 0, context: nil, characters: text, charactersIgnoringModifiers: text, isARepeat: false, keyCode: code)! } let typeAhead = SheetTypeAhead() var handedOn: String? typeAhead.begin(with: event("x", 7), expired: { handedOn = typeAhead.heldText }) typeAhead.hold(event("y", 16)) typeAhead.hold(event("\r", 36)) try await Task.sleep(for: .milliseconds(1300)) XCTAssertEqual(handedOn, "xy", "the typed text, without the Return") } /// Review #72 delta 2, finding 2: when the next key (not the timer) finds /// the field late, that key goes to the formula bar too. @MainActor func testAKeyThatFindsTheFieldLateIsHandedOnToo() async throws { let model = fixtureModel(SheetServerFixture()) var formulaBar = 0 let host = NSHostingView(rootView: SheetGrid(model: model, beginEditing: { formulaBar += 1 }, typeAheadTimeout: 0)) 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() defer { window.orderOut(nil) } try await Task.sleep(for: .milliseconds(200)) click(NSPoint(x: 100, y: 400 - 32 - 32 - 16), window: window) try await Task.sleep(for: .milliseconds(100)) // Both in one turn of the run loop: the second finds the deadline passed. key("x", code: 7, window: window) key("y", code: 16, window: window) XCTAssertEqual(model.draft, "xy", "the late key was lost") XCTAssertEqual(formulaBar, 1, "the edit carries on in the formula bar") } @MainActor func testWhichKeysStartTyping() { func event(_ chars: String, _ ignoring: String, _ code: UInt16, _ flags: NSEvent.ModifierFlags = []) -> NSEvent { NSEvent.keyEvent(with: .keyDown, location: .zero, modifierFlags: flags, timestamp: 0, windowNumber: 0, context: nil, characters: chars, charactersIgnoringModifiers: ignoring, isARepeat: false, keyCode: code)! } func fn(_ key: Int) -> String { String(UnicodeScalar(UInt16(key))!) } XCTAssertTrue(SheetTypeAhead.startsTyping(event("a", "a", 0))) XCTAssertTrue(SheetTypeAhead.startsTyping(event("=", "=", 24))) XCTAssertTrue(SheetTypeAhead.startsTyping(event(" ", " ", 49))) XCTAssertTrue(SheetTypeAhead.startsTyping(event("å", "a", 0, [.option])), "Option characters are text") XCTAssertTrue(SheetTypeAhead.startsTyping(event("", "e", 14, [.option])), "a dead key starts a composition") XCTAssertTrue(SheetTypeAhead.startsTyping(event("ü", "ü", 33))) XCTAssertFalse(SheetTypeAhead.startsTyping(event("c", "c", 8, [.command]))) XCTAssertFalse(SheetTypeAhead.startsTyping(event("\u{3}", "c", 8, [.control]))) XCTAssertFalse(SheetTypeAhead.startsTyping(event("\r", "\r", 36))) XCTAssertFalse(SheetTypeAhead.startsTyping(event("\t", "\t", 48))) XCTAssertFalse(SheetTypeAhead.startsTyping(event("\u{1b}", "\u{1b}", 53))) XCTAssertFalse(SheetTypeAhead.startsTyping(event("\u{7f}", "\u{7f}", 51))) XCTAssertFalse(SheetTypeAhead.startsTyping(event(fn(NSUpArrowFunctionKey), fn(NSUpArrowFunctionKey), 126, [.function, .numericPad]))) XCTAssertFalse(SheetTypeAhead.startsTyping(event(fn(NSF2FunctionKey), fn(NSF2FunctionKey), 120, [.function]))) } } #endif