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