Sources/OrgEditorAppKit/Keys.swift

3959d9c38d34f2d30757a8c9c88309a5328522e5
orgstar/Sources/OrgEditorAppKit/Keys.swift history · blame · raw

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