DesktopWidgetWindowManager.swift 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. import AppKit
  2. import Combine
  3. import SwiftUI
  4. final class DesktopWidgetWindowManager: ObservableObject {
  5. static let shared = DesktopWidgetWindowManager()
  6. private let storageKey = "widgetInstancesData"
  7. private var windowsByInstanceID: [UUID: NSPanel] = [:]
  8. /// Bumps when persisted widget instances are added or removed so SwiftUI can refresh pickers.
  9. @Published private(set) var instancesChangeToken: Int = 0
  10. private init() {}
  11. private func notifyInstancesChanged() {
  12. instancesChangeToken += 1
  13. }
  14. func show(instance: WidgetInstance, appProvider: (UUID) -> LauncherApp?) {
  15. guard let app = appProvider(instance.appID) else { return }
  16. let resolvedVariant = WidgetTemplates.variant(for: app, variantID: instance.variantID)
  17. var resolvedInstance = instance
  18. if resolvedInstance.origin == nil {
  19. resolvedInstance.origin = nextAutoPlacement(for: resolvedVariant, appProvider: appProvider)
  20. }
  21. let panel = makePanel(for: resolvedInstance, app: app, variant: resolvedVariant)
  22. windowsByInstanceID[instance.id] = panel
  23. persistUpsert(instance: resolvedInstance)
  24. if let origin = resolvedInstance.origin {
  25. panel.setFrameOrigin(NSPoint(x: origin.x, y: origin.y))
  26. // Persist immediately so future auto-placement has accurate collision data.
  27. persistOrigin(instanceID: instance.id, origin: panel.frame.origin)
  28. } else {
  29. panel.center()
  30. // Persist immediately so future auto-placement has accurate collision data.
  31. persistOrigin(instanceID: instance.id, origin: panel.frame.origin)
  32. }
  33. // Ensure the newly added widget is visually on top.
  34. panel.orderFront(nil)
  35. panel.orderFrontRegardless()
  36. notifyInstancesChanged()
  37. }
  38. /// Returns `true` if there is already a persisted widget instance for the given `appID + variantID`.
  39. /// This is used by the widget picker UI to toggle `+`/`-` for each widget card.
  40. func hasInstance(appID: UUID, variantID: String) -> Bool {
  41. return loadInstances().contains { $0.appID == appID && $0.variantID == variantID }
  42. }
  43. /// Removes any widget instances matching the given `appID + variantID`.
  44. /// - Returns: number of instances removed.
  45. func removeInstances(appID: UUID, variantID: String) -> Int {
  46. let instances = loadInstances()
  47. let removed = instances.filter { $0.appID == appID && $0.variantID == variantID }
  48. let remaining = instances.filter { !($0.appID == appID && $0.variantID == variantID) }
  49. for instance in removed {
  50. if let win = windowsByInstanceID.removeValue(forKey: instance.id) {
  51. win.close()
  52. }
  53. }
  54. saveInstances(remaining)
  55. notifyInstancesChanged()
  56. return removed.count
  57. }
  58. func restore(appProvider: (UUID) -> LauncherApp?) {
  59. let instances = loadInstances()
  60. for instance in instances {
  61. guard windowsByInstanceID[instance.id] == nil else { continue }
  62. show(instance: instance, appProvider: appProvider)
  63. }
  64. }
  65. func removeAll(forAppID appID: UUID) {
  66. let instances = loadInstances()
  67. let remaining = instances.filter { $0.appID != appID }
  68. let removed = instances.filter { $0.appID == appID }
  69. for instance in removed {
  70. if let win = windowsByInstanceID.removeValue(forKey: instance.id) {
  71. win.close()
  72. }
  73. }
  74. saveInstances(remaining)
  75. notifyInstancesChanged()
  76. }
  77. // MARK: - Panel construction
  78. private func makePanel(for instance: WidgetInstance, app: LauncherApp, variant: WidgetVariant) -> NSPanel {
  79. let size = panelSize(for: variant)
  80. let panel: NSPanel
  81. if variant.layoutMode.needsKeyCapablePanel {
  82. // Key-capable so embedded web views and search fields receive clicks and typing reliably.
  83. panel = InteractiveMapsWidgetPanel(
  84. contentRect: NSRect(x: 0, y: 0, width: size.width, height: size.height),
  85. styleMask: [.nonactivatingPanel, .borderless],
  86. backing: .buffered,
  87. defer: false
  88. )
  89. panel.becomesKeyOnlyIfNeeded = true
  90. } else {
  91. panel = DesktopWidgetPanel(
  92. contentRect: NSRect(x: 0, y: 0, width: size.width, height: size.height),
  93. styleMask: [.nonactivatingPanel, .borderless],
  94. backing: .buffered,
  95. defer: false
  96. )
  97. panel.becomesKeyOnlyIfNeeded = false
  98. }
  99. panel.isReleasedWhenClosed = false
  100. panel.isFloatingPanel = false
  101. panel.isMovable = true
  102. // One level above desktop icons so Finder desktop clicks do not leave our widget behind the desktop layer.
  103. let desktopIconLevel = Int(CGWindowLevelForKey(.desktopIconWindow))
  104. panel.level = NSWindow.Level(rawValue: desktopIconLevel + 1)
  105. // System window shadow is drawn as a rectangular halo; with transparent, rounded content it reads as ugly black lines.
  106. panel.hasShadow = false
  107. panel.isOpaque = false
  108. panel.backgroundColor = .clear
  109. panel.isMovableByWindowBackground = true
  110. panel.hidesOnDeactivate = false
  111. panel.ignoresMouseEvents = false
  112. panel.collectionBehavior = [
  113. .canJoinAllSpaces,
  114. .stationary,
  115. .ignoresCycle,
  116. ]
  117. let root = DesktopWidgetHostView(
  118. app: app,
  119. variant: variant,
  120. onRemove: { self.close(instanceID: instance.id) }
  121. )
  122. let hosting = NSHostingView(rootView: root)
  123. hosting.translatesAutoresizingMaskIntoConstraints = false
  124. let container = NSView()
  125. container.translatesAutoresizingMaskIntoConstraints = false
  126. container.wantsLayer = true
  127. container.layer?.backgroundColor = NSColor.clear.cgColor
  128. container.layer?.borderWidth = 0
  129. container.layer?.cornerRadius = 22
  130. container.layer?.masksToBounds = true
  131. container.addSubview(hosting)
  132. hosting.wantsLayer = true
  133. hosting.layer?.borderWidth = 0
  134. hosting.layer?.backgroundColor = NSColor.clear.cgColor
  135. NSLayoutConstraint.activate([
  136. hosting.leadingAnchor.constraint(equalTo: container.leadingAnchor),
  137. hosting.trailingAnchor.constraint(equalTo: container.trailingAnchor),
  138. hosting.topAnchor.constraint(equalTo: container.topAnchor),
  139. hosting.bottomAnchor.constraint(equalTo: container.bottomAnchor),
  140. ])
  141. panel.contentView = container
  142. NotificationCenter.default.addObserver(
  143. forName: NSWindow.didMoveNotification,
  144. object: panel,
  145. queue: .main
  146. ) { [weak self, weak panel] _ in
  147. guard let self, let panel else { return }
  148. self.persistOrigin(instanceID: instance.id, origin: panel.frame.origin)
  149. }
  150. return panel
  151. }
  152. private func panelSize(for variant: WidgetVariant) -> CGSize {
  153. if variant.layoutMode == .interactiveMap {
  154. switch variant.size {
  155. case .small:
  156. return CGSize(width: 340, height: 420)
  157. case .medium:
  158. return CGSize(width: 460, height: 400)
  159. case .large:
  160. return CGSize(width: 520, height: 560)
  161. }
  162. }
  163. if let override = variant.layoutMode.desktopPanelSizeOverride() {
  164. return override
  165. }
  166. switch variant.size {
  167. case .small:
  168. return CGSize(width: 220, height: 210)
  169. case .medium:
  170. return CGSize(width: 390, height: 210)
  171. case .large:
  172. return CGSize(width: 390, height: 400)
  173. }
  174. }
  175. /// Region where macOS system desktop widgets (Calendar, Weather, Photos, etc.) usually sit.
  176. /// Those windows are composited above normal third-party desktop windows, so our panels cannot
  177. /// appear “on top” of them—auto-placement must avoid this area so the user sees our widget beside them.
  178. private func reservedSystemDesktopWidgetZone(in visibleFrame: NSRect) -> NSRect {
  179. let margin: CGFloat = 18
  180. let w = min(560, visibleFrame.width * 0.48)
  181. let h = min(420, visibleFrame.height * 0.55)
  182. return NSRect(
  183. x: visibleFrame.minX + margin,
  184. y: visibleFrame.maxY - margin - h,
  185. width: w,
  186. height: h
  187. )
  188. }
  189. private func nextAutoPlacement(for variant: WidgetVariant, appProvider: (UUID) -> LauncherApp?) -> WidgetInstance.Origin {
  190. let panelSizeForNew = panelSize(for: variant)
  191. let frame = NSScreen.main?.visibleFrame ?? NSRect(x: 100, y: 100, width: 1200, height: 800)
  192. let systemWidgetZone = reservedSystemDesktopWidgetZone(in: frame)
  193. let margin: CGFloat = 18
  194. let gapX: CGFloat = 26
  195. let gapY: CGFloat = 20
  196. let cellW = panelSizeForNew.width + gapX
  197. let cellH = panelSizeForNew.height + gapY
  198. // Existing widgets:
  199. // 1) Live panels already on screen (most reliable; avoids missing persisted origins).
  200. // 2) Persisted widget origins (fallback for already-closed widgets).
  201. let liveRects: [NSRect] = windowsByInstanceID.values.map { $0.frame }
  202. let persistedRects: [NSRect] = loadInstances().compactMap { instance in
  203. guard let origin = instance.origin else { return nil }
  204. guard let app = appProvider(instance.appID) else { return nil }
  205. let v = WidgetTemplates.variant(for: app, variantID: instance.variantID)
  206. let s = panelSize(for: v)
  207. return NSRect(x: origin.x, y: origin.y, width: s.width, height: s.height)
  208. }
  209. let existingRects = liveRects + persistedRects
  210. let keepOut: CGFloat = 8
  211. func overlapsExisting(_ candidate: NSRect) -> Bool {
  212. let inflated = candidate.insetBy(dx: -keepOut, dy: -keepOut)
  213. return existingRects.contains(where: { $0.intersects(inflated) })
  214. }
  215. func overlapsSystemWidgetZone(_ candidate: NSRect) -> Bool {
  216. candidate.intersects(systemWidgetZone)
  217. }
  218. let cols = max(1, Int((frame.width - margin * 2) / max(cellW, 1)))
  219. let maxSlots = 200
  220. // Scan row-major for the first slot that avoids our widgets and Apple's desktop widget zone.
  221. for slot in 0..<maxSlots {
  222. let row = slot / cols
  223. let col = slot % cols
  224. let x = frame.minX + margin + CGFloat(col) * cellW
  225. let y = frame.maxY - margin - panelSizeForNew.height - CGFloat(row) * cellH
  226. let candidate = NSRect(x: x, y: y, width: panelSizeForNew.width, height: panelSizeForNew.height)
  227. // Keep inside visible bounds with margin.
  228. guard candidate.minX >= frame.minX + margin,
  229. candidate.maxX <= frame.maxX - margin,
  230. candidate.minY >= frame.minY + margin,
  231. candidate.maxY <= frame.maxY - margin else {
  232. continue
  233. }
  234. if !overlapsExisting(candidate), !overlapsSystemWidgetZone(candidate) {
  235. return WidgetInstance.Origin(x: candidate.minX, y: candidate.minY)
  236. }
  237. }
  238. // Fallback: first column to the right of the system widget zone, then continue the grid.
  239. let safeMinX = max(systemWidgetZone.maxX + gapX, frame.minX + margin)
  240. for slot in 0..<maxSlots {
  241. let row = slot / cols
  242. let col = slot % cols
  243. let x = safeMinX + CGFloat(col) * cellW
  244. let y = frame.maxY - margin - panelSizeForNew.height - CGFloat(row) * cellH
  245. let candidate = NSRect(x: x, y: y, width: panelSizeForNew.width, height: panelSizeForNew.height)
  246. guard candidate.minX >= frame.minX + margin,
  247. candidate.maxX <= frame.maxX - margin,
  248. candidate.minY >= frame.minY + margin,
  249. candidate.maxY <= frame.maxY - margin else {
  250. continue
  251. }
  252. if !overlapsExisting(candidate) {
  253. return WidgetInstance.Origin(x: candidate.minX, y: candidate.minY)
  254. }
  255. }
  256. // Last resort: center of screen (usually clear of the top-left widget stack).
  257. let cx = frame.midX - panelSizeForNew.width / 2
  258. let cy = frame.midY - panelSizeForNew.height / 2
  259. let x = min(max(cx, frame.minX + margin), frame.maxX - margin - panelSizeForNew.width)
  260. let y = min(max(cy, frame.minY + margin), frame.maxY - margin - panelSizeForNew.height)
  261. return WidgetInstance.Origin(x: x, y: y)
  262. }
  263. private func close(instanceID: UUID) {
  264. if let win = windowsByInstanceID.removeValue(forKey: instanceID) {
  265. win.close()
  266. }
  267. let instances = loadInstances().filter { $0.id != instanceID }
  268. saveInstances(instances)
  269. notifyInstancesChanged()
  270. }
  271. // MARK: - Persistence
  272. private func loadInstances() -> [WidgetInstance] {
  273. guard let data = UserDefaults.standard.data(forKey: storageKey) else { return [] }
  274. do {
  275. return try JSONDecoder().decode([WidgetInstance].self, from: data)
  276. } catch {
  277. return []
  278. }
  279. }
  280. private func saveInstances(_ instances: [WidgetInstance]) {
  281. do {
  282. let data = try JSONEncoder().encode(instances)
  283. UserDefaults.standard.set(data, forKey: storageKey)
  284. } catch {
  285. // Ignore and keep UI responsive.
  286. }
  287. }
  288. private func persistUpsert(instance: WidgetInstance) {
  289. var instances = loadInstances()
  290. if let idx = instances.firstIndex(where: { $0.id == instance.id }) {
  291. instances[idx] = instance
  292. } else {
  293. instances.append(instance)
  294. }
  295. saveInstances(instances)
  296. }
  297. private func persistOrigin(instanceID: UUID, origin: NSPoint) {
  298. var instances = loadInstances()
  299. guard let idx = instances.firstIndex(where: { $0.id == instanceID }) else { return }
  300. instances[idx].origin = WidgetInstance.Origin(x: origin.x, y: origin.y)
  301. saveInstances(instances)
  302. }
  303. }
  304. private final class DesktopWidgetPanel: NSPanel {
  305. override var canBecomeKey: Bool { false }
  306. override var canBecomeMain: Bool { false }
  307. override func mouseDown(with event: NSEvent) {
  308. orderFront(nil)
  309. super.mouseDown(with: event)
  310. }
  311. }
  312. /// Used for the interactive Google Maps widget so `TextField` and toolbar buttons can become first responder.
  313. private final class InteractiveMapsWidgetPanel: NSPanel {
  314. override var canBecomeKey: Bool { true }
  315. override var canBecomeMain: Bool { false }
  316. override func mouseDown(with event: NSEvent) {
  317. orderFront(nil)
  318. super.mouseDown(with: event)
  319. }
  320. }
  321. private struct DesktopWidgetHostView: View {
  322. let app: LauncherApp
  323. let variant: WidgetVariant
  324. let onRemove: () -> Void
  325. var body: some View {
  326. DesktopWidgetView(app: app, variant: variant, isPreview: false)
  327. .contextMenu {
  328. Button("Remove Widget", role: .destructive) {
  329. onRemove()
  330. }
  331. }
  332. }
  333. }