Sources/OrgEditorAppKit/Keys.swift

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