Sources/OrgEditorAppKit/Keys.swift
134 lines · 5542 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 var onMouseDown: (() -> Void)?
18 /// Each editor keeps its own undo history, not the window's.
19 private let ownUndoManager = UndoManager()
20 override var undoManager: UndoManager? { ownUndoManager }
21 var lineNumberFont = NSFont.monospacedDigitSystemFont(ofSize: 11, weight: .regular)
22 var lineNumberColor = NSColor.tertiaryLabelColor
23 var currentLineNumberColor = NSColor.labelColor
24 /// Line starts, kept by the editor, for the line numbers.
25 var lineIndex: LineIndex?
26 var showsLineNumbers = false {
27 didSet { if showsLineNumbers != oldValue { updateGutter() } }
28 }
29
30 override func drawBackground(in rect: NSRect) {
31 super.drawBackground(in: rect)
32 drawLineNumbers(in: rect)
33 }
34
35 /// Redraws the line number margin, as when the caret changes line.
36 func redrawLineNumbers() {
37 guard showsLineNumbers else { return }
38 setNeedsDisplay(NSRect(x: 0, y: visibleRect.minY, width: textContainerInset.width, height: visibleRect.height))
39 }
40 /// Draw the caret as a block over the next character, for normal and visual states.
41 var blockCursor = false {
42 didSet {
43 guard blockCursor != oldValue else { return }
44 needsDisplay = true
45 }
46 }
47
48 override func drawInsertionPoint(in rect: NSRect, color: NSColor, turnedOn flag: Bool) {
49 guard blockCursor else { return super.drawInsertionPoint(in: rect, color: color, turnedOn: flag) }
50 var block = rect
51 block.size.width = max(rect.width, blockWidth)
52 if flag {
53 color.withAlphaComponent(0.45).setFill()
54 block.fill(using: .sourceOver)
55 } else {
56 setNeedsDisplay(block, avoidAdditionalLayout: true)
57 }
58 }
59
60 override func setNeedsDisplay(_ rect: NSRect, avoidAdditionalLayout flag: Bool) {
61 var widened = rect
62 if blockCursor { widened.size.width += blockWidth }
63 super.setNeedsDisplay(widened, avoidAdditionalLayout: flag)
64 }
65
66 private var blockWidth: CGFloat {
67 let font = self.font ?? NSFont.monospacedSystemFont(ofSize: 13, weight: .regular)
68 return ("x" as NSString).size(withAttributes: [.font: font]).width
69 }
70
71 override func keyDown(with event: NSEvent) {
72 if !hasMarkedText(), keyHandler?(event) == true { return }
73 super.keyDown(with: event)
74 }
75
76 override func performKeyEquivalent(with event: NSEvent) -> Bool {
77 if window?.firstResponder === self, !hasMarkedText(), event.modifierFlags.contains(.command), keyHandler?(event) == true {
78 return true
79 }
80 return super.performKeyEquivalent(with: event)
81 }
82
83 /// ⌘-click: given the clicked offset, true when it followed a link.
84 var onCommandClick: ((Int) -> Bool)?
85
86 override func mouseDown(with event: NSEvent) {
87 if event.modifierFlags.contains(.command), let onCommandClick {
88 let offset = characterIndexForInsertion(at: convert(event.locationInWindow, from: nil))
89 if onCommandClick(offset) { return }
90 }
91 onMouseDown?()
92 super.mouseDown(with: event)
93 }
94}
95
96enum KeyEvents {
97 /// Device-dependent bits for the left and right Option keys (`NX_DEVICELALTKEYMASK`,
98 /// `NX_DEVICERALTKEYMASK`).
99 static let leftOption: UInt = 0x20
100 static let rightOption: UInt = 0x40
101
102 static let named: [UInt16: String] = [
103 48: "TAB", 36: "RET", 76: "RET", 49: "SPC", 53: "ESC", 51: "DEL", 117: "<delete>",
104 123: "<left>", 124: "<right>", 125: "<down>", 126: "<up>",
105 115: "<home>", 119: "<end>", 116: "<prior>", 121: "<next>",
106 122: "<f1>", 120: "<f2>", 99: "<f3>", 118: "<f4>", 96: "<f5>", 97: "<f6>",
107 98: "<f7>", 100: "<f8>", 101: "<f9>", 109: "<f10>", 103: "<f11>", 111: "<f12>",
108 ]
109
110 /// The chord for a key press, or nil when it types a character with Option.
111 static func chord(for event: NSEvent, optionAsMeta: OptionAsMeta) -> KeyChord? {
112 guard event.type == .keyDown else { return nil }
113 let flags = event.modifierFlags
114 var modifiers: KeyChord.Modifiers = []
115 if flags.contains(.control) { modifiers.insert(.control) }
116 if flags.contains(.command) { modifiers.insert(.command) }
117 if flags.contains(.option) {
118 let raw = flags.rawValue
119 let meta = (raw & leftOption != 0 && optionAsMeta.contains(.left)) || (raw & rightOption != 0 && optionAsMeta.contains(.right))
120 if meta || !modifiers.isEmpty {
121 modifiers.insert(.meta)
122 } else {
123 return nil
124 }
125 }
126 if let name = named[event.keyCode] {
127 if flags.contains(.shift) { modifiers.insert(.shift) }
128 return KeyChord(name, modifiers)
129 }
130 guard let characters = event.charactersIgnoringModifiers, characters.count == 1 else { return nil }
131 return KeyChord(characters, modifiers)
132 }
133}
134#endif