-
-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathSaneBarApp.swift
More file actions
405 lines (338 loc) · 15.5 KB
/
SaneBarApp.swift
File metadata and controls
405 lines (338 loc) · 15.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
import AppKit
import KeyboardShortcuts
import os.log
import SaneUI
@preconcurrency import ScreenCaptureKit
import SwiftUI
private let appLogger = Logger(subsystem: "com.sanebar.app", category: "App")
// MARK: - AppDelegate
// CLEAN: Single initialization path - only MenuBarManager creates status items
class SaneBarAppDelegate: NSObject, NSApplicationDelegate {
enum DuplicateLaunchResolution: Equatable {
case noConflict
case waitForHandoff
case terminateCurrent
}
static let duplicateLaunchGraceNanoseconds: UInt64 = 2_000_000_000
static let automaticTerminationReason = "SaneBar must stay active as a menu bar app"
private var keepAliveActivity: NSObjectProtocol?
static func duplicateLaunchResolution(othersAtLaunch: Int, othersAfterGrace: Int?) -> DuplicateLaunchResolution {
guard othersAtLaunch > 0 else { return .noConflict }
guard let othersAfterGrace else { return .waitForHandoff }
return othersAfterGrace > 0 ? .terminateCurrent : .noConflict
}
// No @main - using main.swift instead
func applicationDidFinishLaunching(_: Notification) {
appLogger.info("🏁 applicationDidFinishLaunching START")
// Near-instant tooltips (default is ~1000ms)
UserDefaults.standard.set(100, forKey: "NSInitialToolTipDelay")
// Keep the menu bar process alive across idle periods.
keepAliveActivity = ProcessInfo.processInfo.beginActivity(
options: [.automaticTerminationDisabled, .suddenTerminationDisabled],
reason: Self.automaticTerminationReason
)
ProcessInfo.processInfo.disableAutomaticTermination(Self.automaticTerminationReason)
ProcessInfo.processInfo.disableSuddenTermination()
// Guard against accidental duplicate launches of the same bundle.
// Use a handoff grace window so update relaunches do not self-terminate.
scheduleDuplicateInstanceTerminationCheckIfNeeded()
// Move to /Applications if running from Downloads or other location (Release only)
#if !DEBUG && !APP_STORE && !SETAPP
if SaneAppMover.moveToApplicationsFolderIfNeeded(prompt: .init(
messageText: "Move to Applications?",
informativeText: "{appName} works best from your Applications folder. Move it there now? You may be asked for your password.",
moveButtonTitle: "Move to Applications",
cancelButtonTitle: "Not Now"
)) { return }
#endif
// CRITICAL: Set activation policy to accessory BEFORE creating status items!
// This ensures NSStatusItem windows are created at the correct window layer (25).
NSApp.setActivationPolicy(.accessory)
// Load cached Pro state before the menu bar runtime creates any
// license-gated status items. Otherwise launch can briefly create and
// tear down the always-hidden separator while `isPro` catches up.
LicenseService.shared.checkCachedLicense()
// Initialize MenuBarManager (creates status items) - MUST be after activation policy is set
_ = MenuBarManager.shared
MenuBarManager.shared.normalizeLicenseDependentDefaults()
// Configure keyboard shortcuts
let shortcutsService = KeyboardShortcutsService.shared
shortcutsService.configure(with: MenuBarManager.shared)
shortcutsService.setDefaultsIfNeeded()
// Apply user's preferred policy (may override to .regular if dock icon enabled)
SaneActivationPolicy.applyInitialPolicy(showDockIcon: MenuBarManager.shared.settings.showDockIcon)
SetappIntegration.logPurchaseType()
SetappIntegration.showReleaseNotesIfNeeded(delay: 1.5)
let launchTier = LicenseService.shared.isPro ? "pro" : "free"
Task.detached {
await EventTracker.log("app_launch_\(launchTier)", tier: launchTier)
}
appLogger.info("🏁 applicationDidFinishLaunching complete")
}
func applicationWillTerminate(_: Notification) {
if let keepAliveActivity {
ProcessInfo.processInfo.endActivity(keepAliveActivity)
self.keepAliveActivity = nil
}
ProcessInfo.processInfo.enableAutomaticTermination(Self.automaticTerminationReason)
ProcessInfo.processInfo.enableSuddenTermination()
}
@MainActor
private func runningDuplicateInstances(bundleID: String, currentPID: pid_t) -> [NSRunningApplication] {
NSRunningApplication.runningApplications(withBundleIdentifier: bundleID)
.filter { $0.processIdentifier != currentPID }
}
@MainActor
private func scheduleDuplicateInstanceTerminationCheckIfNeeded() {
guard let bundleID = Bundle.main.bundleIdentifier else { return }
let currentPID = ProcessInfo.processInfo.processIdentifier
let initialOthers = runningDuplicateInstances(bundleID: bundleID, currentPID: currentPID)
let initialResolution = Self.duplicateLaunchResolution(
othersAtLaunch: initialOthers.count,
othersAfterGrace: nil
)
guard initialResolution == .waitForHandoff else { return }
appLogger.warning(
"Duplicate launch detected for bundle \(bundleID, privacy: .public). Waiting \(Self.duplicateLaunchGraceNanoseconds / 1_000_000_000)s for handoff before termination."
)
Task { @MainActor in
try? await Task.sleep(nanoseconds: Self.duplicateLaunchGraceNanoseconds)
let remainingOthers = runningDuplicateInstances(bundleID: bundleID, currentPID: currentPID).count
let finalResolution = Self.duplicateLaunchResolution(
othersAtLaunch: initialOthers.count,
othersAfterGrace: remainingOthers
)
switch finalResolution {
case .noConflict:
appLogger.info("Duplicate launch handoff resolved; keeping current instance alive.")
case .waitForHandoff:
break
case .terminateCurrent:
appLogger.error(
"Duplicate instance still running after grace period for bundle \(bundleID, privacy: .public). Terminating current launch."
)
NSApp.terminate(nil)
}
}
}
func application(_: NSApplication, open urls: [URL]) {
guard let url = urls.first else { return }
appLogger.log("🌐 URL open request: \(url.absoluteString, privacy: .public)")
handleURL(url)
}
func applicationDockMenu(_: NSApplication) -> NSMenu? {
let menu = NSMenu()
let showAllItem = NSMenuItem(
title: "Show All Icons",
action: #selector(showAllIconsFromDock(_:)),
keyEquivalent: ""
)
showAllItem.target = self
menu.addItem(showAllItem)
if LicenseService.shared.distributionChannel.supportsInAppUpdates {
menu.addItem(NSMenuItem.separator())
let checkUpdatesItem = NSMenuItem(
title: "Check for Updates...",
action: #selector(checkForUpdatesFromDock(_:)),
keyEquivalent: ""
)
checkUpdatesItem.target = self
menu.addItem(checkUpdatesItem)
}
menu.addItem(NSMenuItem.separator())
let settingsItem = NSMenuItem(
title: "Settings...",
action: #selector(openSettingsFromDock(_:)),
keyEquivalent: ","
)
settingsItem.target = self
menu.addItem(settingsItem)
if LicenseService.shared.usesSetappDistribution {
let whatsNewItem = NSMenuItem(
title: "What's New...",
action: #selector(showReleaseNotesFromDock(_:)),
keyEquivalent: ""
)
whatsNewItem.target = self
menu.addItem(whatsNewItem)
menu.addItem(NSMenuItem.separator())
} else {
menu.addItem(NSMenuItem.separator())
}
let quitItem = NSMenuItem(
title: "Quit SaneBar",
action: #selector(quitFromDock(_:)),
keyEquivalent: "q"
)
quitItem.target = self
menu.addItem(quitItem)
return menu
}
@MainActor
@objc private func showAllIconsFromDock(_: Any?) {
Task {
await MenuBarManager.shared.hidingService.showAll()
}
}
@MainActor
@objc private func checkForUpdatesFromDock(_: Any?) {
MenuBarManager.shared.userDidClickCheckForUpdates()
}
@MainActor
@objc private func openSettingsFromDock(_: Any?) {
SettingsOpener.open()
}
@MainActor
@objc private func showReleaseNotesFromDock(_: Any?) {
SetappIntegration.showReleaseNotes()
}
@MainActor
@objc private func quitFromDock(_: Any?) {
NSApplication.shared.terminate(nil)
}
private func handleURL(_ url: URL) {
guard url.scheme?.lowercased() == "sanebar" else { return }
let rawCommand = (url.host?.isEmpty == false) ? url.host : url.path.split(separator: "/").first.map(String.init)
let command = rawCommand?.lowercased() ?? ""
let queryItems = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems
let searchQuery = queryItems?.first(where: { $0.name == "q" })?.value
appLogger.log("🌐 URL command: \(command, privacy: .public) query: \(searchQuery ?? "", privacy: .public)")
Task { @MainActor in
switch command {
case "toggle":
MenuBarManager.shared.toggleHiddenItems()
case "show":
MenuBarManager.shared.showHiddenItems()
case "hide":
MenuBarManager.shared.hideHiddenItems()
case "search":
if MenuBarManager.shared.settings.requireAuthToShowHiddenIcons {
let ok = await MenuBarManager.shared.authenticate(reason: "Unlock hidden icons")
guard ok else {
appLogger.log("🌐 URL command blocked by auth: search")
return
}
}
SearchWindowController.shared.show(mode: .findIcon, prefill: searchQuery)
case "settings":
SettingsOpener.open()
default:
appLogger.log("🌐 Unknown URL command: \(command, privacy: .public)")
}
}
}
}
// MARK: - Settings Opener
/// Opens Settings window programmatically
enum SettingsOpener {
@MainActor private static var settingsWindow: NSWindow?
@MainActor private static var windowDelegate: SettingsWindowDelegate?
@MainActor static func open() {
// DON'T force .regular here - respect the user's showDockIcon setting
// An .accessory app CAN have visible windows (the dock icon just won't show)
// This fixes the bug where dock icon appears when Settings opens despite setting being OFF
NSApp.activate()
let window = settingsWindow ?? makeWindow()
window.makeKeyAndOrderFront(nil)
window.orderFrontRegardless()
}
@MainActor static func close() {
settingsWindow?.close()
}
@MainActor static func captureSnapshotPNG(to path: String) async -> Bool {
guard let window = settingsWindow,
window.isVisible,
let outputURL = snapshotOutputURL(for: path) else {
return false
}
guard let pngData = await captureWindowPNGData(window: window) ?? captureContentPNGData(window: window) else {
return false
}
do {
try FileManager.default.createDirectory(
at: outputURL.deletingLastPathComponent(),
withIntermediateDirectories: true
)
try pngData.write(to: outputURL, options: .atomic)
return true
} catch {
appLogger.error("Failed to write settings snapshot: \(error.localizedDescription, privacy: .public)")
return false
}
}
@MainActor private static func makeWindow() -> NSWindow {
let settingsView = SettingsView()
let hostingController = NSHostingController(rootView: settingsView)
let window = NSWindow(contentViewController: hostingController)
window.title = "SaneBar Settings"
window.appearance = NSAppearance(named: .darkAqua)
window.styleMask = [.titled, .closable]
window.setContentSize(NSSize(width: 450, height: 400))
window.center()
window.isReleasedWhenClosed = false
let delegate = SettingsWindowDelegate()
window.delegate = delegate
windowDelegate = delegate
settingsWindow = window
return window
}
private static func snapshotOutputURL(for path: String) -> URL? {
let trimmed = path.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty else { return nil }
return URL(fileURLWithPath: trimmed).standardizedFileURL
}
@MainActor private static func captureWindowPNGData(window: NSWindow) async -> Data? {
guard #available(macOS 14.4, *),
let cgImage = await captureWindowImage(window: window) else {
return nil
}
let bitmap = NSBitmapImageRep(cgImage: cgImage)
return bitmap.representation(using: .png, properties: [:])
}
@MainActor private static func captureContentPNGData(window: NSWindow) -> Data? {
guard let contentView = window.contentView else { return nil }
contentView.layoutSubtreeIfNeeded()
window.displayIfNeeded()
let bounds = contentView.bounds.integral
guard bounds.width > 0,
bounds.height > 0,
let bitmap = contentView.bitmapImageRepForCachingDisplay(in: bounds) else {
return nil
}
bitmap.size = bounds.size
contentView.cacheDisplay(in: bounds, to: bitmap)
return bitmap.representation(using: .png, properties: [:])
}
@available(macOS 14.4, *)
@MainActor private static func captureWindowImage(window: NSWindow) async -> CGImage? {
do {
let shareableContent = try await SCShareableContent.currentProcess
guard let shareableWindow = shareableContent.windows.first(where: { $0.windowID == CGWindowID(window.windowNumber) }) else {
return nil
}
let filter = SCContentFilter(desktopIndependentWindow: shareableWindow)
let config = SCStreamConfiguration()
let scale = window.screen?.backingScaleFactor ?? NSScreen.main?.backingScaleFactor ?? 2
config.width = max(1, Int(window.frame.width * scale))
config.height = max(1, Int(window.frame.height * scale))
return try await withCheckedThrowingContinuation { continuation in
SCScreenshotManager.captureImage(contentFilter: filter, configuration: config) { image, error in
if let error {
continuation.resume(throwing: error)
} else {
continuation.resume(returning: image)
}
}
}
} catch {
appLogger.error("Failed to capture settings window via ScreenCaptureKit: \(error.localizedDescription, privacy: .public)")
return nil
}
}
}
/// Handles settings window lifecycle events
private class SettingsWindowDelegate: NSObject, NSWindowDelegate {
func windowWillClose(_: Notification) {
SaneActivationPolicy.restorePolicy(showDockIcon: MenuBarManager.shared.settings.showDockIcon)
}
}