215 lines
8.1 KiB
Swift
215 lines
8.1 KiB
Swift
import AppKit
|
|
import SwiftUI
|
|
|
|
/// The keys the overlays react to, from a text field or a bare key catcher.
|
|
enum OverlayKey: Equatable {
|
|
case up, down, commandUp, commandDown, commandLeft, commandRight, enter, escape
|
|
case commandP
|
|
|
|
/// Maps the text system's commands back to the keys that produced them.
|
|
init?(selector: Selector) {
|
|
switch selector {
|
|
case #selector(NSResponder.moveUp(_:)): self = .up
|
|
case #selector(NSResponder.moveDown(_:)): self = .down
|
|
case #selector(NSResponder.moveToBeginningOfDocument(_:)): self = .commandUp
|
|
case #selector(NSResponder.moveToEndOfDocument(_:)): self = .commandDown
|
|
case #selector(NSResponder.moveToBeginningOfLine(_:)), #selector(NSResponder.moveToLeftEndOfLine(_:)): self = .commandLeft
|
|
case #selector(NSResponder.moveToEndOfLine(_:)), #selector(NSResponder.moveToRightEndOfLine(_:)): self = .commandRight
|
|
case #selector(NSResponder.insertNewline(_:)): self = .enter
|
|
case #selector(NSResponder.cancelOperation(_:)): self = .escape
|
|
default: return nil
|
|
}
|
|
}
|
|
|
|
/// Maps a raw key event, for overlays without a text field.
|
|
init?(event: NSEvent) {
|
|
let command = event.modifierFlags.contains(.command)
|
|
switch event.keyCode {
|
|
case 126: self = command ? .commandUp : .up
|
|
case 125: self = command ? .commandDown : .down
|
|
case 123 where command: self = .commandLeft
|
|
case 124 where command: self = .commandRight
|
|
case 36, 76: self = .enter
|
|
case 53: self = .escape
|
|
default:
|
|
guard command, event.charactersIgnoringModifiers?.lowercased() == "p" else { return nil }
|
|
self = .commandP
|
|
}
|
|
}
|
|
}
|
|
|
|
/// A borderless single-line field that hands navigation keys to the overlay before the text system sees them.
|
|
/// It fills the frame it is given and centres the text in it, so the whole box takes the I-beam and the click.
|
|
struct OverlayCommandField: NSViewRepresentable {
|
|
@Binding var text: String
|
|
var placeholder: String
|
|
var font: NSFont
|
|
/// nil selects the whole text on focus, so typing replaces a seeded query.
|
|
var initialSelection: NSRange?
|
|
/// Space between the box's edges and the text.
|
|
var horizontalInset: CGFloat = 0
|
|
var onKey: (OverlayKey) -> Bool
|
|
|
|
func makeCoordinator() -> Coordinator { Coordinator(self) }
|
|
|
|
func makeNSView(context: Context) -> CommandFieldBox {
|
|
let field = FocusingTextField()
|
|
field.isBordered = false
|
|
field.drawsBackground = false
|
|
field.focusRingType = .none
|
|
field.font = font
|
|
field.textColor = NSColor(hex: 0xF4F5F4)
|
|
field.placeholderAttributedString = NSAttributedString(
|
|
string: placeholder,
|
|
attributes: [.foregroundColor: NSColor(hex: 0x6C7783), .font: font]
|
|
)
|
|
field.stringValue = text
|
|
field.delegate = context.coordinator
|
|
field.cell?.isScrollable = true
|
|
field.cell?.wraps = false
|
|
field.initialSelection = initialSelection
|
|
return CommandFieldBox(field: field, inset: horizontalInset)
|
|
}
|
|
|
|
func updateNSView(_ box: CommandFieldBox, context: Context) {
|
|
context.coordinator.parent = self
|
|
if box.field.stringValue != text { box.field.stringValue = text }
|
|
}
|
|
|
|
func sizeThatFits(_ proposal: ProposedViewSize, nsView box: CommandFieldBox, context: Context) -> CGSize? {
|
|
let fieldHeight = box.field.intrinsicContentSize.height
|
|
let width = proposal.width.flatMap { $0.isFinite ? $0 : nil } ?? max(box.field.intrinsicContentSize.width, 0) + 2 * box.inset
|
|
let height = proposal.height.flatMap { $0.isFinite ? max($0, fieldHeight) : nil } ?? fieldHeight
|
|
return CGSize(width: width, height: height)
|
|
}
|
|
|
|
final class Coordinator: NSObject, NSTextFieldDelegate {
|
|
var parent: OverlayCommandField
|
|
|
|
init(_ parent: OverlayCommandField) {
|
|
self.parent = parent
|
|
}
|
|
|
|
func controlTextDidChange(_ note: Notification) {
|
|
guard let field = note.object as? NSTextField else { return }
|
|
parent.text = field.stringValue
|
|
}
|
|
|
|
func control(_ control: NSControl, textView: NSTextView, doCommandBy selector: Selector) -> Bool {
|
|
guard let key = OverlayKey(selector: selector) else { return false }
|
|
return parent.onKey(key)
|
|
}
|
|
}
|
|
}
|
|
|
|
/// The box around an `OverlayCommandField`: an I-beam over all of it, and a click anywhere focuses the field.
|
|
final class CommandFieldBox: NSView {
|
|
let field: NSTextField
|
|
let inset: CGFloat
|
|
|
|
init(field: NSTextField, inset: CGFloat) {
|
|
self.field = field
|
|
self.inset = inset
|
|
super.init(frame: .zero)
|
|
addSubview(field)
|
|
}
|
|
|
|
required init?(coder: NSCoder) {
|
|
fatalError("CommandFieldBox is built in code")
|
|
}
|
|
|
|
override func layout() {
|
|
super.layout()
|
|
let height = min(field.intrinsicContentSize.height, bounds.height)
|
|
field.frame = NSRect(x: inset, y: ((bounds.height - height) / 2).rounded(), width: max(0, bounds.width - 2 * inset), height: height)
|
|
}
|
|
|
|
override func resetCursorRects() {
|
|
addCursorRect(bounds, cursor: .iBeam)
|
|
}
|
|
|
|
override func mouseDown(with event: NSEvent) {
|
|
guard field.currentEditor() == nil else { return }
|
|
window?.makeFirstResponder(field)
|
|
}
|
|
}
|
|
|
|
/// An invisible first responder that forwards the overlay keys and swallows the ones it handles.
|
|
struct OverlayKeyCatcher: NSViewRepresentable {
|
|
var onKey: (OverlayKey) -> Bool
|
|
|
|
func makeNSView(context: Context) -> CatcherView {
|
|
let view = CatcherView()
|
|
view.onKey = onKey
|
|
return view
|
|
}
|
|
|
|
func updateNSView(_ view: CatcherView, context: Context) {
|
|
view.onKey = onKey
|
|
}
|
|
|
|
final class CatcherView: NSView {
|
|
var onKey: (OverlayKey) -> Bool = { _ in false }
|
|
|
|
override var acceptsFirstResponder: Bool { true }
|
|
|
|
override func viewDidMoveToWindow() {
|
|
super.viewDidMoveToWindow()
|
|
DispatchQueue.main.async { [weak self] in
|
|
guard let self, let window = self.window else { return }
|
|
window.makeFirstResponder(self)
|
|
}
|
|
}
|
|
|
|
override func keyDown(with event: NSEvent) {
|
|
if let key = OverlayKey(event: event), onKey(key) { return }
|
|
super.keyDown(with: event)
|
|
}
|
|
|
|
override func performKeyEquivalent(with event: NSEvent) -> Bool {
|
|
guard window?.firstResponder === self, let key = OverlayKey(event: event) else {
|
|
return super.performKeyEquivalent(with: event)
|
|
}
|
|
return onKey(key) || super.performKeyEquivalent(with: event)
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Takes focus once it is on screen and applies the initial selection.
|
|
private final class FocusingTextField: NSTextField {
|
|
var initialSelection: NSRange?
|
|
private var focused = false
|
|
|
|
override class var cellClass: AnyClass? {
|
|
get { PointerBoundFieldCell.self }
|
|
set {}
|
|
}
|
|
|
|
override func viewDidMoveToWindow() {
|
|
super.viewDidMoveToWindow()
|
|
guard !focused, window != nil else { return }
|
|
focused = true
|
|
DispatchQueue.main.async { [weak self] in
|
|
guard let self, let window = self.window, window.makeFirstResponder(self) else { return }
|
|
guard let editor = self.currentEditor() as? NSTextView else { return }
|
|
editor.insertionPointColor = NSColor(hex: 0xE8913A)
|
|
let length = (self.stringValue as NSString).length
|
|
editor.selectedRange = self.initialSelection.map { NSRange(location: min($0.location, length), length: min($0.length, length)) }
|
|
?? NSRange(location: 0, length: length)
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Edits through a PointerBoundTextView instead of the window's shared field editor, which sets the I-beam on every mouse move.
|
|
private final class PointerBoundFieldCell: NSTextFieldCell {
|
|
private lazy var editor: PointerBoundTextView = {
|
|
let editor = PointerBoundTextView()
|
|
editor.isFieldEditor = true
|
|
return editor
|
|
}()
|
|
|
|
override func fieldEditor(for controlView: NSView) -> NSTextView? {
|
|
editor
|
|
}
|
|
}
|