Sources/OrgEditorAppKit/Keys.swift

30f6716c5b85f009c8cee977f3e5e4e4b5df3d09
orgstar/Sources/OrgEditorAppKit/Keys.swift history · blame · raw

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