Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SP Term9// File : Packages/SPTermKit/Sources/WindowManager/PlacementEngine.swift10// Module : WindowManager11// Repository : https://git.spboucher.ai/sp-term12// Created : 2026-11-1713// Last Modified : 2026-11-1714//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author : Simon-Pierre Boucher20// Position : Professor of Finance21// Institution : Université du Québec en Outaouais (UQO)22// Department : Département des sciences administratives23// Organization : SP Boucher24//25// Website : https://spboucher.ai26// Git : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General : info@spboucher.ai33// Professional : contact@spboucher.ai34// Direct : simon@spboucher.ai35// Research : research@spboucher.ai36// Development : dev@spboucher.ai37// Support : support@spboucher.ai38// Security/Admin : admin@spboucher.ai39// Notifications : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification : Public66// Distribution : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License : None specified (no license file in this repository)80// Maintainer : Simon-Pierre Boucher81// Technical Contact: dev@spboucher.ai82//83// =============================================================================84// END OF SP BOUCHER SOURCE HEADER85// =============================================================================8687import CoreGraphics88import Foundation89import WorkspaceKit9091/// Pure window placement rules. The single guarantee everything else builds on:92/// **a frame returned by this engine is always reachable** — its title bar lies inside the93/// visible area of an existing display — whatever happened to the monitors since it was saved.94public enum PlacementEngine {95 public static let minimumWindowSize = CGSize(width: 480, height: 300)96 public static let defaultWindowSize = CGSize(width: 1040, height: 680)97 /// Height of the strip at the top of a window that must stay on screen so it can be dragged.98 public static let titleBarHeight: CGFloat = 2899 static let cascadeStep: CGFloat = 26100101 // MARK: Screens102103 /// The display used when nothing better is known: the main one, else the first.104 public static func fallbackScreen(in screens: [ScreenDescriptor]) -> ScreenDescriptor? {105 screens.first(where: \.isMain) ?? screens.first106 }107108 /// Finds the display a saved reference designates among the displays available now.109 public static func match(_ reference: ScreenReference, in screens: [ScreenDescriptor]) -> (ScreenDescriptor, PlacementReason)? {110 if let same = screens.first(where: { $0.id == reference.displayID }) {111 return (same, same.frame == reference.frame ? .sameScreen : .screenGeometryChanged)112 }113 // Display ids change (other port, reboot): fall back to the same model at the same size.114 if let byName = screens.first(where: { $0.name == reference.name && $0.frame.size == reference.frame.size }) {115 return (byName, .matchedByName)116 }117 return nil118 }119120 /// Display for a logical slot of a multi-monitor preset: slot 0 is the main display, the121 /// others follow in left-to-right order. Slots beyond the available displays wrap onto the122 /// last one, so a "second monitor" window lands on the only display when there is one.123 public static func screen(forSlot slot: Int, in screens: [ScreenDescriptor]) -> ScreenDescriptor? {124 guard let main = fallbackScreen(in: screens) else { return nil }125 let others = screens.filter { $0.id != main.id }.sorted { a, b in126 a.frame.minX != b.frame.minX ? a.frame.minX < b.frame.minX : a.frame.minY < b.frame.minY127 }128 let ordered = [main] + others129 return ordered[min(max(slot, 0), ordered.count - 1)]130 }131132 /// The display containing the largest part of `frame`.133 public static func screen(containing frame: CGRect, in screens: [ScreenDescriptor]) -> ScreenDescriptor? {134 var best: (screen: ScreenDescriptor, area: CGFloat)?135 for screen in screens {136 let overlap = screen.frame.intersection(frame)137 guard !overlap.isNull, overlap.width > 0, overlap.height > 0 else { continue }138 let area = overlap.width * overlap.height139 if best == nil || area > best!.area { best = (screen, area) }140 }141 return best?.screen142 }143144 // MARK: Reachability145146 /// `true` when enough of the window's title bar is inside a display's visible area to grab it.147 public static func isReachable(_ frame: CGRect, in screens: [ScreenDescriptor]) -> Bool {148 let titleBar = CGRect(x: frame.minX, y: frame.maxY - titleBarHeight, width: frame.width, height: titleBarHeight)149 return screens.contains { screen in150 let visible = screen.visibleFrame.intersection(titleBar)151 return !visible.isNull && visible.width >= min(120, frame.width) && visible.height >= titleBarHeight - 0.5152 }153 }154155 /// Shrinks and moves `frame` so it lies entirely inside `visible`.156 public static func clamp(_ frame: CGRect, to visible: CGRect) -> CGRect {157 var result = frame158 result.size.width = min(max(result.width, min(minimumWindowSize.width, visible.width)), visible.width)159 result.size.height = min(max(result.height, min(minimumWindowSize.height, visible.height)), visible.height)160 result.origin.x = min(max(result.minX, visible.minX), visible.maxX - result.width)161 result.origin.y = min(max(result.minY, visible.minY), visible.maxY - result.height)162 return result.integral163 }164165 // MARK: Placement166167 /// Default frame for the `cascadeIndex`-th new window on a display: centered, cascading.168 public static func frameForNewWindow(on screen: ScreenDescriptor, size: CGSize = defaultWindowSize,169 cascadeIndex: Int = 0) -> CGRect {170 let visible = screen.visibleFrame171 let width = min(size.width, visible.width)172 let height = min(size.height, visible.height)173 let freeX = max(0, visible.width - width)174 let freeY = max(0, visible.height - height)175 // Wrap the cascade so the twentieth window does not slide off the display.176 let maxSteps = max(1, Int(min(freeX, freeY) / 2 / cascadeStep))177 let offset = CGFloat(cascadeIndex % maxSteps) * cascadeStep178 let frame = CGRect(x: visible.minX + freeX / 2 + offset, y: visible.minY + freeY / 2 - offset, width: width, height: height)179 return clamp(frame, to: visible)180 }181182 /// Moves a frame from one display to another keeping its relative position and size.183 public static func move(_ frame: CGRect, from source: CGRect, to target: ScreenDescriptor) -> CGRect {184 let visible = target.visibleFrame185 guard source.width > 0, source.height > 0 else { return frameForNewWindow(on: target) }186 let relativeX = (frame.minX - source.minX) / source.width187 let relativeY = (frame.minY - source.minY) / source.height188 let widthShare = frame.width / source.width189 let heightShare = frame.height / source.height190 let moved = CGRect(x: visible.minX + relativeX * visible.width, y: visible.minY + relativeY * visible.height,191 width: widthShare * visible.width, height: heightShare * visible.height)192 return clamp(moved, to: visible)193 }194195 /// Where a saved window should be restored given the displays available now.196 /// Returns `nil` only when there is no display at all.197 public static func resolve(savedFrame: CGRect?, savedScreen: ScreenReference?, screenSlot: Int? = nil,198 in screens: [ScreenDescriptor], cascadeIndex: Int = 0) -> Placement? {199 guard let fallback = fallbackScreen(in: screens) else { return nil }200 guard let savedFrame, savedFrame.width > 0, savedFrame.height > 0 else {201 let target = screenSlot.flatMap { screen(forSlot: $0, in: screens) } ?? fallback202 return Placement(frame: frameForNewWindow(on: target, cascadeIndex: cascadeIndex), screenID: target.id, reason: .defaultPlacement)203 }204 if let savedScreen, let (found, reason) = match(savedScreen, in: screens) {205 switch reason {206 case .sameScreen:207 return Placement(frame: clamp(savedFrame, to: found.visibleFrame), screenID: found.id, reason: .sameScreen)208 default:209 // Same monitor, other resolution or position in the arrangement: keep proportions.210 return Placement(frame: move(savedFrame, from: savedScreen.frame, to: found), screenID: found.id, reason: reason)211 }212 }213 if savedScreen == nil, let current = screen(containing: savedFrame, in: screens) {214 return Placement(frame: clamp(savedFrame, to: current.visibleFrame), screenID: current.id, reason: .sameScreen)215 }216 // The display is gone: bring the window to the fallback display, same proportions.217 let source = savedScreen?.frame ?? savedFrame218 return Placement(frame: move(savedFrame, from: source, to: fallback), screenID: fallback.id, reason: .screenMissing)219 }220221 /// Called when the display configuration changes while the app runs: returns a new frame for222 /// every window that is no longer reachable (display unplugged, resolution lowered…).223 /// Windows that are still reachable are left alone.224 public static func rescue(windows: [WindowID: CGRect], previousScreens: [ScreenDescriptor],225 currentScreens: [ScreenDescriptor]) -> [WindowID: Placement] {226 guard let fallback = fallbackScreen(in: currentScreens) else { return [:] }227 var result: [WindowID: Placement] = [:]228 for (id, frame) in windows.sorted(by: { $0.key.raw.uuidString < $1.key.raw.uuidString }) {229 if isReachable(frame, in: currentScreens) {230 // Reachable but possibly overflowing a display that shrank: keep it fully visible.231 if let screen = screen(containing: frame, in: currentScreens), !screen.visibleFrame.contains(frame),232 previousScreens.contains(where: { $0.id == screen.id && $0.visibleFrame != screen.visibleFrame }) {233 result[id] = Placement(frame: clamp(frame, to: screen.visibleFrame), screenID: screen.id, reason: .screenGeometryChanged)234 }235 continue236 }237 let origin = screen(containing: frame, in: previousScreens)238 if let origin, let (found, reason) = match(origin.reference, in: currentScreens) {239 result[id] = Placement(frame: move(frame, from: origin.frame, to: found), screenID: found.id, reason: reason)240 } else {241 result[id] = Placement(frame: move(frame, from: origin?.frame ?? frame, to: fallback), screenID: fallback.id, reason: .screenMissing)242 }243 }244 return result245 }246247 /// Tiles `count` windows over a display's visible area (used when several windows of a248 /// multi-monitor workspace must share one display).249 public static func tile(count: Int, in visible: CGRect, gap: CGFloat = 8) -> [CGRect] {250 guard count > 0 else { return [] }251 let columns = Int(Double(count).squareRoot().rounded(.up))252 let rows = Int((Double(count) / Double(columns)).rounded(.up))253 let width = (visible.width - gap * CGFloat(columns - 1)) / CGFloat(columns)254 let height = (visible.height - gap * CGFloat(rows - 1)) / CGFloat(rows)255 return (0..<count).map { index in256 let column = index % columns, row = index / columns257 // Row 0 is the top row; AppKit's y axis grows upwards.258 return CGRect(x: visible.minX + CGFloat(column) * (width + gap),259 y: visible.maxY - CGFloat(row + 1) * height - CGFloat(row) * gap,260 width: width, height: height).integral261 }262 }263264 /// Frames for the windows of a workspace being opened: saved positions are honoured when265 /// their display exists, slots are mapped to displays, and windows that end up on the same266 /// display without a usable saved frame are tiled instead of stacked on top of each other.267 public static func arrange(_ windows: [WindowModel], in screens: [ScreenDescriptor]) -> [WindowID: Placement] {268 guard fallbackScreen(in: screens) != nil else { return [:] }269 var result: [WindowID: Placement] = [:]270 var unplaced: [UInt32: [WindowID]] = [:]271 for (index, window) in windows.enumerated() {272 guard let placement = resolve(savedFrame: window.frame, savedScreen: window.screen, screenSlot: window.screenSlot,273 in: screens, cascadeIndex: index) else { continue }274 result[window.id] = placement275 if placement.reason == .defaultPlacement { unplaced[placement.screenID, default: []].append(window.id) }276 }277 for (screenID, ids) in unplaced where ids.count > 1 {278 guard let screen = screens.first(where: { $0.id == screenID }) else { continue }279 let frames = tile(count: ids.count, in: screen.visibleFrame.insetBy(dx: 8, dy: 8))280 for (id, frame) in zip(ids, frames) {281 result[id] = Placement(frame: clamp(frame, to: screen.visibleFrame), screenID: screenID, reason: .defaultPlacement)282 }283 }284 return result285 }286}287