Sources/OrgEditorAppKit/Keys.swift

1d52ac3e828cb73639dc1c0cd5b6c9f0795b14a7
orgstar/Sources/OrgEditorAppKit/Keys.swift history · blame · raw

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