| 1 | #if os(macOS) |
| 2 | import AppKit |
| 3 | import SwiftUI |
| 4 | |
| 5 | /// The keystroke that starts a cell edit, delivered to the cell's own text |
| 6 | /// field rather than interpreted by the grid. |
| 7 | /// |
| 8 | /// Typing on a selected cell replaces it (Numbers, Excel, Google Sheets). The |
| 9 | /// grid is not a text view, so it cannot read a keystroke as text: a dead key |
| 10 | /// (´ then e makes é) arrives with no characters at all, and an input method |
| 11 | /// (Japanese, Chinese) composes only inside a text input client. So the grid |
| 12 | /// does not try. It holds the raw key events, opens the cell's field, and once |
| 13 | /// that field has keyboard focus replays them into its field editor, where the |
| 14 | /// system's text input machinery treats them as if they had been typed there. |
| 15 | /// Events that arrive while the field is still coming up are held in order. |
| 16 | @MainActor final class SheetTypeAhead { |
| 17 | private(set) var held: [NSEvent] = [] |
| 18 | /// True from the keystroke that opened the field until it has them all. |
| 19 | private(set) var awaitingField = false |
| 20 | private var deadline: TimeInterval = 0 |
| 21 | /// Keys that change the input mode, not the text (JIS 英数 and かな): they |
| 22 | /// arrive as key-downs with no characters, like a dead key, and are not one. |
| 23 | static let modeKeys: Set<UInt16> = [102, 104] |
| 24 | |
| 25 | /// Whether a key, pressed on a selected cell, should start replacing it. |
| 26 | /// Anything that is not text (arrows, Return, Tab, Escape, Delete, function |
| 27 | /// keys) or that is a shortcut (Command, Control) is left to the grid. |
| 28 | static func startsTyping(_ event: NSEvent) -> Bool { |
| 29 | guard event.type == .keyDown, event.modifierFlags.intersection([.command, .control]).isEmpty, |
| 30 | event.specialKey == nil, !modeKeys.contains(event.keyCode) |
| 31 | else { return false } |
| 32 | // A dead key has no characters yet; what it will compose is still text. |
| 33 | // With Option (US ´ is Option-E) the unmodified key still names a |
| 34 | // character; a layout's own dead key (Spanish ´, German ^, French ^) may |
| 35 | // name none at all, and that empty key-down is a dead key too: modifier |
| 36 | // keys arrive as flagsChanged, and every other non-text key is special. |
| 37 | let text = (event.characters ?? "").isEmpty ? event.charactersIgnoringModifiers ?? "" : event.characters ?? "" |
| 38 | guard let scalar = text.unicodeScalars.first else { return true } |
| 39 | return !CharacterSet.controlCharacters.contains(scalar) |
| 40 | } |
| 41 | |
| 42 | private var generation = 0 |
| 43 | /// `expired` runs if the field has not come a second later; the grid then |
| 44 | /// hands what was typed to the formula bar rather than drop it. |
| 45 | func begin(with event: NSEvent, timeout: TimeInterval = 1, expired: @escaping () -> Void) { |
| 46 | held = [event] |
| 47 | awaitingField = true |
| 48 | deadline = ProcessInfo.processInfo.systemUptime + timeout |
| 49 | generation += 1 |
| 50 | let current = generation |
| 51 | DispatchQueue.main.asyncAfter(deadline: .now() + timeout) { [weak self] in |
| 52 | guard let self, self.awaitingField, self.generation == current else { return } |
| 53 | expired() |
| 54 | } |
| 55 | } |
| 56 | /// The text the held keys carry, for the formula bar if the field never |
| 57 | /// comes. A dead key's composition is lost there; its base letter is not. |
| 58 | var heldText: String { |
| 59 | held.compactMap(\.characters).joined().filter { !$0.unicodeScalars.contains { CharacterSet.controlCharacters.contains($0) } } |
| 60 | } |
| 61 | func hold(_ event: NSEvent) { held.append(event) } |
| 62 | /// A field that never came must not swallow keys. |
| 63 | var expired: Bool { awaitingField && ProcessInfo.processInfo.systemUptime > deadline } |
| 64 | func cancel() { |
| 65 | held = [] |
| 66 | awaitingField = false |
| 67 | } |
| 68 | |
| 69 | /// Called once the cell's field is first responder. The replay waits one |
| 70 | /// turn of the run loop so the window has switched its text input context to |
| 71 | /// the new field editor; anything typed meanwhile is still held, in order. |
| 72 | func fieldFocused(_ field: NSTextField) { |
| 73 | guard awaitingField else { return } |
| 74 | DispatchQueue.main.async { [weak self, weak field] in |
| 75 | guard let self, let field else { return } |
| 76 | self.replay(into: field) |
| 77 | } |
| 78 | } |
| 79 | func replay(into field: NSTextField) { |
| 80 | let events = held |
| 81 | held = [] |
| 82 | awaitingField = false |
| 83 | // Typing replaces the cell, but only once text (or an input method's |
| 84 | // marked text) actually arrives: the keys go in over the whole contents, |
| 85 | // selected, and a key that turns out to type nothing leaves the cell as |
| 86 | // it was, so a click away commits nothing. |
| 87 | field.currentEditor()?.selectAll(nil) |
| 88 | for (index, event) in events.enumerated() { |
| 89 | guard let editor = field.currentEditor() else { |
| 90 | // Return or Tab ended this edit; what followed starts the next one. |
| 91 | for later in events[index...].reversed() { NSApp.postEvent(later, atStart: true) } |
| 92 | return |
| 93 | } |
| 94 | editor.keyDown(with: event) |
| 95 | } |
| 96 | } |
| 97 | } |
| 98 | |
| 99 | /// Watches the window's key events for the grid, ahead of SwiftUI, so the |
| 100 | /// first keystroke reaches `SheetTypeAhead` whole (with its key code and |
| 101 | /// modifiers) instead of as characters a dead key does not have yet. |
| 102 | struct SheetKeyMonitor: NSViewRepresentable { |
| 103 | /// Returns true when the event was taken. |
| 104 | let handle: @MainActor (NSEvent) -> Bool |
| 105 | func makeNSView(context: Context) -> MonitorView { |
| 106 | let view = MonitorView() |
| 107 | view.handle = handle |
| 108 | return view |
| 109 | } |
| 110 | func updateNSView(_ view: MonitorView, context: Context) { view.handle = handle } |
| 111 | static func dismantleNSView(_ view: MonitorView, coordinator: ()) { view.stop() } |
| 112 | |
| 113 | @MainActor final class MonitorView: NSView { |
| 114 | var handle: (@MainActor (NSEvent) -> Bool)? |
| 115 | private var monitor: Any? |
| 116 | override func viewDidMoveToWindow() { |
| 117 | super.viewDidMoveToWindow() |
| 118 | stop() |
| 119 | guard window != nil else { return } |
| 120 | monitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { [weak self] incoming in |
| 121 | // Local monitors run on the main thread, inside sendEvent. |
| 122 | nonisolated(unsafe) let event = incoming |
| 123 | let taken = MainActor.assumeIsolated { () -> Bool in |
| 124 | guard let self, let window = self.window, event.window === window, |
| 125 | let handle = self.handle |
| 126 | else { return false } |
| 127 | return handle(event) |
| 128 | } |
| 129 | return taken ? nil : event |
| 130 | } |
| 131 | } |
| 132 | func stop() { |
| 133 | if let monitor { NSEvent.removeMonitor(monitor) } |
| 134 | monitor = nil |
| 135 | } |
| 136 | } |
| 137 | } |
| 138 | #endif |
| 139 | |