Sources/OrgEditorAppKit/Keys.swift

172 lines · 7235 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    var lineNumbersType = LineNumbersType.absolute {
 58        didSet { if lineNumbersType != oldValue { needsDisplay = true } }
 59    }
 60
 61    override func drawBackground(in rect: NSRect) {
 62        super.drawBackground(in: rect)
 63        drawLineNumbers(in: rect)
 64    }
 65
 66    /// Redraws the line number margin, as when the caret changes line.
 67    func redrawLineNumbers() {
 68        guard showsLineNumbers else { return }
 69        setNeedsDisplay(NSRect(x: 0, y: visibleRect.minY, width: textContainerInset.width, height: visibleRect.height))
 70    }
 71    /// Draw the caret as a block over the next character, for normal and visual states.
 72    var blockCursor = false {
 73        didSet {
 74            guard blockCursor != oldValue else { return }
 75            needsDisplay = true
 76        }
 77    }
 78
 79    override func drawInsertionPoint(in rect: NSRect, color: NSColor, turnedOn flag: Bool) {
 80        guard blockCursor else { return super.drawInsertionPoint(in: rect, color: color, turnedOn: flag) }
 81        var block = rect
 82        block.size.width = max(rect.width, blockWidth)
 83        if flag {
 84            color.withAlphaComponent(0.45).setFill()
 85            block.fill(using: .sourceOver)
 86        } else {
 87            setNeedsDisplay(block, avoidAdditionalLayout: true)
 88        }
 89    }
 90
 91    override func setNeedsDisplay(_ rect: NSRect, avoidAdditionalLayout flag: Bool) {
 92        var widened = rect
 93        if blockCursor { widened.size.width += blockWidth }
 94        super.setNeedsDisplay(widened, avoidAdditionalLayout: flag)
 95    }
 96
 97    private var blockWidth: CGFloat {
 98        let font = self.font ?? NSFont.monospacedSystemFont(ofSize: 13, weight: .regular)
 99        return ("x" as NSString).size(withAttributes: [.font: font]).width
100    }
101
102    override func keyDown(with event: NSEvent) {
103        if !hasMarkedText(), keyHandler?(event) == true { return }
104        super.keyDown(with: event)
105    }
106
107    override func performKeyEquivalent(with event: NSEvent) -> Bool {
108        if window?.firstResponder === self, !hasMarkedText(), event.modifierFlags.contains(.command), keyHandler?(event) == true {
109            return true
110        }
111        return super.performKeyEquivalent(with: event)
112    }
113
114    /// ⌘-click: given the clicked offset, true when it followed a link.
115    var onCommandClick: ((Int) -> Bool)?
116
117    /// A plain single click: given the clicked offset, true when it was handled.
118    var onClick: ((Int) -> Bool)?
119
120    override func mouseDown(with event: NSEvent) {
121        if event.modifierFlags.contains(.command), let onCommandClick {
122            let offset = characterIndexForInsertion(at: convert(event.locationInWindow, from: nil))
123            if onCommandClick(offset) { return }
124        }
125        onMouseDown?()
126        if event.modifierFlags.intersection([.command, .shift, .option, .control]).isEmpty, event.clickCount == 1,
127           onClick?(characterIndexForInsertion(at: convert(event.locationInWindow, from: nil))) == true {
128            return
129        }
130        super.mouseDown(with: event)
131    }
132}
133
134enum KeyEvents {
135    /// Device-dependent bits for the left and right Option keys (`NX_DEVICELALTKEYMASK`,
136    /// `NX_DEVICERALTKEYMASK`).
137    static let leftOption: UInt = 0x20
138    static let rightOption: UInt = 0x40
139
140    static let named: [UInt16: String] = [
141        48: "TAB", 36: "RET", 76: "RET", 49: "SPC", 53: "ESC", 51: "DEL", 117: "<delete>",
142        123: "<left>", 124: "<right>", 125: "<down>", 126: "<up>",
143        115: "<home>", 119: "<end>", 116: "<prior>", 121: "<next>",
144        122: "<f1>", 120: "<f2>", 99: "<f3>", 118: "<f4>", 96: "<f5>", 97: "<f6>",
145        98: "<f7>", 100: "<f8>", 101: "<f9>", 109: "<f10>", 103: "<f11>", 111: "<f12>",
146    ]
147
148    /// The chord for a key press, or nil when it types a character with Option.
149    static func chord(for event: NSEvent, optionAsMeta: OptionAsMeta) -> KeyChord? {
150        guard event.type == .keyDown else { return nil }
151        let flags = event.modifierFlags
152        var modifiers: KeyChord.Modifiers = []
153        if flags.contains(.control) { modifiers.insert(.control) }
154        if flags.contains(.command) { modifiers.insert(.command) }
155        if flags.contains(.option) {
156            let raw = flags.rawValue
157            let meta = (raw & leftOption != 0 && optionAsMeta.contains(.left)) || (raw & rightOption != 0 && optionAsMeta.contains(.right))
158            if meta || !modifiers.isEmpty {
159                modifiers.insert(.meta)
160            } else {
161                return nil
162            }
163        }
164        if let name = named[event.keyCode] {
165            if flags.contains(.shift) { modifiers.insert(.shift) }
166            return KeyChord(name, modifiers)
167        }
168        guard let characters = event.charactersIgnoringModifiers, characters.count == 1 else { return nil }
169        return KeyChord(characters, modifiers)
170    }
171}
172#endif