fixes cursor

This commit is contained in:
2026-10-05 10:32:09 +02:00
parent 336987d821
commit 201c59c659
12 changed files with 460 additions and 46 deletions
@@ -1,22 +1,72 @@
import AppKit
/// An NSTextView that only sets its I-beam while it is the view under the pointer.
/// An NSTextView that takes its pointer from `PointerPolicy`, and only while it is the view under the pointer.
/// On macOS 26 SwiftTerm makes the window send every mouse move to the first responder, and NSTextView
/// sets the I-beam on each one, which fights the arrow over the other columns and a splitter's resize cursor.
class PointerBoundTextView: NSTextView {
class PointerBoundTextView: NSTextView, PointerTextTarget {
var pointerLayer = PointerLayer.workspace
/// False while the view stays alive but is not shown, so its text takes no I-beam.
var isPointerActive = true {
didSet { if isPointerActive != oldValue { PointerPolicy.setNeedsRefresh(in: window) } }
}
/// Grows the view to at least the clip view's height, so the empty area below the text still takes the I-beam and clicks.
var fillsClipView = false {
didSet { fitClipView() }
}
override func mouseMoved(with event: NSEvent) {
guard isUnderPointer else { return }
super.mouseMoved(with: event)
var acceptsPointerText: Bool { isPointerActive && isSelectable }
func isPointerOverText(atWindowPoint point: NSPoint) -> Bool {
isTopmost(atWindowPoint: point)
}
func updatePointer(atWindowPoint point: NSPoint) {
applyPointer(pointerShape(atWindowPoint: point), atWindowPoint: point)
}
/// Sets the cursor for a shape the policy picked; subclasses add their extras here.
func applyPointer(_ shape: PointerShape, atWindowPoint point: NSPoint) {
shape.cursor.set()
}
/// The first click in an inactive window already places the caret or starts a selection.
override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true }
override func resetCursorRects() {
addPointerCursorRect(visibleRectWithoutScrollers)
}
override func mouseMoved(with event: NSEvent) {
guard let point = mouseLocation, isTopmost(atWindowPoint: point) else { return }
super.mouseMoved(with: event)
applyPointer(pointerShape(isOverText: true), atWindowPoint: point)
}
/// An update meant for another view is handed to the view under the mouse.
override func cursorUpdate(with event: NSEvent) {
guard isUnderPointer else { return }
super.cursorUpdate(with: event)
guard let window, let point = mouseLocation else { return }
if PointerPolicy.isSelecting || isTopmost(atWindowPoint: point) {
updatePointer(atWindowPoint: point)
} else {
PointerPolicy.updateCursor(in: window)
}
}
/// NSTextView tracks the whole drag inside `mouseDown`, so the selection ends when it returns.
override func mouseDown(with event: NSEvent) {
PointerPolicy.beginSelection()
super.mouseDown(with: event)
PointerPolicy.endSelection(in: window)
}
override func viewWillMove(toWindow newWindow: NSWindow?) {
if newWindow == nil { PointerPolicy.setNeedsRefresh(in: window) }
super.viewWillMove(toWindow: newWindow)
}
override func viewDidMoveToWindow() {
super.viewDidMoveToWindow()
PointerPolicy.setNeedsRefresh(in: window)
}
override func viewDidMoveToSuperview() {
@@ -39,12 +89,7 @@ class PointerBoundTextView: NSTextView {
sizeToFit()
}
/// A splitter's hit area lies on top of the text view's edge, so the visible rect alone is not enough.
private var isUnderPointer: Bool {
guard let window, let content = window.contentView else { return false }
let location = window.mouseLocationOutsideOfEventStream
guard visibleRect.contains(convert(location, from: nil)),
let hit = content.hitTest(content.superview?.convert(location, from: nil) ?? location) else { return false }
return hit.isDescendant(of: self)
var mouseLocation: NSPoint? {
window?.mouseLocationOutsideOfEventStream
}
}
@@ -0,0 +1,241 @@
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, which keep the arrow.
var visibleRectWithoutScrollers: NSRect {
let scrollers = [enclosingScrollView?.verticalScroller, enclosingScrollView?.horizontalScroller]
return scrollers.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)
}
}
+10 -2
View File
@@ -54,7 +54,7 @@ private struct SplitterHandle: NSViewRepresentable {
}
}
final class SplitterHandleView: NSView {
final class SplitterHandleView: NSView, PointerOwner {
var axis: Axis = .vertical {
didSet { if axis != oldValue { window?.invalidateCursorRects(for: self) } }
}
@@ -86,6 +86,10 @@ final class SplitterHandleView: NSView {
cursor.set()
}
func updatePointer(atWindowPoint point: NSPoint) {
cursor.set()
}
override func mouseEntered(with event: NSEvent) {
onHover(true)
cursor.set()
@@ -117,8 +121,12 @@ final class SplitterHandleView: NSView {
override func mouseUp(with event: NSEvent) {
guard dragStart != nil else { return }
let inside = bounds.contains(convert(event.locationInWindow, from: nil))
(inside ? cursor : NSCursor.arrow).set()
endDrag()
if inside {
cursor.set()
} else if let window {
PointerPolicy.updateCursor(in: window)
}
onHover(inside)
onEnd()
}