Sources/OrgEditorAppKit/Keys.swift
191 lines · 7927 bytes
1#if os(macOS)
2import AppKit
3import OrgCore
4
5/// Which Option keys act as Meta. The others type characters, as usual on a Mac.
6public struct OptionAsMeta: OptionSet, Sendable {
7 public let rawValue: Int
8 public init(rawValue: Int) { self.rawValue = rawValue }
9 public static let left = OptionAsMeta(rawValue: 1)
10 public static let right = OptionAsMeta(rawValue: 2)
11}
12
13/// A text view that offers key presses to the editor's keymap before the text system.
14final class OrgTextView: NSTextView {
15 /// Returns true when the key was handled.
16 var keyHandler: ((NSEvent) -> Bool)?
17 /// The text as shown, for accessibility.
18 var accessibleText: (() -> AccessibleText)?
19 var onMouseDown: (() -> Void)?
20 /// Files and an image pasted or dropped; each returns whether it took them.
21 var onFiles: (([URL]) -> Bool)?
22 var onImage: ((Data, String) -> Bool)?
23 /// The view gained or lost focus, or its window key status: the selection's color changes.
24 var onFocusChange: (() -> Void)?
25 private var keyObservers: [NSObjectProtocol] = []
26
27 override func becomeFirstResponder() -> Bool {
28 defer { onFocusChange?() }
29 return super.becomeFirstResponder()
30 }
31
32 override func resignFirstResponder() -> Bool {
33 defer { onFocusChange?() }
34 return super.resignFirstResponder()
35 }
36
37 override func viewDidMoveToWindow() {
38 super.viewDidMoveToWindow()
39 keyObservers.forEach(NotificationCenter.default.removeObserver)
40 keyObservers = [NSWindow.didBecomeKeyNotification, NSWindow.didResignKeyNotification].map { name in
41 NotificationCenter.default.addObserver(forName: name, object: window, queue: .main) { [weak self] _ in
42 MainActor.assumeIsolated { self?.onFocusChange?() }
43 }
44 }
45 }
46 /// The editor's undo history, shared by its views, not the window's.
47 var sharedUndoManager = UndoManager()
48 override var undoManager: UndoManager? { sharedUndoManager }
49 var lineNumberFont = NSFont.monospacedDigitSystemFont(ofSize: 11, weight: .regular)
50 var lineNumberColor = NSColor.tertiaryLabelColor
51 var currentLineNumberColor = NSColor.labelColor
52 /// Line starts, kept by the editor, for the line numbers.
53 var lineIndex: LineIndex?
54 var showsLineNumbers = false {
55 didSet { if showsLineNumbers != oldValue { updateGutter() } }
56 }
57 /// The widest the text container gets, centred in the view; 0 for the view's width.
58 var textWidth: CGFloat = 0 {
59 didSet { if textWidth != oldValue { updateGutter() } }
60 }
61
62 /// The view has another width; during a live resize, called once at its end.
63 var onWidthChange: (() -> Void)?
64
65 override func setFrameSize(_ newSize: NSSize) {
66 let widthChanged = newSize.width != frame.width
67 super.setFrameSize(newSize)
68 if widthChanged, textWidth > 0 { updateGutter() }
69 if widthChanged, !inLiveResize { onWidthChange?() }
70 }
71
72 override func viewDidEndLiveResize() {
73 super.viewDidEndLiveResize()
74 onWidthChange?()
75 }
76 var lineNumbersType = LineNumbersType.absolute {
77 didSet { if lineNumbersType != oldValue { needsDisplay = true } }
78 }
79
80 override func drawBackground(in rect: NSRect) {
81 super.drawBackground(in: rect)
82 drawLineNumbers(in: rect)
83 }
84
85 /// Redraws the line number margin, as when the caret changes line.
86 func redrawLineNumbers() {
87 guard showsLineNumbers else { return }
88 setNeedsDisplay(NSRect(x: 0, y: visibleRect.minY, width: textContainerInset.width, height: visibleRect.height))
89 }
90 /// Draw the caret as a block over the next character, for normal and visual states.
91 var blockCursor = false {
92 didSet {
93 guard blockCursor != oldValue else { return }
94 needsDisplay = true
95 }
96 }
97
98 override func drawInsertionPoint(in rect: NSRect, color: NSColor, turnedOn flag: Bool) {
99 guard blockCursor else { return super.drawInsertionPoint(in: rect, color: color, turnedOn: flag) }
100 var block = rect
101 block.size.width = max(rect.width, blockWidth)
102 if flag {
103 color.withAlphaComponent(0.45).setFill()
104 block.fill(using: .sourceOver)
105 } else {
106 setNeedsDisplay(block, avoidAdditionalLayout: true)
107 }
108 }
109
110 override func setNeedsDisplay(_ rect: NSRect, avoidAdditionalLayout flag: Bool) {
111 var widened = rect
112 if blockCursor { widened.size.width += blockWidth }
113 super.setNeedsDisplay(widened, avoidAdditionalLayout: flag)
114 }
115
116 private var blockWidth: CGFloat {
117 let font = self.font ?? NSFont.monospacedSystemFont(ofSize: 13, weight: .regular)
118 return ("x" as NSString).size(withAttributes: [.font: font]).width
119 }
120
121 override func keyDown(with event: NSEvent) {
122 if !hasMarkedText(), keyHandler?(event) == true { return }
123 super.keyDown(with: event)
124 }
125
126 override func performKeyEquivalent(with event: NSEvent) -> Bool {
127 if window?.firstResponder === self, !hasMarkedText(), event.modifierFlags.contains(.command), keyHandler?(event) == true {
128 return true
129 }
130 return super.performKeyEquivalent(with: event)
131 }
132
133 /// ⌘-click: given the clicked offset, true when it followed a link.
134 var onCommandClick: ((Int) -> Bool)?
135
136 /// A plain single click: given the clicked offset, true when it was handled.
137 var onClick: ((Int) -> Bool)?
138
139 override func mouseDown(with event: NSEvent) {
140 if event.modifierFlags.contains(.command), let onCommandClick {
141 let offset = characterIndexForInsertion(at: convert(event.locationInWindow, from: nil))
142 if onCommandClick(offset) { return }
143 }
144 onMouseDown?()
145 if event.modifierFlags.intersection([.command, .shift, .option, .control]).isEmpty, event.clickCount == 1,
146 onClick?(characterIndexForInsertion(at: convert(event.locationInWindow, from: nil))) == true {
147 return
148 }
149 super.mouseDown(with: event)
150 }
151}
152
153enum KeyEvents {
154 /// Device-dependent bits for the left and right Option keys (`NX_DEVICELALTKEYMASK`,
155 /// `NX_DEVICERALTKEYMASK`).
156 static let leftOption: UInt = 0x20
157 static let rightOption: UInt = 0x40
158
159 static let named: [UInt16: String] = [
160 48: "TAB", 36: "RET", 76: "RET", 49: "SPC", 53: "ESC", 51: "DEL", 117: "<delete>",
161 123: "<left>", 124: "<right>", 125: "<down>", 126: "<up>",
162 115: "<home>", 119: "<end>", 116: "<prior>", 121: "<next>",
163 122: "<f1>", 120: "<f2>", 99: "<f3>", 118: "<f4>", 96: "<f5>", 97: "<f6>",
164 98: "<f7>", 100: "<f8>", 101: "<f9>", 109: "<f10>", 103: "<f11>", 111: "<f12>",
165 ]
166
167 /// The chord for a key press, or nil when it types a character with Option.
168 static func chord(for event: NSEvent, optionAsMeta: OptionAsMeta) -> KeyChord? {
169 guard event.type == .keyDown else { return nil }
170 let flags = event.modifierFlags
171 var modifiers: KeyChord.Modifiers = []
172 if flags.contains(.control) { modifiers.insert(.control) }
173 if flags.contains(.command) { modifiers.insert(.command) }
174 if flags.contains(.option) {
175 let raw = flags.rawValue
176 let meta = (raw & leftOption != 0 && optionAsMeta.contains(.left)) || (raw & rightOption != 0 && optionAsMeta.contains(.right))
177 if meta || !modifiers.isEmpty {
178 modifiers.insert(.meta)
179 } else {
180 return nil
181 }
182 }
183 if let name = named[event.keyCode] {
184 if flags.contains(.shift) { modifiers.insert(.shift) }
185 return KeyChord(name, modifiers)
186 }
187 guard let characters = event.charactersIgnoringModifiers, characters.count == 1 else { return nil }
188 return KeyChord(characters, modifiers)
189 }
190}
191#endif