Sources/OrgEditorAppKit/Keys.swift

169 lines · 7075 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    /// The view gained or lost focus, or its window key status: the selection's color changes.
 21    var onFocusChange: (() -> Void)?
 22    private var keyObservers: [NSObjectProtocol] = []
 23
 24    override func becomeFirstResponder() -> Bool {
 25        defer { onFocusChange?() }
 26        return super.becomeFirstResponder()
 27    }
 28
 29    override func resignFirstResponder() -> Bool {
 30        defer { onFocusChange?() }
 31        return super.resignFirstResponder()
 32    }
 33
 34    override func viewDidMoveToWindow() {
 35        super.viewDidMoveToWindow()
 36        keyObservers.forEach(NotificationCenter.default.removeObserver)
 37        keyObservers = [NSWindow.didBecomeKeyNotification, NSWindow.didResignKeyNotification].map { name in
 38            NotificationCenter.default.addObserver(forName: name, object: window, queue: .main) { [weak self] _ in
 39                MainActor.assumeIsolated { self?.onFocusChange?() }
 40            }
 41        }
 42    }
 43    /// The editor's undo history, shared by its views, not the window's.
 44    var sharedUndoManager = UndoManager()
 45    override var undoManager: UndoManager? { sharedUndoManager }
 46    var lineNumberFont = NSFont.monospacedDigitSystemFont(ofSize: 11, weight: .regular)
 47    var lineNumberColor = NSColor.tertiaryLabelColor
 48    var currentLineNumberColor = NSColor.labelColor
 49    /// Line starts, kept by the editor, for the line numbers.
 50    var lineIndex: LineIndex?
 51    var showsLineNumbers = false {
 52        didSet { if showsLineNumbers != oldValue { updateGutter() } }
 53    }
 54    var lineNumbersType = LineNumbersType.absolute {
 55        didSet { if lineNumbersType != oldValue { needsDisplay = true } }
 56    }
 57
 58    override func drawBackground(in rect: NSRect) {
 59        super.drawBackground(in: rect)
 60        drawLineNumbers(in: rect)
 61    }
 62
 63    /// Redraws the line number margin, as when the caret changes line.
 64    func redrawLineNumbers() {
 65        guard showsLineNumbers else { return }
 66        setNeedsDisplay(NSRect(x: 0, y: visibleRect.minY, width: textContainerInset.width, height: visibleRect.height))
 67    }
 68    /// Draw the caret as a block over the next character, for normal and visual states.
 69    var blockCursor = false {
 70        didSet {
 71            guard blockCursor != oldValue else { return }
 72            needsDisplay = true
 73        }
 74    }
 75
 76    override func drawInsertionPoint(in rect: NSRect, color: NSColor, turnedOn flag: Bool) {
 77        guard blockCursor else { return super.drawInsertionPoint(in: rect, color: color, turnedOn: flag) }
 78        var block = rect
 79        block.size.width = max(rect.width, blockWidth)
 80        if flag {
 81            color.withAlphaComponent(0.45).setFill()
 82            block.fill(using: .sourceOver)
 83        } else {
 84            setNeedsDisplay(block, avoidAdditionalLayout: true)
 85        }
 86    }
 87
 88    override func setNeedsDisplay(_ rect: NSRect, avoidAdditionalLayout flag: Bool) {
 89        var widened = rect
 90        if blockCursor { widened.size.width += blockWidth }
 91        super.setNeedsDisplay(widened, avoidAdditionalLayout: flag)
 92    }
 93
 94    private var blockWidth: CGFloat {
 95        let font = self.font ?? NSFont.monospacedSystemFont(ofSize: 13, weight: .regular)
 96        return ("x" as NSString).size(withAttributes: [.font: font]).width
 97    }
 98
 99    override func keyDown(with event: NSEvent) {
100        if !hasMarkedText(), keyHandler?(event) == true { return }
101        super.keyDown(with: event)
102    }
103
104    override func performKeyEquivalent(with event: NSEvent) -> Bool {
105        if window?.firstResponder === self, !hasMarkedText(), event.modifierFlags.contains(.command), keyHandler?(event) == true {
106            return true
107        }
108        return super.performKeyEquivalent(with: event)
109    }
110
111    /// ⌘-click: given the clicked offset, true when it followed a link.
112    var onCommandClick: ((Int) -> Bool)?
113
114    /// A plain single click: given the clicked offset, true when it was handled.
115    var onClick: ((Int) -> Bool)?
116
117    override func mouseDown(with event: NSEvent) {
118        if event.modifierFlags.contains(.command), let onCommandClick {
119            let offset = characterIndexForInsertion(at: convert(event.locationInWindow, from: nil))
120            if onCommandClick(offset) { return }
121        }
122        onMouseDown?()
123        if event.modifierFlags.intersection([.command, .shift, .option, .control]).isEmpty, event.clickCount == 1,
124           onClick?(characterIndexForInsertion(at: convert(event.locationInWindow, from: nil))) == true {
125            return
126        }
127        super.mouseDown(with: event)
128    }
129}
130
131enum KeyEvents {
132    /// Device-dependent bits for the left and right Option keys (`NX_DEVICELALTKEYMASK`,
133    /// `NX_DEVICERALTKEYMASK`).
134    static let leftOption: UInt = 0x20
135    static let rightOption: UInt = 0x40
136
137    static let named: [UInt16: String] = [
138        48: "TAB", 36: "RET", 76: "RET", 49: "SPC", 53: "ESC", 51: "DEL", 117: "<delete>",
139        123: "<left>", 124: "<right>", 125: "<down>", 126: "<up>",
140        115: "<home>", 119: "<end>", 116: "<prior>", 121: "<next>",
141        122: "<f1>", 120: "<f2>", 99: "<f3>", 118: "<f4>", 96: "<f5>", 97: "<f6>",
142        98: "<f7>", 100: "<f8>", 101: "<f9>", 109: "<f10>", 103: "<f11>", 111: "<f12>",
143    ]
144
145    /// The chord for a key press, or nil when it types a character with Option.
146    static func chord(for event: NSEvent, optionAsMeta: OptionAsMeta) -> KeyChord? {
147        guard event.type == .keyDown else { return nil }
148        let flags = event.modifierFlags
149        var modifiers: KeyChord.Modifiers = []
150        if flags.contains(.control) { modifiers.insert(.control) }
151        if flags.contains(.command) { modifiers.insert(.command) }
152        if flags.contains(.option) {
153            let raw = flags.rawValue
154            let meta = (raw & leftOption != 0 && optionAsMeta.contains(.left)) || (raw & rightOption != 0 && optionAsMeta.contains(.right))
155            if meta || !modifiers.isEmpty {
156                modifiers.insert(.meta)
157            } else {
158                return nil
159            }
160        }
161        if let name = named[event.keyCode] {
162            if flags.contains(.shift) { modifiers.insert(.shift) }
163            return KeyChord(name, modifiers)
164        }
165        guard let characters = event.charactersIgnoringModifiers, characters.count == 1 else { return nil }
166        return KeyChord(characters, modifiers)
167    }
168}
169#endif