From f15f3d0d63867031cc8135366fbef29ff1a232b5 Mon Sep 17 00:00:00 2001 From: Mars-den <338431790+Mars-den@users.noreply.github.com> Date: Sat, 31 Oct 2026 04:44:43 +0400 Subject: [PATCH 1/7] =?UTF-8?q?=E2=9C=A8=20Add=20opt-in=20automatic=20init?= =?UTF-8?q?ial=20window=20placement?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Loop/App/AppDelegate.swift | 2 + Loop/Extensions/Defaults+Extensions.swift | 3 + .../InitialWindowFrameManager.swift | 178 ++++++++++++++++++ .../InitialWindowFrames.swift | 53 ++++++ .../Window Manipulation/WindowEngine.swift | 8 +- Loop/Window Management/Window/Window.swift | 4 +- LoopTests/InitialWindowPlacementTests.swift | 59 ++++++ README.md | 6 + 8 files changed, 310 insertions(+), 3 deletions(-) create mode 100644 Loop/Window Management/Window Manipulation/InitialWindowFrameManager.swift create mode 100644 Loop/Window Management/Window Manipulation/InitialWindowFrames.swift create mode 100644 LoopTests/InitialWindowPlacementTests.swift diff --git a/Loop/App/AppDelegate.swift b/Loop/App/AppDelegate.swift index 29458cf77..fe5fe3642 100644 --- a/Loop/App/AppDelegate.swift +++ b/Loop/App/AppDelegate.swift @@ -68,6 +68,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate { LoopManager.shared.start() WindowDragManager.shared.addObservers() StashManager.shared.start() + InitialWindowFrameManager.shared.start() AccessibilityManager.requestAccess() // Wait for the app to settle before showing the update window @@ -179,6 +180,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate { LoopManager.shared.shutdown() WindowDragManager.shared.shutdown() StashManager.shared.shutdown() + InitialWindowFrameManager.shared.shutdown() return .terminateNow } diff --git a/Loop/Extensions/Defaults+Extensions.swift b/Loop/Extensions/Defaults+Extensions.swift index daf2adeb4..d9e7d94f0 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: []) + /// Initial geometry by app bundle ID, using the existing custom-action model. + static let initialWindowFrames = Key<[String: WindowAction]>("initialWindowFrames", default: [:]) + // About #if RELEASE static let includeDevelopmentVersions = Key("includeDevelopmentVersions", default: false) diff --git a/Loop/Window Management/Window Manipulation/InitialWindowFrameManager.swift b/Loop/Window Management/Window Manipulation/InitialWindowFrameManager.swift new file mode 100644 index 000000000..c7bb10d56 --- /dev/null +++ b/Loop/Window Management/Window Manipulation/InitialWindowFrameManager.swift @@ -0,0 +1,178 @@ +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 + workspaceObservers.append(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(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) } + }) + 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? + guard AXObserverCreate(pid, { observer, element, notification, _ in + MainActor.assumeIsolated { + InitialWindowFrameManager.shared.receive(observer, element: element, notification: notification as String) + } + }, &observer) == .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 } + // 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, placement: .init(bounds: bounds, willChangeScreens: false)) + 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..e8568ffbb --- /dev/null +++ b/Loop/Window Management/Window Manipulation/InitialWindowFrames.swift @@ -0,0 +1,53 @@ +import AppKit +import Defaults + +enum InitialWindowFrames { + /// 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, id != Bundle.main.bundleIdentifier, + let url = app.bundleURL, !Defaults[.excludedApps].contains(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 = constrain(context.getTargetFrame().padded, to: context.paddedBounds) else { return nil } + return (frame, 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, skip, ready } + + /// 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 130ea55b4..738a8690e 100644 --- a/Loop/Window Management/Window Manipulation/WindowEngine.swift +++ b/Loop/Window Management/Window Manipulation/WindowEngine.swift @@ -217,7 +217,7 @@ enum WindowEngine { // MARK: - Size Constraints - private static func handleSizeConstrainedWindow( + static func handleSizeConstrainedWindow( window: Window, actualFrame: CGRect, targetFrame: CGRect, @@ -349,7 +349,11 @@ enum WindowEngine { frame.origin.y = requestedFrame.midY - actualSize.height / 2 } - return frame.pushInside(bounds) + frame = frame.pushInside(bounds) + // Keep the title bar reachable when an app's minimum size exceeds the display. + frame.origin.x = max(bounds.minX, frame.minX) + frame.origin.y = max(bounds.minY, frame.minY) + return frame } static func shouldAnchorDuringAnimation( diff --git a/Loop/Window Management/Window/Window.swift b/Loop/Window Management/Window/Window.swift index b15762ffc..59d3b38ec 100644 --- a/Loop/Window Management/Window/Window.swift +++ b/Loop/Window Management/Window/Window.swift @@ -558,8 +558,10 @@ final class Window { } } + /// - Parameter placement: When `nil`, the window is moved, then resized. func setFrameSynchronously( _ rect: CGRect, + placement: FramePlacement? = nil, resolvedProperties: ResolvedProperties? = nil ) { guard !applyOwnWindowFrameSynchronously(rect) else { @@ -569,7 +571,7 @@ final class Window { let shouldSetSize = resolvedProperties?.isResizable ?? true performFrameAdjustment(resolvedProperties: resolvedProperties) { - writeChangedFrame(rect, with: $0, placement: nil, shouldSetSize: shouldSetSize) + writeChangedFrame(rect, with: $0, placement: placement, shouldSetSize: shouldSetSize) } } diff --git a/LoopTests/InitialWindowPlacementTests.swift b/LoopTests/InitialWindowPlacementTests.swift new file mode 100644 index 000000000..5853f71b4 --- /dev/null +++ b/LoopTests/InitialWindowPlacementTests.swift @@ -0,0 +1,59 @@ +@testable import Loop +import SwiftUI +import Testing + +struct InitialWindowPlacementTests { + @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(WindowEngine.anchoredFrame(for: oversized.size, within: bounds, targetEdges: [.trailing, .bottom], bounds: bounds) + == CGRect(x: -1600, y: 25, width: 2000, height: 1200)) + #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) + } +} diff --git a/README.md b/README.md index 8471ee803..fad04e94e 100644 --- a/README.md +++ b/README.md @@ -48,6 +48,12 @@ The preview window enables you to see the resize action *before* committing to i
+### Initial window frames (local development) + +Entries in `Defaults[.initialWindowFrames]` map app bundle IDs to custom `WindowAction` values with `sizeMode: .custom`. Each entry opts that app into automatic initial placement; removing it stops observation. No settings UI is included yet. + +Only new standard, resizable windows are placed on their current display. Existing, excluded, minimized and fullscreen windows are left alone. Placement does not activate the app or change Undo history. Registration retries are bounded; window readiness is checked immediately, then after cumulative waits of 25, 100 and 350 ms, provided the frame has not changed. + ### Keyboard Shortcuts Loop allows you to assign any key in tandem with the trigger key to initiate a window manipulation action. From 42d4e029ce92a976bb970e43f02919e468fea268 Mon Sep 17 00:00:00 2001 From: Mars-den <338431790+Mars-den@users.noreply.github.com> Date: Sun, 1 Nov 2026 04:31:30 +0400 Subject: [PATCH 2/7] Fix initial placement recentering native tabbed windows Skip automatic placement when a direct accessibility tab group contains multiple tabs. Bound child accessibility calls and document the conservative exclusion of new or restored multi-tab windows. AI-assisted with OpenAI ChatGPT. Manually reviewed and approved by the author; author verified behavior with Finder and Ghostty. --- .../InitialWindowFrameManager.swift | 3 +++ .../Window Manipulation/InitialWindowFrames.swift | 14 ++++++++++++++ README.md | 2 ++ 3 files changed, 19 insertions(+) diff --git a/Loop/Window Management/Window Manipulation/InitialWindowFrameManager.swift b/Loop/Window Management/Window Manipulation/InitialWindowFrameManager.swift index c7bb10d56..e52fac4ac 100644 --- a/Loop/Window Management/Window Manipulation/InitialWindowFrameManager.swift +++ b/Loop/Window Management/Window Manipulation/InitialWindowFrameManager.swift @@ -151,6 +151,9 @@ final class InitialWindowFrameManager { 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 } diff --git a/Loop/Window Management/Window Manipulation/InitialWindowFrames.swift b/Loop/Window Management/Window Manipulation/InitialWindowFrames.swift index e8568ffbb..26247c680 100644 --- a/Loop/Window Management/Window Manipulation/InitialWindowFrames.swift +++ b/Loop/Window Management/Window Manipulation/InitialWindowFrames.swift @@ -34,6 +34,20 @@ enum InitialWindowFrames { enum Readiness { case wait, skip, 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 { diff --git a/README.md b/README.md index fad04e94e..0e4ba05fd 100644 --- a/README.md +++ b/README.md @@ -54,6 +54,8 @@ Entries in `Defaults[.initialWindowFrames]` map app bundle IDs to custom `Window Only new standard, resizable windows are placed on their current display. Existing, excluded, minimized and fullscreen windows are left alone. Placement does not activate the app or change Undo history. Registration retries are bounded; window readiness is checked immediately, then after cumulative waits of 25, 100 and 350 ms, provided the frame has not changed. +Windows exposing a top-level multi-tab bar are also left alone: opening a native tab can report a new accessibility window without creating a separate visible window. This conservatively skips newly opened or restored multi-tab windows too. + ### Keyboard Shortcuts Loop allows you to assign any key in tandem with the trigger key to initiate a window manipulation action. From 03751f1324bf01a8dea7ff931d15cd18b7da5800 Mon Sep 17 00:00:00 2001 From: Kai Azim Date: Sat, 21 Nov 2026 23:11:18 -0600 Subject: [PATCH 3/7] =?UTF-8?q?=F0=9F=8E=A8=20Keep=20initial=20placement?= =?UTF-8?q?=20out=20of=20shared=20window=20code?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Use the existing setFrameSynchronously instead of changing it, and let handleSizeConstrainedWindow correct the position - Leave anchoredFrame unchanged, as it runs for every resize - Drop the README section for the hidden initialWindowFrames key --- .../Window Manipulation/InitialWindowFrameManager.swift | 2 +- .../Window Manipulation/WindowEngine.swift | 6 +----- Loop/Window Management/Window/Window.swift | 4 +--- LoopTests/InitialWindowPlacementTests.swift | 2 -- README.md | 8 -------- 5 files changed, 3 insertions(+), 19 deletions(-) diff --git a/Loop/Window Management/Window Manipulation/InitialWindowFrameManager.swift b/Loop/Window Management/Window Manipulation/InitialWindowFrameManager.swift index e52fac4ac..34aa0e29d 100644 --- a/Loop/Window Management/Window Manipulation/InitialWindowFrameManager.swift +++ b/Loop/Window Management/Window Manipulation/InitialWindowFrameManager.swift @@ -167,7 +167,7 @@ final class InitialWindowFrameManager { 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, placement: .init(bounds: bounds, willChangeScreens: false)) + window.setFrameSynchronously(frame) guard let applied = readableFrame(window.axWindow) else { return .skip } _ = WindowEngine.handleSizeConstrainedWindow( window: window, diff --git a/Loop/Window Management/Window Manipulation/WindowEngine.swift b/Loop/Window Management/Window Manipulation/WindowEngine.swift index 738a8690e..2374f4eda 100644 --- a/Loop/Window Management/Window Manipulation/WindowEngine.swift +++ b/Loop/Window Management/Window Manipulation/WindowEngine.swift @@ -349,11 +349,7 @@ enum WindowEngine { frame.origin.y = requestedFrame.midY - actualSize.height / 2 } - frame = frame.pushInside(bounds) - // Keep the title bar reachable when an app's minimum size exceeds the display. - frame.origin.x = max(bounds.minX, frame.minX) - frame.origin.y = max(bounds.minY, frame.minY) - return frame + return frame.pushInside(bounds) } static func shouldAnchorDuringAnimation( diff --git a/Loop/Window Management/Window/Window.swift b/Loop/Window Management/Window/Window.swift index 59d3b38ec..b15762ffc 100644 --- a/Loop/Window Management/Window/Window.swift +++ b/Loop/Window Management/Window/Window.swift @@ -558,10 +558,8 @@ final class Window { } } - /// - Parameter placement: When `nil`, the window is moved, then resized. func setFrameSynchronously( _ rect: CGRect, - placement: FramePlacement? = nil, resolvedProperties: ResolvedProperties? = nil ) { guard !applyOwnWindowFrameSynchronously(rect) else { @@ -571,7 +569,7 @@ final class Window { let shouldSetSize = resolvedProperties?.isResizable ?? true performFrameAdjustment(resolvedProperties: resolvedProperties) { - writeChangedFrame(rect, with: $0, placement: placement, shouldSetSize: shouldSetSize) + writeChangedFrame(rect, with: $0, placement: nil, shouldSetSize: shouldSetSize) } } diff --git a/LoopTests/InitialWindowPlacementTests.swift b/LoopTests/InitialWindowPlacementTests.swift index 5853f71b4..40e6993c5 100644 --- a/LoopTests/InitialWindowPlacementTests.swift +++ b/LoopTests/InitialWindowPlacementTests.swift @@ -7,8 +7,6 @@ struct InitialWindowPlacementTests { 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(WindowEngine.anchoredFrame(for: oversized.size, within: bounds, targetEdges: [.trailing, .bottom], bounds: bounds) - == CGRect(x: -1600, y: 25, width: 2000, height: 1200)) #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) diff --git a/README.md b/README.md index 0e4ba05fd..8471ee803 100644 --- a/README.md +++ b/README.md @@ -48,14 +48,6 @@ The preview window enables you to see the resize action *before* committing to i
-### Initial window frames (local development) - -Entries in `Defaults[.initialWindowFrames]` map app bundle IDs to custom `WindowAction` values with `sizeMode: .custom`. Each entry opts that app into automatic initial placement; removing it stops observation. No settings UI is included yet. - -Only new standard, resizable windows are placed on their current display. Existing, excluded, minimized and fullscreen windows are left alone. Placement does not activate the app or change Undo history. Registration retries are bounded; window readiness is checked immediately, then after cumulative waits of 25, 100 and 350 ms, provided the frame has not changed. - -Windows exposing a top-level multi-tab bar are also left alone: opening a native tab can report a new accessibility window without creating a separate visible window. This conservatively skips newly opened or restored multi-tab windows too. - ### Keyboard Shortcuts Loop allows you to assign any key in tandem with the trigger key to initiate a window manipulation action. From aa89b2af7fcce0c81ad8a30d7d7f8f8058bf2229 Mon Sep 17 00:00:00 2001 From: Mars-den <338431790+Mars-den@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:11:08 +0400 Subject: [PATCH 4/7] =?UTF-8?q?=F0=9F=8E=A8=20Match=20Loop=20style=20for?= =?UTF-8?q?=20initial=20window=20placement?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Expand dense guards and observer setup - Add headers to the new Swift files - Clarify what initialWindowFrames stores AI-assisted with OpenAI Codex for the style edits and verification. --- Loop/Extensions/Defaults+Extensions.swift | 2 +- .../InitialWindowFrameManager.swift | 219 ++++++++++++++---- .../InitialWindowFrames.swift | 66 ++++-- LoopTests/InitialWindowPlacementTests.swift | 9 +- 4 files changed, 231 insertions(+), 65 deletions(-) diff --git a/Loop/Extensions/Defaults+Extensions.swift b/Loop/Extensions/Defaults+Extensions.swift index d9e7d94f0..62f8aeda3 100644 --- a/Loop/Extensions/Defaults+Extensions.swift +++ b/Loop/Extensions/Defaults+Extensions.swift @@ -87,7 +87,7 @@ extension Defaults.Keys { /// Excluded apps static let excludedApps = Key<[URL]>("excludedApps", default: []) - /// Initial geometry by app bundle ID, using the existing custom-action model. + /// 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 diff --git a/Loop/Window Management/Window Manipulation/InitialWindowFrameManager.swift b/Loop/Window Management/Window Manipulation/InitialWindowFrameManager.swift index 34aa0e29d..c4030d1a6 100644 --- a/Loop/Window Management/Window Manipulation/InitialWindowFrameManager.swift +++ b/Loop/Window Management/Window Manipulation/InitialWindowFrameManager.swift @@ -1,3 +1,8 @@ +// +// InitialWindowFrameManager.swift +// Loop +// + import Defaults import SwiftUI @@ -23,24 +28,56 @@ final class InitialWindowFrameManager { private init() {} func start() { - guard subscriptions.isEmpty else { return } + 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() } } + Task { + for await _ in frames { + reset() + } + }, + Task { + for await _ in exclusions { + reset() + } + }, + Task { + for await _ in permission { + reset() + } + } ] let center = NSWorkspace.shared.notificationCenter - workspaceObservers.append(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(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) } - }) + 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() } @@ -49,42 +86,74 @@ final class InitialWindowFrameManager { subscriptions.removeAll() workspaceObservers.forEach { NSWorkspace.shared.notificationCenter.removeObserver($0) } workspaceObservers.removeAll() - for pid in Set(observations.keys).union(registrations.keys) { remove(pid) } + 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 } + 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) } + 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) } + 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 } + 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 } + 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 } } + 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 } + 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) @@ -95,29 +164,40 @@ final class InitialWindowFrameManager { let application = AXUIElementCreateApplication(pid) AXUIElementSetMessagingTimeout(application, 0.1) var observer: AXObserver? - guard AXObserverCreate(pid, { observer, element, notification, _ in - MainActor.assumeIsolated { - InitialWindowFrameManager.shared.receive(observer, element: element, notification: notification as String) - } - }, &observer) == .success, let observer, - AXObserverAddNotification(observer, application, kAXWindowCreatedNotification as CFString, nil) == .success else { return false } + 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) } + 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) } + 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 } + 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) @@ -128,37 +208,73 @@ final class InitialWindowFrameManager { } 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 } + 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 } + 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 } } + 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 } + 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 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 } + 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 } + 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 } + 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 } + } catch { + return .wait + } } } observation.pending[element] = (token, task) @@ -166,9 +282,14 @@ final class InitialWindowFrameManager { 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 } + let (frame, bounds) = InitialWindowFrames.frame(for: window, on: screen) + else { + return .skip + } window.setFrameSynchronously(frame) - guard let applied = readableFrame(window.axWindow) else { return .skip } + guard let applied = readableFrame(window.axWindow) else { + return .skip + } _ = WindowEngine.handleSizeConstrainedWindow( window: window, actualFrame: applied, diff --git a/Loop/Window Management/Window Manipulation/InitialWindowFrames.swift b/Loop/Window Management/Window Manipulation/InitialWindowFrames.swift index 26247c680..e4bfee0a3 100644 --- a/Loop/Window Management/Window Manipulation/InitialWindowFrames.swift +++ b/Loop/Window Management/Window Manipulation/InitialWindowFrames.swift @@ -1,3 +1,8 @@ +// +// InitialWindowFrames.swift +// Loop +// + import AppKit import Defaults @@ -5,45 +10,72 @@ enum InitialWindowFrames { /// 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, id != Bundle.main.bundleIdentifier, - let url = app.bundleURL, !Defaults[.excludedApps].contains(url), + guard let id = app.bundleIdentifier, + id != Bundle.main.bundleIdentifier, + let url = app.bundleURL, + !Defaults[.excludedApps].contains(url), let action = Defaults[.initialWindowFrames][id], - action.direction == .custom, action.sizeMode == .custom else { return nil } + 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 } + 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 = constrain(context.getTargetFrame().padded, to: context.paddedBounds) else { return nil } + guard let frame = constrain(context.getTargetFrame().padded, to: context.paddedBounds) else { + return nil + } return (frame, 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 } + 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, skip, ready } + 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 } + guard error == .success else { + throw error + } let role: String? = try child.getValue(.role) - guard role == NSAccessibility.Role.tabGroup.rawValue else { continue } + guard role == NSAccessibility.Role.tabGroup.rawValue else { + continue + } let tabs: [AXUIElement] = try child.getValue(.tabs) ?? [] - if tabs.count > 1 { return true } + if tabs.count > 1 { + return true + } } return false } @@ -53,9 +85,15 @@ enum InitialWindowFrames { 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 } + 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 diff --git a/LoopTests/InitialWindowPlacementTests.swift b/LoopTests/InitialWindowPlacementTests.swift index 40e6993c5..986751bf8 100644 --- a/LoopTests/InitialWindowPlacementTests.swift +++ b/LoopTests/InitialWindowPlacementTests.swift @@ -1,3 +1,8 @@ +// +// InitialWindowPlacementTests.swift +// LoopTests +// + @testable import Loop import SwiftUI import Testing @@ -44,7 +49,9 @@ struct InitialWindowPlacementTests { task = Task { await InitialWindowFrames.waitUntilReady { attempts += 1 - if attempts == 1 { continuation.resume() } + if attempts == 1 { + continuation.resume() + } return attempts == 1 ? .wait : .ready } } From b1eaa3fd5b2d59191a1d10dab74cc092b8353669 Mon Sep 17 00:00:00 2001 From: Mars-den <338431790+Mars-den@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:22:01 +0400 Subject: [PATCH 5/7] =?UTF-8?q?=E2=9C=A8=20Configure=20per-app=20initial?= =?UTF-8?q?=20window=20placement=20in=20Behavior=20settings?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Use a single modal to manage apps and edit their initial window frames with the existing custom action editor. AI-assisted with OpenAI Codex for implementation and build verification. --- .../Behavior/BehaviorConfiguration.swift | 11 ++ ...tialWindowPlacementConfigurationView.swift | 135 ++++++++++++++++++ .../CustomActionConfigurationView.swift | 74 +++++----- 3 files changed, 188 insertions(+), 32 deletions(-) create mode 100644 Loop/Settings Window/Settings/Behavior/InitialWindowPlacementConfigurationView.swift 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..cf6d47198 --- /dev/null +++ b/Loop/Settings Window/Settings/Behavior/InitialWindowPlacementConfigurationView.swift @@ -0,0 +1,135 @@ +// +// 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 appIDs: [String] = [] + @State private var selectedIDs = Set() + @State private var pickerError: String? + + var body: some View { + if let editingID { + CustomActionConfigurationView( + action: $draft, + 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: $appIDs, 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) + } 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) + .task(id: frames.keys.sorted()) { + let ids = frames.keys.sorted() + appIDs.removeAll { !ids.contains($0) } + appIDs.append(contentsOf: ids.filter { !appIDs.contains($0) }) + selectedIDs.formIntersection(ids) + } + } + + 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 id != Bundle.main.bundleIdentifier, !Defaults[.excludedApps].contains(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, keybind: [], unit: .percentage, anchor: .center, width: 80, height: 80, positionMode: .generic, sizeMode: .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( From 92d09a9cf4620902fa52cef67a9c53b90f28af1b Mon Sep 17 00:00:00 2001 From: Mars-den <338431790+Mars-den@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:48:14 +0400 Subject: [PATCH 6/7] =?UTF-8?q?=F0=9F=90=9E=20Preserve=20initial=20window?= =?UTF-8?q?=20size=20at=20display=20edges?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fit the requested frame before applying inner padding and pass explicit zero dimensions through to the window setter. Cover both cases with placement tests. Use the custom editor defaults, share the app exclusion check, and disable drag reordering in the placement list. AI-assisted with OpenAI Codex for implementation and verification. --- ...tialWindowPlacementConfigurationView.swift | 23 ++++++------- .../InitialWindowFrames.swift | 34 ++++++++++++++++--- LoopTests/InitialWindowPlacementTests.swift | 34 +++++++++++++++++++ 3 files changed, 74 insertions(+), 17 deletions(-) diff --git a/Loop/Settings Window/Settings/Behavior/InitialWindowPlacementConfigurationView.swift b/Loop/Settings Window/Settings/Behavior/InitialWindowPlacementConfigurationView.swift index cf6d47198..1adfff32b 100644 --- a/Loop/Settings Window/Settings/Behavior/InitialWindowPlacementConfigurationView.swift +++ b/Loop/Settings Window/Settings/Behavior/InitialWindowPlacementConfigurationView.swift @@ -12,7 +12,6 @@ struct InitialWindowPlacementConfigurationView: View { @Default(.initialWindowFrames) private var frames @State private var editingID: String? @State private var draft = WindowAction(.custom) - @State private var appIDs: [String] = [] @State private var selectedIDs = Set() @State private var pickerError: String? @@ -20,6 +19,7 @@ struct InitialWindowPlacementConfigurationView: 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 @@ -48,7 +48,7 @@ struct InitialWindowPlacementConfigurationView: View { } .luminareRoundingBehavior(top: true) - LuminareList(items: $appIDs, selection: $selectedIDs, id: \.self) { item in + 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) { @@ -73,6 +73,7 @@ struct InitialWindowPlacementConfigurationView: View { .help("Edit placement") } .padding(.horizontal, 12) + .moveDisabled(true) } emptyView: { VStack { Text("No configured apps") @@ -85,12 +86,6 @@ struct InitialWindowPlacementConfigurationView: View { } .luminareListFixedHeight(until: 250) .luminareRoundingBehavior(bottom: true) - .task(id: frames.keys.sorted()) { - let ids = frames.keys.sorted() - appIDs.removeAll { !ids.contains($0) } - appIDs.append(contentsOf: ids.filter { !appIDs.contains($0) }) - selectedIDs.formIntersection(ids) - } } if let pickerError { @@ -105,7 +100,9 @@ struct InitialWindowPlacementConfigurationView: View { } private func appName(_ id: String) -> String { - guard let url = NSWorkspace.shared.urlForApplication(withBundleIdentifier: id) else { return id } + guard let url = NSWorkspace.shared.urlForApplication(withBundleIdentifier: id) else { + return id + } return FileManager.default.displayName(atPath: url.path) } @@ -114,12 +111,14 @@ struct InitialWindowPlacementConfigurationView: View { 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 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 id != Bundle.main.bundleIdentifier, !Defaults[.excludedApps].contains(url) else { + guard InitialWindowFrames.allowsPlacement(bundleID: id, url: url) else { pickerError = String(localized: "Loop skips window placement for this app.") return } @@ -127,7 +126,7 @@ struct InitialWindowPlacementConfigurationView: View { } private func edit(_ id: String) { - draft = frames[id] ?? WindowAction(.custom, keybind: [], unit: .percentage, anchor: .center, width: 80, height: 80, positionMode: .generic, sizeMode: .custom) + draft = frames[id] ?? WindowAction(.custom) draft.direction = .custom draft.sizeMode = .custom editingID = id diff --git a/Loop/Window Management/Window Manipulation/InitialWindowFrames.swift b/Loop/Window Management/Window Manipulation/InitialWindowFrames.swift index e4bfee0a3..eb3fe061b 100644 --- a/Loop/Window Management/Window Manipulation/InitialWindowFrames.swift +++ b/Loop/Window Management/Window Manipulation/InitialWindowFrames.swift @@ -7,13 +7,16 @@ 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, - id != Bundle.main.bundleIdentifier, let url = app.bundleURL, - !Defaults[.excludedApps].contains(url), + allowsPlacement(bundleID: id, url: url), let action = Defaults[.initialWindowFrames][id], action.direction == .custom, action.sizeMode == .custom @@ -32,18 +35,39 @@ enum InitialWindowFrames { let properties = Window.ResolvedProperties(from: window) let context = ResizeContext(window: window, initialFrame: properties.frame, screen: screen, action: action) context.resolvedWindowProperties = properties - guard let frame = constrain(context.getTargetFrame().padded, to: context.paddedBounds) else { + guard let frame = placementFrame(in: context) else { return nil } return (frame, context.paddedBounds) } + /// Fit the requested size on the display before inner padding clips the frame to its bounds. + static func placementFrame(in context: ResizeContext) -> CGRect? { + let bounds = context.paddedBounds + let rawFrame = WindowFrameResolver.getFrame(resizeContext: context).frame + // The resolver also returns zero for invalid geometry. Only forward an explicitly requested zero. + guard rawFrame.size.width > 0 || context.action.width == 0, + rawFrame.size.height > 0 || context.action.height == 0, + let fitted = constrain(rawFrame, to: bounds) + else { + return nil + } + + let padded = context.padding.applyToWindow( + frame: fitted, + paddedBounds: bounds, + action: context.action, + resolvedWindowProperties: context.resolvedWindowProperties + ) + return constrain(padded, to: bounds) + } + /// 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, + frame.size.width >= 0, + frame.size.height >= 0, bounds.size.width > 0, bounds.size.height > 0 else { diff --git a/LoopTests/InitialWindowPlacementTests.swift b/LoopTests/InitialWindowPlacementTests.swift index 986751bf8..90edebb17 100644 --- a/LoopTests/InitialWindowPlacementTests.swift +++ b/LoopTests/InitialWindowPlacementTests.swift @@ -8,6 +8,40 @@ import SwiftUI import Testing struct InitialWindowPlacementTests { + @Test func coordinatePlacementKeepsItsSizeAtTheRightEdge() { + 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) + #expect(InitialWindowFrames.placementFrame(in: context) == CGRect(x: -500, y: 0, width: 500, height: 400)) + } + + @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) From 89a84bb03ea0c44a8e225fc377670c17540323bb Mon Sep 17 00:00:00 2001 From: Mars-den <338431790+Mars-den@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:57:05 +0400 Subject: [PATCH 7/7] =?UTF-8?q?=F0=9F=90=9E=20Match=20custom=20action=20cl?= =?UTF-8?q?ipping=20for=20initial=20window=20placement?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Use the shared padded target and verify that the right-edge placement matches a custom action. AI-assisted with OpenAI Codex for implementation and testing. --- .../InitialWindowFrames.swift | 19 +++++-------------- LoopTests/InitialWindowPlacementTests.swift | 6 ++++-- 2 files changed, 9 insertions(+), 16 deletions(-) diff --git a/Loop/Window Management/Window Manipulation/InitialWindowFrames.swift b/Loop/Window Management/Window Manipulation/InitialWindowFrames.swift index eb3fe061b..c4480f234 100644 --- a/Loop/Window Management/Window Manipulation/InitialWindowFrames.swift +++ b/Loop/Window Management/Window Manipulation/InitialWindowFrames.swift @@ -41,25 +41,16 @@ enum InitialWindowFrames { return (frame, context.paddedBounds) } - /// Fit the requested size on the display before inner padding clips the frame to its bounds. + /// Use the same padded target as a custom action invoked by a keybind. static func placementFrame(in context: ResizeContext) -> CGRect? { - let bounds = context.paddedBounds - let rawFrame = WindowFrameResolver.getFrame(resizeContext: context).frame + let target = context.getTargetFrame() // The resolver also returns zero for invalid geometry. Only forward an explicitly requested zero. - guard rawFrame.size.width > 0 || context.action.width == 0, - rawFrame.size.height > 0 || context.action.height == 0, - let fitted = constrain(rawFrame, to: bounds) + guard target.raw.size.width > 0 || context.action.width == 0, + target.raw.size.height > 0 || context.action.height == 0 else { return nil } - - let padded = context.padding.applyToWindow( - frame: fitted, - paddedBounds: bounds, - action: context.action, - resolvedWindowProperties: context.resolvedWindowProperties - ) - return constrain(padded, to: bounds) + return constrain(target.padded, to: context.paddedBounds) } /// Keep the requested frame within the display's usable area. diff --git a/LoopTests/InitialWindowPlacementTests.swift b/LoopTests/InitialWindowPlacementTests.swift index 90edebb17..90eeb7274 100644 --- a/LoopTests/InitialWindowPlacementTests.swift +++ b/LoopTests/InitialWindowPlacementTests.swift @@ -8,7 +8,7 @@ import SwiftUI import Testing struct InitialWindowPlacementTests { - @Test func coordinatePlacementKeepsItsSizeAtTheRightEdge() { + @Test func coordinatePlacementMatchesCustomActionAtTheRightEdge() { let bounds = CGRect(x: -1000, y: 0, width: 1000, height: 800) let action = WindowAction( .custom, @@ -22,7 +22,9 @@ struct InitialWindowPlacementTests { sizeMode: .custom ) let context = ResizeContext(bounds: bounds, padding: .zero, action: action) - #expect(InitialWindowFrames.placementFrame(in: context) == CGRect(x: -500, y: 0, width: 500, height: 400)) + 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])