diff --git a/Sources/PureMouseSettingsUI/AppsPane.swift b/Sources/PureMouseSettingsUI/AppsPane.swift index 69d1c0b..93220a3 100644 --- a/Sources/PureMouseSettingsUI/AppsPane.swift +++ b/Sources/PureMouseSettingsUI/AppsPane.swift @@ -22,7 +22,8 @@ struct AppsPane: View { // Tied to the app: switching from one to another (the status menu's "Settings for // …") starts a page, so no editor, picker, disclosure or icon is left over. AppPage(key: key, identity: identities.identity(key), segment: list.segment, - select: { list.select($0) }, back: { list.close() }, remove: { remove(key) }) + select: { segment in navigate { list.select(segment) } }, + back: { navigate { list.close() } }, remove: { navigate { remove(key) } }) .id(key) } else { appList @@ -80,7 +81,7 @@ struct AppsPane: View { } else { ForEach(apps, id: \.self) { id in AppRow(identity: identities.identity(id), summary: list.summary(id, in: model.config)) { - list.show(id) + navigate { list.show(id) } } .contextMenu { Button("Remove…") { removing = id } @@ -104,11 +105,14 @@ struct AppsPane: View { .onChange(of: apps.count) { settings?.refit() } } + /// Changes between the list and a page, or a page's segments, as the window's one transition. + private func navigate(_ change: () -> Void) { + if let settings { settings.transition(change) } else { change() } + } + /// Opens the page of the app a request named, listing it first when it is not there. private func openRequested() { - guard let id = settings?.app else { return } - settings?.app = nil - list.add(id, in: model.config) + settings?.openRequested(in: &list, config: model.config) } /// The configured apps and those added here, by name. @@ -125,7 +129,7 @@ struct AppsPane: View { if !running.isEmpty { Section("Running") { ForEach(running) { entry in - Button(entry.name) { list.add(entry.id, in: model.config) } + Button(entry.name) { navigate { list.add(entry.id, in: model.config) } } } } } @@ -152,7 +156,7 @@ struct AppsPane: View { Alerts.show(alert.title, alert.message) return } - list.add(id, in: model.config) + navigate { list.add(id, in: model.config) } } if let window = settings?.window { panel.beginSheetModal(for: window, completionHandler: finish) diff --git a/Sources/PureMouseSettingsUI/DevCapture.swift b/Sources/PureMouseSettingsUI/DevCapture.swift index ca297fb..d7bd43f 100644 --- a/Sources/PureMouseSettingsUI/DevCapture.swift +++ b/Sources/PureMouseSettingsUI/DevCapture.swift @@ -23,6 +23,109 @@ enum DevCapture { private static var faked = false private static var shadow = false + /// Captures a page change on an unlocked spare Mac (`PUREMOUSE_DEV_FILMSTRIP=`): frame + /// 0 before the change, then frames at about 60 Hz for `PUREMOUSE_DEV_FILMSTRIP_SECONDS` (default + /// 0.6), each the window server's image of this process's windows. The frames are taken on a + /// background thread, so an animation the main thread drives (a window frame) shows as it + /// happens, and written once the run ends, with `frames.txt` giving each frame's time in ms from + /// the moment the change began on the main thread (frame 0's is negative). Then it quits. + static func filmstrip(_ environment: [String: String], change: @escaping () -> Void) { + guard let path = environment["PUREMOUSE_DEV_FILMSTRIP"] else { return } + let directory = URL(filePath: path, directoryHint: .isDirectory) + do { + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + } catch { + FileHandle.standardError.write(Data("filmstrip directory failed: \(error)\n".utf8)) + NSApp.terminateClosingSheets() + return + } + let delay = environment["PUREMOUSE_DEV_CAPTURE_DELAY"].flatMap(Double.init) ?? 2.5 + let seconds = environment["PUREMOUSE_DEV_FILMSTRIP_SECONDS"].flatMap(Double.init) ?? 0.6 + DispatchQueue.main.asyncAfter(deadline: .now() + delay) { + let film = Film(ids: windowIDs(), shadow: shadow) + let change = Change(run: change) + Thread.detachNewThread { + film.run(seconds: seconds) { + DispatchQueue.main.async { + film.mark(returned: false) + change.run() + film.mark(returned: true) + } + } + DispatchQueue.main.async { + if !film.write(to: directory) { + FileHandle.standardError.write(Data("filmstrip write failed\n".utf8)) + } + NSApp.terminateClosingSheets() + } + } + } + } + + /// The change a filmstrip films, handed to its thread to start on main. + @MainActor private final class Change { + let run: () -> Void + init(run: @escaping () -> Void) { self.run = run } + } + + /// A filmstrip's frames and their times, taken on its own thread; the change's times are set on main. + private final class Film: @unchecked Sendable { + private let ids: [CGWindowID] + private let shadow: Bool + private let lock = NSLock() + private var frames: [(time: UInt64, image: CGImage?)] = [] + private var began: UInt64? + private var returned: UInt64? + + init(ids: [CGWindowID], shadow: Bool) { + self.ids = ids + self.shadow = shadow + } + + func mark(returned isEnd: Bool) { + let now = DispatchTime.now().uptimeNanoseconds + lock.withLock { if isEnd { returned = now } else { began = now } } + } + + /// Captures until `seconds` have passed, starting the change once frame 0 is taken. + func run(seconds: Double, startChange: () -> Void) { + let interval = UInt64(1_000_000_000 / 60) + let start = DispatchTime.now().uptimeNanoseconds + let end = start + UInt64(seconds * 1_000_000_000) + var next = start + while next <= end { + let now = DispatchTime.now().uptimeNanoseconds + if now < next { usleep(useconds_t((next - now) / 1000)) } + let time = DispatchTime.now().uptimeNanoseconds + let image = DevCapture.composite(ids, shadow: shadow) + let count = lock.withLock { + frames.append((time, image)) + return frames.count + } + if count == 1 { startChange() } + // A slow capture skips the slots it missed rather than bunching up. + repeat { next += interval } while next < DispatchTime.now().uptimeNanoseconds + } + } + + @MainActor func write(to directory: URL) -> Bool { + let (frames, began, returned) = lock.withLock { (self.frames, self.began, self.returned) } + let zero = Double(began ?? frames.first?.time ?? 0) + func ms(_ time: UInt64) -> String { String(format: "%.1f", (Double(time) - zero) / 1e6) } + var lines = ["# frame, ms from the change beginning on the main thread"] + if let returned { lines.append("# the change returned at \(ms(returned))") } + for (index, frame) in frames.enumerated() { + let url = directory.appendingPathComponent(String(format: "%03d.png", index)) + guard let image = frame.image, + let png = NSBitmapImageRep(cgImage: image).representation(using: .png, properties: [:]), + (try? png.write(to: url)) != nil else { return false } + lines.append(String(format: "%03d ", index) + ms(frame.time)) + } + let text = lines.joined(separator: "\n") + "\n" + return (try? text.write(to: directory.appendingPathComponent("frames.txt"), atomically: true, encoding: .utf8)) != nil + } + } + static func schedule(_ environment: [String: String]) { guard let path = environment["PUREMOUSE_DEV_CAPTURE"] else { return } let delay = environment["PUREMOUSE_DEV_CAPTURE_DELAY"].flatMap(Double.init) ?? 2.5 @@ -90,16 +193,19 @@ enum DevCapture { report("after fake") } - /// This process's on-screen windows, front to back, composited into one image. - private static func write(to url: URL) -> Bool { + /// This process's on-screen windows, front to back. + private static func windowIDs() -> [CGWindowID] { let pid = ProcessInfo.processInfo.processIdentifier let info = CGWindowListCopyWindowInfo([.optionOnScreenOnly, .excludeDesktopElements], kCGNullWindowID) as? [[String: Any]] ?? [] - var ids: [UnsafeRawPointer?] = info + return info .filter { ($0[kCGWindowOwnerPID as String] as? Int).map(pid_t.init) == pid } - .compactMap { ($0[kCGWindowNumber as String] as? Int).flatMap { UnsafeRawPointer(bitPattern: UInt($0)) } } - guard !ids.isEmpty, let windows = CFArrayCreate(nil, &ids, ids.count, nil), - let image = composite(windows), + .compactMap { ($0[kCGWindowNumber as String] as? Int).map(CGWindowID.init) } + } + + /// This process's on-screen windows, front to back, composited into one image. + private static func write(to url: URL) -> Bool { + guard let image = composite(windowIDs(), shadow: shadow), let png = NSBitmapImageRep(cgImage: image).representation(using: .png, properties: [:]) else { return false } return (try? png.write(to: url)) != nil @@ -177,9 +283,12 @@ enum DevCapture { /// `CGWindowListCreateImageFromArray`, looked up at run time: it is deprecated in favour of /// ScreenCaptureKit, which needs the Screen Recording permission even for a process's own windows. - private static func composite(_ windows: CFArray) -> CGImage? { + /// The filmstrip calls it off the main thread. + nonisolated private static func composite(_ ids: [CGWindowID], shadow: Bool) -> CGImage? { typealias Create = @convention(c) (CGRect, CFArray, CGWindowImageOption) -> Unmanaged? - guard let symbol = dlsym(UnsafeMutableRawPointer(bitPattern: -2), "CGWindowListCreateImageFromArray") + var pointers: [UnsafeRawPointer?] = ids.map { UnsafeRawPointer(bitPattern: UInt($0)) } + guard !pointers.isEmpty, let windows = CFArrayCreate(nil, &pointers, pointers.count, nil), + let symbol = dlsym(UnsafeMutableRawPointer(bitPattern: -2), "CGWindowListCreateImageFromArray") else { return nil } let create = unsafeBitCast(symbol, to: Create.self) let options: CGWindowImageOption = shadow ? [.bestResolution] : [.boundsIgnoreFraming, .bestResolution] diff --git a/Sources/PureMouseSettingsUI/DevHooks.swift b/Sources/PureMouseSettingsUI/DevHooks.swift index 5eae6c6..7fdb04d 100644 --- a/Sources/PureMouseSettingsUI/DevHooks.swift +++ b/Sources/PureMouseSettingsUI/DevHooks.swift @@ -91,6 +91,17 @@ public enum DevHooks { DispatchQueue.main.asyncAfter(deadline: .now() + delay) { send(key: name) } } DevCapture.schedule(environment) + if let target = environment["PUREMOUSE_DEV_FILMSTRIP_TO"] { + DevCapture.filmstrip(environment) { + if let pane = SettingsPane(rawValue: target) { + show(ShowRequest(pane: pane)) + } else if target == "back" { + send(key: "esc") + } else if target.hasPrefix("app:") { + show(ShowRequest(app: String(target.dropFirst(4)))) + } + } + } DevAXDump.schedule(environment, show: show) } } diff --git a/Sources/PureMouseSettingsUI/MouseTab.swift b/Sources/PureMouseSettingsUI/MouseTab.swift index 10eb78c..8b36dbe 100644 --- a/Sources/PureMouseSettingsUI/MouseTab.swift +++ b/Sources/PureMouseSettingsUI/MouseTab.swift @@ -21,8 +21,10 @@ final class MouseSelection { @MainActor final class MouseTab: NSViewController, IdealSized { let selection: MouseSelection - /// Called when the segment changes, after its pane shows, so the window can refit to it. + /// Called when the segment changes, after its pane shows. var didSelect: (MouseSegment) -> Void = { _ in } + /// Runs a segment change on screen as the window's one page transition (`SettingsTabs.transition`). + var transition: (() -> Void) -> Void = { $0() } /// Called as the segment changes away from Buttons, whichever way the change came (the strip /// or a request), so Find by Pressing, which belongs to Buttons, ends with it. var willLeaveButtons: () -> Void = {} @@ -68,7 +70,11 @@ final class MouseTab: NSViewController, IdealSized { guard segment != selection.segment else { return } if selection.segment == .buttons { willLeaveButtons() } selection.segment = segment - if isViewLoaded { show(segment) } + if isViewLoaded, view.window != nil { + transition { show(segment) } + } else if isViewLoaded { + show(segment) + } didSelect(segment) } diff --git a/Sources/PureMouseSettingsUI/PaneHost.swift b/Sources/PureMouseSettingsUI/PaneHost.swift index 45dc927..65a7463 100644 --- a/Sources/PureMouseSettingsUI/PaneHost.swift +++ b/Sources/PureMouseSettingsUI/PaneHost.swift @@ -88,6 +88,9 @@ struct PaneForm: View { var body: some View { Form { content } .formStyle(.grouped) + // Looks the same, but leaves the window's own background (tinted by the desktop) + // showing, so a page change's snapshot matches the page (`PaneTransition`). + .scrollContentBackground(.hidden) .scrollBounceBehavior(.basedOnSize) .frame(maxHeight: maxHeight) .fixedSize(horizontal: false, vertical: true) diff --git a/Sources/PureMouseSettingsUI/PaneTransition.swift b/Sources/PureMouseSettingsUI/PaneTransition.swift new file mode 100644 index 0000000..d2397a6 --- /dev/null +++ b/Sources/PureMouseSettingsUI/PaneTransition.swift @@ -0,0 +1,352 @@ +import AppKit + +/// The one owner of the Settings window's frame (docs/ui-design.md, Motion and Sizing). A page +/// change (a tab, a Mouse segment, an app's page and back) runs `change`: the old page is +/// snapshotted, the change is made and laid out, and one transaction starts the window frame moving +/// to the new page's height while the snapshot fades out and the new page fades in, with one duration +/// and curve. A height change inside a page (`fit`) moves the frame the same way, with no fade. +/// +/// While either runs, the page's container (the tab view) is held against the top of the window at +/// the new height, so nothing slides as the frame moves: the window's bottom edge covers or uncovers +/// the page. Left to the tab controller's own constraints (top and bottom at priority 749, above the +/// window's own height at 500), the tab view takes the new height before the window does and sits +/// against the bottom, so the page slid with the frame. A hidden window and Reduce Motion take the +/// new size at once, as AppKit does. +@MainActor +final class PaneTransition { + /// How a change shows. + enum Style: Equatable { + /// The page swaps and the window takes its new size at once. + case instant + /// One transition of this length: the pages cross-fade, and the frame moves if the + /// height changed. + case animated(TimeInterval) + } + + /// The shortest and longest a page change takes. AppKit's own resize time (about 0.2 s per + /// 150 pt) sets it between them, so a fade with little or no height change is still seen. + static let durations: ClosedRange = 0.2...0.35 + + static func style(visible: Bool, reduceMotion: Bool, resizeTime: TimeInterval) -> Style { + guard visible, !reduceMotion else { return .instant } + return .animated(min(max(resizeTime, durations.lowerBound), durations.upperBound)) + } + + /// Whether the system asks for less motion; replaced in tests. + var reduceMotion: () -> Bool = { NSWorkspace.shared.accessibilityDisplayShouldReduceMotion } + + /// Animation dependencies are replaceable for deterministic lifecycle tests. + var isVisible: (NSWindow) -> Bool = { $0.isVisible } + var now: () -> TimeInterval = { CACurrentMediaTime() } + var animateGroup: (TimeInterval, @escaping () -> Void, @escaping @MainActor @Sendable () -> Void) -> Void = { duration, changes, completion in + NSAnimationContext.runAnimationGroup { context in + context.duration = duration + context.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut) + changes() + } completionHandler: { + MainActor.assumeIsolated { completion() } + } + } + + /// The view the snapshot covers: the window's content view (the tab controller's). + private unowned let host: NSView + /// The window frame that fits the page now, or nil when there is nothing to measure. + private let target: () -> NSRect? + /// The view that holds the page (the tab view): held at the top while the frame moves, and + /// faded in over a page change. + private let container: () -> NSView? + + /// How many `change` calls are open: only the outermost one snapshots and animates. + private var depth = 0 + /// The old page, taken by `begin` for `end`. + private var snapshot: NSView? + private var flight: Flight? + private var nextFlight = 0 + /// Coalesce fits requested synchronously by measurement or layout into another pass. + private var fitting = false + private var fitRequested = false + + private static let fadeKey = "PaneTransition.fadeIn" + + /// An animation under way: its destination, pins and original end time. + private struct Flight { + let id: Int + var target: NSRect + var snapshot: NSView? + var pins: [NSLayoutConstraint] = [] + /// The tab controller's own bottom constraints, off while the page is pinned. + var released: [NSLayoutConstraint] = [] + var frameGeneration = 0 + var framePending = false + var fadePending = false + let deadline: TimeInterval + } + + init(host: NSView, target: @escaping () -> NSRect?, container: @escaping () -> NSView?) { + self.host = host + self.target = target + self.container = container + } + + /// Whether a change is being made (between `begin` and `end`): the frame waits for it. + var isChanging: Bool { depth > 0 } + + /// Whether an animation is under way. + var isAnimating: Bool { flight != nil } + + /// Makes a page change as one transition. Nested calls join the outer one. + func change(_ swap: () -> Void) { + begin() + swap() + end() + } + + /// Starts a page change: ends one under way at once, and snapshots the page as it is. + func begin() { + depth += 1 + guard depth == 1 else { return } + settle() + snapshot = takeSnapshot() + // The new page stays hidden under the snapshot until its fade starts: AppKit and SwiftUI + // can draw between the swap and the animation, which showed both pages for a frame. + if snapshot != nil { setPageOpacity(0) } + } + + /// Ends a page change: lays the new page out, measures it and starts the frame and fade. + func end() { + depth -= 1 + guard depth == 0 else { return } + let snapshot = self.snapshot + self.snapshot = nil + // Layout can consume an app-page request and call change again. Keep it inside this + // change so it joins the snapshot already taken rather than starting a second flight. + depth = 1 + // Twice: a change can set state that a pane acts on in its first update (a request for an + // app's page), which then changes what it shows. + host.layoutSubtreeIfNeeded() + host.layoutSubtreeIfNeeded() + let window = host.window + let target = window == nil ? nil : target() + depth = 0 + guard let window, let target else { + snapshot?.removeFromSuperview() + setPageOpacity(1) + return + } + animate(window, to: target, fading: snapshot) + } + + /// Fits the window to the page after its height changed in place (a disclosure, a notice): the + /// frame moves as in a page change, with no fade. A change being made fits when it ends. + func fit() { + guard !isChanging, host.window != nil else { return } + if fitting { + fitRequested = true + return + } + fitting = true + defer { fitting = false } + repeat { + fitRequested = false + fitOnce() + } while fitRequested && !isChanging && host.window != nil + } + + private func fitOnce() { + guard let window = host.window else { return } + var measured = target() + // Measurement can synchronously request another fit. Measure again before retargeting, + // so all those requests share one frame generation and use the latest size. + while fitRequested && !isChanging && host.window != nil { + fitRequested = false + measured = target() + } + guard !isChanging, host.window === window else { return } + if var flight { + let target = measured ?? flight.target + // Policy may have changed even when the measured target has not. + guard case .animated = Self.style(visible: isVisible(window), reduceMotion: reduceMotion(), + resizeTime: window.animationResizeTime(target)), + flight.deadline > now() else { + flight.target = target + self.flight = flight + settle() + return + } + guard flight.target != target else { return } + flight.target = target + self.flight = flight + pin(height: window.contentRect(forFrameRect: target).height) + runFrame(window, to: target, duration: max(0, flight.deadline - now()), id: flight.id) + } else { + guard let target = measured, window.frame != target else { return } + animate(window, to: target, fading: nil) + } + } + + /// Ends an outstanding change when the window closes, including a snapshot taken before `end`. + func cancel() { + snapshot?.removeFromSuperview() + snapshot = nil + setPageOpacity(1) + settle() + } + + // MARK: Running + + private func animate(_ window: NSWindow, to target: NSRect, fading snapshot: NSView?) { + let style = Self.style(visible: isVisible(window), reduceMotion: reduceMotion(), + resizeTime: window.animationResizeTime(target)) + guard case .animated(let duration) = style, window.frame != target || snapshot != nil else { + snapshot?.removeFromSuperview() + setPageOpacity(1) + if window.frame != target { window.setFrame(target, display: isVisible(window)) } + return + } + nextFlight += 1 + let id = nextFlight + flight = Flight(id: id, target: target, snapshot: snapshot, framePending: true, deadline: now() + duration) + pin(height: window.contentRect(forFrameRect: target).height) + // Separate completion ownership: replacing a frame animation can complete its AppKit + // group immediately. It must neither complete the fade nor release the page's pins. + CATransaction.begin() + if let snapshot { + flight?.fadePending = true + animateGroup(duration, { [self] in + snapshot.animator().alphaValue = 0 + if let layer = container()?.layer { + CATransaction.begin() + CATransaction.setDisableActions(true) + layer.opacity = 1 + let fade = CABasicAnimation(keyPath: "opacity") + fade.fromValue = 0 + fade.toValue = 1 + fade.duration = duration + fade.beginTime = layer.convertTime(now(), from: nil) + fade.fillMode = .backwards + fade.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut) + layer.add(fade, forKey: Self.fadeKey) + CATransaction.commit() + } + }, { [weak self] in + guard let self, flight?.id == id else { return } + flight?.fadePending = false + finishIfReady() + }) + } + runFrame(window, to: target, duration: duration, id: id) + CATransaction.commit() + } + + /// Retargets share the original deadline; only the latest frame completion owns the pins. + private func runFrame(_ window: NSWindow, to target: NSRect, duration: TimeInterval, id: Int) { + flight?.frameGeneration += 1 + let generation = flight?.frameGeneration + flight?.framePending = true + animateGroup(duration, { + if window.frame != target { window.animator().setFrame(target, display: true) } + }, { [weak self] in + guard let self, flight?.id == id, flight?.frameGeneration == generation else { return } + flight?.framePending = false + finishIfReady() + }) + } + + private func finishIfReady() { + guard let flight, !flight.framePending, !flight.fadePending else { return } + land() + } + + /// Layer opacity does not take the live view out of AppKit hit testing. Before a swap it is + /// zero; the final model value and explicit fade are installed together before commit. + private func setPageOpacity(_ opacity: Float) { + guard let page = container() else { return } + page.wantsLayer = true + CATransaction.begin() + CATransaction.setDisableActions(true) + page.layer?.opacity = opacity + CATransaction.commit() + } + + /// Ends an animation under way at once: the frame at its target, the snapshot gone, the page + /// shown and unpinned. + private func settle() { + guard let flight, let window = host.window else { return land() } + if window.frame != flight.target { window.setFrame(flight.target, display: isVisible(window)) } + land() + } + + private func land() { + guard let flight else { return } + self.flight = nil + flight.snapshot?.removeFromSuperview() + if let page = container() { + setPageOpacity(1) + page.layer?.removeAnimation(forKey: Self.fadeKey) + } + guard !flight.pins.isEmpty else { return } + NSLayoutConstraint.deactivate(flight.pins) + NSLayoutConstraint.activate(flight.released) + host.layoutSubtreeIfNeeded() + fillContainer() + } + + // MARK: Snapshot and pin + + /// The page as drawn now, in a view over it pinned to the top. Only the content is drawn, with + /// the window's background left clear, so the real background (tinted by the desktop) shows + /// through: a snapshot with the background drawn in did not match it. Nil when the change will + /// not animate. + private func takeSnapshot() -> NSView? { + guard let window = host.window, isVisible(window), !reduceMotion(), + host.bounds.width > 0, host.bounds.height > 0, + let rep = host.bitmapImageRepForCachingDisplay(in: host.bounds) else { return nil } + host.cacheDisplay(in: host.bounds, to: rep) + let view = SnapshotView(frame: host.bounds) + view.wantsLayer = true + view.layer?.contents = rep.cgImage + view.layer?.contentsScale = window.backingScaleFactor + view.autoresizingMask = [.width, host.isFlipped ? .maxYMargin : .minYMargin] + host.addSubview(view, positioned: .above, relativeTo: nil) + return view + } + + /// Holds the page's container at `height` against the top of the window's content, so the + /// frame's bottom edge moves over the page instead of the page moving with it. + private func pin(height: CGFloat) { + guard var flight, let container = container() else { return } + if flight.pins.isEmpty { + // The container's bottom is tied to the window's (the tab controller's, at 749), which + // with a fixed height would size the window through layout at once, outrunning the + // animation: it is let go until the frame arrives. + flight.released = host.constraints.filter { constraint in + constraint.isActive && [constraint.firstItem, constraint.secondItem].contains { $0 === container } + && [constraint.firstAttribute, constraint.secondAttribute].contains(.bottom) + } + NSLayoutConstraint.deactivate(flight.released) + flight.pins = [container.topAnchor.constraint(equalTo: host.topAnchor), + container.heightAnchor.constraint(equalToConstant: height)] + NSLayoutConstraint.activate(flight.pins) + } else { + flight.pins[1].constant = height + } + self.flight = flight + host.layoutSubtreeIfNeeded() + fillContainer() + } + + /// Gives the selected page the tab view's whole content area, as the tab view itself would. + private func fillContainer() { + guard let tabView = container() as? NSTabView, + let page = tabView.selectedTabViewItem?.view else { return } + if page.frame != tabView.contentRect { page.frame = tabView.contentRect } + } +} + +/// A visual copy of the old page never intercepts input or appears to assistive technology. +@MainActor +final class SnapshotView: NSView { + override func hitTest(_ point: NSPoint) -> NSView? { nil } + override func isAccessibilityElement() -> Bool { false } + override func accessibilityIsIgnored() -> Bool { true } +} diff --git a/Sources/PureMouseSettingsUI/SettingsContext.swift b/Sources/PureMouseSettingsUI/SettingsContext.swift index 90577bb..23000d4 100644 --- a/Sources/PureMouseSettingsUI/SettingsContext.swift +++ b/Sources/PureMouseSettingsUI/SettingsContext.swift @@ -1,6 +1,7 @@ import AppKit import Observation import PureMouseAppSupport +import PureMouseKit /// What a pane may ask of the window around it. @MainActor @Observable @@ -24,6 +25,29 @@ final class SettingsContext { var window: NSWindow? { tabs?.view.window } + /// Applies the navigation part of `SettingsWindowController.show`, before activation or a + /// sheet is presented. Only an actual page change takes a snapshot. + func show(_ request: ShowRequest?) { + let change = { + if let pane = request?.pane { self.tabs?.open(pane) } + if let app = request?.app { self.app = app } + } + if let pane = request?.pane, tabs?.changesPage(to: pane) == true { + transition(change) + } else { + change() + } + } + + /// Apps consumes a request during layout, joining a tab transition if one is being made. + /// Repeating the current app leaves its segment and any animation under way alone. + func openRequested(in list: inout AppList, config: ConfigTree) { + guard let app else { return } + self.app = nil + guard list.open != config.appKey(app) else { return } + transition { list.add(app, in: config) } + } + /// Shows a tab, or Mouse on a segment (the banner's "more notices" opens General). func open(_ pane: SettingsPane) { tabs?.open(pane) @@ -52,6 +76,12 @@ final class SettingsContext { rowRequest = RowRequest(id: (rowRequest?.id ?? 0) + 1, button: button) } + /// Changes what the pane shows (an app's page, back to the list) as the window's one page + /// transition: the content cross-fades as the frame moves (`SettingsTabs.transition`). + func transition(_ change: () -> Void) { + if let tabs { tabs.transition(change) } else { change() } + } + /// Fits the window to its pane once a change in the pane's height has laid out /// (`SettingsTabs.refit`). func refit() { diff --git a/Sources/PureMouseSettingsUI/SettingsWindow.swift b/Sources/PureMouseSettingsUI/SettingsWindow.swift index e281012..9fc9ca5 100644 --- a/Sources/PureMouseSettingsUI/SettingsWindow.swift +++ b/Sources/PureMouseSettingsUI/SettingsWindow.swift @@ -39,7 +39,8 @@ public final class SettingsWindowController: NSWindowController, NSWindowDelegat segment: defaults.string(forKey: Self.segmentKey)) tabs.selectSegment(saved.segment) tabs.tabStyle = .toolbar - tabs.transitionOptions = [.crossfade, .allowUserInteraction] + // No transition of its own: the page change is one transition with the window frame (`PaneTransition`). + tabs.transitionOptions = [] for tab in SettingsTab.shown { let lazy = LazyPane { [tabs] in Self.content(for: tab, model: model, context: context, tabs: tabs) } lazy.title = tab.title @@ -98,9 +99,9 @@ public final class SettingsWindowController: NSWindowController, NSWindowDelegat case .pointer: host(MouseSegmentPane { PointerPane() }) } } - mouse.didSelect = { [weak tabs] in - tabs?.selectSegment($0) - context.refit() + mouse.didSelect = { [weak tabs] in tabs?.selectSegment($0) } + mouse.transition = { [weak tabs] swap in + if let tabs { tabs.transition(swap) } else { swap() } } mouse.willLeaveButtons = { [weak model] in model?.cancelCapture() @@ -120,7 +121,7 @@ public final class SettingsWindowController: NSWindowController, NSWindowDelegat // Someone is looking: let the daemon check what it only learns by looking (Logi Options+). model.askDaemonToRecheck() if let request { model.select(for: request) } - if let pane = request?.pane { tabs.open(pane) } + context.show(request) guard let window else { return } if !window.isVisible, !restorePosition(of: window) { window.center() } NSApp.activate() @@ -128,7 +129,6 @@ public final class SettingsWindowController: NSWindowController, NSWindowDelegat DispatchQueue.main.async { [context] in window.makeFirstResponder(nil) if let sheet = request?.sheet { context.sheet = sheet } - if let app = request?.app { context.app = app } } } @@ -163,6 +163,7 @@ public final class SettingsWindowController: NSWindowController, NSWindowDelegat } public func windowWillClose(_ notification: Notification) { + tabs.pageTransition.cancel() // Let AppKit finish closing first. A request to show Settings in that gap (the menu bar app // rings the doorbell) keeps the window, so the helper stays. DispatchQueue.main.async { [weak self] in @@ -172,7 +173,8 @@ public final class SettingsWindowController: NSWindowController, NSWindowDelegat } } -/// Fits the window to each pane's height, keeping its top edge still, and remembers the pane. +/// Fits the window to each pane's height, keeping its top edge still, and remembers the pane. Its +/// `PaneTransition` is the one thing that moves the window frame. @MainActor final class SettingsTabs: NSTabViewController { var didSelect: (SettingsTab) -> Void = { _ in } @@ -180,10 +182,17 @@ final class SettingsTabs: NSTabViewController { /// Called when another tab replaces Mouse, whichever way the change came. var didLeaveMouse: () -> Void = {} private var shownTab: SettingsTab? + private var tabChangeStarted = false /// The Mouse tab's segment, kept while another tab shows and used when Mouse is first built. private(set) var segment: MouseSegment = .buttons /// The Mouse tab, once built. weak var mouse: MouseTab? + /// The window frame's one owner: page changes and in-place height changes go through it. + private(set) lazy var pageTransition = PaneTransition(host: view) { [weak self] in + self?.fittedFrame() + } container: { [weak self] in + self?.tabView + } /// The selected tab's item; nil while nothing is selected (the index is -1). private var selectedItem: NSTabViewItem? { @@ -203,11 +212,33 @@ final class SettingsTabs: NSTabViewController { mouse?.select(segment) } - /// Shows a tab, or Mouse on a segment. + /// Shows a tab, or Mouse on a segment, as one transition. func open(_ pane: SettingsPane) { + guard changesPage(to: pane) else { return } + let next = SettingsSelection(tab: selectedTab ?? .mouse, segment: segment).opening(pane) + transition { + selectSegment(next.segment) + if let index = SettingsTab.shown.firstIndex(of: next.tab) { selectedTabViewItemIndex = index } + } + } + + /// Plain activation and repeated page requests leave an existing flight alone. + func changesPage(to pane: SettingsPane) -> Bool { let next = SettingsSelection(tab: selectedTab ?? .mouse, segment: segment).opening(pane) - selectSegment(next.segment) - if let index = SettingsTab.shown.firstIndex(of: next.tab) { selectedTabViewItemIndex = index } + return selectedTab != next.tab || (next.tab == .mouse && segment != next.segment) + } + + /// Makes a change to what the window shows (a tab, a segment, an app's page) as one transition: + /// the content cross-fades as the frame moves to the new height (`PaneTransition`). + func transition(_ change: () -> Void) { + pageTransition.change(change) + } + + override func tabView(_ tabView: NSTabView, willSelect tabViewItem: NSTabViewItem?) { + // A toolbar click arrives here without `open`: the change starts before the old pane goes. + tabChangeStarted = (tabViewItem?.identifier as? String) != shownTab?.rawValue + if tabChangeStarted { pageTransition.begin() } + super.tabView(tabView, willSelect: tabViewItem) } override func tabView(_ tabView: NSTabView, didSelect tabViewItem: NSTabViewItem?) { @@ -218,42 +249,42 @@ final class SettingsTabs: NSTabViewController { shownTab = tab didSelect(tab) } - fitWindow(animated: view.window?.isVisible == true) + if tabChangeStarted { + tabChangeStarted = false + pageTransition.end() + } // No field or button starts focused: Tab still reaches them. DispatchQueue.main.async { [weak self] in self?.view.window?.makeFirstResponder(nil) } } override func preferredContentSizeDidChange(for viewController: NSViewController) { - super.preferredContentSizeDidChange(for: viewController) + // Not passed to super: the window frame has one owner (`PaneTransition`). guard let selected = selectedItem?.viewController, viewController === selected else { return } - fitWindow(animated: view.window?.isVisible == true) + pageTransition.fit() } /// Fits the window to the current pane after its content changed height. The nested hosting /// controller's size follows its content, but it never tells its parent, so this passes it - /// up (the Apps pane calls it when its list grows or shrinks; the Mouse tab when its - /// segment changes). + /// up (`SettingsContext.refit()`: the Apps list growing, a disclosure, a notice). func refit() { - guard let pane = selectedItem?.viewController else { return } - (pane.children.first as? MouseTab)?.fit() - let size = pane.measuredSize(maxHeight: LazyPane.maxHeight(on: view.window?.screen)) - if pane.preferredContentSize != size { pane.preferredContentSize = size } - fitWindow(animated: view.window?.isVisible == true) + pageTransition.fit() } - private func fitWindow(animated: Bool) { - guard let window = view.window, - let content = selectedItem?.viewController else { return } - // Measured now, not read from `preferredContentSize`, which is only as fresh as the pane's - // last layout (stale or zero before the first), and capped to the screen the window is on. - let size = content.measuredSize(maxHeight: LazyPane.maxHeight(on: window.screen)) - guard size.height.isFinite, size.height > 0 else { return } + /// The window frame that fits the current pane, its top edge where it is now; nil when there + /// is no window or nothing to measure. The pane is measured now, not read from + /// `preferredContentSize`, which is only as fresh as its last layout (stale or zero before the + /// first), and capped to the screen the window is on. + private func fittedFrame() -> NSRect? { + guard let window = view.window, let pane = selectedItem?.viewController else { return nil } + (pane.children.first as? MouseTab)?.fit() + let size = pane.measuredSize(maxHeight: LazyPane.maxHeight(on: window.screen)) + guard size.height.isFinite, size.height > 0 else { return nil } + if pane.preferredContentSize != size { pane.preferredContentSize = size } let contentRect = NSRect(x: 0, y: 0, width: SettingsWindowController.width, height: size.height) var frame = window.frameRect(forContentRect: contentRect) frame.origin.x = window.frame.minX frame.origin.y = window.frame.maxY - frame.height - guard frame != window.frame else { return } - window.setFrame(frame, display: true, animate: animated) + return frame } } diff --git a/Tests/PureMouseSettingsTests/AppsPaneTests.swift b/Tests/PureMouseSettingsTests/AppsPaneTests.swift index e1611fc..76c3f99 100644 --- a/Tests/PureMouseSettingsTests/AppsPaneTests.swift +++ b/Tests/PureMouseSettingsTests/AppsPaneTests.swift @@ -91,7 +91,7 @@ import Testing #expect(page.contains(#".accessibilityLabel("Back to Apps")"#)) // The Apps tab shows the page in place of the list, and the row and the request open the same one. let apps = try Self.source("PureMouseSettingsUI/AppsPane.swift") - #expect(apps.contains("AppPage(key:") && apps.contains("back: { list.close() }")) + #expect(apps.contains("AppPage(key:") && apps.contains("back: { navigate { list.close() } }")) #expect(apps.contains("list.show(id)") && apps.contains("list.add(id, in: model.config)")) #expect(!apps.contains(".sheet(")) } diff --git a/Tests/PureMouseSettingsTests/PaneTransitionTests.swift b/Tests/PureMouseSettingsTests/PaneTransitionTests.swift new file mode 100644 index 0000000..d254972 --- /dev/null +++ b/Tests/PureMouseSettingsTests/PaneTransitionTests.swift @@ -0,0 +1,412 @@ +import AppKit +import PureMouseAppSupport +import PureMouseKit +import Testing +@testable import PureMouseSettingsUI + +// The Settings window's one transition (`PaneTransition`): when it animates, that it alone moves +// the frame, and that a page change still lands on the pane's measured height. The animation +// itself is checked on screen with the filmstrip hook (docs/development.md). + +@MainActor @Suite struct PaneTransitionStyleTests { + @Test func aHiddenWindowOrReduceMotionChangesAtOnce() { + #expect(PaneTransition.style(visible: false, reduceMotion: false, resizeTime: 0.3) == .instant) + #expect(PaneTransition.style(visible: true, reduceMotion: true, resizeTime: 0.3) == .instant) + #expect(PaneTransition.style(visible: false, reduceMotion: true, resizeTime: 0.3) == .instant) + } + + @Test func theLengthIsAppKitsResizeTimeWithinBounds() { + let bounds = PaneTransition.durations + #expect(PaneTransition.style(visible: true, reduceMotion: false, resizeTime: 0) == .animated(bounds.lowerBound), + "a fade with no height change is still seen") + #expect(PaneTransition.style(visible: true, reduceMotion: false, resizeTime: 0.25) == .animated(0.25)) + #expect(PaneTransition.style(visible: true, reduceMotion: false, resizeTime: 2) == .animated(bounds.upperBound)) + } + + @Test func onlyThePaneTransitionMovesTheWindowFrame() throws { + let ui = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent() + .deletingLastPathComponent().appending(path: "Sources/PureMouseSettingsUI") + let files = try FileManager.default.contentsOfDirectory(at: ui, includingPropertiesForKeys: nil) + .filter { $0.pathExtension == "swift" } + for file in files where file.lastPathComponent != "PaneTransition.swift" { + let code = try String(contentsOf: file, encoding: .utf8).components(separatedBy: "\n") + .filter { !$0.trimmingCharacters(in: .whitespaces).hasPrefix("//") }.joined(separator: "\n") + #expect(!code.contains("setFrame("), "\(file.lastPathComponent) sizes the window") + #expect(!code.contains("setContentSize("), "\(file.lastPathComponent) sizes the window") + #expect(!code.contains(".crossfade"), "\(file.lastPathComponent) adds a second cross-fade") + } + // NSTabViewController's own handler sizes the window to the pane's preferred size. + let window = try String(contentsOf: ui.appending(path: "SettingsWindow.swift"), encoding: .utf8) + let start = try #require(window.range(of: "final class SettingsTabs")) + let tabs = window[start.lowerBound...] + let body = tabs[..<(tabs.range(of: "\n}\n")?.lowerBound ?? tabs.endIndex)] + #expect(body.contains("override func preferredContentSizeDidChange")) + #expect(!body.contains("super.preferredContentSizeDidChange"), "the tab controller sizes the window too") + } +} + +@MainActor @Suite struct PaneTransitionTests { + /// A hidden window with a content view, and a transition over it whose target is `height` tall. + @MainActor private final class Rig { + let window = NSWindow(contentRect: NSRect(x: 200, y: 200, width: 600, height: 300), + styleMask: [.titled], backing: .buffered, defer: true) + let container = NSView() + var height: CGFloat = 300 + var measured = 0 + var onMeasure: (() -> Void)? + var time: TimeInterval = 100 + var visible = true + var reduced = false + var durations: [TimeInterval] = [] + var completions: [@MainActor @Sendable () -> Void] = [] + + func controlledAnimation() { + transition.isVisible = { [unowned self] _ in visible } + transition.reduceMotion = { [unowned self] in reduced } + transition.now = { [unowned self] in time } + transition.animateGroup = { [unowned self] duration, changes, completion in + durations.append(duration) + changes() + completions.append(completion) + } + } + lazy var transition = PaneTransition(host: window.contentView!) { [unowned self] in + measured += 1 + let update = onMeasure + onMeasure = nil + update?() + var frame = window.frameRect(forContentRect: NSRect(x: 0, y: 0, width: 600, height: height)) + frame.origin = NSPoint(x: window.frame.minX, y: window.frame.maxY - frame.height) + return frame + } container: { [unowned self] in container } + + init() { + window.isReleasedWhenClosed = false + container.wantsLayer = true + container.frame = window.contentView!.bounds + window.contentView!.addSubview(container) + } + } + + @Test func aHiddenWindowTakesTheNewHeightAtOnceWithNoSnapshot() { + let rig = Rig() + rig.transition.reduceMotion = { false } + let top = rig.window.frame.maxY + let views = rig.window.contentView!.subviews.count + rig.transition.change { rig.height = 450 } + #expect(rig.window.contentLayoutRect.height == 450) + #expect(rig.window.frame.maxY == top, "the top edge stays") + #expect(!rig.transition.isAnimating) + #expect(rig.window.contentView!.subviews.count == views, "no snapshot left over the page") + #expect(rig.container.alphaValue == 1) + } + + @Test func aChangeMeasuresOnceWhenItEndsAndNestedChangesJoinIt() { + let rig = Rig() + rig.transition.change { + #expect(rig.transition.isChanging) + rig.transition.change { rig.height = 420 } + rig.transition.fit() + #expect(rig.measured == 0, "nothing measures or moves the frame mid-change") + } + #expect(!rig.transition.isChanging) + #expect(rig.measured == 1) + #expect(rig.window.contentLayoutRect.height == 420) + } + + @Test func navigationConsumedDuringMeasurementJoinsTheOriginalChange() { + let rig = Rig() + rig.controlledAnimation() + rig.onMeasure = { + #expect(rig.transition.isChanging) + rig.transition.change { rig.height = 460 } + } + rig.transition.change { rig.height = 450 } + #expect(rig.measured == 1) + #expect(rig.durations.count == 2, "one fade and one frame group, with no second flight") + #expect(!rig.transition.isChanging) + rig.transition.cancel() + #expect(rig.window.contentLayoutRect.height == 460) + } + + @Test func growthInAPageFitsTheWindow() { + let rig = Rig() + rig.height = 360 + rig.transition.fit() + #expect(rig.window.contentLayoutRect.height == 360) + #expect(!rig.transition.isAnimating) + } + + @Test func nothingToMeasureLeavesTheFrame() { + let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 600, height: 300), + styleMask: [.titled], backing: .buffered, defer: true) + window.isReleasedWhenClosed = false + let frame = window.frame + let transition = PaneTransition(host: window.contentView!) { nil } container: { nil } + transition.change {} + transition.fit() + #expect(window.frame == frame) + } + + @Test func incomingPageIsHiddenDuringSwapButStillAcceptsInput() throws { + let rig = Rig() + rig.controlledAnimation() + let button = NSButton(frame: NSRect(x: 10, y: 10, width: 100, height: 30)) + rig.container.addSubview(button) + rig.transition.change { + #expect(rig.container.alphaValue == 1) + #expect(rig.container.layer?.opacity == 0, "no incoming ink before the fade is attached") + #expect(rig.container.hitTest(NSPoint(x: 20, y: 20)) === button) + CATransaction.flush() // Even a layout-triggered commit during the swap stays hidden. + #expect(rig.container.layer?.opacity == 0) + rig.height = 450 + } + #expect(rig.container.alphaValue == 1) + #expect(rig.container.layer?.opacity == 1) + let fade = try #require(rig.container.layer?.animation(forKey: "PaneTransition.fadeIn") as? CABasicAnimation) + #expect(fade.fromValue as? Int == 0) + #expect(fade.toValue as? Int == 1) + #expect(fade.fillMode == .backwards, "the first frame is hidden even before the animation starts") + #expect(fade.beginTime == rig.time) + #expect(fade.duration == rig.durations[0]) + rig.transition.cancel() + #expect(rig.container.layer?.opacity == 1) + #expect(rig.container.layer?.animation(forKey: "PaneTransition.fadeIn") == nil) + } + + @Test(arguments: [true, false]) func retargetWaitsForBothFadeAndLatestFrame(fadeFirst: Bool) throws { + let rig = Rig() + rig.controlledAnimation() + rig.transition.change { rig.height = 450 } + #expect(rig.transition.isAnimating) + #expect(rig.container.alphaValue == 1) + let duration = try #require(rig.durations.first) + rig.time += duration / 2 + rig.height = 470 + rig.transition.fit() + #expect(rig.durations.count == 3) + #expect(abs(rig.durations[2] - duration / 2) < 0.00001) + rig.completions[1]() // AppKit cancels the original frame animation. + #expect(rig.transition.isAnimating) + rig.completions[fadeFirst ? 0 : 2]() + #expect(rig.transition.isAnimating, "the remaining visual work still owns the pins") + rig.completions[fadeFirst ? 2 : 0]() + #expect(!rig.transition.isAnimating) + #expect(rig.window.contentView!.subviews.count == 1) + } + + @Test func frameOnlyRetargetIgnoresCancelledCompletionAndKeepsPins() { + let rig = Rig() + rig.controlledAnimation() + let bottom = rig.container.bottomAnchor.constraint(equalTo: rig.window.contentView!.bottomAnchor) + bottom.isActive = true + rig.height = 450 + rig.transition.fit() + let pins = rig.window.contentView!.constraints.filter { $0.isActive && $0.firstAttribute == .top } + #expect(!pins.isEmpty) + #expect(!bottom.isActive) + rig.time += 0.05 + rig.height = 470 + rig.transition.fit() + #expect(rig.completions.count == 2) + rig.completions[0]() + #expect(rig.transition.isAnimating) + #expect(!bottom.isActive) + #expect(pins.allSatisfy { $0.isActive }, "the top pin survives the cancelled group's callback") + #expect(rig.container.constraints.contains { $0.isActive && $0.firstAttribute == .height && $0.constant == 470 }) + rig.completions[1]() + #expect(!rig.transition.isAnimating) + #expect(bottom.isActive) + #expect(pins.allSatisfy { !$0.isActive }) + } + + @Test func reentrantMeasurementRetargetsOnceAndKeepsPinsUntilLatestCompletion() { + let rig = Rig() + rig.controlledAnimation() + let bottom = rig.container.bottomAnchor.constraint(equalTo: rig.window.contentView!.bottomAnchor) + bottom.isActive = true + rig.height = 450 + rig.transition.fit() + let pins = rig.window.contentView!.constraints.filter { $0.isActive && $0.firstAttribute == .top } + #expect(!pins.isEmpty) + rig.height = 470 + rig.onMeasure = { + rig.transition.fit() + rig.height = 490 + } + rig.transition.fit() + #expect(rig.measured == 3, "the nested request gets one fresh measurement") + #expect(rig.completions.count == 2, "measurement requests coalesce into one retarget") + #expect(rig.container.constraints.contains { $0.isActive && $0.firstAttribute == .height && $0.constant == 490 }) + rig.completions[0]() + #expect(rig.transition.isAnimating) + #expect(!bottom.isActive) + #expect(pins.allSatisfy { $0.isActive }) + rig.completions[1]() + #expect(!rig.transition.isAnimating) + #expect(bottom.isActive) + #expect(pins.allSatisfy { !$0.isActive }) + } + + @Test func staleCompletionCannotLandANewerFlight() { + let rig = Rig() + rig.controlledAnimation() + rig.transition.change { rig.height = 450 } + rig.transition.change { rig.height = 400 } + #expect(rig.completions.count == 4) + rig.completions[0]() + rig.completions[1]() + #expect(rig.transition.isAnimating) + #expect(rig.window.contentView!.subviews.count == 2) + rig.completions[2]() + rig.completions[3]() + #expect(!rig.transition.isAnimating) + } + + @Test func closingDuringAFlightCleansUp() { + let rig = Rig() + rig.controlledAnimation() + let bottom = rig.container.bottomAnchor.constraint(equalTo: rig.window.contentView!.bottomAnchor) + bottom.isActive = true + rig.transition.change { rig.height = 450 } + #expect(!bottom.isActive) + rig.transition.cancel() + #expect(!rig.transition.isAnimating) + #expect(bottom.isActive) + #expect(rig.window.contentView!.subviews.count == 1) + #expect(rig.container.alphaValue == 1) + rig.completions[0]() + #expect(!rig.transition.isAnimating) + } + + @Test(arguments: [true, false]) func policyChangeDuringFlightLandsImmediately(hidden: Bool) { + let rig = Rig() + rig.controlledAnimation() + rig.transition.change { rig.height = 450 } + rig.visible = !hidden + rig.reduced = !hidden + rig.height = 470 + rig.transition.fit() + #expect(!rig.transition.isAnimating) + #expect(rig.window.contentLayoutRect.height == 470) + #expect(rig.window.contentView!.subviews.count == 1) + #expect(rig.durations.count == 2) + } + + @Test func unchangedTargetStillRechecksMotionPolicy() { + let rig = Rig() + rig.controlledAnimation() + rig.transition.change { rig.height = 450 } + rig.reduced = true + rig.transition.fit() + #expect(!rig.transition.isAnimating) + #expect(rig.window.contentView!.subviews.count == 1) + #expect(rig.durations.count == 2) + } + + @Test func snapshotIgnoresInputAndAccessibility() throws { + let rig = Rig() + rig.controlledAnimation() + rig.transition.begin() + let snapshot = try #require(rig.window.contentView!.subviews.last as? SnapshotView) + #expect(snapshot.hitTest(NSPoint(x: 10, y: 10)) == nil) + #expect(snapshot.accessibilityIsIgnored()) + #expect(!snapshot.isAccessibilityElement()) + rig.transition.end() + rig.transition.cancel() + } + + /// Settings' tabs in a hidden window: each tab's plain pane asks for its own height. + private func tabs(heights: [SettingsTab: CGFloat]) -> (SettingsTabs, NSWindow) { + let tabs = SettingsTabs() + tabs.transitionOptions = [] + for tab in SettingsTab.shown { + let pane = NSViewController() + pane.view = NSView(frame: NSRect(x: 0, y: 0, width: 600, height: 100)) + pane.preferredContentSize = NSSize(width: 600, height: heights[tab] ?? 300) + let item = NSTabViewItem(viewController: pane) + item.identifier = tab.rawValue + tabs.addTabViewItem(item) + } + let window = NSWindow(contentViewController: tabs) + window.isReleasedWhenClosed = false + tabs.pageTransition.reduceMotion = { false } + return (tabs, window) + } + + @Test func aTabChangeInAHiddenWindowLandsOnThePanesHeight() { + let (tabs, window) = tabs(heights: [.general: 320, .mouse: 480, .apps: 240, .about: 260]) + let steps: [(SettingsPane, CGFloat)] = [(.tab(.apps), 240), (.tab(.general), 320), (.mouse(.buttons), 480), (.tab(.about), 260)] + for (pane, height) in steps { + tabs.open(pane) + #expect(window.contentLayoutRect.height == height, "\(pane)") + #expect(!tabs.pageTransition.isAnimating, "\(pane)") + } + } + + @Test func visibleShowActivationAndSamePageRequestsDoNotFade() { + let (tabs, window) = tabs(heights: [.mouse: 300]) + tabs.open(.mouse(.pointer)) + defer { window.close() } + let context = SettingsContext() + context.tabs = tabs + tabs.pageTransition.isVisible = { _ in true } + var animations = 0 + tabs.pageTransition.animateGroup = { _, changes, _ in + animations += 1 + changes() + } + // The navigation path used by show(nil), show(ShowRequest()), and sheet-only requests. + context.show(nil) + context.show(ShowRequest()) + context.show(ShowRequest(pane: .tab(.mouse))) + context.show(ShowRequest(pane: .mouse(.pointer))) + context.show(ShowRequest(sheet: .presets)) + #expect(animations == 0) + #expect(!tabs.pageTransition.isAnimating) + context.show(ShowRequest(pane: .mouse(.buttons))) + #expect(animations == 2, "a different segment still transitions") + context.show(nil) + context.show(ShowRequest(pane: .mouse(.buttons))) + #expect(animations == 2, "activation leaves the existing flight alone") + tabs.pageTransition.cancel() + } + + @Test func repeatingAnAppRequestDoesNotFadeOrResetItsSegment() { + let (tabs, window) = tabs(heights: [.apps: 300]) + tabs.open(.tab(.apps)) + defer { window.close() } + let context = SettingsContext() + context.tabs = tabs + tabs.pageTransition.isVisible = { _ in true } + var animations = 0 + tabs.pageTransition.animateGroup = { _, changes, _ in + animations += 1 + changes() + } + let config = ConfigTree() + var list = AppList() + context.show(ShowRequest(app: "com.apple.Safari")) + context.openRequested(in: &list, config: config) + #expect(animations == 2) + tabs.pageTransition.cancel() + list.select(.scrolling) + context.show(ShowRequest(app: "com.apple.Safari")) + context.openRequested(in: &list, config: config) + #expect(animations == 2) + #expect(list.segment == .scrolling) + #expect(context.app == nil) + context.show(ShowRequest(app: "com.apple.TextEdit")) + context.openRequested(in: &list, config: config) + #expect(animations == 4) + #expect(list.segment == .buttons) + tabs.pageTransition.cancel() + } + + @Test func aTallPaneLandsAtTheCap() { + let (tabs, window) = tabs(heights: [.apps: 2400]) + tabs.open(.tab(.apps)) + #expect(window.contentLayoutRect.height <= SettingsWindowController.maxContentHeight) + #expect(window.contentLayoutRect.height == LazyPane.maxHeight(on: window.screen)) + } +} diff --git a/docs/development.md b/docs/development.md index 69daa3e..9a46cea 100644 --- a/docs/development.md +++ b/docs/development.md @@ -197,6 +197,19 @@ with no glass: enough to check its rows and words in either appearance. A window (`screencapture -l`) leaves out the menu's blur, so the README's menu shots take the shape and shadow from a window capture and the body from a screen capture of the same rect. +For a Settings transition, a debug helper can capture a filmstrip on the unlocked spare Mac. +Set `PUREMOUSE_DEV_FILMSTRIP` to an output directory and `PUREMOUSE_DEV_FILMSTRIP_TO` to a tab or +Mouse segment (the same names as `PUREMOUSE_DEV_PANE`), `app:`, or `back`. After the +usual capture delay it takes `000.png` before the change, then frames at about 60 Hz for +`PUREMOUSE_DEV_FILMSTRIP_SECONDS` (default 0.6), and quits. The frames are taken on a background +thread, so a window frame animated by the main thread shows as it moves, and are written at the +end with `frames.txt`, each frame's time in milliseconds from the moment the change began on the +main thread. Use the same isolated config, daemon and companion directory as other dev runs; the +window-server captures need no Screen Recording permission. Each capture takes some milliseconds, +so the spacing between frames varies; `frames.txt` has the real times. Now and then a frame catches +the window between two sizes, with a few transparent rows along its top or bottom edge: that is the +capture's timing, not the window's drawing. + ### UI matrix `scripts/ui-matrix.sh` is the repeatable run of the accessibility dump and the captures. It runs diff --git a/docs/ui-design.md b/docs/ui-design.md index 268812c..72fe955 100644 --- a/docs/ui-design.md +++ b/docs/ui-design.md @@ -37,6 +37,14 @@ answering a question people have, and a good default means most people never tou ([Sizing](#implementation)). - It reopens on the last tab and segment (`SettingsSelection`) and remembers its position, not its size: the size always comes from the pane (no frame autosave). +- **Changing page** (a tab, a Mouse segment, an app's page and back) is one transition, as in + System Settings: the old page fades out and the new one in while the window frame moves to the + new height, with one duration and curve. The page stays against the top: + the toolbar and strip hold still and the window's bottom edge covers or uncovers the page, which + never slides. Two pages of the same height only cross-fade. A height change inside a page (a + disclosure, a notice, the Apps list growing) moves the frame the same way, without a fade. The + window opens at its size with no animation; a hidden window and Reduce Motion change at once, + with no fade ([Sizing](#implementation)). - Mouse's header strip has a leading slot for the mouse pop-up (`MousePopUp`: All Mice, then each known mouse), shown with two or more mice known or any `devices` entry. Its closed text is the mouse's name, in a pop-up as wide as the name needs, up to 240 pt and the width the strip leaves it @@ -481,7 +489,32 @@ Where the rules above live in `Sources/PureMouseSettingsUI` and `Sources/PureMou `preferredContentSize` for it, which is only as fresh as the pane's last layout. Fitting the same content twice gives the same size. A pane whose height changes while shown calls `SettingsContext.refit()` (a nested `NSHostingController` updates its `preferredContentSize` - without telling the tab controller), and `fitWindow` ignores a size that is zero or not finite. + without telling the tab controller), and `SettingsTabs.fittedFrame()` ignores a size that is zero + or not finite. +- **Transitions.** `PaneTransition` (owned by `SettingsTabs`) is the one thing that moves the window + frame. A page change goes through `SettingsTabs.transition` (`open`, a toolbar click through + `tabView(_:willSelect:)` and `didSelect`, `MouseTab.transition` for segments, + `SettingsContext.transition` for an app's page and Back): it snapshots the page + (`cacheDisplay`, with the window's background left clear, so the real one shows through), makes + the change, lays out and measures once, then starts the frame (`window.animator().setFrame`) + and cross-fade in the same Core Animation transaction, with separate `NSAnimationContext` + completion groups for the frame and fade and a shared + duration from `animationResizeTime` held to 0.2–0.35 s, ease in and out. While it runs the tab + view is pinned to the top at the new height (its bottom constraints let go), so the page does not + slide. `refit()` and `preferredContentSizeDidChange` call `fit()`, the same frame animation with + no fade, retargeting one under way to its original end time; a hidden window or Reduce Motion + lands it immediately. Each frame retarget has a generation token: a cancelled group's completion + cannot remove the pins, and landing waits for both the latest frame and any fade. The incoming + page's view alpha stays at 1 for input; its layer opacity is zero during the swap. The final + layer opacity and an explicit fade from zero (with backwards fill and a layer-local start time) + are installed in one transaction, so a commit cannot expose the new page before the fade. + The snapshot ignores input and accessibility. Plain activation, a same-page request and opening + a sheet on the current page do not cross-fade; only a changed tab, segment or app page does. + Closing the window cleans up a flight; a change started mid-flight first lands the old one. The + tab controller has no transition of its own (`transitionOptions = []`) and its + `preferredContentSizeDidChange` does not reach super, which would size the window too. Grouped + forms hide their scroll background (`PaneForm`), which looks the same but lets the snapshot match + the window. The filmstrip hook checks it on screen ([development](development.md#screenshots)). A disclosure opened on a full pane scrolls rather than growing the window. `AppPage` and `AdvancedSheet` take their form caps from the same number. - **Advanced.** `PaneFooter` (Restore Defaults, Advanced…) opens an `AdvancedSheet`, which never