Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
127 changes: 114 additions & 13 deletions Annotate/ToolbarPanel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@ import SwiftUI

/// The floating toolbar lives in its own non-activating child panel of the overlay window.
/// A panel is what makes the bar draggable without any hand-rolled hit testing: AppKit moves
/// it for us through `isMovableByWindowBackground`. It never becomes key, so every keystroke
/// keeps going to the canvas, and it rides along with the overlay because a child window
/// follows its parent's ordering and its moves.
/// it for us through `isMovableByWindowBackground`, and `performDrag` covers the presses AppKit
/// does not treat as background. It never becomes key, so every keystroke keeps going to the
/// canvas, and it rides along with the overlay because a child window follows its parent's
/// ordering and its moves.
final class ToolbarPanel: NSPanel {
/// Margin kept between the bar and the overlay edges, and the bar's default lift off the
/// bottom. 20 pt is the resting place the bar has always had.
Expand Down Expand Up @@ -41,6 +42,22 @@ final class ToolbarPanel: NSPanel {
/// Button mouse-up that lands after the bar has moved can still be refused.
private let press: ToolbarPress
private let deliverAction: (ToolbarAction) -> Void
/// True once this press has been handed to the window server, so a drag that keeps
/// reporting events is never started twice.
private var hasStartedWindowDrag = false
/// The mouse-down that began the current press. `performDrag` wants the original press,
/// even when the drag is only handed over once the pointer has moved.
private var pressEvent: NSEvent?
/// Polls the button after a hand-off to the window server, which can return before the
/// drag is over and may keep the mouse-up for itself.
private var releaseWatch: Timer?
/// Starts the window server's move of the bar. Replaced in tests: the real move follows
/// the mouse hardware, which a synthetic press never holds down.
var windowDragger: (NSWindow, NSEvent) -> Void = { window, event in
window.performDrag(with: event)
}
/// Whether the primary button is down. Replaced in tests for the same reason.
var isPrimaryButtonDown: () -> Bool = { NSEvent.pressedMouseButtons & 1 != 0 }

init(overlay: OverlayWindow, model: ToolbarModel, perform: @escaping (ToolbarAction) -> Void) {
self.overlay = overlay
Expand Down Expand Up @@ -108,15 +125,31 @@ final class ToolbarPanel: NSPanel {
/// still inside the control; the bar travels with the pointer, so that test is always true
/// during a drag. Screen-space travel (and the bar's own origin, when AppKit swallows the
/// dragged events) is what actually tells a click from a drag.
///
/// A press on a chip is not always carried by AppKit. On macOS 27 the drag region AppKit
/// reports for the panel leaves out everything the hosting view draws, so only the
/// transparent edge and the gaps between segments move the bar natively. When the pointer
/// slides along a bar that is not following it, the chip still holds the press, and the
/// drag is started here.
override func sendEvent(_ event: NSEvent) {
switch event.type {
case .leftMouseDown:
stopWatchingForRelease()
isUserDragging = true
hasStartedWindowDrag = false
pressEvent = event
press.begin(screenPoint: screenPoint(for: event), windowOrigin: frame.origin)
super.sendEvent(event)
case .leftMouseDragged:
press.consider(screenPoint: screenPoint(for: event), windowOrigin: frame.origin)
super.sendEvent(event)
let point = screenPoint(for: event)
press.consider(screenPoint: point, windowOrigin: frame.origin)
if isUserDragging, !hasStartedWindowDrag, press.isDrag, let pressEvent,
press.pointerHasSlidAlongTheBar(screenPoint: point, windowOrigin: frame.origin)
{
carryChipDrag(from: pressEvent, at: event)
} else {
super.sendEvent(event)
}
case .leftMouseUp:
press.consider(screenPoint: screenPoint(for: event), windowOrigin: frame.origin)
super.sendEvent(event)
Expand All @@ -132,23 +165,78 @@ final class ToolbarPanel: NSPanel {
/// get that far, so start the drag explicitly.
override func mouseDown(with event: NSEvent) {
isUserDragging = true
performDrag(with: event)
// `performDrag` swallows dragged events, so judge the gesture against the bar's origin
// before closing it. Chip actions are refused while `press.isDrag` is still set.
startWindowDrag(with: event)
}

/// Hands the rest of a press on a chip to the window server. The chip's `Button` is still
/// tracking the press, and the window server may keep the mouse-up for itself, which would
/// leave the chip pressed. A mouse-up delivered here ends that press first, while
/// `press.isDrag` is set, so the action it fires is refused.
private func carryChipDrag(from pressEvent: NSEvent, at event: NSEvent) {
if let release = NSEvent.mouseEvent(
with: .leftMouseUp,
location: event.locationInWindow,
modifierFlags: event.modifierFlags,
timestamp: event.timestamp,
windowNumber: windowNumber,
context: nil,
eventNumber: event.eventNumber,
clickCount: 1,
pressure: 0
) {
// `super`, because this panel's own mouse-up handling would close the gesture.
super.sendEvent(release)
}
startWindowDrag(with: pressEvent)
}

/// Starts the window server's move of the bar, at most once per press. `event` is the
/// press's original mouse-down, as `performDrag` asks for.
private func startWindowDrag(with event: NSEvent) {
hasStartedWindowDrag = true
windowDragger(self, event)
// `performDrag` returns right away and may never send the mouse-up, so `sendEvent`
// cannot be relied on to see the end of the gesture. Close it once the button is back
// up, whether or not a mouse-up ever arrives.
if isPrimaryButtonDown() {
watchForRelease()
} else {
finishWindowDrag()
}
}

private func watchForRelease() {
stopWatchingForRelease()
let watch = Timer(timeInterval: 1.0 / 60, repeats: true) { [weak self] _ in
MainActor.assumeIsolated {
guard let self, !self.isPrimaryButtonDown() else { return }
self.finishWindowDrag()
}
}
RunLoop.main.add(watch, forMode: .common)
releaseWatch = watch
}

private func stopWatchingForRelease() {
releaseWatch?.invalidate()
releaseWatch = nil
}

/// `performDrag` swallows dragged events, so judge the gesture against the bar's origin
/// before closing it. Chip actions are refused while `press.isDrag` is still set.
private func finishWindowDrag() {
press.consider(windowOrigin: frame.origin)
// `performDrag` may swallow the whole gesture, mouse-up included, in which case
// `sendEvent` never sees the end of it and this is the only place left to close it.
// The button being back up is what tells the two apart: if it is still down the drag
// is still running, so leave the gesture open for the mouse-up to close.
guard NSEvent.pressedMouseButtons & 1 == 0 else { return }
endUserDrag()
}

/// Closes a user gesture and writes down the move it made, if it made one. A click that
/// moved nothing leaves the pending flag clear, so it never records a position the user
/// did not choose. Safe to call more than once for the same gesture.
private func endUserDrag() {
stopWatchingForRelease()
isUserDragging = false
hasStartedWindowDrag = false
pressEvent = nil
press.end()
guard hasPendingSave else { return }
hasPendingSave = false
Expand Down Expand Up @@ -189,6 +277,7 @@ final class ToolbarPanel: NSPanel {
}

func tearDown() {
stopWatchingForRelease()
NotificationCenter.default.removeObserver(self, name: NSWindow.didMoveNotification, object: self)
detach()
close()
Expand Down Expand Up @@ -474,6 +563,18 @@ final class ToolbarPress {
}
}

/// True once the pointer has slid `dragThreshold` across the bar since the press began,
/// which only happens when nothing is moving the bar along with it. A bar that follows the
/// pointer keeps the pointer on the same spot, however far the two travel together.
func pointerHasSlidAlongTheBar(screenPoint: NSPoint, windowOrigin: NSPoint) -> Bool {
guard let startPoint = startScreenPoint, let startOrigin = startWindowOrigin else {
return false
}
let dx = (screenPoint.x - windowOrigin.x) - (startPoint.x - startOrigin.x)
let dy = (screenPoint.y - windowOrigin.y) - (startPoint.y - startOrigin.y)
return hypot(dx, dy) >= Self.dragThreshold
}

func end() {
startScreenPoint = nil
startWindowOrigin = nil
Expand Down
Loading
Loading