Files
helder/Sources/HelderUI/Components/PointerPolicy.swift
T

245 lines
9.9 KiB
Swift

import AppKit
import SwiftUI
/// The two pointers the rule picks between. A view may add its own extra on top: ⌘'s pointing hand, a splitter's resize.
enum PointerShape: Equatable {
case iBeam
case arrow
var cursor: NSCursor { self == .iBeam ? .iBeam : .arrow }
}
/// Where a text-capable view lives: in a column, or in the open overlay.
enum PointerLayer: Equatable {
case workspace
case overlay
}
/// What the rule looks at for one point.
struct PointerState: Equatable {
var layer: PointerLayer
var overlayOpen: Bool
/// False for a disabled field, or a text view kept alive behind another pane.
var isEnabled: Bool
/// The point lies on the view's text area and no other view covers it.
var isOverText: Bool
/// A drag-selection that began in a text area is still held.
var isSelecting: Bool
}
/// The one pointer rule: the I-beam only where a single click places a caret or starts a text selection.
enum PointerPolicy {
static func shape(_ state: PointerState) -> PointerShape {
if state.isSelecting { return .iBeam }
guard state.isEnabled, state.isOverText else { return .arrow }
return state.overlayOpen && state.layer == .workspace ? .arrow : .iBeam
}
}
// MARK: - AppKit
/// A view that sets its own cursor when the pointer is re-read without a mouse move.
@MainActor
protocol PointerOwner: NSView {
func updatePointer(atWindowPoint point: NSPoint)
}
/// A view with selectable or editable text. It takes its pointer from `PointerPolicy` and never decides itself.
@MainActor
protocol PointerTextTarget: PointerOwner {
var pointerLayer: PointerLayer { get }
var acceptsPointerText: Bool { get }
func isPointerOverText(atWindowPoint point: NSPoint) -> Bool
}
extension PointerTextTarget {
func pointerShape(atWindowPoint point: NSPoint) -> PointerShape {
pointerShape(isOverText: isPointerOverText(atWindowPoint: point))
}
/// The rule's pointer when the caller already knows whether the point lies on the text.
func pointerShape(isOverText: Bool) -> PointerShape {
PointerPolicy.shape(PointerState(layer: pointerLayer, overlayOpen: PointerPolicy.isOverlayOpen(in: window),
isEnabled: acceptsPointerText, isOverText: isOverText,
isSelecting: PointerPolicy.isSelecting))
}
/// Cursor rects ignore an overlay on top, so the I-beam rect exists only while the rule allows it.
var allowsIBeamRect: Bool {
PointerPolicy.shape(PointerState(layer: pointerLayer, overlayOpen: PointerPolicy.isOverlayOpen(in: window),
isEnabled: acceptsPointerText, isOverText: true, isSelecting: false)) == .iBeam
}
func updatePointer(atWindowPoint point: NSPoint) {
pointerShape(atWindowPoint: point).cursor.set()
}
func addPointerCursorRect(_ rect: NSRect) {
guard allowsIBeamRect else { return }
addCursorRect(rect, cursor: .iBeam)
}
}
extension NSView {
/// The view a click at the window point would reach, when the point lies in this view's visible part.
func hitView(atWindowPoint point: NSPoint) -> NSView? {
guard let window, let content = window.contentView, visibleRect.contains(convert(point, from: nil)) else { return nil }
return content.hitTest(content.superview?.convert(point, from: nil) ?? point)
}
/// True when a click at the window point reaches this view or a subview.
/// A splitter's hit area lies on top of a text view's edge, so the visible rect alone is not enough.
func isTopmost(atWindowPoint point: NSPoint) -> Bool {
hitView(atWindowPoint: point)?.isDescendant(of: self) ?? false
}
/// The visible rect minus the enclosing scroll view's scrollers and line-number ruler, which keep the arrow.
/// The clip view runs under a visible ruler, so the visible rect alone would give the gutter the I-beam.
var visibleRectWithoutScrollers: NSRect {
let scroll = enclosingScrollView
let ruler: NSView? = scroll?.rulersVisible == true ? scroll?.verticalRulerView : nil
let strips: [NSView?] = [scroll?.verticalScroller, scroll?.horizontalScroller, ruler]
return strips.compactMap { $0 }.filter { !$0.isHidden && $0.superview != nil }
.reduce(visibleRect) { $0.removing(convert($1.bounds, from: $1)) }
}
}
extension NSRect {
/// The rect minus a strip that spans its full height or width along one edge, such as a scroller.
func removing(_ strip: NSRect) -> NSRect {
let overlap = intersection(strip)
guard !overlap.isEmpty else { return self }
var rest = self
if overlap.height >= height {
rest.origin.x = overlap.minX > minX ? minX : overlap.maxX
rest.size.width = overlap.minX > minX ? overlap.minX - minX : maxX - overlap.maxX
} else if overlap.width >= width {
rest.origin.y = overlap.minY > minY ? minY : overlap.maxY
rest.size.height = overlap.minY > minY ? overlap.minY - minY : maxY - overlap.maxY
}
return rest
}
}
@MainActor
extension PointerPolicy {
private static var selectionDrag = false
private static var pendingRefresh: Set<Int> = []
private static var isUpdatingCursor = false
/// The button check ends a drag whose mouse-up went to another view or window.
static var isSelecting: Bool {
if selectionDrag, NSEvent.pressedMouseButtons & 1 == 0 { selectionDrag = false }
return selectionDrag
}
static func beginSelection() {
selectionDrag = true
}
static func endSelection(in window: NSWindow?) {
selectionDrag = false
if let window { updateCursor(in: window) }
}
static func isOverlayOpen(in window: NSWindow?) -> Bool {
guard let window else { return false }
return WorkspaceRegistry.model(for: window)?.overlay.isPresented ?? false
}
/// Re-reads the pointer for a mouse that has not moved, once SwiftUI has applied the change that asked for it.
static func setNeedsRefresh(in window: NSWindow?) {
// Teardown calls this from a deallocating window, where forming a weak reference aborts; keep only its number.
guard let number = window?.windowNumber, pendingRefresh.insert(number).inserted else { return }
DispatchQueue.main.async {
MainActor.assumeIsolated {
defer { pendingRefresh.remove(number) }
guard let window = NSApp.window(withWindowNumber: number) else { return }
refresh(in: window)
}
}
}
/// Rebuilds every cursor rect, then sets the cursor for where the mouse rests.
static func refresh(in window: NSWindow) {
// A splitter drag turns the rects off and owns the cursor until it ends.
guard window.areCursorRectsEnabled else { return }
window.contentView?.layoutSubtreeIfNeeded()
window.resetCursorRects()
updateCursor(in: window)
}
/// Asks the view under the mouse for its pointer; anything that is not text gets the arrow.
/// Views call this from `cursorUpdate`, so a nested call returns at once.
static func updateCursor(in window: NSWindow) {
guard !isUpdatingCursor, window.isKeyWindow, window.areCursorRectsEnabled, !isSelecting,
let content = window.contentView else { return }
isUpdatingCursor = true
defer { isUpdatingCursor = false }
let point = window.mouseLocationOutsideOfEventStream
guard content.bounds.contains(content.convert(point, from: nil)),
NSWindow.windowNumber(at: NSEvent.mouseLocation, belowWindowWithWindowNumber: 0) == window.windowNumber else { return }
let hit = content.hitTest(content.superview?.convert(point, from: nil) ?? point)
var view = hit
while let current = view {
if let owner = current as? PointerOwner {
owner.updatePointer(atWindowPoint: point)
return
}
view = current.superview
}
if let hit, let region = textRegion(in: content, at: point, under: hit) {
region.updatePointer(atWindowPoint: point)
} else {
NSCursor.arrow.set()
}
}
/// A region counts only when the click would land on its own hosting or scroll view, not on a scroller or another view.
private static func textRegion(in view: NSView, at point: NSPoint, under hit: NSView) -> PointerTextRegionView? {
if let region = view as? PointerTextRegionView, !region.isHiddenOrHasHiddenAncestor, region.isDescendant(of: hit),
region.isPointerOverText(atWindowPoint: point) { return region }
for subview in view.subviews {
if let region = textRegion(in: subview, at: point, under: hit) { return region }
}
return nil
}
}
// MARK: - SwiftUI text
/// Gives SwiftUI text that selects on click, such as the Markdown preview, the policy's I-beam. It takes no clicks.
struct PointerTextRegion: NSViewRepresentable {
func makeNSView(context: Context) -> PointerTextRegionView {
PointerTextRegionView()
}
func updateNSView(_ view: PointerTextRegionView, context: Context) {}
}
final class PointerTextRegionView: NSView, PointerTextTarget {
let pointerLayer = PointerLayer.workspace
var acceptsPointerText: Bool { true }
override func hitTest(_ point: NSPoint) -> NSView? { nil }
func isPointerOverText(atWindowPoint point: NSPoint) -> Bool {
visibleRectWithoutScrollers.contains(convert(point, from: nil))
}
override func resetCursorRects() {
addPointerCursorRect(visibleRectWithoutScrollers)
}
override func viewDidMoveToWindow() {
super.viewDidMoveToWindow()
PointerPolicy.setNeedsRefresh(in: window)
}
override func viewWillMove(toWindow newWindow: NSWindow?) {
if newWindow == nil { PointerPolicy.setNeedsRefresh(in: window) }
super.viewWillMove(toWindow: newWindow)
}
}