import AppKit import SwiftUI /// The 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 case pointingHand var cursor: NSCursor { switch self { case .iBeam: .iBeam case .arrow: .arrow case .pointingHand: .pointingHand } } } /// Where a text-capable or clickable view lives: in a column, or in the open overlay. enum PointerLayer: Equatable, Sendable { 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, /// the pointing hand only where a left click runs an action, the arrow everywhere else. enum PointerPolicy { static func shape(_ state: PointerState) -> PointerShape { if state.isSelecting { return .iBeam } guard state.isEnabled, state.isOverText, !isBehindOverlay(state.layer, overlayOpen: state.overlayOpen) else { return .arrow } return .iBeam } /// The pointer over a view that runs an action on a left click: a button, a clickable row. static func shape(forClickable layer: PointerLayer, overlayOpen: Bool, isEnabled: Bool, isSelecting: Bool = false) -> PointerShape { if isSelecting { return .iBeam } guard isEnabled, !isBehindOverlay(layer, overlayOpen: overlayOpen) else { return .arrow } return .pointingHand } /// An open overlay takes the pointer from every column behind it. static func isBehindOverlay(_ layer: PointerLayer, overlayOpen: Bool) -> Bool { overlayOpen && layer == .workspace } } // 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 rect.isUsableCursorRect, 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, visibleBounds.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 within the view's own bounds. SwiftUI's platform-view host does not clip, /// so a hosted view's visible rect alone can span the whole window. var visibleBounds: NSRect { let rect = visibleRect.intersection(bounds) return rect.isUsableCursorRect ? rect : .zero } /// 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(visibleBounds) { $0.removing(convert($1.bounds, from: $1)) } } } extension NSView { fileprivate var enclosingClipView: NSClipView? { var view = superview while let current = view { if let clip = current as? NSClipView { return clip } view = current.superview } return nil } fileprivate var isInScroller: Bool { var view: NSView? = self while let current = view { if current is NSScroller { return true } view = current.superview } return false } } extension NSRect { /// False for an empty rect and for the null rect a missed intersection gives, whose origin is infinite; /// `addCursorRect` raises on a non-finite rect. var isUsableCursorRect: Bool { !isNull && !isEmpty && origin.x.isFinite && origin.y.isFinite && size.width.isFinite && size.height.isFinite } /// The rect minus a strip that spans its full height or width along one edge, such as a scroller. func removing(_ strip: NSRect) -> NSRect { guard isUsableCursorRect else { return .zero } let overlap = intersection(strip) guard overlap.isUsableCursorRect 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 = [] 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 scheduleUpdate(in: window) } /// The Git view counts as an overlay: it covers every column and its own views sit on the overlay layer. static func isOverlayOpen(in window: NSWindow?) -> Bool { guard let window, let model = WorkspaceRegistry.model(for: window) else { return false } return model.overlay.isPresented || model.layout.isGitViewOpen } /// 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) } private static var cursorUpdateMonitor: Any? private static var pendingUpdate: Set = [] /// Answers every cursor update and mouse move in a key window through `scheduleUpdate`. It swallows the cursor update: /// AppKit hands it to the hit view, and over a region view, which takes no clicks, the hosting view sets the arrow. /// Mouse moves pass on untouched; they cover views whose tracking areas AppKit never fires, such as an overlay's field. static func installCursorUpdateMonitor() { guard cursorUpdateMonitor == nil else { return } cursorUpdateMonitor = NSEvent.addLocalMonitorForEvents(matching: [.cursorUpdate, .mouseMoved]) { event in let swallow = MainActor.assumeIsolated { guard let window = event.window, window.isKeyWindow, window.areCursorRectsEnabled, !isSelecting else { return false } scheduleUpdate(in: window) return event.type == .cursorUpdate } return swallow ? nil : event } } private static var claimedClasses: Set = [] /// Gives the window's hosting view a `cursorUpdate:` that asks the policy. AppKit calls it directly on every display /// cycle that moves a tracking area, outside any event the monitor sees, and the hosting view's own answer is the arrow. static func claimCursorUpdates(of view: NSView) { guard let viewClass = object_getClass(view), claimedClasses.insert(ObjectIdentifier(viewClass)).inserted else { return } let block: @convention(block) (AnyObject, NSEvent) -> Void = { object, _ in MainActor.assumeIsolated { scheduleUpdate(in: (object as? NSView)?.window) } } let selector = #selector(NSResponder.cursorUpdate(with:)) let types = method_getTypeEncoding(class_getInstanceMethod(NSView.self, selector)!) class_replaceMethod(viewClass, selector, imp_implementationWithBlock(block), types) } /// Runs `updateCursor` once, after the current event. Inside an event SwiftUI's hit test returns its root view, /// not the view under the mouse. It never resets the cursor rects: that would fire new cursor updates. static func scheduleUpdate(in window: NSWindow?) { guard let number = window?.windowNumber, pendingUpdate.insert(number).inserted else { return } DispatchQueue.main.async { MainActor.assumeIsolated { pendingUpdate.remove(number) guard let window = NSApp.window(withWindowNumber: number) else { return } updateCursor(in: window) } } } /// Asks the view under the mouse for its pointer; anything that is not text or clickable gets the arrow. /// Call it outside an event (`scheduleUpdate`); 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 overlayOpen = isOverlayOpen(in: window) let hit = content.hitTest(content.superview?.convert(point, from: nil) ?? point) var view = hit while let current = view { if let owner = current as? PointerOwner { // A column's text view under the open overlay yields to the overlay's own regions. let behind = (owner as? PointerTextTarget).map { isBehindOverlay($0.pointerLayer, overlayOpen: overlayOpen) } ?? false if !behind { owner.updatePointer(atWindowPoint: point) return } break } view = current.superview } if let hit, let region = region(in: content, at: point, under: hit, overlayOpen: overlayOpen) { region.updatePointer(atWindowPoint: point) } else { NSCursor.arrow.set() } } /// The topmost region under the point; with an overlay open, the overlay's regions come first. /// A column region counts when the hit view lies in its scroll view or in none, and never over a scroller. private static func region(in content: NSView, at point: NSPoint, under hit: NSView, overlayOpen: Bool) -> PointerRegionView? { guard !hit.isInScroller else { return nil } var found: [PointerRegionView] = [] collectRegions(in: content, at: point, into: &found) // SwiftUI spreads a scroll view's platform views over several containers, and while it rebuilds a row // the hit view is its root graphics view, so a region need not sit under the hit view. let clip = hit.enclosingClipView let reachable = found.filter { region in clip == nil || region.enclosingClipView === clip || (overlayOpen && region.pointerLayer == .overlay) } let overlayRegions = overlayOpen ? reachable.filter { $0.pointerLayer == .overlay } : [] return (overlayRegions.isEmpty ? reachable : overlayRegions).last } /// Skips hidden subtrees only: SwiftUI's hosts do not clip, so a region may lie outside its ancestors' frames. private static func collectRegions(in view: NSView, at point: NSPoint, into found: inout [PointerRegionView]) { guard !view.isHidden else { return } if let region = view as? PointerRegionView, region.isPointerOverRegion(atWindowPoint: point) { found.append(region) } for subview in view.subviews { collectRegions(in: subview, at: point, into: &found) } } } // MARK: - SwiftUI regions /// A SwiftUI-placed view that only marks an area for the pointer. It takes no clicks. class PointerRegionView: NSView, PointerOwner { var pointerLayer = PointerLayer.workspace { didSet { if pointerLayer != oldValue { pointerChanged() } } } private lazy var tracker = PointerTracker(view: self) override func hitTest(_ point: NSPoint) -> NSView? { nil } override func updateTrackingAreas() { super.updateTrackingAreas() tracker.update() } override func setFrameOrigin(_ newOrigin: NSPoint) { super.setFrameOrigin(newOrigin) tracker.update() } override func setFrameSize(_ newSize: NSSize) { super.setFrameSize(newSize) tracker.update() } func isPointerOverRegion(atWindowPoint point: NSPoint) -> Bool { visibleRectWithoutScrollers.contains(convert(point, from: nil)) } func updatePointer(atWindowPoint point: NSPoint) { NSCursor.arrow.set() } func pointerChanged() { window?.invalidateCursorRects(for: self) PointerPolicy.setNeedsRefresh(in: window) } 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) } } /// Re-reads the pointer whenever the mouse enters or leaves a view or crosses into its cursor area. /// A separate owner, because SwiftTerm's enter and exit handlers cannot be overridden. final class PointerTracker: NSResponder { private weak var view: NSView? private var area: NSTrackingArea? init(view: NSView) { self.view = view super.init() } required init?(coder: NSCoder) { fatalError("PointerTracker is built in code") } /// Fits the tracking area to the view's visible part; call it from every `updateTrackingAreas` and frame change. /// Not `.inVisibleRect`: in SwiftUI's non-clipping host the visible rect spans the window, so the mouse would never enter. func update() { guard let view else { return } let rect = view.visibleBounds // Re-added even when the rect is unchanged: an area added while its view was moving keeps a stale position. if let area { view.removeTrackingArea(area) } area = nil guard rect.isUsableCursorRect else { return } let area = NSTrackingArea(rect: rect, options: [.cursorUpdate, .mouseEnteredAndExited, .activeInKeyWindow], owner: self) view.addTrackingArea(area) self.area = area } override func mouseEntered(with event: NSEvent) { pointerMoved() } override func mouseExited(with event: NSEvent) { pointerMoved() } override func cursorUpdate(with event: NSEvent) { pointerMoved() } private func pointerMoved() { PointerPolicy.scheduleUpdate(in: view?.window) } } extension EnvironmentValues { /// The overlay host and the Git view set `.overlay`, so the regions inside them keep their pointer while the columns lose theirs. @Entry var pointerLayer = PointerLayer.workspace /// False under `disabledLook`, whose hit-testing switch SwiftUI does not expose. @Entry var allowsPointerHand = true } // 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) { view.pointerLayer = context.environment.pointerLayer } } final class PointerTextRegionView: PointerRegionView, PointerTextTarget { var acceptsPointerText: Bool { true } func isPointerOverText(atWindowPoint point: NSPoint) -> Bool { isPointerOverRegion(atWindowPoint: point) } override func updatePointer(atWindowPoint point: NSPoint) { pointerShape(atWindowPoint: point).cursor.set() } override func resetCursorRects() { addPointerCursorRect(visibleRectWithoutScrollers) } } // MARK: - SwiftUI clickables extension View { /// Shows the pointing hand over this view; apply it to the exact view a left click acts on. /// A `.disabled` or `disabledLook` ancestor turns it into the arrow. func pointerHand(_ isEnabled: Bool = true) -> some View { background(PointerHandRegion(isEnabled: isEnabled)) } } struct PointerHandRegion: NSViewRepresentable { var isEnabled: Bool func makeNSView(context: Context) -> PointerHandRegionView { let view = PointerHandRegionView() updateNSView(view, context: context) return view } func updateNSView(_ view: PointerHandRegionView, context: Context) { let environment = context.environment view.pointerLayer = environment.pointerLayer view.isClickable = isEnabled && environment.isEnabled && environment.allowsPointerHand } } final class PointerHandRegionView: PointerRegionView { var isClickable = true { didSet { if isClickable != oldValue { pointerChanged() } } } private func shape(isSelecting: Bool) -> PointerShape { PointerPolicy.shape(forClickable: pointerLayer, overlayOpen: PointerPolicy.isOverlayOpen(in: window), isEnabled: isClickable, isSelecting: isSelecting) } override func updatePointer(atWindowPoint point: NSPoint) { shape(isSelecting: PointerPolicy.isSelecting).cursor.set() } /// Cursor rects ignore an overlay on top, so the hand rect exists only while the rule allows it. override func resetCursorRects() { let rect = visibleRectWithoutScrollers guard rect.isUsableCursorRect, shape(isSelecting: false) == .pointingHand else { return } addCursorRect(rect, cursor: .pointingHand) } }