oficina / sheets Public

Clone
git clone https://amadan.net/oficina/sheets

Plain git — no account needed to clone.

Download

Download this file

1#if os(macOS)
2import AppKit
3import Carbon
4import SwiftUI
5import XCTest
6import RastrilloApple
7@testable import SheetsKit
8
9/// Paul, 2026-11-26: "the first character typed focusses the cell and doesn't
10/// actually type into it." Two causes: a save in flight disabled the field (so
11/// keys typed meanwhile reached no responder), and the grid read keys as
12/// characters, which a dead key or an input method does not produce.
13final class FirstKeystrokeTests: XCTestCase {
14 /// Records what reaches the cell's field editor. In `inputMethod` mode it
15 /// stands in for an input method: it takes the key without inserting it,
16 /// and the test then composes exactly as the system would.
17 final class RecordingFieldEditor: NSTextView {
18 var keys: [NSEvent] = []
19 var inputMethod = false
20 override func keyDown(with event: NSEvent) {
21 keys.append(event)
22 if !inputMethod { super.keyDown(with: event) }
23 }
24 }
25 @MainActor final class FieldEditorDelegate: NSObject, NSWindowDelegate {
26 let editor: RecordingFieldEditor = {
27 let editor = RecordingFieldEditor()
28 editor.isFieldEditor = true
29 return editor
30 }()
31 func windowWillReturnFieldEditor(_ sender: NSWindow, to client: Any?) -> Any? {
32 client is SheetCellEditor.CellTextField ? editor : nil
33 }
34 }
35
36 @MainActor private func host(_ model: SheetModel, delegate: NSWindowDelegate? = nil) async throws -> (NSWindow, NSView) {
37 let host = NSHostingView(rootView: SheetGrid(model: model))
38 let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 640, height: 400), styleMask: [.titled], backing: .buffered, defer: false)
39 window.delegate = delegate
40 window.contentView = host; NSApp.setActivationPolicy(.regular); window.makeKeyAndOrderFront(nil); NSApp.activate()
41 try await Task.sleep(for: .milliseconds(200))
42 // A2: below the header row and A1.
43 click(NSPoint(x: 100, y: 400 - 32 - 32 - 16), window: window)
44 try await Task.sleep(for: .milliseconds(100))
45 return (window, host)
46 }
47 @MainActor private func click(_ point: NSPoint, window: NSWindow, count: Int = 1) {
48 for type in [NSEvent.EventType.leftMouseDown, .leftMouseUp] {
49 window.sendEvent(NSEvent.mouseEvent(with: type, location: point, modifierFlags: [], timestamp: 0, windowNumber: window.windowNumber, context: nil, eventNumber: 1, clickCount: count, pressure: 1)!)
50 }
51 }
52 @MainActor private func key(_ text: String, ignoring: String? = nil, code: UInt16, modifiers: NSEvent.ModifierFlags = [], window: NSWindow) {
53 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)!)
54 }
55 @MainActor private func editors(_ view: NSView) -> [NSTextField] {
56 ((view as? SheetCellEditor.CellTextField).map { [$0] } ?? []) + view.subviews.flatMap(editors)
57 }
58
59 @MainActor func testTypingReplacesAndReturnKeeps() async throws {
60 let server = SheetServerFixture()
61 let model = fixtureModel(server)
62 let a2 = Coordinate(r: 1, c: 0)
63 model.cells[a2] = Cell(r: 1, c: 0, raw: "old", display: "old")
64 let (window, _) = try await host(model)
65 defer { window.orderOut(nil) }
66 XCTAssertEqual(model.selection.start, a2)
67 key("n", code: 45, window: window)
68 try await Task.sleep(for: .milliseconds(150))
69 XCTAssertEqual(model.draft, "n", "typing on a selected cell replaces it")
70 key("\u{1b}", code: 53, window: window)
71 try await Task.sleep(for: .milliseconds(100))
72 XCTAssertEqual(model.draft, "old")
73 // Return edits without replacing; so does F2.
74 key("\r", code: 36, window: window)
75 try await Task.sleep(for: .milliseconds(150))
76 XCTAssertTrue(window.firstResponder is NSTextView)
77 key("!", code: 18, modifiers: [.shift], window: window)
78 try await Task.sleep(for: .milliseconds(100))
79 XCTAssertEqual(model.draft, "old!")
80 key("\u{1b}", code: 53, window: window)
81 try await Task.sleep(for: .milliseconds(100))
82 let f2 = String(UnicodeScalar(UInt16(NSF2FunctionKey))!)
83 key(f2, code: 120, modifiers: [.function], window: window)
84 try await Task.sleep(for: .milliseconds(150))
85 XCTAssertTrue(window.firstResponder is NSTextView)
86 XCTAssertEqual(model.draft, "old")
87 }
88
89 /// A dead key has no characters; the grid used to drop it, so ´ then e
90 /// gave "e". Now the raw events reach the field editor in order, where the
91 /// system composes them; the composition then lands in the draft.
92 @MainActor func testDeadKeyReachesTheFieldAndComposes() async throws {
93 let delegate = FieldEditorDelegate()
94 let model = fixtureModel(SheetServerFixture())
95 let (window, _) = try await host(model, delegate: delegate)
96 defer { window.orderOut(nil) }
97 delegate.editor.inputMethod = true
98 // Option-E is ´ on a US layout: no characters until the next key.
99 key("", ignoring: "e", code: 14, modifiers: [.option], window: window)
100 key("e", code: 14, window: window)
101 try await Task.sleep(for: .milliseconds(200))
102 XCTAssertTrue(window.firstResponder === delegate.editor, "the cell's field must have focus")
103 XCTAssertEqual(delegate.editor.keys.map(\.keyCode), [14, 14], "both keys, in order, reach the text input")
104 XCTAssertEqual(delegate.editor.keys.first?.modifierFlags.contains(.option), true)
105 XCTAssertEqual(delegate.editor.keys.first?.characters, "", "the dead key arrives as a dead key")
106 // What the keyboard layout does with that pair:
107 delegate.editor.setMarkedText("´", selectedRange: NSRange(location: 1, length: 0), replacementRange: NSRange(location: NSNotFound, length: 0))
108 delegate.editor.insertText("é", replacementRange: NSRange(location: NSNotFound, length: 0))
109 try await Task.sleep(for: .milliseconds(50))
110 XCTAssertEqual(model.draft, "é")
111 }
112
113 /// An input method (Japanese) must see the first key too, or "ka" becomes
114 /// "kあ" instead of "か".
115 @MainActor func testInputMethodSeesTheFirstKey() async throws {
116 let delegate = FieldEditorDelegate()
117 let model = fixtureModel(SheetServerFixture())
118 let (window, _) = try await host(model, delegate: delegate)
119 defer { window.orderOut(nil) }
120 delegate.editor.inputMethod = true
121 key("k", code: 40, window: window)
122 key("a", code: 0, window: window)
123 try await Task.sleep(for: .milliseconds(200))
124 XCTAssertEqual(delegate.editor.keys.compactMap(\.characters), ["k", "a"])
125 XCTAssertEqual(model.draft, "", "nothing is inserted behind the input method's back")
126 let none = NSRange(location: NSNotFound, length: 0)
127 delegate.editor.setMarkedText("k", selectedRange: NSRange(location: 1, length: 0), replacementRange: none)
128 delegate.editor.setMarkedText("か", selectedRange: NSRange(location: 1, length: 0), replacementRange: none)
129 delegate.editor.insertText("か", replacementRange: none)
130 try await Task.sleep(for: .milliseconds(50))
131 XCTAssertEqual(model.draft, "か")
132 delegate.editor.inputMethod = false
133 key("\r", code: 36, window: window)
134 try await Task.sleep(for: .milliseconds(100))
135 XCTAssertEqual(model.displayCell(Coordinate(r: 1, c: 0))?.display, "か")
136 XCTAssertEqual(model.selection.start, Coordinate(r: 2, c: 0))
137 }
138
139 /// Typing straight on after Return, while the server has not answered.
140 /// The field used to be disabled for the save: grey, and the next key went
141 /// nowhere.
142 @MainActor func testTypingDuringASaveIsNotLost() async throws {
143 let server = SheetServerFixture()
144 server.hold()
145 let model = fixtureModel(server)
146 let (window, host) = try await host(model)
147 defer { window.orderOut(nil) }
148 key("h", code: 4, window: window)
149 try await Task.sleep(for: .milliseconds(100))
150 key("\r", code: 36, window: window)
151 key("x", code: 7, window: window)
152 key("y", code: 16, window: window)
153 try await Task.sleep(for: .milliseconds(200))
154 XCTAssertEqual(server.heldCount, 1, "the first save is still waiting for the server")
155 XCTAssertEqual(model.selection.start, Coordinate(r: 2, c: 0))
156 XCTAssertEqual(model.draft, "xy")
157 XCTAssertTrue(editors(host).allSatisfy(\.isEnabled), "no field greys while a save is in flight")
158 XCTAssertEqual(model.displayCell(Coordinate(r: 1, c: 0))?.display, "h")
159 server.release(stopHolding: true)
160 key("\r", code: 36, window: window)
161 await model.settle()
162 XCTAssertEqual(server.value(1, 0), "h")
163 XCTAssertEqual(server.value(2, 0), "xy")
164 }
165
166 /// Return to the cell looking committed (editor gone, value painted).
167 /// Before this change it was the server's round trip plus ~20 ms, grey
168 /// throughout (measured on main 26d271a: 172 ms median at 150 ms latency).
169 @MainActor func testReturnLooksCommittedWithinAFrame() async throws {
170 var samples: [Double] = []
171 for _ in 0..<5 {
172 let server = SheetServerFixture()
173 server.hold() // the server never answers during the measurement
174 let model = fixtureModel(server)
175 let (window, host) = try await host(model)
176 key("h", code: 4, window: window)
177 try await Task.sleep(for: .milliseconds(120))
178 let start = ProcessInfo.processInfo.systemUptime
179 key("\r", code: 36, window: window)
180 while ProcessInfo.processInfo.systemUptime - start < 2 {
181 host.layoutSubtreeIfNeeded(); window.displayIfNeeded()
182 if editors(host).isEmpty, model.displayCell(Coordinate(r: 1, c: 0))?.display == "h" { break }
183 try await Task.sleep(for: .milliseconds(1))
184 }
185 samples.append((ProcessInfo.processInfo.systemUptime - start) * 1000)
186 server.release(stopHolding: true)
187 window.orderOut(nil)
188 }
189 let median = samples.sorted()[samples.count / 2]
190 print("MEASURE return->committed with the server not answering: median \(String(format: "%.1f", median)) ms, all \(samples.map { String(format: "%.1f", $0) })")
191 XCTAssertLessThan(median, 50)
192 }
193
194 /// Review #72, finding 2: a selected cell scrolled out of the lazy grid
195 /// has no field. Typing must bring it into view and type into it, and
196 /// must never empty the draft for a field that does not exist (the next
197 /// click would commit that empty draft over the cell).
198 @MainActor func testTypingOnACellScrolledOutOfViewBringsItBack() async throws {
199 let server = SheetServerFixture()
200 let model = fixtureModel(server, rows: 120, cols: 4)
201 let far = Coordinate(r: 100, c: 0)
202 model.cells[far] = Cell(r: 100, c: 0, raw: "keep me", display: "keep me")
203 let (window, host) = try await host(model)
204 defer { window.orderOut(nil) }
205 model.select(far)
206 key("x", code: 7, window: window)
207 XCTAssertEqual(model.draft, "keep me", "the draft changes only once the cell's field has the keys")
208 try await Task.sleep(for: .milliseconds(400))
209 XCTAssertFalse(editors(host).isEmpty, "the cell was scrolled into view and opened")
210 XCTAssertEqual(model.draft, "x")
211 key("\r", code: 36, window: window)
212 await model.settle()
213 XCTAssertEqual(server.value(100, 0), "x")
214 }
215
216 /// Review #72, finding 4: a layout's own dead key (Spanish ´, German ^)
217 /// needs no Option and its key-down may carry no characters at all. The
218 /// layouts are read with UCKeyTranslate, not selected, so the machine's
219 /// keyboard is left alone: find each layout's unmodified dead keys, check
220 /// they compose, and check such a key-down starts typing whatever AppKit
221 /// puts in its character fields.
222 @MainActor func testLayoutDeadKeysWithoutOptionStartTyping() throws {
223 for id in ["com.apple.keylayout.Spanish-ISO", "com.apple.keylayout.German"] {
224 let filter = [kTISPropertyInputSourceID as String: id] as CFDictionary
225 guard let list = TISCreateInputSourceList(filter, true)?.takeRetainedValue() as? [TISInputSource],
226 let source = list.first,
227 let raw = TISGetInputSourceProperty(source, kTISPropertyUnicodeKeyLayoutData) else {
228 XCTFail("\(id) is not installed"); continue
229 }
230 let data = Unmanaged<CFData>.fromOpaque(raw).takeUnretainedValue() as Data
231 var deadKeys: [(UInt16, String)] = []
232 data.withUnsafeBytes { buffer in
233 let layout = buffer.bindMemory(to: UCKeyboardLayout.self).baseAddress!
234 func translate(_ code: UInt16, _ state: inout UInt32) -> String {
235 var chars = [UniChar](repeating: 0, count: 4); var length = 0
236 UCKeyTranslate(layout, code, UInt16(kUCKeyActionDown), 0, UInt32(LMGetKbdType()), 0, &state, 4, &length, &chars)
237 return String(utf16CodeUnits: chars, count: length)
238 }
239 for code in UInt16(0)..<UInt16(51) {
240 var state: UInt32 = 0
241 guard translate(code, &state).isEmpty, state != 0 else { continue }
242 deadKeys.append((code, translate(14, &state))) // then e
243 }
244 }
245 XCTAssertFalse(deadKeys.isEmpty, "\(id) has an unmodified dead key")
246 XCTAssertTrue(deadKeys.contains { ["é", "ê", "è"].contains($0.1) }, "\(id): a dead key then e composes (\(deadKeys))")
247 for (code, _) in deadKeys {
248 for ignoring in ["", "´", "^"] {
249 let event = NSEvent.keyEvent(with: .keyDown, location: .zero, modifierFlags: [], timestamp: 0, windowNumber: 0, context: nil, characters: "", charactersIgnoringModifiers: ignoring, isARepeat: false, keyCode: code)!
250 XCTAssertTrue(SheetTypeAhead.startsTyping(event), "\(id) dead key \(code) with ignoring \"\(ignoring)\"")
251 }
252 }
253 }
254 }
255
256 /// Review #72 delta, finding 6: on a wide sheet the first key took up to
257 /// 900 ms to reach the cell's field. First key to glyph (the key's text in
258 /// the cell's draft) must not grow with the sheet's width.
259 @MainActor func testFirstKeyReachesTheFieldWithinFramesOnWideSheets() async throws {
260 var report: [String] = []
261 for cols in [10, 60, 200] {
262 var samples: [Double] = []
263 // Six tries, the first a warm-up: a busy machine stalls one now and then.
264 for attempt in 0..<6 {
265 let model = fixtureModel(SheetServerFixture(), rows: 120, cols: cols)
266 let (window, _) = try await host(model)
267 let point = Coordinate(r: 1 + attempt, c: 1)
268 model.select(point)
269 try await Task.sleep(for: .milliseconds(150))
270 let start = ProcessInfo.processInfo.systemUptime
271 key("x", code: 7, window: window)
272 while model.draft != "x", ProcessInfo.processInfo.systemUptime - start < 3 {
273 try await Task.sleep(for: .milliseconds(1))
274 }
275 samples.append((ProcessInfo.processInfo.systemUptime - start) * 1000)
276 XCTAssertEqual(model.draft, "x", "\(cols) columns: the key never arrived")
277 window.orderOut(nil)
278 }
279 samples.removeFirst()
280 let median = samples.sorted()[samples.count / 2]
281 report.append("\(cols) cols: median \(String(format: "%.1f", median)) ms \(samples.map { String(format: "%.0f", $0) })")
282 XCTAssertLessThan(median, 50, "\(cols) columns: one or two frames, whatever the width")
283 }
284 print("MEASURE first key to glyph: " + report.joined(separator: "; "))
285 }
286
287 /// Review #72 delta, finding 1: no editor of the old sheet survives, or
288 /// opens during, a switch to another.
289 @MainActor func testNoEditorSurvivesASheetSwitch() async throws {
290 let server = SheetServerFixture()
291 server.holdPages()
292 let model = fixtureModel(server)
293 let (window, host) = try await host(model)
294 defer { window.orderOut(nil) }
295 key("x", code: 7, window: window)
296 try await Task.sleep(for: .milliseconds(150))
297 XCTAssertFalse(editors(host).isEmpty)
298 model.discard()
299 let opening = Task { await model.open(SheetSummary(ID: 2, Title: "", TabID: 0, TabName: "")) }
300 let loading = await eventually { server.requests.contains("GET /sheets/2") }
301 XCTAssertTrue(loading)
302 key("\u{1b}", code: 53, window: window)
303 try await Task.sleep(for: .milliseconds(100))
304 key("y", code: 16, window: window)
305 try await Task.sleep(for: .milliseconds(150))
306 XCTAssertTrue(editors(host).isEmpty, "no editor opens while the sheet is being replaced")
307 server.releasePages()
308 await opening.value
309 try await Task.sleep(for: .milliseconds(100))
310 XCTAssertEqual(model.page?.Sheet.ID, 2)
311 XCTAssertTrue(editors(host).isEmpty)
312 XCTAssertEqual(model.draft, "")
313 }
314
315 @MainActor func testAnOpenEditorClosesWhenTheSheetChanges() async throws {
316 let server = SheetServerFixture()
317 let model = fixtureModel(server)
318 let (window, host) = try await host(model)
319 defer { window.orderOut(nil) }
320 // A1, where the new sheet's selection starts too: only the page changes.
321 model.select(Coordinate(r: 0, c: 0))
322 key("x", code: 7, window: window)
323 try await Task.sleep(for: .milliseconds(150))
324 XCTAssertFalse(editors(host).isEmpty)
325 model.discard()
326 await model.open(SheetSummary(ID: 2, Title: "", TabID: 0, TabName: ""))
327 try await Task.sleep(for: .milliseconds(100))
328 XCTAssertTrue(editors(host).isEmpty, "a stray editor of the old sheet stayed open")
329 }
330
331 /// Review #72 delta, finding 5: an empty key-down that types nothing (or
332 /// an input-mode key) must not clear the cell.
333 @MainActor func testAKeyThatTypesNothingLeavesTheCellAlone() async throws {
334 let delegate = FieldEditorDelegate()
335 let server = SheetServerFixture()
336 let model = fixtureModel(server)
337 model.cells[Coordinate(r: 1, c: 0)] = Cell(r: 1, c: 0, raw: "keep", display: "keep")
338 let (window, host) = try await host(model, delegate: delegate)
339 defer { window.orderOut(nil) }
340 XCTAssertEqual(model.draft, "keep")
341 // JIS かな: an input-mode key, not text.
342 XCTAssertFalse(SheetTypeAhead.startsTyping(NSEvent.keyEvent(with: .keyDown, location: .zero, modifierFlags: [], timestamp: 0, windowNumber: 0, context: nil, characters: "", charactersIgnoringModifiers: "", isARepeat: false, keyCode: 104)!))
343 // An empty key-down the system then makes nothing of.
344 delegate.editor.inputMethod = true
345 key("", code: 10, window: window)
346 try await Task.sleep(for: .milliseconds(200))
347 XCTAssertFalse(editors(host).isEmpty, "a dead key opens the cell")
348 XCTAssertEqual(model.draft, "keep", "nothing typed, nothing replaced")
349 click(NSPoint(x: 260, y: 320), window: window)
350 try await Task.sleep(for: .milliseconds(100))
351 await model.settle()
352 XCTAssertTrue(server.batches.isEmpty, "a click away wrote the cell")
353 XCTAssertEqual(model.displayCell(Coordinate(r: 1, c: 0))?.display, "keep")
354 }
355
356 /// Held keys are never dropped: if the field does not come, what was typed
357 /// is handed on (to the formula bar) rather than discarded.
358 @MainActor func testHeldKeysAreHandedOnIfTheFieldNeverComes() async throws {
359 func event(_ text: String, _ code: UInt16) -> NSEvent {
360 NSEvent.keyEvent(with: .keyDown, location: .zero, modifierFlags: [], timestamp: 0, windowNumber: 0, context: nil, characters: text, charactersIgnoringModifiers: text, isARepeat: false, keyCode: code)!
361 }
362 let typeAhead = SheetTypeAhead()
363 var handedOn: String?
364 typeAhead.begin(with: event("x", 7), expired: { handedOn = typeAhead.heldText })
365 typeAhead.hold(event("y", 16))
366 typeAhead.hold(event("\r", 36))
367 try await Task.sleep(for: .milliseconds(1300))
368 XCTAssertEqual(handedOn, "xy", "the typed text, without the Return")
369 }
370
371 /// Review #72 delta 2, finding 2: when the next key (not the timer) finds
372 /// the field late, that key goes to the formula bar too.
373 @MainActor func testAKeyThatFindsTheFieldLateIsHandedOnToo() async throws {
374 let model = fixtureModel(SheetServerFixture())
375 var formulaBar = 0
376 let host = NSHostingView(rootView: SheetGrid(model: model, beginEditing: { formulaBar += 1 }, typeAheadTimeout: 0))
377 let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 640, height: 400), styleMask: [.titled], backing: .buffered, defer: false)
378 window.contentView = host; NSApp.setActivationPolicy(.regular); window.makeKeyAndOrderFront(nil); NSApp.activate()
379 defer { window.orderOut(nil) }
380 try await Task.sleep(for: .milliseconds(200))
381 click(NSPoint(x: 100, y: 400 - 32 - 32 - 16), window: window)
382 try await Task.sleep(for: .milliseconds(100))
383 // Both in one turn of the run loop: the second finds the deadline passed.
384 key("x", code: 7, window: window)
385 key("y", code: 16, window: window)
386 XCTAssertEqual(model.draft, "xy", "the late key was lost")
387 XCTAssertEqual(formulaBar, 1, "the edit carries on in the formula bar")
388 }
389
390 @MainActor func testWhichKeysStartTyping() {
391 func event(_ chars: String, _ ignoring: String, _ code: UInt16, _ flags: NSEvent.ModifierFlags = []) -> NSEvent {
392 NSEvent.keyEvent(with: .keyDown, location: .zero, modifierFlags: flags, timestamp: 0, windowNumber: 0, context: nil, characters: chars, charactersIgnoringModifiers: ignoring, isARepeat: false, keyCode: code)!
393 }
394 func fn(_ key: Int) -> String { String(UnicodeScalar(UInt16(key))!) }
395 XCTAssertTrue(SheetTypeAhead.startsTyping(event("a", "a", 0)))
396 XCTAssertTrue(SheetTypeAhead.startsTyping(event("=", "=", 24)))
397 XCTAssertTrue(SheetTypeAhead.startsTyping(event(" ", " ", 49)))
398 XCTAssertTrue(SheetTypeAhead.startsTyping(event("å", "a", 0, [.option])), "Option characters are text")
399 XCTAssertTrue(SheetTypeAhead.startsTyping(event("", "e", 14, [.option])), "a dead key starts a composition")
400 XCTAssertTrue(SheetTypeAhead.startsTyping(event("ü", "ü", 33)))
401 XCTAssertFalse(SheetTypeAhead.startsTyping(event("c", "c", 8, [.command])))
402 XCTAssertFalse(SheetTypeAhead.startsTyping(event("\u{3}", "c", 8, [.control])))
403 XCTAssertFalse(SheetTypeAhead.startsTyping(event("\r", "\r", 36)))
404 XCTAssertFalse(SheetTypeAhead.startsTyping(event("\t", "\t", 48)))
405 XCTAssertFalse(SheetTypeAhead.startsTyping(event("\u{1b}", "\u{1b}", 53)))
406 XCTAssertFalse(SheetTypeAhead.startsTyping(event("\u{7f}", "\u{7f}", 51)))
407 XCTAssertFalse(SheetTypeAhead.startsTyping(event(fn(NSUpArrowFunctionKey), fn(NSUpArrowFunctionKey), 126, [.function, .numericPad])))
408 XCTAssertFalse(SheetTypeAhead.startsTyping(event(fn(NSF2FunctionKey), fn(NSF2FunctionKey), 120, [.function])))
409 }
410}
411#endif
412