-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNotificationLightMac.swift
More file actions
829 lines (710 loc) · 29.7 KB
/
NotificationLightMac.swift
File metadata and controls
829 lines (710 loc) · 29.7 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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
import SwiftUI
import AVFoundation
import Cocoa
import ApplicationServices
import CoreImage
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_ notification: Notification) {
NSWindow.allowsAutomaticWindowTabbing = false
}
func application(_ application: NSApplication, open urls: [URL]) {
for url in urls {
AppSelectionManager.shared.handleDeepLink(url)
}
enforceSingleWindow()
}
private func enforceSingleWindow() {
// Keep the main window (key window or first window) and close others
let windows = NSApplication.shared.windows
guard windows.count > 1 else { return }
// Prefer the key window, or the first one if none are key
let keepWindow = NSApplication.shared.keyWindow ?? windows.first
for window in windows {
if window !== keepWindow {
window.close()
}
}
keepWindow?.makeKeyAndOrderFront(nil)
}
func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {
if let window = sender.windows.first {
window.makeKeyAndOrderFront(nil)
}
return true
}
}
@main
struct NotificationLightMacApp: App {
@NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
@StateObject private var appSelectionManager = AppSelectionManager.shared
var body: some Scene {
WindowGroup {
ContentView()
.environmentObject(appSelectionManager) // Inject into environment
}
.windowStyle(HiddenTitleBarWindowStyle())
.commands {
CommandGroup(replacing: .newItem) { }
}
}
}
// MARK: - Extensions
extension NSImage {
var averageColor: Color {
guard let cgImage = self.cgImage(forProposedRect: nil, context: nil, hints: nil) else { return .gray }
let inputImage = CIImage(cgImage: cgImage)
let extent = inputImage.extent
let inputExtent = CIVector(x: extent.origin.x, y: extent.origin.y, z: extent.size.width, w: extent.size.height)
guard let filter = CIFilter(name: "CIAreaAverage", parameters: [kCIInputImageKey: inputImage, kCIInputExtentKey: inputExtent]) else { return .gray }
guard let outputImage = filter.outputImage else { return .gray }
var bitmap = [UInt8](repeating: 0, count: 4)
let context = CIContext(options: [.workingColorSpace: NSNull()])
context.render(outputImage, toBitmap: &bitmap, rowBytes: 4, bounds: CGRect(x: 0, y: 0, width: 1, height: 1), format: .RGBA8, colorSpace: nil)
return Color(red: Double(bitmap[0]) / 255.0, green: Double(bitmap[1]) / 255.0, blue: Double(bitmap[2]) / 255.0)
}
}
// MARK: - Visual Effects
struct VisualEffectView: NSViewRepresentable {
func makeNSView(context: Context) -> NSVisualEffectView {
let view = NSVisualEffectView()
view.blendingMode = .behindWindow
view.state = .active
view.material = .hudWindow // Gives a nice dark/light blur depending on system theme
return view
}
func updateNSView(_ nsView: NSVisualEffectView, context: Context) {}
}
struct WindowAccessor: NSViewRepresentable {
var callback: (NSWindow?) -> Void
func makeNSView(context: Context) -> NSView {
let view = NSView()
DispatchQueue.main.async { self.callback(view.window) }
return view
}
func updateNSView(_ nsView: NSView, context: Context) {}
}
// MARK: - Models
struct WatchedApp: Identifiable, Codable, Hashable {
var id: String { bundleIdentifier }
let name: String
let bundleIdentifier: String
let iconPath: String?
}
// MARK: - App Selection Manager
class AppSelectionManager: ObservableObject {
static let shared = AppSelectionManager()
@Published var showSettings: Bool = false
@Published var watchedApps: [WatchedApp] = [] {
didSet {
saveApps()
notificationWatcher?.updateWatchedApps(watchedApps)
}
}
@Published var isMonitoring = false {
didSet {
if isMonitoring {
startMonitoring()
} else {
stopMonitoring()
}
}
}
@Published var activeAppIDs: Set<String> = [] {
didSet {
updateLight()
}
}
@Published var showDebugLogs: Bool = true {
didSet {
UserDefaults.standard.set(showDebugLogs, forKey: "ShowDebugLogs")
}
}
@Published var enableBlur: Bool = false {
didSet {
UserDefaults.standard.set(enableBlur, forKey: "EnableBlur")
}
}
@Published var accessibilityPermissionGranted = false
@Published var debugLog: String = "Waiting for notifications..."
private var notificationWatcher: NotificationWatcher?
private var workspaceObserver: NSObjectProtocol?
private init() {
loadApps()
// Load Settings
showDebugLogs = UserDefaults.standard.object(forKey: "ShowDebugLogs") as? Bool ?? true
enableBlur = UserDefaults.standard.object(forKey: "EnableBlur") as? Bool ?? false
checkAccessibilityPermissions()
// Setup Notification Watcher
notificationWatcher = NotificationWatcher(
watchedApps: watchedApps,
onNotificationDetected: { [weak self] bundleID, name in
DispatchQueue.main.async {
self?.handleNewNotification(bundleID: bundleID, name: name)
}
},
logHandler: { [weak self] log in
DispatchQueue.main.async {
self?.debugLog = "LOG: \(log)"
}
}
)
// Setup Workspace Observer for App Activation
workspaceObserver = NSWorkspace.shared.notificationCenter.addObserver(
forName: NSWorkspace.didActivateApplicationNotification,
object: nil,
queue: .main
) { [weak self] notification in
self?.handleAppActivation(notification)
}
}
deinit {
if let observer = workspaceObserver {
NSWorkspace.shared.notificationCenter.removeObserver(observer)
}
}
// MARK: - Deep Linking
func handleDeepLink(_ url: URL) {
guard url.scheme == "notilight" else { return }
switch url.host {
case "start": isMonitoring = true
case "stop": isMonitoring = false
case "toggle": isMonitoring.toggle()
case "clear": activeAppIDs.removeAll()
case "test": CameraManager.shared.toggleCamera()
case "settings": showSettings = true
case "add": addApp()
default: break
}
}
// MARK: - App Management
func addApp() {
let panel = NSOpenPanel()
panel.allowedContentTypes = [.application]
panel.allowsMultipleSelection = true
panel.canChooseDirectories = false
if panel.runModal() == .OK {
for url in panel.urls {
if let bundle = Bundle(url: url),
let bundleID = bundle.bundleIdentifier {
// Try to get a friendly name
let name = bundle.object(forInfoDictionaryKey: "CFBundleDisplayName") as? String ??
bundle.object(forInfoDictionaryKey: "CFBundleName") as? String ??
url.deletingPathExtension().lastPathComponent
let newApp = WatchedApp(name: name, bundleIdentifier: bundleID, iconPath: url.path)
if !watchedApps.contains(where: { $0.bundleIdentifier == bundleID }) {
watchedApps.append(newApp)
}
}
}
}
}
func removeApp(_ app: WatchedApp) {
if let index = watchedApps.firstIndex(of: app) {
watchedApps.remove(at: index)
}
activeAppIDs.remove(app.bundleIdentifier)
}
func toggleActiveState(for app: WatchedApp) {
if activeAppIDs.contains(app.bundleIdentifier) {
activeAppIDs.remove(app.bundleIdentifier)
} else {
// Manual toggle ON (for testing or manual reminder)
activeAppIDs.insert(app.bundleIdentifier)
}
}
// MARK: - Monitoring Logic
func checkAccessibilityPermissions() {
let options = [kAXTrustedCheckOptionPrompt.takeUnretainedValue() as String: true]
accessibilityPermissionGranted = AXIsProcessTrustedWithOptions(options as CFDictionary)
}
private func startMonitoring() {
checkAccessibilityPermissions()
if !accessibilityPermissionGranted {
isMonitoring = false
return
}
notificationWatcher?.start()
}
private func stopMonitoring() {
notificationWatcher?.stop()
activeAppIDs.removeAll()
updateLight()
}
private func handleNewNotification(bundleID: String, name: String) {
// Find the app in our list that matches the name/ID
if let app = watchedApps.first(where: { $0.bundleIdentifier == bundleID || $0.name == name }) {
activeAppIDs.insert(app.bundleIdentifier)
debugLog = "Active: \(app.name)"
} else {
// Fallback: search by name
if let app = watchedApps.first(where: { name.localizedCaseInsensitiveContains($0.name) }) {
activeAppIDs.insert(app.bundleIdentifier)
debugLog = "Active (Match): \(app.name)"
}
}
}
private func handleAppActivation(_ notification: Notification) {
guard let app = notification.userInfo?[NSWorkspace.applicationUserInfoKey] as? NSRunningApplication,
let bundleID = app.bundleIdentifier else { return }
if activeAppIDs.contains(bundleID) {
activeAppIDs.remove(bundleID)
debugLog = "Cleared: \(app.localizedName ?? bundleID)"
}
}
private func updateLight() {
if !activeAppIDs.isEmpty {
CameraManager.shared.toggleCamera(forceOn: true)
} else {
CameraManager.shared.toggleCamera(forceOff: true)
}
}
// MARK: - Persistence
private func saveApps() {
if let encoded = try? JSONEncoder().encode(watchedApps) {
UserDefaults.standard.set(encoded, forKey: "WatchedApps")
}
}
private func loadApps() {
if let data = UserDefaults.standard.data(forKey: "WatchedApps"),
let decoded = try? JSONDecoder().decode([WatchedApp].self, from: data) {
watchedApps = decoded
}
}
}
// MARK: - Notification Watcher
class NotificationWatcher {
private var appObserver: AXObserver?
private var watchedApps: [WatchedApp]
private let onNotificationDetected: (String, String) -> Void // BundleID or Name, DisplayName
private let logHandler: (String) -> Void
private var isRunning = false
init(watchedApps: [WatchedApp], onNotificationDetected: @escaping (String, String) -> Void, logHandler: @escaping (String) -> Void) {
self.watchedApps = watchedApps
self.onNotificationDetected = onNotificationDetected
self.logHandler = logHandler
}
func updateWatchedApps(_ apps: [WatchedApp]) {
self.watchedApps = apps
}
func start() {
guard !isRunning else { return }
let bundleID = "com.apple.notificationcenterui"
guard let app = NSRunningApplication.runningApplications(withBundleIdentifier: bundleID).first else {
logHandler("Error: Notification Center process not found")
return
}
let pid = app.processIdentifier
// Create Observer
var observer: AXObserver?
let result = AXObserverCreate(pid, { (observer, element, notification, refcon) in
guard let refcon = refcon else { return }
let watcher = Unmanaged<NotificationWatcher>.fromOpaque(refcon).takeUnretainedValue()
if notification == kAXWindowCreatedNotification as CFString {
watcher.handleWindowCreated(element: element)
}
}, &observer)
guard result == .success, let axObserver = observer else {
logHandler("Error: Failed to create AXObserver")
return
}
self.appObserver = axObserver
let selfPtr = UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque())
let appElement = AXUIElementCreateApplication(pid)
AXObserverAddNotification(axObserver, appElement, kAXWindowCreatedNotification as CFString, selfPtr)
CFRunLoopAddSource(CFRunLoopGetCurrent(), AXObserverGetRunLoopSource(axObserver), .defaultMode)
isRunning = true
logHandler("Started listening for new notifications")
}
func stop() {
guard isRunning, let axObserver = appObserver else { return }
CFRunLoopRemoveSource(CFRunLoopGetCurrent(), AXObserverGetRunLoopSource(axObserver), .defaultMode)
self.appObserver = nil
isRunning = false
logHandler("Stopped watching")
}
private func handleWindowCreated(element: AXUIElement) {
// Inspect for app name match
if let match = findMatchingApp(element: element) {
// We found a notification for a watched app!
// We pass matched app info back
onNotificationDetected(match.bundleIdentifier, match.name)
}
}
private func findMatchingApp(element: AXUIElement) -> WatchedApp? {
var foundApp: WatchedApp?
func traverse(_ el: AXUIElement, depth: Int) {
if foundApp != nil { return }
if depth > 4 { return }
// Helper to check text against apps
func check(_ text: String?) {
guard let text = text, foundApp == nil else { return }
if let match = watchedApps.first(where: { text.localizedCaseInsensitiveContains($0.name) }) {
foundApp = match
}
}
check(getAXAttributeString(el, kAXTitleAttribute as CFString))
check(getAXAttributeString(el, kAXValueAttribute as CFString))
check(getAXAttributeString(el, kAXDescriptionAttribute as CFString))
if foundApp != nil { return }
if let children = getAXAttributeArray(el, kAXChildrenAttribute as CFString) as? [AXUIElement] {
for child in children {
traverse(child, depth: depth + 1)
}
}
}
traverse(element, depth: 0)
return foundApp
}
}
// Helpers
func getAXAttributeString(_ element: AXUIElement, _ attribute: CFString) -> String? {
var value: AnyObject?
let result = AXUIElementCopyAttributeValue(element, attribute, &value)
if result == .success, let str = value as? String { return str }
return nil
}
func getAXAttributeArray(_ element: AXUIElement, _ attribute: CFString) -> [Any]? {
var value: AnyObject?
let result = AXUIElementCopyAttributeValue(element, attribute, &value)
if result == .success, let arr = value as? [Any] { return arr }
return nil
}
// MARK: - Camera Manager
class CameraManager: NSObject, ObservableObject {
static let shared = CameraManager()
private let captureSession = AVCaptureSession()
@Published var isCameraOn = false
@Published var errorMessage: String?
override init() {
super.init()
checkPermissions()
}
private func checkPermissions() {
switch AVCaptureDevice.authorizationStatus(for: .video) {
case .authorized:
setupCamera()
case .notDetermined:
AVCaptureDevice.requestAccess(for: .video) { granted in
if granted { DispatchQueue.main.async { self.setupCamera() } }
}
case .denied, .restricted:
errorMessage = "Camera access denied."
@unknown default: break
}
}
private func setupCamera() {
captureSession.beginConfiguration()
captureSession.sessionPreset = .low
let discoverySession = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInWideAngleCamera, .externalUnknown], mediaType: .video, position: .unspecified)
guard let device = discoverySession.devices.first else {
DispatchQueue.main.async { self.errorMessage = "No camera found." }
captureSession.commitConfiguration()
return
}
do {
let input = try AVCaptureDeviceInput(device: device)
if captureSession.canAddInput(input) { captureSession.addInput(input) }
let output = AVCaptureVideoDataOutput()
if captureSession.canAddOutput(output) { captureSession.addOutput(output) }
captureSession.commitConfiguration()
} catch {
DispatchQueue.main.async { self.errorMessage = "Setup error: \(error.localizedDescription)" }
captureSession.commitConfiguration()
}
}
func toggleCamera(forceOn: Bool? = nil, forceOff: Bool? = nil) {
DispatchQueue.global(qos: .userInitiated).async {
if let forceOff = forceOff, forceOff {
if self.captureSession.isRunning {
self.captureSession.stopRunning()
DispatchQueue.main.async { self.isCameraOn = false }
}
return
}
if let forceOn = forceOn, forceOn {
if !self.captureSession.isRunning {
self.captureSession.startRunning()
DispatchQueue.main.async { self.isCameraOn = true }
}
return
}
if self.captureSession.isRunning {
self.captureSession.stopRunning()
DispatchQueue.main.async { self.isCameraOn = false }
} else {
self.captureSession.startRunning()
DispatchQueue.main.async { self.isCameraOn = true }
}
}
}
}
// MARK: - Views
struct SettingsView: View {
@EnvironmentObject var appManager: AppSelectionManager
@StateObject private var cameraManager = CameraManager.shared
@Environment(\.presentationMode) var presentationMode
var body: some View {
VStack(spacing: 20) {
Text("Settings")
.font(.headline)
Divider()
Toggle("Show Debug Logs", isOn: $appManager.showDebugLogs)
.toggleStyle(SwitchToggleStyle(tint: .green))
Toggle("Enable Window Blur", isOn: $appManager.enableBlur)
.toggleStyle(SwitchToggleStyle(tint: .green))
Divider()
Button(action: {
cameraManager.toggleCamera()
}) {
HStack {
Image(systemName: cameraManager.isCameraOn ? "camera.fill" : "camera")
.foregroundColor(cameraManager.isCameraOn ? .green : .primary)
Text(cameraManager.isCameraOn ? "Turn Off Light" : "Test Light")
}
.frame(width: 150)
.padding(8)
.background(Color.white.opacity(0.1))
.cornerRadius(8)
}
.buttonStyle(PlainButtonStyle())
Spacer()
Button("Done") {
presentationMode.wrappedValue.dismiss()
}
}
.padding()
.frame(width: 300, height: 300)
}
}
struct AppCardView: View {
let app: WatchedApp
let isActive: Bool
let onRemove: () -> Void
let onToggle: () -> Void
@EnvironmentObject var appManager: AppSelectionManager
var body: some View {
Button(action: onToggle) {
ZStack {
// Background Blur (App Card level)
if let iconPath = app.iconPath {
let icon = NSWorkspace.shared.icon(forFile: iconPath)
icon.averageColor
.opacity(appManager.enableBlur ? 0.2 : 0.4) // Adjust opacity for vibrancy
.blur(radius: 20)
} else {
Color.gray.opacity(0.3)
.blur(radius: 20)
}
// Content
VStack {
let icon = NSWorkspace.shared.icon(forFile: app.iconPath ?? "")
Image(nsImage: icon)
.resizable()
.frame(width: 48, height: 48)
Text(app.name)
.font(.headline)
.lineLimit(1)
.foregroundColor(.primary)
}
.padding()
// Active Indicator (Border)
if isActive {
RoundedRectangle(cornerRadius: 12)
.stroke(Color.green, lineWidth: 3)
}
// Delete Button
VStack {
HStack {
Spacer()
Button(action: onRemove) {
Image(systemName: "xmark.circle.fill")
.foregroundColor(.gray.opacity(0.8))
}
.buttonStyle(PlainButtonStyle())
.padding(5)
}
Spacer()
}
}
.frame(width: 120, height: 120)
.background(
appManager.enableBlur ? Color.white.opacity(0.1) : Color(nsColor: .windowBackgroundColor).opacity(0.6)
)
.cornerRadius(12)
.shadow(radius: 2)
}
.buttonStyle(PlainButtonStyle())
}
}
struct ContentView: View {
@EnvironmentObject var appManager: AppSelectionManager
@StateObject private var cameraManager = CameraManager.shared
// showSettings moved to appManager
@State private var showHelp = false
let columns = [
GridItem(.adaptive(minimum: 120))
]
var body: some View {
VStack(spacing: 0) {
// Header
HStack {
VStack(alignment: .leading) {
Text("Notification Light")
.font(.title)
.fontWeight(.bold)
Text(appManager.isMonitoring ? "Monitoring Active" : "Monitoring Paused")
.font(.subheadline)
.foregroundColor(appManager.isMonitoring ? .green : .secondary)
}
Spacer()
Toggle("", isOn: $appManager.isMonitoring)
.toggleStyle(SwitchToggleStyle(tint: .green))
.disabled(!appManager.accessibilityPermissionGranted)
.padding(.trailing, 10)
Button(action: { showHelp = true }) {
Image(systemName: "info.circle")
.font(.title2)
.foregroundColor(.secondary)
}
.buttonStyle(PlainButtonStyle())
.padding(.trailing, 8)
.alert(isPresented: $showHelp) {
Alert(
title: Text("How to Stop the Light"),
message: Text("To turn the light OFF, simply open (focus) the app that sent the notification.\n\nAlternatively, click the App Card in the grid to manually clear it.\n\nClick 'Clear All' at the bottom to reset everything."),
dismissButton: .default(Text("OK"))
)
}
Button(action: { appManager.showSettings = true }) {
Image(systemName: "gear")
.font(.title2)
.foregroundColor(.secondary)
}
.buttonStyle(PlainButtonStyle())
.keyboardShortcut(",", modifiers: .command)
.sheet(isPresented: $appManager.showSettings) {
SettingsView()
}
}
.padding()
.background(
appManager.enableBlur
? Color(nsColor: .controlBackgroundColor).opacity(0.3)
: Color(nsColor: .controlBackgroundColor)
)
if !appManager.accessibilityPermissionGranted {
HStack {
Image(systemName: "exclamationmark.triangle.fill")
.foregroundColor(.orange)
Text("Accessibility Permission Needed")
Button("Open Settings") {
let url = URL(string: "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility")!
NSWorkspace.shared.open(url)
}
}
.padding(8)
.background(Color.orange.opacity(0.1))
}
ScrollView {
LazyVGrid(columns: columns, spacing: 20) {
ForEach(appManager.watchedApps) { app in
AppCardView(
app: app,
isActive: appManager.activeAppIDs.contains(app.bundleIdentifier),
onRemove: { appManager.removeApp(app) },
onToggle: { appManager.toggleActiveState(for: app) }
)
}
// Add Button Card
Button(action: appManager.addApp) {
ZStack {
if appManager.enableBlur {
Color.white.opacity(0.1)
} else {
Color(nsColor: .controlBackgroundColor).opacity(0.5)
}
VStack {
Image(systemName: "plus")
.font(.largeTitle)
.foregroundColor(.secondary)
Text("Add App")
.foregroundColor(.secondary)
}
}
.frame(width: 120, height: 120)
.cornerRadius(12)
.overlay(
RoundedRectangle(cornerRadius: 12)
.stroke(Color.secondary.opacity(0.3), style: StrokeStyle(lineWidth: 2, dash: [5]))
)
}
.buttonStyle(PlainButtonStyle())
}
.padding()
}
Divider()
// Footer Log
VStack(alignment: .leading) {
HStack {
if cameraManager.isCameraOn {
Label("Light ON", systemImage: "camera.fill")
.foregroundColor(.green)
} else {
Label("Light OFF", systemImage: "camera")
.foregroundColor(.secondary)
}
// Simple "Clear All" button for convenience
if !appManager.activeAppIDs.isEmpty {
Spacer()
Button("Clear All") {
appManager.activeAppIDs.removeAll()
}
.font(.caption)
}
if appManager.showDebugLogs {
Spacer()
Text(appManager.debugLog)
.font(.caption2)
.foregroundColor(.secondary)
.lineLimit(1)
}
}
.padding(.horizontal)
.padding(.vertical, 8)
}
.background(
appManager.enableBlur
? Color(nsColor: .controlBackgroundColor).opacity(0.3)
: Color(nsColor: .controlBackgroundColor)
)
}
.frame(minWidth: 500, minHeight: 400)
.background(
Group {
if appManager.enableBlur {
VisualEffectView().ignoresSafeArea()
} else {
Color(nsColor: .windowBackgroundColor)
}
}
)
// Window Accessor to toggle transparency on the window itself
.background(WindowAccessor { window in
guard let window = window else { return }
if appManager.enableBlur {
window.isOpaque = false
window.backgroundColor = .clear
// Adding fullSizeContentView to style mask helps the view extend behind titlebar
if !window.styleMask.contains(.fullSizeContentView) {
window.styleMask.insert(.fullSizeContentView)
}
window.titlebarAppearsTransparent = true
} else {
window.isOpaque = true
window.backgroundColor = .windowBackgroundColor
// We might want to remove fullSizeContentView if it wasn't there,
// but HiddenTitleBarWindowStyle likely adds it anyway.
}
})
}
}