diff --git a/Loop/App/AppDelegate.swift b/Loop/App/AppDelegate.swift index 43b93cada..8cf1fd249 100644 --- a/Loop/App/AppDelegate.swift +++ b/Loop/App/AppDelegate.swift @@ -70,6 +70,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate { LoopSocketManager.shared.start() WindowDragManager.shared.addObservers() StashManager.shared.start() + InitialWindowFrameManager.shared.start() AccessibilityManager.requestAccess() // Wait for the app to settle before showing the update window @@ -180,6 +181,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate { LoopManager.shared.shutdown() WindowDragManager.shared.shutdown() StashManager.shared.shutdown() + InitialWindowFrameManager.shared.shutdown() LoopSocketManager.shared.shutdown() return .terminateNow } diff --git a/Loop/Extensions/Defaults+Extensions.swift b/Loop/Extensions/Defaults+Extensions.swift index daf2adeb4..62f8aeda3 100644 --- a/Loop/Extensions/Defaults+Extensions.swift +++ b/Loop/Extensions/Defaults+Extensions.swift @@ -87,6 +87,9 @@ extension Defaults.Keys { /// Excluded apps static let excludedApps = Key<[URL]>("excludedApps", default: []) + /// Maps an app's bundle identifier to the custom window action that sets its initial size and position. + static let initialWindowFrames = Key<[String: WindowAction]>("initialWindowFrames", default: [:]) + // About #if RELEASE static let includeDevelopmentVersions = Key("includeDevelopmentVersions", default: false) diff --git a/Loop/Settings Window/Settings/Behavior/BehaviorConfiguration.swift b/Loop/Settings Window/Settings/Behavior/BehaviorConfiguration.swift index 4bfc006d0..1a9783140 100644 --- a/Loop/Settings Window/Settings/Behavior/BehaviorConfiguration.swift +++ b/Loop/Settings Window/Settings/Behavior/BehaviorConfiguration.swift @@ -30,6 +30,8 @@ struct BehaviorConfigurationView: View { @State private var isPaddingConfigurationViewPresented = false + @State private var isPlacementPresented = false + var body: some View { LuminareForm { generalSection @@ -91,6 +93,15 @@ struct BehaviorConfigurationView: View { } .luminareModalCornerRadius(24) } + + LuminareButton("Initial Window Placement", "Configure…") { + isPlacementPresented = true + } + .luminareModal(isPresented: $isPlacementPresented) { + InitialWindowPlacementConfigurationView(isPresented: $isPlacementPresented) + .frame(width: 400) + } + .luminareModalCornerRadius(24) } } diff --git a/Loop/Settings Window/Settings/Behavior/InitialWindowPlacementConfigurationView.swift b/Loop/Settings Window/Settings/Behavior/InitialWindowPlacementConfigurationView.swift new file mode 100644 index 000000000..1adfff32b --- /dev/null +++ b/Loop/Settings Window/Settings/Behavior/InitialWindowPlacementConfigurationView.swift @@ -0,0 +1,134 @@ +// +// InitialWindowPlacementConfigurationView.swift +// Loop +// + +import Defaults +import Luminare +import SwiftUI + +struct InitialWindowPlacementConfigurationView: View { + @Binding var isPresented: Bool + @Default(.initialWindowFrames) private var frames + @State private var editingID: String? + @State private var draft = WindowAction(.custom) + @State private var selectedIDs = Set() + @State private var pickerError: String? + + var body: some View { + if let editingID { + CustomActionConfigurationView( + action: $draft, + // Done saves the edited placement and returns to the app list in the same modal. + isPresented: Binding( + get: { true }, + set: { presented in + guard !presented else { return } + frames[editingID] = draft + selectedIDs = [editingID] + self.editingID = nil + } + ), + placementAppName: appName(editingID) + ) + } else { + LuminareForm { + Text("Initial Window Placement") + .font(.headline) + + LuminareSection { + LuminareButtonRow { + Button("Add") { chooseApp() } + Button("Remove", role: .destructive) { + frames = frames.filter { !selectedIDs.contains($0.key) } + selectedIDs.removeAll() + } + .disabled(selectedIDs.isEmpty) + .keyboardShortcut(.delete) + } + .luminareRoundingBehavior(top: true) + + LuminareList(items: .constant(frames.keys.sorted()), selection: $selectedIDs, id: \.self) { item in + let id = item.wrappedValue + HStack(spacing: 8) { + if let url = NSWorkspace.shared.urlForApplication(withBundleIdentifier: id) { + Image(nsImage: NSWorkspace.shared.icon(forFile: url.path)) + .resizable() + .frame(width: 24, height: 24) + } else { + Image(systemName: "app") + .frame(width: 24, height: 24) + } + + Text(verbatim: appName(id)) + Spacer() + + Button { + edit(id) + } label: { + Image(systemName: "slider.horizontal.3") + } + .buttonStyle(.plain) + .accessibilityLabel("Edit placement") + .help("Edit placement") + } + .padding(.horizontal, 12) + .moveDisabled(true) + } emptyView: { + VStack { + Text("No configured apps") + .font(.title3) + Text("Click “Add” to add an app") + .font(.caption) + } + .foregroundStyle(.secondary) + .padding() + } + .luminareListFixedHeight(until: 250) + .luminareRoundingBehavior(bottom: true) + } + + if let pickerError { + Text(verbatim: pickerError) + .foregroundStyle(.secondary) + } + + Button("Done") { isPresented = false } + .buttonStyle(.luminare(overrideUseMainStyle: true)) + } + } + } + + private func appName(_ id: String) -> String { + guard let url = NSWorkspace.shared.urlForApplication(withBundleIdentifier: id) else { + return id + } + return FileManager.default.displayName(atPath: url.path) + } + + private func chooseApp() { + let panel = NSOpenPanel() + panel.allowedContentTypes = [.application] + panel.directoryURL = FileManager.default.urls(for: .applicationDirectory, in: .localDomainMask).first + pickerError = nil + guard panel.runModal() == .OK, let url = panel.url else { + return + } + guard let id = Bundle(url: url)?.bundleIdentifier else { + pickerError = String(localized: "This app has no bundle identifier.") + return + } + guard InitialWindowFrames.allowsPlacement(bundleID: id, url: url) else { + pickerError = String(localized: "Loop skips window placement for this app.") + return + } + edit(id) + } + + private func edit(_ id: String) { + draft = frames[id] ?? WindowAction(.custom) + draft.direction = .custom + draft.sizeMode = .custom + editingID = id + } +} diff --git a/Loop/Settings Window/Settings/Keybinds/Modal Views/CustomActionConfigurationView.swift b/Loop/Settings Window/Settings/Keybinds/Modal Views/CustomActionConfigurationView.swift index 3d048cee3..7db6e0853 100644 --- a/Loop/Settings Window/Settings/Keybinds/Modal Views/CustomActionConfigurationView.swift +++ b/Loop/Settings Window/Settings/Keybinds/Modal Views/CustomActionConfigurationView.swift @@ -32,6 +32,8 @@ struct CustomActionConfigurationView: View { } } + private let placementAppName: String? + private let anchors: [CustomWindowActionAnchor] = [ .topLeft, .top, .topRight, .left, .center, .right, .bottomLeft, .bottom, .bottomRight ] @@ -47,7 +49,8 @@ struct CustomActionConfigurationView: View { private let previewController = PreviewController() private let screenSize: CGSize = NSScreen.main?.frame.size ?? NSScreen.screens[0].frame.size - init(action: Binding, isPresented: Binding) { + init(action: Binding, isPresented: Binding, placementAppName: String? = nil) { + self.placementAppName = placementAppName _windowAction = action _isPresented = isPresented _action = State(initialValue: action.wrappedValue) @@ -70,16 +73,21 @@ struct CustomActionConfigurationView: View { @ViewBuilder private func configurationSections() -> some View { - LuminareSection(outerPadding: 0) { - LuminareTextField( - WindowDirection.custom.name, - text: Binding( - get: { action.name ?? "" }, - set: { action.name = $0 } + if let placementAppName { + Text(verbatim: placementAppName) + .font(.headline) + } else { + LuminareSection(outerPadding: 0) { + LuminareTextField( + WindowDirection.custom.name, + text: Binding( + get: { action.name ?? "" }, + set: { action.name = $0 } + ) ) - ) - .luminareFilledStates(.none) - .luminareBorderedStates(.none) + .luminareFilledStates(.none) + .luminareBorderedStates(.none) + } } LuminareSection(outerPadding: 0) { @@ -287,32 +295,34 @@ struct CustomActionConfigurationView: View { @ViewBuilder private func sizeConfiguration() -> some View { - LuminarePicker( - elements: CustomWindowActionSizeMode.allCases, - selection: Binding( - get: { - action.sizeMode ?? .custom - }, - set: { newValue in - withAnimation(luminareAnimation) { - action.sizeMode = newValue + if placementAppName == nil { + LuminarePicker( + elements: CustomWindowActionSizeMode.allCases, + selection: Binding( + get: { + action.sizeMode ?? .custom + }, + set: { newValue in + withAnimation(luminareAnimation) { + action.sizeMode = newValue + } } + ), + columns: 3 + ) { mode in + VStack(spacing: 4) { + mode.image + Text(mode.name) } - ), - columns: 3 - ) { mode in - VStack(spacing: 4) { - mode.image - Text(mode.name) + .padding(.vertical, 15) + .compositingGroup() } - .padding(.vertical, 15) - .compositingGroup() + .luminareContentSize(hasFixedHeight: true) + .luminareRoundingBehavior( + top: true, + bottom: action.sizeMode != .custom + ) } - .luminareContentSize(hasFixedHeight: true) - .luminareRoundingBehavior( - top: true, - bottom: action.sizeMode != .custom - ) if action.sizeMode ?? .custom == .custom { LuminareSlider( diff --git a/Loop/Window Management/Window Manipulation/InitialWindowFrameManager.swift b/Loop/Window Management/Window Manipulation/InitialWindowFrameManager.swift new file mode 100644 index 000000000..c4030d1a6 --- /dev/null +++ b/Loop/Window Management/Window Manipulation/InitialWindowFrameManager.swift @@ -0,0 +1,302 @@ +// +// InitialWindowFrameManager.swift +// Loop +// + +import Defaults +import SwiftUI + +@MainActor +final class InitialWindowFrameManager { + static let shared = InitialWindowFrameManager() + + private final class Observation { + let observer: AXObserver + var seen = Set() + var pending: [AXUIElement: (token: UUID, task: Task<(), Never>)] = [:] + + init(observer: AXObserver) { + self.observer = observer + } + } + + private var observations: [pid_t: Observation] = [:] + private var registrations: [pid_t: (token: UUID, task: Task<(), Never>)] = [:] + private var subscriptions: [Task<(), Never>] = [] + private var workspaceObservers: [NSObjectProtocol] = [] + + private init() {} + + func start() { + guard subscriptions.isEmpty else { + return + } + let frames = Defaults.updates(.initialWindowFrames, initial: false) + let exclusions = Defaults.updates(.excludedApps, initial: false) + let permission = AccessibilityManager.shared.stream(initial: false) + subscriptions = [ + Task { + for await _ in frames { + reset() + } + }, + Task { + for await _ in exclusions { + reset() + } + }, + Task { + for await _ in permission { + reset() + } + } + ] + let center = NSWorkspace.shared.notificationCenter + let launchObserver = center.addObserver( + forName: NSWorkspace.didLaunchApplicationNotification, + object: nil, + queue: .main + ) { [weak self] notification in + guard let app = notification.userInfo?[NSWorkspace.applicationUserInfoKey] as? NSRunningApplication else { + return + } + MainActor.assumeIsolated { + self?.register(app, includeExisting: true) + } + } + workspaceObservers.append(launchObserver) + let terminationObserver = center.addObserver( + forName: NSWorkspace.didTerminateApplicationNotification, + object: nil, + queue: .main + ) { [weak self] notification in + guard let app = notification.userInfo?[NSWorkspace.applicationUserInfoKey] as? NSRunningApplication else { + return + } + MainActor.assumeIsolated { + self?.remove(app.processIdentifier) + } + } + workspaceObservers.append(terminationObserver) + reset() + } + + func shutdown() { + subscriptions.forEach { $0.cancel() } + subscriptions.removeAll() + workspaceObservers.forEach { NSWorkspace.shared.notificationCenter.removeObserver($0) } + workspaceObservers.removeAll() + for pid in Set(observations.keys).union(registrations.keys) { + remove(pid) + } + } + + private func action(for app: NSRunningApplication) -> WindowAction? { + guard !subscriptions.isEmpty, + AccessibilityManager.shared.isGranted, + !app.isTerminated, + app.activationPolicy == .regular + else { + return nil + } + return InitialWindowFrames.action(for: app) + } + + private func reset() { + guard !Task.isCancelled, !subscriptions.isEmpty else { + return + } + for pid in Set(observations.keys).union(registrations.keys) { + remove(pid) + } + // Configuration changes establish a fresh baseline, never rearrange existing windows. + for app in NSWorkspace.shared.runningApplications { + register(app, includeExisting: false) + } + } + + private func remove(_ pid: pid_t) { + registrations.removeValue(forKey: pid)?.task.cancel() + guard let observation = observations.removeValue(forKey: pid) else { + return + } + observation.pending.values.forEach { $0.task.cancel() } + CFRunLoopRemoveSource(CFRunLoopGetMain(), AXObserverGetRunLoopSource(observation.observer), .commonModes) + } + + private func register(_ app: NSRunningApplication, includeExisting: Bool) { + let pid = app.processIdentifier + guard action(for: app) != nil, + observations[pid] == nil, + registrations[pid] == nil + else { + return + } + let token = UUID() + let task = Task { + defer { + if registrations[pid]?.token == token { + registrations[pid] = nil + } + } + // AX may not be ready when the workspace reports an application launch. + for delay in [Duration.zero, .milliseconds(200), .milliseconds(500), .seconds(1)] { + do { + if delay > .zero { + try await Task.sleep(for: delay) + } + } catch { + return + } + guard !Task.isCancelled, action(for: app) != nil else { + return + } + if install(app, includeExisting: includeExisting) { + return + } + } + } + registrations[pid] = (token, task) + } + + private func install(_ app: NSRunningApplication, includeExisting: Bool) -> Bool { + let pid = app.processIdentifier + let application = AXUIElementCreateApplication(pid) + AXUIElementSetMessagingTimeout(application, 0.1) + var observer: AXObserver? + let result = AXObserverCreate(pid, { observer, element, notification, _ in + MainActor.assumeIsolated { + InitialWindowFrameManager.shared.receive(observer, element: element, notification: notification as String) + } + }, &observer) + guard result == .success, + let observer, + AXObserverAddNotification(observer, application, kAXWindowCreatedNotification as CFString, nil) == .success + else { + return false + } + guard let windows: [AXUIElement] = try? application.getValue(.windows) else { + AXObserverRemoveNotification(observer, application, kAXWindowCreatedNotification as CFString) + return false + } + let observation = Observation(observer: observer) + if !includeExisting { + observation.seen = Set(windows) + } + observations[pid] = observation + CFRunLoopAddSource(CFRunLoopGetMain(), AXObserverGetRunLoopSource(observer), .commonModes) + for window in windows { + AXObserverAddNotification(observer, window, kAXUIElementDestroyedNotification as CFString, nil) + if includeExisting { + created(window, app: app, observation: observation) + } + } + return true + } + + private func receive(_ observer: AXObserver, element: AXUIElement, notification: String) { + guard let (pid, observation) = observations.first(where: { CFEqual($0.value.observer, observer) }) else { + return + } + if notification == kAXUIElementDestroyedNotification { + observation.pending.removeValue(forKey: element)?.task.cancel() + observation.seen.remove(element) + } else if notification == kAXWindowCreatedNotification, let app = NSRunningApplication(processIdentifier: pid) { + AXObserverAddNotification(observer, element, kAXUIElementDestroyedNotification as CFString, nil) + created(element, app: app, observation: observation) + } + } + + private func readableFrame(_ element: AXUIElement) -> CGRect? { + guard let position: CGPoint = try? element.getValue(.position), + let size: CGSize = try? element.getValue(.size), + [position.x, position.y, size.width, size.height].allSatisfy(\.isFinite), + size.width > 0, + size.height > 0 + else { + return nil + } + return CGRect(origin: position, size: size) + } + + private func created(_ element: AXUIElement, app: NSRunningApplication, observation: Observation) { + guard observation.seen.insert(element).inserted, let configured = action(for: app) else { + return + } + AXUIElementSetMessagingTimeout(element, 0.1) + var initialFrame = readableFrame(element) + let pid = app.processIdentifier + let token = UUID() + let task = Task { + defer { + if observation.pending[element]?.token == token { + observation.pending[element] = nil + } + } + _ = await InitialWindowFrames.waitUntilReady { + guard observations[pid] === observation, action(for: app) == configured else { + return .skip + } + guard let frame = readableFrame(element) else { + return .wait + } + if let initialFrame, initialFrame != frame { + return .skip + } + initialFrame = frame + do { + guard let role: String = try element.getValue(.subrole), + let minimized: Bool = try element.getValue(.minimized) + else { + return .wait + } + let fullscreen: Bool = try element.getValue(.fullScreen) ?? false + guard role == NSAccessibility.Subrole.standardWindow.rawValue, + !minimized, + !fullscreen + else { + return .skip + } + // Native tabs can publish a new AX window even though the user + // is still in the same window. Do not reposition the tab group. + guard try !InitialWindowFrames.hasMultipleWindowTabs(element) else { + return .skip + } + // Window.isResizable returns true on AX errors; automatic placement must wait instead. + guard try element.canSetValue(.size), + let candidate = try? Window(element: element, pid: pid) + else { + return .wait + } + guard readableFrame(element) == frame else { + return .skip + } + return place(candidate) + } catch { + return .wait + } + } + } + observation.pending[element] = (token, task) + } + + private func place(_ window: Window) -> InitialWindowFrames.Readiness { + guard let screen = ScreenUtility.screenContaining(window), + let (frame, bounds) = InitialWindowFrames.frame(for: window, on: screen) + else { + return .skip + } + window.setFrameSynchronously(frame) + guard let applied = readableFrame(window.axWindow) else { + return .skip + } + _ = WindowEngine.handleSizeConstrainedWindow( + window: window, + actualFrame: applied, + targetFrame: frame, + bounds: bounds, + resolvedProperties: nil + ) + return .ready + } +} diff --git a/Loop/Window Management/Window Manipulation/InitialWindowFrames.swift b/Loop/Window Management/Window Manipulation/InitialWindowFrames.swift new file mode 100644 index 000000000..c4480f234 --- /dev/null +++ b/Loop/Window Management/Window Manipulation/InitialWindowFrames.swift @@ -0,0 +1,120 @@ +// +// InitialWindowFrames.swift +// Loop +// + +import AppKit +import Defaults + +enum InitialWindowFrames { + static func allowsPlacement(bundleID: String, url: URL) -> Bool { + bundleID != Bundle.main.bundleIdentifier && !Defaults[.excludedApps].contains(url) + } + + /// Returns an app's configured initial frame action without changing any windows. + /// Dynamic size modes depend on a window's current size or action history. + static func action(for app: NSRunningApplication) -> WindowAction? { + guard let id = app.bundleIdentifier, + let url = app.bundleURL, + allowsPlacement(bundleID: id, url: url), + let action = Defaults[.initialWindowFrames][id], + action.direction == .custom, + action.sizeMode == .custom + else { + return nil + } + return action + } + + /// Calculates the configured frame on the supplied display without resizing the window. + /// Uses actual window properties so pixel dimensions are not scaled as an editor preview. + static func frame(for window: Window, on screen: NSScreen) -> (frame: CGRect, bounds: CGRect)? { + guard let app = window.nsRunningApplication, let action = action(for: app) else { + return nil + } + let properties = Window.ResolvedProperties(from: window) + let context = ResizeContext(window: window, initialFrame: properties.frame, screen: screen, action: action) + context.resolvedWindowProperties = properties + guard let frame = placementFrame(in: context) else { + return nil + } + return (frame, context.paddedBounds) + } + + /// Use the same padded target as a custom action invoked by a keybind. + static func placementFrame(in context: ResizeContext) -> CGRect? { + let target = context.getTargetFrame() + // The resolver also returns zero for invalid geometry. Only forward an explicitly requested zero. + guard target.raw.size.width > 0 || context.action.width == 0, + target.raw.size.height > 0 || context.action.height == 0 + else { + return nil + } + return constrain(target.padded, to: context.paddedBounds) + } + + /// Keep the requested frame within the display's usable area. + static func constrain(_ frame: CGRect, to bounds: CGRect) -> CGRect? { + guard frame.isFinite, + bounds.isFinite, + frame.size.width >= 0, + frame.size.height >= 0, + bounds.size.width > 0, + bounds.size.height > 0 + else { + return nil + } + var result = frame + result.size = CGSize(width: min(frame.width, bounds.width), height: min(frame.height, bounds.height)) + return result.pushInside(bounds) + } + + enum Readiness { + case wait + case skip + case ready + } + + /// Check direct window children only; do not search through app content. + static func hasMultipleWindowTabs(_ window: AXUIElement) throws -> Bool { + let children: [AXUIElement] = try window.getValue(.children) ?? [] + for child in children { + let error = AXUIElementSetMessagingTimeout(child, 0.1) + guard error == .success else { + throw error + } + let role: String? = try child.getValue(.role) + guard role == NSAccessibility.Role.tabGroup.rawValue else { + continue + } + let tabs: [AXUIElement] = try child.getValue(.tabs) ?? [] + if tabs.count > 1 { + return true + } + } + return false + } + + /// Wait briefly for accessibility readiness; cancellation ends the wait. + @MainActor + static func waitUntilReady(_ check: () -> Readiness) async -> Bool { + for delay in [Duration.zero, .milliseconds(25), .milliseconds(75), .milliseconds(250)] { + do { + if delay > .zero { + try await Task.sleep(for: delay) + } + } catch { + return false + } + guard !Task.isCancelled else { + return false + } + switch check() { + case .wait: continue + case .skip: return false + case .ready: return !Task.isCancelled + } + } + return false + } +} diff --git a/Loop/Window Management/Window Manipulation/WindowEngine.swift b/Loop/Window Management/Window Manipulation/WindowEngine.swift index 2ab3b8490..93671774a 100644 --- a/Loop/Window Management/Window Manipulation/WindowEngine.swift +++ b/Loop/Window Management/Window Manipulation/WindowEngine.swift @@ -230,7 +230,7 @@ enum WindowEngine { // MARK: - Size Constraints - private static func handleSizeConstrainedWindow( + static func handleSizeConstrainedWindow( window: Window, actualFrame: CGRect, targetFrame: CGRect, diff --git a/LoopTests/InitialWindowPlacementTests.swift b/LoopTests/InitialWindowPlacementTests.swift new file mode 100644 index 000000000..90eeb7274 --- /dev/null +++ b/LoopTests/InitialWindowPlacementTests.swift @@ -0,0 +1,100 @@ +// +// InitialWindowPlacementTests.swift +// LoopTests +// + +@testable import Loop +import SwiftUI +import Testing + +struct InitialWindowPlacementTests { + @Test func coordinatePlacementMatchesCustomActionAtTheRightEdge() { + let bounds = CGRect(x: -1000, y: 0, width: 1000, height: 800) + let action = WindowAction( + .custom, + keybind: [], + unit: .percentage, + width: 50, + height: 50, + xPoint: 80, + yPoint: 0, + positionMode: .coordinates, + sizeMode: .custom + ) + let context = ResizeContext(bounds: bounds, padding: .zero, action: action) + let customFrame = context.getTargetFrame().padded + #expect(customFrame == CGRect(x: -200, y: 0, width: 200, height: 400)) + #expect(InitialWindowFrames.placementFrame(in: context) == customFrame) + } + + @Test(arguments: [CGSize(width: 0, height: 50), CGSize(width: 50, height: 0), .zero]) + func explicitZeroDimensionsReachTheWindowSetter(_ size: CGSize) { + let bounds = CGRect(x: 0, y: 0, width: 1000, height: 800) + let action = WindowAction( + .custom, + keybind: [], + unit: .percentage, + width: size.width, + height: size.height, + positionMode: .coordinates, + sizeMode: .custom + ) + let context = ResizeContext(bounds: bounds, padding: .zero, action: action) + let target = InitialWindowFrames.placementFrame(in: context) + #expect(target?.size == CGSize(width: size.width * 10, height: size.height * 8)) + } + + @Test func frameStaysReachableOnASecondaryDisplay() { + let bounds = CGRect(x: -1600, y: 25, width: 1600, height: 1000) + let oversized = CGRect(x: -1800, y: -100, width: 2000, height: 1200) + #expect(InitialWindowFrames.constrain(oversized, to: bounds) == bounds) + #expect(InitialWindowFrames.constrain(CGRect(x: 100, y: 900, width: 800, height: 600), to: bounds) + == CGRect(x: -800, y: 425, width: 800, height: 600)) + #expect(InitialWindowFrames.constrain(CGRect(x: 0, y: 0, width: -800, height: 600), to: bounds) == nil) + } + + @Test @MainActor func retriesAnInitiallyNonresizableWindow() async { + var attempts = 0 + let ready = await InitialWindowFrames.waitUntilReady { + attempts += 1 + return attempts == 1 ? .wait : .ready + } + #expect(ready) + #expect(attempts == 2) + } + + @Test @MainActor func skipStopsImmediatelyAndWaitingIsBounded() async { + var skipped = 0 + let shouldSkip = await InitialWindowFrames.waitUntilReady { + skipped += 1 + return .skip + } + var waited = 0 + let neverReady = await InitialWindowFrames.waitUntilReady { + waited += 1 + return .wait + } + #expect(!shouldSkip && skipped == 1) + #expect(!neverReady && waited == 4) + } + + @Test @MainActor func cancellationStopsPendingPlacement() async { + var attempts = 0 + var task: Task? + await withCheckedContinuation { continuation in + task = Task { + await InitialWindowFrames.waitUntilReady { + attempts += 1 + if attempts == 1 { + continuation.resume() + } + return attempts == 1 ? .wait : .ready + } + } + } + task?.cancel() + let ready = await task?.value + #expect(ready == false) + #expect(attempts == 1) + } +}