From 1f0eea3cc6042779773e39b71a28a962f78d73b0 Mon Sep 17 00:00:00 2001 From: Hariharan Mudaliar Date: Mon, 1 Dec 2025 13:01:44 +0530 Subject: [PATCH 1/5] Working a bit --- .../DynamicIslandViewCoordinator.swift | 2 +- DynamicIsland/Localizable.xcstrings | 131 +++++++-- .../components/OSD/CustomOSDView.swift | 182 +++++++++++++ .../components/Settings/SettingsView.swift | 229 +++++++++++++--- .../managers/CustomOSDWindowManager.swift | 252 ++++++++++++++++++ .../managers/SystemChangesObserver.swift | 67 +++-- DynamicIsland/managers/SystemHUDManager.swift | 105 +++++++- DynamicIsland/models/Constants.swift | 8 + 8 files changed, 883 insertions(+), 93 deletions(-) create mode 100644 DynamicIsland/components/OSD/CustomOSDView.swift create mode 100644 DynamicIsland/managers/CustomOSDWindowManager.swift diff --git a/DynamicIsland/DynamicIslandViewCoordinator.swift b/DynamicIsland/DynamicIslandViewCoordinator.swift index 68c1c9f..f4da796 100644 --- a/DynamicIsland/DynamicIslandViewCoordinator.swift +++ b/DynamicIsland/DynamicIslandViewCoordinator.swift @@ -135,7 +135,7 @@ class DynamicIslandViewCoordinator: ObservableObject { sneakPeekDuration = resolvedDuration if type != .music && type != .timer && type != .reminder { // close() - if !hudReplacement { + if !Defaults[.enableSystemHUD] { return } } diff --git a/DynamicIsland/Localizable.xcstrings b/DynamicIsland/Localizable.xcstrings index 3023e82..f76b7e6 100644 --- a/DynamicIsland/Localizable.xcstrings +++ b/DynamicIsland/Localizable.xcstrings @@ -1119,6 +1119,10 @@ } } }, + "• Frosted Glass: Translucent blur effect" : { + "comment" : "A bullet point in the \"Appearance\" section of the Custom OSD settings, describing a glass material option.", + "isCommentAutoGenerated" : true + }, "• Improved performance" : { "localizations" : { "ar" : { @@ -1219,6 +1223,10 @@ } } }, + "• Liquid Glass: Modern glass effect (macOS 26+)" : { + "comment" : "A description of the \"Liquid Glass\" option in the Custom OSD settings.", + "isCommentAutoGenerated" : true + }, "• New feature 1" : { "localizations" : { "ar" : { @@ -1319,6 +1327,10 @@ } } }, + "• Solid Dark/Light/Auto: Opaque backgrounds" : { + "comment" : "A bullet point in the \"Appearance\" section of the Custom OSD settings, describing the appearance of the OSD when using solid colors.", + "isCommentAutoGenerated" : true + }, "• Thinking" : { "localizations" : { "fr" : { @@ -2324,6 +2336,10 @@ } } }, + "Adjust settings above to see changes in real-time. The actual OSD appears at the bottom center of your screen." : { + "comment" : "A footer in the \"Preview\" section of the Custom OSD settings, explaining how to use the live preview feature.", + "isCommentAutoGenerated" : true + }, "AI Assistant" : { "localizations" : { "fr" : { @@ -3270,6 +3286,16 @@ } } }, + "Atoll" : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Atoll" + } + } + } + }, "Attached Files" : { "localizations" : { "fr" : { @@ -3492,6 +3518,10 @@ } } }, + "Backlight" : { + "comment" : "A control for adjusting the keyboard backlight intensity.", + "isCommentAutoGenerated" : true + }, "Battery" : { "localizations" : { "ar" : { @@ -4074,6 +4104,10 @@ } } }, + "Brightness" : { + "comment" : "A control that adjusts the brightness of the device.", + "isCommentAutoGenerated" : true + }, "Brightness HUD" : { "localizations" : { "fr" : { @@ -4084,6 +4118,10 @@ } } }, + "Brightness OSD" : { + "comment" : "A label for a toggle that controls whether the brightness OSD is enabled", + "isCommentAutoGenerated" : true + }, "Built-in" : { "comment" : "A label indicating that an animation is a built-in one.", "isCommentAutoGenerated" : true, @@ -4097,6 +4135,7 @@ } }, "Built-in System Monitoring" : { + "extractionState" : "stale", "localizations" : { "fr" : { "stringUnit" : { @@ -4107,6 +4146,7 @@ } }, "Built-in system monitoring detects volume, brightness, and keyboard backlight changes directly without requiring external apps." : { + "extractionState" : "stale", "localizations" : { "de" : { "stringUnit" : { @@ -4997,6 +5037,14 @@ } } }, + "Choose which system controls should display custom OSD windows." : { + "comment" : "A footer description for the \"Controls\" section of the Custom OSD settings view.", + "isCommentAutoGenerated" : true + }, + "Choose which system controls should display HUD notifications." : { + "comment" : "A footer for the \"Controls\" section in the HUD settings, explaining that users can choose which system controls should display HUD notifications.", + "isCommentAutoGenerated" : true + }, "Choose your preferred AI model and configuration" : { "localizations" : { "fr" : { @@ -5448,6 +5496,10 @@ } } }, + "Color options control the icon and progress bar appearance. Auto adapts to system theme." : { + "comment" : "A description under the \"Appearance\" section of the Custom OSD settings, explaining that the color options control the icon and progress bar appearance, and that \"Auto\" automatically adapts to the system theme.", + "isCommentAutoGenerated" : true + }, "Color Picked!" : { "localizations" : { "fr" : { @@ -5754,9 +5806,8 @@ "comment" : "A footer for the \"Timer Widget\" section in the Lock Screen Settings view.", "isCommentAutoGenerated" : true }, - "Controls whether Atoll mirrors lock/unlock events with its own live activity and audible chimes." : { - "comment" : "A footer for the \"Live Activity & Feedback\" section in the Lock Screen Settings.", - "isCommentAutoGenerated" : true + "Controls whether Dynamic Island mirrors lock/unlock events with its own live activity and audible chimes." : { + }, "Copy event link" : { "comment" : "A tooltip for a button that copies the link of a reminder event to the clipboard.", @@ -6192,6 +6243,14 @@ } } }, + "Custom OSD" : { + "comment" : "The title of the settings screen for customizing the OSD.", + "isCommentAutoGenerated" : true + }, + "Custom OSD is disabled because HUDs are enabled. Disable HUDs in the HUDs tab to use Custom OSD." : { + "comment" : "A message displayed below the toggle to inform the user that they cannot enable Custom OSD if HUDs are enabled.", + "isCommentAutoGenerated" : true + }, "Custom Timer" : { "localizations" : { "fr" : { @@ -6919,6 +6978,10 @@ } } }, + "Display custom macOS-style OSD windows at the bottom center of the screen when adjusting volume, brightness, or keyboard backlight." : { + "comment" : "A description of the functionality of the Custom OSD feature.", + "isCommentAutoGenerated" : true + }, "Display Mode" : { "localizations" : { "fr" : { @@ -7302,16 +7365,6 @@ } } }, - "Atoll" : { - "localizations" : { - "fr" : { - "stringUnit" : { - "state" : "translated", - "value" : "Atoll" - } - } - } - }, "dynamic.island" : { "localizations" : { "fr" : { @@ -7561,6 +7614,7 @@ "isCommentAutoGenerated" : true }, "Enable Built-in System HUD" : { + "extractionState" : "stale", "localizations" : { "fr" : { "stringUnit" : { @@ -7571,6 +7625,7 @@ } }, "Enable built-in system monitoring to replace macOS HUD notifications with Atoll displays." : { + "extractionState" : "stale", "localizations" : { "fr" : { "stringUnit" : { @@ -7691,6 +7746,10 @@ } } }, + "Enable Custom OSD" : { + "comment" : "A toggle that enables or disables the custom OSD feature.", + "isCommentAutoGenerated" : true + }, "Enable global keyboard shortcuts above to customize your shortcuts." : { }, @@ -7800,6 +7859,7 @@ } }, "Enable HUD replacement" : { + "extractionState" : "stale", "localizations" : { "ar" : { "stringUnit" : { @@ -7899,6 +7959,10 @@ } } }, + "Enable HUDs" : { + "comment" : "A toggle that enables or disables the use of HUDs.", + "isCommentAutoGenerated" : true + }, "Enable music live activity" : { "localizations" : { "ar" : { @@ -10115,6 +10179,14 @@ } } }, + "HUDs are disabled because Custom OSD is enabled. Disable Custom OSD in the Custom OSD tab to use HUDs." : { + "comment" : "A message displayed below the toggle to disable HUDs, explaining that it's disabled because Custom OSD is enabled.", + "isCommentAutoGenerated" : true + }, + "Icon & Progress Color" : { + "comment" : "A picker that lets users choose the color scheme for the icon and progress bar in the OSD.", + "isCommentAutoGenerated" : true + }, "Idle" : { "comment" : "A label displayed alongside the status of a GPU device.", "isCommentAutoGenerated" : true, @@ -10537,6 +10609,10 @@ } } }, + "Keyboard Backlight OSD" : { + "comment" : "A label displayed above the toggle for the keyboard backlight OSD.", + "isCommentAutoGenerated" : true + }, "Keyboard shortcuts are disabled" : { "localizations" : { "fr" : { @@ -10723,6 +10799,10 @@ } } }, + "Live Preview" : { + "comment" : "A section header that indicates the live preview of custom OSD settings.", + "isCommentAutoGenerated" : true + }, "Live stream indicator" : { "comment" : "A visual indicator that appears when a music stream is live.", "isCommentAutoGenerated" : true @@ -11289,6 +11369,10 @@ "comment" : "A picker that lets the user select the material of the lock screen glass.", "isCommentAutoGenerated" : true }, + "Material Options:" : { + "comment" : "A label describing the material options for the custom OSD.", + "isCommentAutoGenerated" : true + }, "Max Capacity: %lld%%" : { "localizations" : { "ar" : { @@ -15495,8 +15579,9 @@ } } }, - "Replaces system HUD notifications with Atoll displays." : { - + "Replaces macOS system HUD with Dynamic Island displays for volume, brightness, and keyboard backlight." : { + "comment" : "A footer description of the HUDs feature.", + "isCommentAutoGenerated" : true }, "Request Access" : { "localizations" : { @@ -16288,6 +16373,7 @@ } }, "Sensitivity" : { + "extractionState" : "stale", "localizations" : { "fr" : { "stringUnit" : { @@ -18794,8 +18880,9 @@ } } }, - "Toggle the Atoll open or closed from anywhere." : { - + "Toggle the Dynamic Island open or closed from anywhere." : { + "comment" : "A description of the \"Toggle Navigation\" keyboard shortcut.", + "isCommentAutoGenerated" : true }, "Total · %@" : { "comment" : "A label displaying the total storage capacity of a disk device. The argument is the total storage capacity of the disk device.", @@ -19860,6 +19947,10 @@ } } }, + "Volume" : { + "comment" : "A button that sets the preview to show a volume OSD.", + "isCommentAutoGenerated" : true + }, "Volume HUD" : { "localizations" : { "fr" : { @@ -19870,6 +19961,10 @@ } } }, + "Volume OSD" : { + "comment" : "A toggle that enables or disables the volume OSD", + "isCommentAutoGenerated" : true + }, "Weather" : { "comment" : "A label and its accompanying text displayed in a lock screen panel.", "isCommentAutoGenerated" : true @@ -20125,7 +20220,7 @@ } } }, - "With %lld graphs enabled, the Atoll will expand horizontally to accommodate all graphs in a single row." : { + "With %lld graphs enabled, the Dynamic Island will expand horizontally to accommodate all graphs in a single row." : { }, "Write" : { diff --git a/DynamicIsland/components/OSD/CustomOSDView.swift b/DynamicIsland/components/OSD/CustomOSDView.swift new file mode 100644 index 0000000..1d582b7 --- /dev/null +++ b/DynamicIsland/components/OSD/CustomOSDView.swift @@ -0,0 +1,182 @@ +#if os(macOS) +import SwiftUI +import Defaults + +/// Custom OSD panel that mimics macOS native OSD appearance +/// Supports volume, brightness, and keyboard backlight displays +struct CustomOSDView: View { + @Binding var type: SneakContentType + @Binding var value: CGFloat + @Binding var icon: String + + @Default(.osdMaterial) var osdMaterial + @Default(.osdIconColorStyle) var osdIconColorStyle + @Environment(\.colorScheme) var colorScheme + + private let iconSize: CGFloat = 56 + private let progressBarHeight: CGFloat = 6 + private let spacing: CGFloat = 20 + private let segmentCount: Int = 16 + + var body: some View { + VStack(spacing: spacing) { + // Icon + Image(systemName: symbolName) + .font(.system(size: iconSize, weight: .regular)) + .foregroundStyle(iconColor) + .symbolRenderingMode(.hierarchical) + + // Progress/Value Indicator + progressView + .frame(width: 140) + } + .frame(width: 200, height: 200) + .background( + backgroundView + .clipShape(RoundedRectangle(cornerRadius: 18, style: .continuous)) + ) + .clipShape(RoundedRectangle(cornerRadius: 18, style: .continuous)) + .shadow(color: Color.black.opacity(0.25), radius: 24, x: 0, y: 8) + } + + // MARK: - Symbol Logic + + private var symbolName: String { + if !icon.isEmpty { + return icon + } + + switch type { + case .volume: + if value < 0.01 { + return "speaker.slash.fill" + } else if value < 0.33 { + return "speaker.fill" + } else if value < 0.66 { + return "speaker.wave.1.fill" + } else { + return "speaker.wave.3.fill" + } + + case .brightness: + return "sun.max.fill" + + case .backlight: + return value >= 0.5 ? "light.max" : "light.min" + + default: + return "questionmark" + } + } + + private var iconColor: Color { + switch osdIconColorStyle { + case .white: + return .white + case .whiteTransparent: + return .white.opacity(0.85) + case .lightGray: + return Color(white: 0.85) + case .darkGray: + return Color(white: 0.3) + case .black: + return .black + case .blackTransparent: + return .black.opacity(0.85) + case .auto: + return colorScheme == .dark ? .white : .black + case .autoTransparent: + return colorScheme == .dark ? .white.opacity(0.85) : .black.opacity(0.85) + } + } + + private var textColor: Color { + switch osdIconColorStyle { + case .white, .whiteTransparent, .lightGray: + return .white + case .darkGray, .black, .blackTransparent: + return .black + case .auto, .autoTransparent: + return colorScheme == .dark ? .white : .black + } + } + + // MARK: - Progress View + + private var progressView: some View { + HStack(spacing: 3) { + ForEach(0..= 4 { - Text("With \(enabledGraphsCount) graphs enabled, the Atoll will expand horizontally to accommodate all graphs in a single row.") + Text("With \(enabledGraphsCount) graphs enabled, the Dynamic Island will expand horizontally to accommodate all graphs in a single row.") .multilineTextAlignment(.trailing) .foregroundStyle(.secondary) .font(.caption) @@ -4360,6 +4360,151 @@ struct ColorPickerSettings: View { } } +struct CustomOSDSettings: View { + @Default(.enableCustomOSD) var enableCustomOSD + @Default(.enableOSDVolume) var enableOSDVolume + @Default(.enableOSDBrightness) var enableOSDBrightness + @Default(.enableOSDKeyboardBacklight) var enableOSDKeyboardBacklight + @Default(.osdMaterial) var osdMaterial + @Default(.osdIconColorStyle) var osdIconColorStyle + @Default(.enableSystemHUD) var enableSystemHUD + + @State private var previewValue: CGFloat = 0.65 + @State private var previewType: SneakContentType = .volume + + private func highlightID(_ title: String) -> String { + SettingsTab.osd.highlightID(for: title) + } + + var body: some View { + Form { + Section { + Toggle("Enable Custom OSD", isOn: $enableCustomOSD) + .settingsHighlight(id: highlightID("Enable Custom OSD")) + .disabled(enableSystemHUD) + .onChange(of: enableCustomOSD) { _, enabled in + if enabled { + // Disable System HUD when OSD is enabled + enableSystemHUD = false + } + } + } header: { + Text("General") + } footer: { + if enableSystemHUD { + Text("Custom OSD is disabled because HUDs are enabled. Disable HUDs in the HUDs tab to use Custom OSD.") + .foregroundStyle(.secondary) + .font(.caption) + } else { + Text("Display custom macOS-style OSD windows at the bottom center of the screen when adjusting volume, brightness, or keyboard backlight.") + .foregroundStyle(.secondary) + .font(.caption) + } + } + + if enableCustomOSD { + Section { + Toggle("Volume OSD", isOn: $enableOSDVolume) + .settingsHighlight(id: highlightID("Volume OSD")) + Toggle("Brightness OSD", isOn: $enableOSDBrightness) + .settingsHighlight(id: highlightID("Brightness OSD")) + Toggle("Keyboard Backlight OSD", isOn: $enableOSDKeyboardBacklight) + .settingsHighlight(id: highlightID("Keyboard Backlight OSD")) + } header: { + Text("Controls") + } footer: { + Text("Choose which system controls should display custom OSD windows.") + .foregroundStyle(.secondary) + .font(.caption) + } + + Section { + Picker("Material", selection: $osdMaterial) { + ForEach(OSDMaterial.allCases, id: \.self) { material in + Text(material.rawValue).tag(material) + } + } + .settingsHighlight(id: highlightID("Material")) + .onChange(of: osdMaterial) { _, _ in + previewValue = previewValue == 0.65 ? 0.651 : 0.65 + } + + Picker("Icon & Progress Color", selection: $osdIconColorStyle) { + ForEach(OSDIconColorStyle.allCases, id: \.self) { style in + Text(style.rawValue).tag(style) + } + } + .settingsHighlight(id: highlightID("Icon & Progress Color")) + .onChange(of: osdIconColorStyle) { _, _ in + previewValue = previewValue == 0.65 ? 0.651 : 0.65 + } + } header: { + Text("Appearance") + } footer: { + VStack(alignment: .leading, spacing: 4) { + Text("Material Options:") + Text("• Frosted Glass: Translucent blur effect") + Text("• Liquid Glass: Modern glass effect (macOS 26+)") + Text("• Solid Dark/Light/Auto: Opaque backgrounds") + Text("") + Text("Color options control the icon and progress bar appearance. Auto adapts to system theme.") + } + .foregroundStyle(.secondary) + .font(.caption) + } + + Section { + HStack { + Spacer() + VStack(spacing: 16) { + Text("Live Preview") + .font(.caption) + .foregroundStyle(.secondary) + + CustomOSDView( + type: .constant(previewType), + value: .constant(previewValue), + icon: .constant("") + ) + .frame(width: 200, height: 200) + + HStack(spacing: 8) { + Button("Volume") { + previewType = .volume + } + .buttonStyle(.bordered) + + Button("Brightness") { + previewType = .brightness + } + .buttonStyle(.bordered) + + Button("Backlight") { + previewType = .backlight + } + .buttonStyle(.bordered) + } + .controlSize(.small) + + Slider(value: $previewValue, in: 0...1) + .frame(width: 160) + } + .padding(.vertical, 12) + Spacer() + } + } header: { + Text("Preview") + } footer: { + Text("Adjust settings above to see changes in real-time. The actual OSD appears at the bottom center of your screen.") + .foregroundStyle(.secondary) + .font(.caption) + } + } + } + .navigationTitle("Custom OSD") + } +} + #Preview { HUD() } diff --git a/DynamicIsland/managers/CustomOSDWindowManager.swift b/DynamicIsland/managers/CustomOSDWindowManager.swift new file mode 100644 index 0000000..d35eafc --- /dev/null +++ b/DynamicIsland/managers/CustomOSDWindowManager.swift @@ -0,0 +1,252 @@ +#if os(macOS) +import AppKit +import SwiftUI +import SkyLightWindow +import QuartzCore +import Defaults + +/// Manages custom OSD windows for volume, brightness, and keyboard backlight controls +/// Mimics macOS native OSD behavior with custom styling +@MainActor +final class CustomOSDWindowManager { + static let shared = CustomOSDWindowManager() + + private var volumeWindow: OSDWindow? + private var brightnessWindow: OSDWindow? + private var backlightWindow: OSDWindow? + + private var hideWorkItem: DispatchWorkItem? + private let displayDuration: TimeInterval = 2.0 + private let animationDuration: TimeInterval = 0.3 + private var isInitialized = false + + // Standard macOS OSD dimensions (approximate) + private let osdWidth: CGFloat = 200 + private let osdHeight: CGFloat = 200 + + private init() {} + + // MARK: - Public API + + func showVolume(value: CGFloat, isMuted: Bool = false, icon: String = "") { + guard Defaults[.enableCustomOSD], isInitialized else { return } + show(type: .volume, value: value, icon: icon) + } + + func showBrightness(value: CGFloat) { + guard Defaults[.enableCustomOSD], isInitialized else { return } + show(type: .brightness, value: value, icon: "") + } + + func showBacklight(value: CGFloat) { + guard Defaults[.enableCustomOSD], isInitialized else { return } + show(type: .backlight, value: value, icon: "") + } + + func initialize() { + isInitialized = true + } + + // MARK: - Private Implementation + + private func show(type: SneakContentType, value: CGFloat, icon: String) { + guard let screen = NSScreen.main else { return } + + // Close other windows first + hideAllWindowsExcept(type: type) + + let window = ensureWindow(for: type) + updateContent(window: window, type: type, value: value, icon: icon) + + let targetFrame = calculateFrame(for: screen) + + if window.nsWindow.alphaValue <= 0.01 { + // Initial presentation + presentWindow(window, targetFrame: targetFrame) + } else { + // Update existing window + window.nsWindow.setFrame(targetFrame, display: true) + window.nsWindow.orderFrontRegardless() + } + + scheduleHide(for: type) + } + + private func ensureWindow(for type: SneakContentType) -> OSDWindow { + let window: OSDWindow + + switch type { + case .volume: + if let existing = volumeWindow { + return existing + } + window = createWindow(for: type) + volumeWindow = window + case .brightness: + if let existing = brightnessWindow { + return existing + } + window = createWindow(for: type) + brightnessWindow = window + case .backlight: + if let existing = backlightWindow { + return existing + } + window = createWindow(for: type) + backlightWindow = window + default: + fatalError("Unsupported OSD type: \(type)") + } + + return window + } + + private func createWindow(for type: SneakContentType) -> OSDWindow { + guard let screen = NSScreen.main else { + fatalError("No main screen available") + } + + let osdView = CustomOSDView(type: .constant(type), value: .constant(0), icon: .constant("")) + let hostingView = NSHostingView(rootView: osdView) + + let frame = calculateFrame(for: screen) + let window = NSWindow( + contentRect: frame, + styleMask: [.borderless, .nonactivatingPanel], + backing: .buffered, + defer: false + ) + + window.isOpaque = false + window.backgroundColor = .clear + window.level = .statusBar + 1 + window.collectionBehavior = [.canJoinAllSpaces, .stationary, .ignoresCycle, .fullScreenAuxiliary] + window.hasShadow = false + window.contentView = hostingView + window.alphaValue = 0 + + // Delegate to SkyLight for proper rendering + SkyLightOperator.shared.delegateWindow(window) + + return OSDWindow(nsWindow: window, hostingView: hostingView, type: type) + } + + private func updateContent(window: OSDWindow, type: SneakContentType, value: CGFloat, icon: String) { + let osdView = CustomOSDView(type: .constant(type), value: .constant(value), icon: .constant(icon)) + window.hostingView.rootView = osdView + } + + private func calculateFrame(for screen: NSScreen) -> NSRect { + let screenFrame = screen.frame + let centerX = screenFrame.midX - (osdWidth / 2) + // Position at bottom center, similar to native macOS OSD + let bottomOffset: CGFloat = 120 // Distance from bottom of screen + let centerY = screenFrame.minY + bottomOffset + + return NSRect(x: centerX, y: centerY, width: osdWidth, height: osdHeight) + } + + private func presentWindow(_ window: OSDWindow, targetFrame: NSRect) { + let startFrame = targetFrame.offsetBy(dx: 0, dy: -20) + window.nsWindow.setFrame(startFrame, display: true) + window.nsWindow.alphaValue = 0 + window.nsWindow.orderFrontRegardless() + + NSAnimationContext.runAnimationGroup { context in + context.duration = animationDuration + context.timingFunction = CAMediaTimingFunction(name: .easeOut) + window.nsWindow.animator().setFrame(targetFrame, display: true) + window.nsWindow.animator().alphaValue = 1 + } + } + + private func hideAllWindowsExcept(type: SneakContentType) { + if type != .volume, let volumeWindow = volumeWindow, volumeWindow.nsWindow.alphaValue > 0.01 { + hideWindowImmediately(volumeWindow) + } + if type != .brightness, let brightnessWindow = brightnessWindow, brightnessWindow.nsWindow.alphaValue > 0.01 { + hideWindowImmediately(brightnessWindow) + } + if type != .backlight, let backlightWindow = backlightWindow, backlightWindow.nsWindow.alphaValue > 0.01 { + hideWindowImmediately(backlightWindow) + } + } + + private func hideWindowImmediately(_ window: OSDWindow) { + NSAnimationContext.runAnimationGroup { context in + context.duration = 0.15 + context.timingFunction = CAMediaTimingFunction(name: .easeIn) + window.nsWindow.animator().alphaValue = 0 + } completionHandler: { + window.nsWindow.orderOut(nil) + } + } + + private func scheduleHide(for type: SneakContentType) { + hideWorkItem?.cancel() + + let workItem = DispatchWorkItem { [weak self] in + guard let self else { return } + Task { @MainActor in + self.hideWindow(for: type) + } + } + + hideWorkItem = workItem + DispatchQueue.main.asyncAfter(deadline: .now() + displayDuration, execute: workItem) + } + + private func hideWindow(for type: SneakContentType) { + let window: OSDWindow? + + switch type { + case .volume: + window = volumeWindow + case .brightness: + window = brightnessWindow + case .backlight: + window = backlightWindow + default: + return + } + + guard let window else { return } + + let currentFrame = window.nsWindow.frame + let hideFrame = currentFrame.offsetBy(dx: 0, dy: -20) + + NSAnimationContext.runAnimationGroup { context in + context.duration = animationDuration + context.timingFunction = CAMediaTimingFunction(name: .easeIn) + window.nsWindow.animator().setFrame(hideFrame, display: true) + window.nsWindow.animator().alphaValue = 0 + } completionHandler: { + window.nsWindow.orderOut(nil) + } + } + + // MARK: - Cleanup + + func tearDown() { + hideWorkItem?.cancel() + hideWorkItem = nil + + volumeWindow?.nsWindow.orderOut(nil) + brightnessWindow?.nsWindow.orderOut(nil) + backlightWindow?.nsWindow.orderOut(nil) + + volumeWindow = nil + brightnessWindow = nil + backlightWindow = nil + } +} + +// MARK: - OSD Window Container + +private struct OSDWindow { + let nsWindow: NSWindow + let hostingView: NSHostingView + let type: SneakContentType +} + +#endif diff --git a/DynamicIsland/managers/SystemChangesObserver.swift b/DynamicIsland/managers/SystemChangesObserver.swift index 4fab402..7c2fafa 100644 --- a/DynamicIsland/managers/SystemChangesObserver.swift +++ b/DynamicIsland/managers/SystemChangesObserver.swift @@ -145,30 +145,61 @@ final class SystemChangesObserver: MediaKeyInterceptorDelegate { if HUDSuppressionCoordinator.shared.shouldSuppressVolumeHUD { return } - coordinator?.toggleSneakPeek( - status: true, - type: .volume, - value: CGFloat(value), - icon: "" - ) + + // Send to custom OSD if enabled + if Defaults[.enableCustomOSD] && Defaults[.enableOSDVolume] { + Task { @MainActor in + CustomOSDWindowManager.shared.showVolume(value: CGFloat(value)) + } + } + + // Send to notch HUD if enabled and OSD is not enabled + if Defaults[.enableSystemHUD] && !Defaults[.enableCustomOSD] && Defaults[.enableVolumeHUD] { + coordinator?.toggleSneakPeek( + status: true, + type: .volume, + value: CGFloat(value), + icon: "" + ) + } } private func sendBrightnessNotification(value: Float) { - coordinator?.toggleSneakPeek( - status: true, - type: .brightness, - value: CGFloat(value), - icon: "" - ) + // Send to custom OSD if enabled + if Defaults[.enableCustomOSD] && Defaults[.enableOSDBrightness] { + Task { @MainActor in + CustomOSDWindowManager.shared.showBrightness(value: CGFloat(value)) + } + } + + // Send to notch HUD if enabled and OSD is not enabled + if Defaults[.enableSystemHUD] && !Defaults[.enableCustomOSD] && Defaults[.enableBrightnessHUD] { + coordinator?.toggleSneakPeek( + status: true, + type: .brightness, + value: CGFloat(value), + icon: "" + ) + } } private func sendKeyboardBacklightNotification(value: Float) { - coordinator?.toggleSneakPeek( - status: true, - type: .backlight, - value: CGFloat(value), - icon: "" - ) + // Send to custom OSD if enabled + if Defaults[.enableCustomOSD] && Defaults[.enableOSDKeyboardBacklight] { + Task { @MainActor in + CustomOSDWindowManager.shared.showBacklight(value: CGFloat(value)) + } + } + + // Send to notch HUD if enabled and OSD is not enabled + if Defaults[.enableSystemHUD] && !Defaults[.enableCustomOSD] && Defaults[.enableKeyboardBacklightHUD] { + coordinator?.toggleSneakPeek( + status: true, + type: .backlight, + value: CGFloat(value), + icon: "" + ) + } } private func configureKeyboardBacklightCallback() { diff --git a/DynamicIsland/managers/SystemHUDManager.swift b/DynamicIsland/managers/SystemHUDManager.swift index e22626d..9f3d8ec 100644 --- a/DynamicIsland/managers/SystemHUDManager.swift +++ b/DynamicIsland/managers/SystemHUDManager.swift @@ -23,16 +23,40 @@ class SystemHUDManager { } private func setupSettingsObserver() { - // Observe master toggle + // Observe master HUD toggle Defaults.publisher(.enableSystemHUD, options: []).sink { [weak self] change in + guard let self = self, self.isSetupComplete else { + return + } + Task { @MainActor in + if change.newValue && !Defaults[.enableCustomOSD] { + await self.startSystemObserver() + } else if !Defaults[.enableCustomOSD] { + // Only stop if OSD is also disabled + await self.stopSystemObserver() + } + } + }.store(in: &cancellables) + + // Observe OSD toggle + Defaults.publisher(.enableCustomOSD, options: []).sink { [weak self] change in guard let self = self, self.isSetupComplete else { return } Task { @MainActor in if change.newValue { - await self.startSystemHUD() + // Start observer for OSD if not already running + if self.changesObserver == nil { + await self.startSystemObserver() + } + } else if Defaults[.enableSystemHUD] { + // Keep observer running for HUD + if self.changesObserver == nil { + await self.startSystemObserver() + } } else { - await self.stopSystemHUD() + // Stop observer if both HUD and OSD are disabled + await self.stopSystemObserver() } } }.store(in: &cancellables) @@ -70,6 +94,40 @@ class SystemHUDManager { keyboardBacklightEnabled: change.newValue ) }.store(in: &cancellables) + + // Observe individual OSD toggles + Defaults.publisher(.enableOSDVolume, options: []).sink { [weak self] change in + guard let self = self, self.isSetupComplete, Defaults[.enableCustomOSD] else { + return + } + self.changesObserver?.update( + volumeEnabled: change.newValue, + brightnessEnabled: Defaults[.enableOSDBrightness], + keyboardBacklightEnabled: Defaults[.enableOSDKeyboardBacklight] + ) + }.store(in: &cancellables) + + Defaults.publisher(.enableOSDBrightness, options: []).sink { [weak self] change in + guard let self = self, self.isSetupComplete, Defaults[.enableCustomOSD] else { + return + } + self.changesObserver?.update( + volumeEnabled: Defaults[.enableOSDVolume], + brightnessEnabled: change.newValue, + keyboardBacklightEnabled: Defaults[.enableOSDKeyboardBacklight] + ) + }.store(in: &cancellables) + + Defaults.publisher(.enableOSDKeyboardBacklight, options: []).sink { [weak self] change in + guard let self = self, self.isSetupComplete, Defaults[.enableCustomOSD] else { + return + } + self.changesObserver?.update( + volumeEnabled: Defaults[.enableOSDVolume], + brightnessEnabled: Defaults[.enableOSDBrightness], + keyboardBacklightEnabled: change.newValue + ) + }.store(in: &cancellables) } private var cancellables = Set() @@ -82,9 +140,15 @@ class SystemHUDManager { func setup(coordinator: DynamicIslandViewCoordinator) { self.coordinator = coordinator - if Defaults[.enableSystemHUD] { + // Initialize OSD manager + Task { @MainActor in + CustomOSDWindowManager.shared.initialize() + } + + // Start observer if either HUD or OSD is enabled + if Defaults[.enableSystemHUD] || Defaults[.enableCustomOSD] { Task { @MainActor in - await startSystemHUD() + await startSystemObserver() self.isSetupComplete = true } } else { @@ -93,42 +157,55 @@ class SystemHUDManager { } @MainActor - private func startSystemHUD() async { + private func startSystemObserver() async { guard let coordinator = coordinator, !isSystemOperationInProgress else { return } isSystemOperationInProgress = true - await stopSystemHUD() // Stop any existing observer + await stopSystemObserver() // Stop any existing observer changesObserver = SystemChangesObserver(coordinator: coordinator) - let volumeEnabled = Defaults[.enableVolumeHUD] - let brightnessEnabled = Defaults[.enableBrightnessHUD] - let keyboardBacklightEnabled = Defaults[.enableKeyboardBacklightHUD] + + // Determine which controls to enable based on HUD or OSD mode + let volumeEnabled: Bool + let brightnessEnabled: Bool + let keyboardBacklightEnabled: Bool + + if Defaults[.enableCustomOSD] { + volumeEnabled = Defaults[.enableOSDVolume] + brightnessEnabled = Defaults[.enableOSDBrightness] + keyboardBacklightEnabled = Defaults[.enableOSDKeyboardBacklight] + } else { + volumeEnabled = Defaults[.enableVolumeHUD] + brightnessEnabled = Defaults[.enableBrightnessHUD] + keyboardBacklightEnabled = Defaults[.enableKeyboardBacklightHUD] + } + changesObserver?.startObserving( volumeEnabled: volumeEnabled, brightnessEnabled: brightnessEnabled, keyboardBacklightEnabled: keyboardBacklightEnabled ) - print("System HUD replacement started") + print("System observer started (HUD: \(Defaults[.enableSystemHUD]), OSD: \(Defaults[.enableCustomOSD]))") isSystemOperationInProgress = false } @MainActor - private func stopSystemHUD() async { + private func stopSystemObserver() async { guard !isSystemOperationInProgress else { return } isSystemOperationInProgress = true changesObserver?.stopObserving() changesObserver = nil - print("System HUD replacement stopped") + print("System observer stopped") isSystemOperationInProgress = false } deinit { cancellables.removeAll() Task { @MainActor in - await stopSystemHUD() + await stopSystemObserver() } } } \ No newline at end of file diff --git a/DynamicIsland/models/Constants.swift b/DynamicIsland/models/Constants.swift index 7ffb760..65a6e8d 100644 --- a/DynamicIsland/models/Constants.swift +++ b/DynamicIsland/models/Constants.swift @@ -587,6 +587,14 @@ extension Defaults.Keys { static let enableKeyboardBacklightHUD = Key("enableKeyboardBacklightHUD", default: true) static let systemHUDSensitivity = Key("systemHUDSensitivity", default: 5) + // MARK: Custom OSD Window Feature + static let enableCustomOSD = Key("enableCustomOSD", default: false) + static let enableOSDVolume = Key("enableOSDVolume", default: true) + static let enableOSDBrightness = Key("enableOSDBrightness", default: true) + static let enableOSDKeyboardBacklight = Key("enableOSDKeyboardBacklight", default: true) + static let osdMaterial = Key("osdMaterial", default: .frosted) + static let osdIconColorStyle = Key("osdIconColorStyle", default: .white) + // MARK: Screen Recording Detection Feature static let enableScreenRecordingDetection = Key("enableScreenRecordingDetection", default: true) static let showRecordingIndicator = Key("showRecordingIndicator", default: true) From 4e0659d4ccb6d78db1aaac0431fd4d513e1b8bb8 Mon Sep 17 00:00:00 2001 From: Hariharan Mudaliar Date: Mon, 1 Dec 2025 20:14:50 +0530 Subject: [PATCH 2/5] Add alpha tags --- DynamicIsland/Localizable.xcstrings | 23 +++++++ .../components/Settings/SettingsView.swift | 67 ++++++++++++++++--- DynamicIsland/models/Constants.swift | 1 + 3 files changed, 83 insertions(+), 8 deletions(-) diff --git a/DynamicIsland/Localizable.xcstrings b/DynamicIsland/Localizable.xcstrings index f76b7e6..cfe724f 100644 --- a/DynamicIsland/Localizable.xcstrings +++ b/DynamicIsland/Localizable.xcstrings @@ -2813,6 +2813,14 @@ } } }, + "ALPHA" : { + "comment" : "A label indicating a feature that is still in development.", + "isCommentAutoGenerated" : true + }, + "Alpha Feature Warning" : { + "comment" : "The title of an alert that warns users about an alpha feature.", + "isCommentAutoGenerated" : true + }, "Always hide in fullscreen" : { "localizations" : { "ar" : { @@ -6246,6 +6254,13 @@ "Custom OSD" : { "comment" : "The title of the settings screen for customizing the OSD.", "isCommentAutoGenerated" : true + }, + "Custom OSD feature requires macOS 15 or later." : { + "comment" : "A description of the Custom OSD feature, visible only on macOS 15 or later.", + "isCommentAutoGenerated" : true + }, + "Custom OSD is an experimental alpha feature and may contain bugs or unexpected behavior.\n\nThis feature requires macOS 15 or later and is still under active development. It's recommended to keep it disabled unless you want to help test it." : { + }, "Custom OSD is disabled because HUDs are enabled. Disable HUDs in the HUDs tab to use Custom OSD." : { "comment" : "A message displayed below the toggle to inform the user that they cannot enable Custom OSD if HUDs are enabled.", @@ -7613,6 +7628,10 @@ "comment" : "A description of the media panel settings in the lock screen settings view.", "isCommentAutoGenerated" : true }, + "Enable Anyway" : { + "comment" : "A button that enables the Custom OSD feature despite the warning.", + "isCommentAutoGenerated" : true + }, "Enable Built-in System HUD" : { "extractionState" : "stale", "localizations" : { @@ -11154,6 +11173,10 @@ "Mac battery at %d percent" : { "comment" : "Mac battery gauge accessibility label" }, + "macOS 15 or later required" : { + "comment" : "A message displayed when the Custom OSD feature is unavailable on this version of macOS.", + "isCommentAutoGenerated" : true + }, "Made with ❤️ by Ebullioscopic" : { "comment" : "A footer text that credits the developer of the app.", "isCommentAutoGenerated" : true diff --git a/DynamicIsland/components/Settings/SettingsView.swift b/DynamicIsland/components/Settings/SettingsView.swift index d11961f..69d261e 100644 --- a/DynamicIsland/components/Settings/SettingsView.swift +++ b/DynamicIsland/components/Settings/SettingsView.swift @@ -261,6 +261,18 @@ struct SettingsView: View { sidebarIcon(for: tab) Text(tab.title) .foregroundStyle(Color.primary) + if tab == .osd { + Spacer() + Text("ALPHA") + .font(.system(size: 9, weight: .bold)) + .foregroundStyle(.white) + .padding(.horizontal, 6) + .padding(.vertical, 2) + .background( + Capsule() + .fill(Color.orange) + ) + } } .padding(.vertical, 4) } @@ -728,7 +740,25 @@ struct SettingsView: View { } case .osd: SettingsForm(tab: .osd) { - CustomOSDSettings() + if #available(macOS 15.0, *) { + CustomOSDSettings() + } else { + VStack(spacing: 16) { + Image(systemName: "exclamationmark.triangle.fill") + .font(.system(size: 48)) + .foregroundStyle(.orange) + + Text("macOS 15 or later required") + .font(.headline) + + Text("Custom OSD feature requires macOS 15 or later.") + .font(.subheadline) + .foregroundStyle(.secondary) + .multilineTextAlignment(.center) + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + .padding() + } } case .battery: SettingsForm(tab: .battery) { @@ -4362,6 +4392,7 @@ struct ColorPickerSettings: View { struct CustomOSDSettings: View { @Default(.enableCustomOSD) var enableCustomOSD + @Default(.hasSeenOSDAlphaWarning) var hasSeenOSDAlphaWarning @Default(.enableOSDVolume) var enableOSDVolume @Default(.enableOSDBrightness) var enableOSDBrightness @Default(.enableOSDKeyboardBacklight) var enableOSDKeyboardBacklight @@ -4369,6 +4400,7 @@ struct CustomOSDSettings: View { @Default(.osdIconColorStyle) var osdIconColorStyle @Default(.enableSystemHUD) var enableSystemHUD + @State private var showAlphaWarning = false @State private var previewValue: CGFloat = 0.65 @State private var previewType: SneakContentType = .volume @@ -4379,15 +4411,22 @@ struct CustomOSDSettings: View { var body: some View { Form { Section { - Toggle("Enable Custom OSD", isOn: $enableCustomOSD) - .settingsHighlight(id: highlightID("Enable Custom OSD")) - .disabled(enableSystemHUD) - .onChange(of: enableCustomOSD) { _, enabled in - if enabled { - // Disable System HUD when OSD is enabled - enableSystemHUD = false + Toggle("Enable Custom OSD", isOn: Binding( + get: { enableCustomOSD }, + set: { newValue in + if newValue && !hasSeenOSDAlphaWarning { + showAlphaWarning = true + } else { + enableCustomOSD = newValue + if newValue { + // Disable System HUD when OSD is enabled + enableSystemHUD = false + } } } + )) + .settingsHighlight(id: highlightID("Enable Custom OSD")) + .disabled(enableSystemHUD) } header: { Text("General") } footer: { @@ -4501,6 +4540,18 @@ struct CustomOSDSettings: View { } } } + .alert("Alpha Feature Warning", isPresented: $showAlphaWarning) { + Button("Cancel", role: .cancel) { + enableCustomOSD = false + } + Button("Enable Anyway") { + hasSeenOSDAlphaWarning = true + enableCustomOSD = true + enableSystemHUD = false + } + } message: { + Text("Custom OSD is an experimental alpha feature and may contain bugs or unexpected behavior.\n\nThis feature requires macOS 15 or later and is still under active development. It's recommended to keep it disabled unless you want to help test it.") + } .navigationTitle("Custom OSD") } } diff --git a/DynamicIsland/models/Constants.swift b/DynamicIsland/models/Constants.swift index 65a6e8d..59eaff6 100644 --- a/DynamicIsland/models/Constants.swift +++ b/DynamicIsland/models/Constants.swift @@ -589,6 +589,7 @@ extension Defaults.Keys { // MARK: Custom OSD Window Feature static let enableCustomOSD = Key("enableCustomOSD", default: false) + static let hasSeenOSDAlphaWarning = Key("hasSeenOSDAlphaWarning", default: false) static let enableOSDVolume = Key("enableOSDVolume", default: true) static let enableOSDBrightness = Key("enableOSDBrightness", default: true) static let enableOSDKeyboardBacklight = Key("enableOSDKeyboardBacklight", default: true) From 39673e9130af1e4c25f3c4e025f1b85cd6348370 Mon Sep 17 00:00:00 2001 From: Hariharan Mudaliar Date: Mon, 1 Dec 2025 21:02:49 +0530 Subject: [PATCH 3/5] BugFix: Reminder Memory Leak --- DynamicIsland/Localizable.xcstrings | 33 ++ .../Providers/CalendarServiceProviding.swift | 12 + .../Calendar/DynamicIslandCalendar.swift | 366 ++++++++++----- .../components/Settings/SettingsView.swift | 19 + .../extensions/Color+AccentColor.swift | 16 + DynamicIsland/managers/CalendarManager.swift | 5 + .../ReminderLiveActivityManager.swift | 422 +++--------------- DynamicIsland/models/Constants.swift | 2 + 8 files changed, 410 insertions(+), 465 deletions(-) create mode 100644 DynamicIsland/extensions/Color+AccentColor.swift diff --git a/DynamicIsland/Localizable.xcstrings b/DynamicIsland/Localizable.xcstrings index cfe724f..0e3b184 100644 --- a/DynamicIsland/Localizable.xcstrings +++ b/DynamicIsland/Localizable.xcstrings @@ -631,6 +631,7 @@ } }, "%@" : { + "extractionState" : "stale", "localizations" : { "ar" : { "stringUnit" : { @@ -3314,6 +3315,10 @@ } } }, + "Auto-scroll to next event" : { + "comment" : "A toggle that enables or disables the automatic scrolling to the next event in the calendar view.", + "isCommentAutoGenerated" : true + }, "Automatically check for updates" : { "localizations" : { "ar" : { @@ -8433,6 +8438,10 @@ } } }, + "Event List" : { + "comment" : "A section header in the calendar settings view, describing the list of calendar events.", + "isCommentAutoGenerated" : true + }, "Exclude apps" : { "localizations" : { "en" : { @@ -9548,6 +9557,14 @@ } } }, + "Hide all-day events" : { + "comment" : "A toggle to hide all-day events in the calendar.", + "isCommentAutoGenerated" : true + }, + "Hide completed reminders" : { + "comment" : "A toggle that lets the user hide completed reminders", + "isCommentAutoGenerated" : true + }, "Hide DynamicIsland Options" : { "localizations" : { "fr" : { @@ -11187,6 +11204,14 @@ }, "Manage the Clock timer from the Clock app." : { + }, + "Mark as complete" : { + "comment" : "An accessibility label for a button that marks an item as complete.", + "isCommentAutoGenerated" : true + }, + "Mark as incomplete" : { + "comment" : "An accessibility label for a button that marks an item as incomplete.", + "isCommentAutoGenerated" : true }, "Match menubar height" : { "localizations" : { @@ -13716,6 +13741,10 @@ } } }, + "No events" : { + "comment" : "A description displayed when there are no events in the calendar.", + "isCommentAutoGenerated" : true + }, "No events today" : { "localizations" : { "ar" : { @@ -16992,6 +17021,10 @@ }, "Show floating pause/stop controls" : { + }, + "Show full event titles" : { + "comment" : "A toggle that shows or hides the full event titles in the calendar view", + "isCommentAutoGenerated" : true }, "Show media output control in other layouts" : { "comment" : "A toggle that lets the user enable or disable the media output control in layouts other than the home screen.", diff --git a/DynamicIsland/Providers/CalendarServiceProviding.swift b/DynamicIsland/Providers/CalendarServiceProviding.swift index f7e8a13..963760e 100644 --- a/DynamicIsland/Providers/CalendarServiceProviding.swift +++ b/DynamicIsland/Providers/CalendarServiceProviding.swift @@ -15,6 +15,7 @@ protocol CalendarServiceProviding { func requestAccess(to type: EKEntityType) async -> Bool func calendars() async -> [CalendarModel] func events(from start: Date, to end: Date, calendars: [String]) async -> [EventModel] + func setReminderCompleted(reminderID: String, completed: Bool) async } class CalendarService: CalendarServiceProviding { @@ -122,6 +123,17 @@ class CalendarService: CalendarServiceProviding { } } } + + @MainActor + func setReminderCompleted(reminderID: String, completed: Bool) async { + guard let reminder = store.calendarItem(withIdentifier: reminderID) as? EKReminder else { return } + reminder.isCompleted = completed + do { + try store.save(reminder, commit: true) + } catch { + print("Failed to update reminder completion: \(error)") + } + } } // MARK: - Model Extensions diff --git a/DynamicIsland/components/Calendar/DynamicIslandCalendar.swift b/DynamicIsland/components/Calendar/DynamicIslandCalendar.swift index fc0b8f4..f5fdd95 100644 --- a/DynamicIsland/components/Calendar/DynamicIslandCalendar.swift +++ b/DynamicIsland/components/Calendar/DynamicIslandCalendar.swift @@ -10,13 +10,12 @@ import Defaults import EventKit struct Config: Equatable { -// var count: Int = 10 // 3 days past + today + 7 days future - var past: Int = 3 - var future: Int = 7 - var steps: Int = 1 // Each step is one day - var spacing: CGFloat = 1 + var past: Int = 7 + var future: Int = 14 + var steps: Int = 1 + var spacing: CGFloat = 0 var showsText: Bool = true - var offset: Int = 2 // Number of dates to the left of the selected date + var offset: Int = 2 } struct WheelPicker: View { @@ -26,26 +25,28 @@ struct WheelPicker: View { @State private var haptics: Bool = false @State private var byClick: Bool = false let config: Config - + var body: some View { ScrollView(.horizontal, showsIndicators: false) { HStack(spacing: config.spacing) { - let totalSteps = config.steps * (config.past + config.future) let spacerNum = config.offset - ForEach(0.. totalSteps + spacerNum - 1){ - Spacer().frame(width: 24, height: 24).id(index) + let dateCount = totalDateItems() + let totalItems = dateCount + 2 * spacerNum + ForEach(0..= spacerNum + dateCount { + Spacer() + .frame(width: 24, height: 24) + .id(index) } else { - let offset = -config.offset - config.past - let date = dateForIndex(index, offset: offset) - let isSelected = isDateSelected(index, offset: offset) - dateButton(date: date, isSelected: isSelected, offset: offset){ + let date = dateForItemIndex(index: index, spacerNum: spacerNum) + let isSelected = Calendar.current.isDate(date, inSameDayAs: selectedDate) + dateButton(date: date, isSelected: isSelected, id: index) { selectedDate = date byClick = true - withAnimation{ - scrollPosition = indexForDate(date, offset: offset) - config.offset + withAnimation { + scrollPosition = index } - if (Defaults[.enableHaptics]) { + if Defaults[.enableHaptics] { haptics.toggle() } } @@ -56,85 +57,109 @@ struct WheelPicker: View { .scrollTargetLayout() } .scrollIndicators(.never) - .scrollPosition(id: $scrollPosition, anchor: .leading) - .scrollTargetBehavior(.viewAligned) // Ensures scroll view snaps to button center + .scrollPosition(id: $scrollPosition, anchor: .center) + .scrollTargetBehavior(.viewAligned) .safeAreaPadding(.horizontal) .sensoryFeedback(.alignment, trigger: haptics) - .onChange(of: scrollPosition) { oldValue, newValue in - if(!byClick){ + .onChange(of: scrollPosition) { _, newValue in + if !byClick { handleScrollChange(newValue: newValue, config: config) - }else{ + } else { byClick = false } } .onAppear { scrollToToday(config: config) } - } - - private func dateButton(date: Date, isSelected: Bool, offset: Int, onClick:@escaping()->Void) -> some View { - Button(action: onClick) { - VStack(spacing: 2) { - dayText(date: dateToString(for: date), isSelected: isSelected) - dateCircle(date: date, isSelected: isSelected) + .onChange(of: selectedDate) { _, newValue in + let targetIndex = indexForDate(newValue) + if scrollPosition != targetIndex { + byClick = true + withAnimation { + scrollPosition = targetIndex + } } } - .buttonStyle(PlainButtonStyle()) - .id(indexForDate(date, offset: offset)) - } - - private func dayText(date: String, isSelected: Bool) -> some View { - Text(date) - .font(.caption2) - .foregroundStyle(isSelected ? Color.accentColor : .gray) } - private func dateCircle(date: Date, isSelected: Bool) -> some View { + private func dateButton(date: Date, isSelected: Bool, id: Int, onClick: @escaping () -> Void) -> some View { + let isToday = Calendar.current.isDateInToday(date) + return Button(action: onClick) { + VStack(spacing: 8) { + dayText(date: dateToString(for: date), isToday: isToday, isSelected: isSelected) + dateCircle(date: date, isToday: isToday, isSelected: isSelected) + } + .padding(.vertical, 4) + .padding(.horizontal, 4) + .background(isSelected ? Color.effectiveAccentBackground : Color.clear) + .cornerRadius(8) + } + .buttonStyle(PlainButtonStyle()) + .id(id) + } + + private func dayText(date: String, isToday: Bool, isSelected: Bool) -> some View { + Text(date) + .font(.caption) + .foregroundColor(isSelected ? .white : Color(white: 0.65)) + } + + private func dateCircle(date: Date, isToday: Bool, isSelected: Bool) -> some View { ZStack { Circle() - .fill(isSelected ? Color.accentColor : .clear) - .frame(width: 24, height: 24) - Text("\(date.date)") - .font(.title3) - .foregroundStyle(isSelected ? .white : .gray) + .fill(isToday ? Color.effectiveAccent : .clear) + .frame(width: 20, height: 20) + Text(date.date) + .font(.body) + .fontWeight(.medium) + .foregroundColor(isSelected ? .white : Color(white: isToday ? 0.9 : 0.65)) } } - + func handleScrollChange(newValue: Int?, config: Config) { - let offset = -config.offset - config.past - let todayIndex = indexForDate(Date(), offset: offset) guard let newIndex = newValue else { return } - let targetDateIndex = newIndex + config.offset - switch targetDateIndex { - case todayIndex - config.past ..< todayIndex + config.future: - selectedDate = dateForIndex(targetDateIndex, offset: offset) - if (Defaults[.enableHaptics]) { + let spacerNum = config.offset + let dateCount = totalDateItems() + guard (spacerNum..<(spacerNum + dateCount)).contains(newIndex) else { return } + let date = dateForItemIndex(index: newIndex, spacerNum: spacerNum) + if !Calendar.current.isDate(date, inSameDayAs: selectedDate) { + selectedDate = date + if Defaults[.enableHaptics] { haptics.toggle() } - default: - return } } private func scrollToToday(config: Config) { let today = Date() - let todayIndex = indexForDate(today, offset: -config.offset - config.past) byClick = true - scrollPosition = todayIndex - config.offset + scrollPosition = indexForDate(today) selectedDate = today } - private func indexForDate(_ date: Date, offset: Int) -> Int { - let calendar = Calendar.current - let startDate = calendar.startOfDay(for: calendar.date(byAdding: .day, value: offset, to: Date()) ?? Date()) - let targetDate = calendar.startOfDay(for: date) - let daysDifference = calendar.dateComponents([.day], from: startDate, to: targetDate).day ?? 0 - return daysDifference + private func indexForDate(_ date: Date) -> Int { + let spacerNum = config.offset + let cal = Calendar.current + let today = cal.startOfDay(for: Date()) + let startDate = cal.startOfDay(for: cal.date(byAdding: .day, value: -config.past, to: today) ?? today) + let target = cal.startOfDay(for: date) + let days = cal.dateComponents([.day], from: startDate, to: target).day ?? 0 + let stepIndex = max(0, min(days / max(config.steps, 1), totalDateItems() - 1)) + return spacerNum + stepIndex } - private func dateForIndex(_ index: Int, offset: Int) -> Date { - let startDate = Calendar.current.date(byAdding: .day, value: offset, to: Date()) ?? Date() - return Calendar.current.date(byAdding: .day, value: index, to: startDate) ?? Date() + private func dateForItemIndex(index: Int, spacerNum: Int) -> Date { + let cal = Calendar.current + let today = cal.startOfDay(for: Date()) + let startDate = cal.date(byAdding: .day, value: -config.past, to: today) ?? today + let stepIndex = index - spacerNum + return cal.date(byAdding: .day, value: stepIndex * max(config.steps, 1), to: startDate) ?? today + } + + private func totalDateItems() -> Int { + let range = config.past + config.future + let step = max(config.steps, 1) + return Int(ceil(Double(range) / Double(step))) + 1 } private func dateToString(for date: Date) -> String { @@ -142,10 +167,6 @@ struct WheelPicker: View { formatter.dateFormat = "E" return formatter.string(from: date) } - - private func isDateSelected(_ index: Int, offset: Int) -> Bool { - Calendar.current.isDate(dateForIndex(index, offset: offset), inSameDayAs: selectedDate) - } } struct CalendarView: View { @@ -187,7 +208,7 @@ struct CalendarView: View { events: calendarManager.events ) if filteredEvents.isEmpty { - EmptyEventsView() + EmptyEventsView(selectedDate: selectedDate) Spacer(minLength: 0) } else { EventListView(events: calendarManager.events) @@ -216,12 +237,14 @@ struct CalendarView: View { } struct EmptyEventsView: View { + let selectedDate: Date + var body: some View { VStack { Image(systemName: "calendar.badge.checkmark") .font(.title) .foregroundColor(Color(white: 0.65)) - Text("No events today") + Text(Calendar.current.isDateInToday(selectedDate) ? "No events today" : "No events") .font(.subheadline) .foregroundColor(.white) Text("Enjoy your free time!") @@ -235,11 +258,16 @@ struct EventListView: View { @Environment(\.openURL) private var openURL @ObservedObject private var calendarManager = CalendarManager.shared let events: [EventModel] - + @Default(.autoScrollToNextEvent) private var autoScrollToNextEvent + @Default(.showFullEventTitles) private var showFullEventTitles static func filteredEvents(events: [EventModel]) -> [EventModel] { events.filter { event in - // Filter out all-day events if setting is enabled + if event.type.isReminder { + if case .reminder(let completed) = event.type { + return !completed || !Defaults[.hideCompletedReminders] + } + } if event.isAllDay && Defaults[.hideAllDayEvents] { return false } @@ -251,42 +279,129 @@ struct EventListView: View { Self.filteredEvents(events: events) } - var body: some View { - List { - ForEach(filteredEvents) { event in - Button(action: { - if let url = event.calendarAppURL() { - openURL(url) - } - }) { - eventRow(event) - } - .padding(.leading, -5) - .buttonStyle(PlainButtonStyle()) - .listRowSeparator(.automatic) - .listRowSeparatorTint(.gray.opacity(0.2)) - .listRowBackground(Color.clear) + private func scrollToRelevantEvent(proxy: ScrollViewProxy) { + guard autoScrollToNextEvent else { return } + let now = Date() + let nonAllDayUpcoming = filteredEvents.first(where: { !$0.isAllDay && $0.end > now }) + let firstAllDay = filteredEvents.first(where: { $0.isAllDay }) + let lastEvent = filteredEvents.last + guard let target = nonAllDayUpcoming ?? firstAllDay ?? lastEvent else { return } + + Task { @MainActor in + withTransaction(Transaction(animation: nil)) { + proxy.scrollTo(target.id, anchor: .top) + } + } + } + + var body: some View { + ScrollViewReader { proxy in + List { + ForEach(filteredEvents) { event in + Button(action: { + if let url = event.calendarAppURL() { + openURL(url) + } + }) { + eventRow(event) + } + .id(event.id) + .padding(.leading, -5) + .buttonStyle(PlainButtonStyle()) + .listRowSeparator(.automatic) + .listRowSeparatorTint(.gray.opacity(0.2)) + .listRowBackground(Color.clear) + } + } + .listStyle(.plain) + .scrollIndicators(.never) + .scrollContentBackground(.hidden) + .background(Color.clear) + .onAppear { + scrollToRelevantEvent(proxy: proxy) + } + .onChange(of: filteredEvents) { _, _ in + scrollToRelevantEvent(proxy: proxy) } } - .listStyle(.plain) - .scrollIndicators(.never) - .scrollContentBackground(.hidden) - .background(Color.clear) Spacer(minLength: 0) } private func eventRow(_ event: EventModel) -> some View { - // Regular event row - return AnyView( - HStack(spacing: 8) { - Circle() - .fill(Color(event.calendar.color)) - .frame(width: 8, height: 8) - HStack { - Text(event.title) - .font(.callout) - .foregroundColor(.white) - .lineLimit(1) + if event.type.isReminder { + let isCompleted: Bool + if case .reminder(let completed) = event.type { + isCompleted = completed + } else { + isCompleted = false + } + return AnyView( + HStack(spacing: 8) { + ReminderToggle( + isOn: Binding( + get: { isCompleted }, + set: { newValue in + Task { + await calendarManager.setReminderCompleted( + reminderID: event.id, completed: newValue + ) + } + } + ), + color: Color(event.calendar.color) + ) + .opacity(1.0) + HStack { + Text(event.title) + .font(.callout) + .foregroundColor(.white) + .lineLimit(showFullEventTitles ? nil : 1) + Spacer(minLength: 0) + VStack(alignment: .trailing, spacing: 4) { + if event.isAllDay { + Text("All-day") + .font(.caption) + .fontWeight(.medium) + .foregroundColor(.white) + .lineLimit(1) + } else { + Text(event.start, style: .time) + .foregroundColor(.white) + .font(.caption) + } + } + } + .opacity( + isCompleted + ? 0.4 + : event.start < Date.now && Calendar.current.isDateInToday(event.start) + ? 0.6 : 1.0 + ) + } + .padding(.vertical, 4) + ) + } else { + return AnyView( + HStack(alignment: .top, spacing: 4) { + Rectangle() + .fill(Color(event.calendar.color)) + .frame(width: 3) + .cornerRadius(1.5) + + VStack(alignment: .leading, spacing: 2) { + Text(event.title) + .font(.callout) + .fontWeight(.medium) + .foregroundColor(.white) + .lineLimit(showFullEventTitles ? nil : 2) + + if let location = event.location, !location.isEmpty { + Text(location) + .font(.caption) + .foregroundColor(Color(white: 0.65)) + .lineLimit(1) + } + } Spacer(minLength: 0) VStack(alignment: .trailing, spacing: 4) { if event.isAllDay { @@ -296,21 +411,48 @@ struct EventListView: View { .foregroundColor(.white) .lineLimit(1) } else { - Text("\(event.start, style: .time)") - .font(.caption) - .fontWeight(.medium) + Text(event.start, style: .time) .foregroundColor(.white) - .lineLimit(1) - Text("\(event.end, style: .time)") - .font(.caption2) + Text(event.end, style: .time) .foregroundColor(Color(white: 0.65)) - .lineLimit(1) } } + .font(.caption) + .frame(minWidth: 44, alignment: .trailing) } - .contentShape(Rectangle()) + .opacity( + event.eventStatus == .ended && Calendar.current.isDateInToday(event.start) + ? 0.6 : 1.0) + ) + } + } +} + +struct ReminderToggle: View { + @Binding var isOn: Bool + var color: Color + + var body: some View { + Button(action: { + isOn.toggle() + }) { + ZStack { + Circle() + .strokeBorder(color, lineWidth: 2) + .frame(width: 14, height: 14) + if isOn { + Circle() + .fill(color) + .frame(width: 8, height: 8) + } + Circle() + .fill(Color.black.opacity(0.001)) + .frame(width: 14, height: 14) } - ) + } + .buttonStyle(PlainButtonStyle()) + .padding(0) + .accessibilityLabel(isOn ? "Mark as incomplete" : "Mark as complete") } } diff --git a/DynamicIsland/components/Settings/SettingsView.swift b/DynamicIsland/components/Settings/SettingsView.swift index 69d261e..c1e9691 100644 --- a/DynamicIsland/components/Settings/SettingsView.swift +++ b/DynamicIsland/components/Settings/SettingsView.swift @@ -614,6 +614,10 @@ struct SettingsView: View { SettingsSearchEntry(tab: .calendar, title: "Countdown style", keywords: ["reminder countdown"], highlightID: SettingsTab.calendar.highlightID(for: "Countdown style")), SettingsSearchEntry(tab: .calendar, title: "Show lock screen reminder", keywords: ["lock screen", "reminder widget"], highlightID: SettingsTab.calendar.highlightID(for: "Show lock screen reminder")), SettingsSearchEntry(tab: .calendar, title: "Chip color", keywords: ["reminder chip", "color"], highlightID: SettingsTab.calendar.highlightID(for: "Chip color")), + SettingsSearchEntry(tab: .calendar, title: "Hide all-day events", keywords: ["calendar", "all-day"], highlightID: SettingsTab.calendar.highlightID(for: "Hide all-day events")), + SettingsSearchEntry(tab: .calendar, title: "Hide completed reminders", keywords: ["reminder", "completed"], highlightID: SettingsTab.calendar.highlightID(for: "Hide completed reminders")), + SettingsSearchEntry(tab: .calendar, title: "Show full event titles", keywords: ["calendar", "titles"], highlightID: SettingsTab.calendar.highlightID(for: "Show full event titles")), + SettingsSearchEntry(tab: .calendar, title: "Auto-scroll to next event", keywords: ["calendar", "scroll"], highlightID: SettingsTab.calendar.highlightID(for: "Auto-scroll to next event")), // Shelf SettingsSearchEntry(tab: .shelf, title: "Enable shelf", keywords: ["shelf", "dock"], highlightID: SettingsTab.shelf.highlightID(for: "Enable shelf")), @@ -1730,6 +1734,10 @@ struct CalendarSettings: View { @Default(.reminderSneakPeekDuration) var reminderSneakPeekDuration @Default(.enableLockScreenReminderWidget) var enableLockScreenReminderWidget @Default(.lockScreenReminderChipStyle) var lockScreenReminderChipStyle + @Default(.hideAllDayEvents) var hideAllDayEvents + @Default(.hideCompletedReminders) var hideCompletedReminders + @Default(.showFullEventTitles) var showFullEventTitles + @Default(.autoScrollToNextEvent) var autoScrollToNextEvent private func highlightID(_ title: String) -> String { SettingsTab.calendar.highlightID(for: title) @@ -1779,6 +1787,17 @@ struct CalendarSettings: View { Defaults.Toggle("Show calendar", key: .showCalendar) .settingsHighlight(id: highlightID("Show calendar")) + + Section(header: Text("Event List")) { + Toggle("Hide all-day events", isOn: $hideAllDayEvents) + .settingsHighlight(id: highlightID("Hide all-day events")) + Toggle("Hide completed reminders", isOn: $hideCompletedReminders) + .settingsHighlight(id: highlightID("Hide completed reminders")) + Toggle("Show full event titles", isOn: $showFullEventTitles) + .settingsHighlight(id: highlightID("Show full event titles")) + Toggle("Auto-scroll to next event", isOn: $autoScrollToNextEvent) + .settingsHighlight(id: highlightID("Auto-scroll to next event")) + } Section(header: Text("Reminder Live Activity")) { Defaults.Toggle("Enable reminder live activity", key: .enableReminderLiveActivity) diff --git a/DynamicIsland/extensions/Color+AccentColor.swift b/DynamicIsland/extensions/Color+AccentColor.swift new file mode 100644 index 0000000..aba982a --- /dev/null +++ b/DynamicIsland/extensions/Color+AccentColor.swift @@ -0,0 +1,16 @@ +#if os(macOS) +import SwiftUI +import Defaults + +extension Color { + /// Returns the accent color configured in settings, falling back to the system accent color. + static var effectiveAccent: Color { + Defaults[.accentColor] + } + + /// Returns a subtle background variant of the accent color. + static var effectiveAccentBackground: Color { + Defaults[.accentColor].opacity(0.25) + } +} +#endif diff --git a/DynamicIsland/managers/CalendarManager.swift b/DynamicIsland/managers/CalendarManager.swift index a2b5c5a..25440e9 100644 --- a/DynamicIsland/managers/CalendarManager.swift +++ b/DynamicIsland/managers/CalendarManager.swift @@ -203,4 +203,9 @@ class CalendarManager: ObservableObject { ) self.events = eventsResult } + + func setReminderCompleted(reminderID: String, completed: Bool) async { + await calendarService.setReminderCompleted(reminderID: reminderID, completed: completed) + await updateEvents() + } } diff --git a/DynamicIsland/managers/ReminderLiveActivityManager.swift b/DynamicIsland/managers/ReminderLiveActivityManager.swift index ad03ca9..90b7240 100644 --- a/DynamicIsland/managers/ReminderLiveActivityManager.swift +++ b/DynamicIsland/managers/ReminderLiveActivityManager.swift @@ -7,7 +7,6 @@ import Combine import Defaults -import EventKit import Foundation import CoreGraphics import os @@ -36,59 +35,23 @@ final class ReminderLiveActivityManager: ObservableObject { private let logger: os.Logger = os.Logger(subsystem: "com.ebullioscopic.Atoll", category: "ReminderLiveActivity") - private enum RefreshReason: String { - case initialization - case defaults - case manual - case eventStoreChange - case calendarListChange - case calendarEventsUpdate - case evaluation - case hover - case ticker - case other - } - private var nextReminder: ReminderEntry? private var cancellables = Set() private var tickerTask: Task? { didSet { oldValue?.cancel() } } private var evaluationTask: Task? - private var refreshTask: Task? - private var pendingRefreshTask: Task? - private var pendingRefreshForce = false - private var pendingRefreshToken = UUID() - private var pendingRefreshReason: RefreshReason = .other - private var lastKnownCalendarIDs = Set() - private var lastRefreshDate: Date? - private var lastRefreshCompletionDate: Date? - private let minimumRefreshInterval: TimeInterval = 60 - private let refreshDebounceInterval: TimeInterval = 0.3 - private var refreshTaskToken = UUID() private var hasShownCriticalSneakPeek = false - private let eventStoreChangeNoiseInterval: TimeInterval = 4 - private let eventStoreForceThrottleInterval: TimeInterval = 20 - private let manualRefreshSuppressionInterval: TimeInterval = 20 - private var lastEventStoreForceRefreshDate: Date? - private var lastManualRefreshDate: Date? - private var pendingEventStoreChange: (date: Date, reason: RefreshReason)? - private var reminderCompletionSuppressionDeadline: Date? - private let reminderCompletionSuppressionInterval: TimeInterval = 15 - private var lastUpcomingSignature: [String] = [] - private var lastNoopEventStoreRefreshDate: Date? - private let noopEventStoreSuppressionInterval: TimeInterval = 30 - private var lastCalendarEventSnapshot: [EventModel] = [] - private var lastCalendarSnapshotDate: Date? - private var lastCalendarEventSnapshotSignature: [String] = [] + private var latestEvents: [EventModel] = [] - private let calendarService: CalendarServiceProviding private let calendarManager = CalendarManager.shared var isActive: Bool { activeReminder != nil } - private init(calendarService: CalendarServiceProviding = CalendarService()) { - self.calendarService = calendarService + private init() { + latestEvents = calendarManager.events setupObservers() - scheduleRefresh(force: true, reason: .initialization) + if !latestEvents.isEmpty { + recalculateUpcomingEntries(reason: "initialization") + } } private func setupObservers() { @@ -96,7 +59,7 @@ final class ReminderLiveActivityManager: ObservableObject { .sink { [weak self] change in guard let self else { return } if change.newValue { - self.scheduleRefresh(force: true, reason: .defaults) + self.recalculateUpcomingEntries(reason: "defaults-toggle") } else { self.deactivateReminder() } @@ -106,7 +69,19 @@ final class ReminderLiveActivityManager: ObservableObject { Defaults.publisher(.reminderLeadTime, options: []) .sink { [weak self] _ in guard let self else { return } - self.scheduleRefresh(force: true, reason: .defaults) + self.recalculateUpcomingEntries(reason: "lead-time") + } + .store(in: &cancellables) + + Defaults.publisher(.hideAllDayEvents, options: []) + .sink { [weak self] _ in + self?.recalculateUpcomingEntries(reason: "hide-all-day") + } + .store(in: &cancellables) + + Defaults.publisher(.hideCompletedReminders, options: []) + .sink { [weak self] _ in + self?.recalculateUpcomingEntries(reason: "hide-completed") } .store(in: &cancellables) @@ -120,16 +95,6 @@ final class ReminderLiveActivityManager: ObservableObject { } .store(in: &cancellables) - calendarManager.$allCalendars - .sink { [weak self] calendars in - guard let self else { return } - let identifiers = Set(calendars.map { $0.id }) - guard identifiers != self.lastKnownCalendarIDs else { return } - self.lastKnownCalendarIDs = identifiers - self.handleEventStoreDrivenChange(reason: .calendarListChange) - } - .store(in: &cancellables) - calendarManager.$events .receive(on: RunLoop.main) .sink { [weak self] events in @@ -137,26 +102,13 @@ final class ReminderLiveActivityManager: ObservableObject { self.handleCalendarEventsUpdate(events) } .store(in: &cancellables) - - NotificationCenter.default.publisher(for: .EKEventStoreChanged) - .sink { [weak self] _ in - guard let self else { return } - self.handleEventStoreDrivenChange(reason: .eventStoreChange) - } - .store(in: &cancellables) } private func cancelAllTimers() { tickerTask = nil evaluationTask?.cancel() evaluationTask = nil - pendingRefreshTask?.cancel() - pendingRefreshTask = nil - pendingRefreshForce = false - refreshTask?.cancel() - refreshTask = nil hasShownCriticalSneakPeek = false - pendingEventStoreChange = nil } private func deactivateReminder() { @@ -165,32 +117,13 @@ final class ReminderLiveActivityManager: ObservableObject { upcomingEntries = [] activeWindowReminders = [] cancelAllTimers() - lastUpcomingSignature = [] - lastNoopEventStoreRefreshDate = nil - } - - private func selectedCalendarIDs() -> [String] { - calendarManager.allCalendars - .filter { calendarManager.getCalendarSelected($0) } - .map { $0.id } } private func handleCalendarEventsUpdate(_ events: [EventModel]) { - let now = Date() - let signature = events.map { $0.id } - if signature == lastCalendarEventSnapshotSignature, - let snapshotDate = lastCalendarSnapshotDate, - now.timeIntervalSince(snapshotDate) < 5 { - return - } - - lastCalendarEventSnapshot = events - lastCalendarSnapshotDate = now - lastCalendarEventSnapshotSignature = signature - + latestEvents = events guard Defaults[.enableReminderLiveActivity] else { return } logger.debug("[Reminder] Applying calendar snapshot update (events=\(events.count, privacy: .public))") - refreshFromEvents(events, referenceDate: now, reason: .calendarEventsUpdate) + recalculateUpcomingEntries(reason: "calendar-events") } private func shouldHide(_ event: EventModel) -> Bool { @@ -211,6 +144,45 @@ final class ReminderLiveActivityManager: ObservableObject { return ReminderEntry(event: event, triggerDate: trigger, leadTime: TimeInterval(leadSeconds)) } + private func recalculateUpcomingEntries(referenceDate: Date = Date(), reason: String) { + guard Defaults[.enableReminderLiveActivity] else { + deactivateReminder() + return + } + + guard calendarManager.hasReminderAccess else { + deactivateReminder() + return + } + + let leadMinutes = Defaults[.reminderLeadTime] + let upcoming = latestEvents + .filter { !shouldHide($0) } + .compactMap { makeEntry(from: $0, leadMinutes: leadMinutes, referenceDate: referenceDate) } + .sorted { $0.triggerDate < $1.triggerDate } + + upcomingEntries = upcoming + updateActiveWindowReminders(for: referenceDate) + + guard let first = upcoming.first else { + clearActiveReminderState() + logger.debug("[Reminder] No upcoming reminders found (reason=\(reason, privacy: .public))") + return + } + + logger.debug("[Reminder] Next reminder ‘\(first.event.title, privacy: .public)’ (reason=\(reason, privacy: .public))") + handleEntrySelection(first, referenceDate: referenceDate) + } + + private func clearActiveReminderState() { + nextReminder = nil + if activeReminder != nil { + activeReminder = nil + } + activeWindowReminders = [] + cancelAllTimers() + } + private func scheduleEvaluation(at date: Date) { evaluationTask?.cancel() let delay = date.timeIntervalSinceNow @@ -226,88 +198,6 @@ final class ReminderLiveActivityManager: ObservableObject { } } - private func scheduleRefresh(force: Bool, reason: RefreshReason = .other) { - let wasPending = pendingRefreshTask != nil - pendingRefreshForce = pendingRefreshForce || force - pendingRefreshToken = UUID() - pendingRefreshReason = reason - let token = pendingRefreshToken - - logger.debug("[Reminder] scheduleRefresh reason=\(reason.rawValue, privacy: .public) force=\(force, privacy: .public) pending=\(wasPending, privacy: .public)") - - refreshTask?.cancel() - pendingRefreshTask?.cancel() - pendingRefreshTask = Task { [weak self] in - guard let self else { return } - do { - try await Task.sleep(nanoseconds: UInt64(self.refreshDebounceInterval * 1_000_000_000)) - } catch { - self.logger.debug("[Reminder] Debounced refresh for reason=\(reason.rawValue, privacy: .public) was cancelled") - return - } - await self.executeScheduledRefresh(token: token) - } - } - - private func executeScheduledRefresh(token: UUID) async { - guard pendingRefreshToken == token else { return } - pendingRefreshTask = nil - - if Task.isCancelled { - logger.debug("[Reminder] Cancelled refresh token=\(token.uuidString, privacy: .public)") - return - } - - let reason = pendingRefreshReason - let now = Date() - let force = pendingRefreshForce - if !force, let last = lastRefreshDate { - let elapsed = now.timeIntervalSince(last) - if elapsed < minimumRefreshInterval { - let remaining = max(minimumRefreshInterval - elapsed, refreshDebounceInterval) - logger.debug("[Reminder] Deferring refresh reason=\(reason.rawValue, privacy: .public); next attempt in \(remaining, format: .fixed(precision: 2))s") - pendingRefreshToken = UUID() - let nextToken = pendingRefreshToken - pendingRefreshTask = Task { [weak self] in - guard let self else { return } - do { - try await Task.sleep(nanoseconds: UInt64(remaining * 1_000_000_000)) - } catch { - self.logger.debug("[Reminder] Deferred refresh for reason=\(reason.rawValue, privacy: .public) was cancelled") - return - } - await self.executeScheduledRefresh(token: nextToken) - } - return - } - } - - pendingRefreshForce = false - lastRefreshDate = now - - let startTime = Date() - logger.debug("[Reminder] Starting refresh reason=\(reason.rawValue, privacy: .public) force=\(force, privacy: .public)") - - refreshTask?.cancel() - let taskToken = UUID() - refreshTaskToken = taskToken - let task = Task { [weak self] in - guard let self else { return } - await self.refreshUpcomingReminder(force: force, reason: reason) - } - refreshTask = task - defer { - if refreshTaskToken == taskToken { - refreshTask = nil - lastRefreshCompletionDate = Date() - let duration = Date().timeIntervalSince(startTime) - logger.debug("[Reminder] Finished refresh reason=\(reason.rawValue, privacy: .public) duration=\(duration, format: .fixed(precision: 2))s upcoming=\(self.upcomingEntries.count, privacy: .public)") - processPendingEventStoreChangeIfNeeded() - } - } - _ = try? await task.value - } - private func startTickerIfNeeded() { guard tickerTask == nil else { return } tickerTask = Task { [weak self] in @@ -328,109 +218,16 @@ final class ReminderLiveActivityManager: ObservableObject { } private func handleEntrySelection(_ entry: ReminderEntry?, referenceDate: Date) { + guard nextReminder != entry else { + Task { await self.evaluateCurrentState(at: referenceDate) } + return + } + nextReminder = entry hasShownCriticalSneakPeek = false Task { await self.evaluateCurrentState(at: referenceDate) } } - private func refreshFromEvents(_ events: [EventModel], referenceDate: Date, reason: RefreshReason) { - let leadMinutes = Defaults[.reminderLeadTime] - let upcoming = events - .filter { !shouldHide($0) } - .compactMap { makeEntry(from: $0, leadMinutes: leadMinutes, referenceDate: referenceDate) } - .sorted { $0.triggerDate < $1.triggerDate } - - upcomingEntries = upcoming - updateActiveWindowReminders(for: referenceDate) - - logger.debug("[Reminder] Reduced \(events.count, privacy: .public) events to \(upcoming.count, privacy: .public) upcoming reminders") - - guard let first = upcoming.first else { - deactivateReminder() - logger.debug("[Reminder] No upcoming reminders found; awaiting next calendar update") - return - } - - logger.debug("[Reminder] Next reminder ‘\(first.event.title, privacy: .public)’ at \(first.triggerDate.timeIntervalSinceReferenceDate, privacy: .public)") - - handleEntrySelection(first, referenceDate: referenceDate) - - let signature = upcoming.map { $0.event.id } - if lastUpcomingSignature == signature { - if reason == .eventStoreChange { - lastNoopEventStoreRefreshDate = Date() - } - } else { - lastNoopEventStoreRefreshDate = nil - } - lastUpcomingSignature = signature - } - - func requestRefresh(force: Bool = false) { - let reason: RefreshReason = force ? .manual : .other - if force { - let now = Date() - if let lastManualRefreshDate, - now.timeIntervalSince(lastManualRefreshDate) < manualRefreshSuppressionInterval { - let delta = now.timeIntervalSince(lastManualRefreshDate) - logger.debug("[Reminder] Skipping manual refresh; last manual was \(delta, format: .fixed(precision: 2))s ago") - return - } - lastManualRefreshDate = now - } - scheduleRefresh(force: force, reason: reason) - } - - private func refreshUpcomingReminder(force: Bool = false, reason: RefreshReason = .other) async { - guard Defaults[.enableReminderLiveActivity] else { - deactivateReminder() - logger.debug("[Reminder] Refresh aborted (feature disabled)") - return - } - - guard calendarManager.hasReminderAccess else { - deactivateReminder() - logger.debug("[Reminder] Refresh aborted; reminder permissions missing") - return - } - - let now = Date() - - if !force, let entry = nextReminder, entry.event.start > now { - logger.debug("[Reminder] Skipping fetch; cached entry \(entry.event.title, privacy: .public) still valid for reason=\(reason.rawValue, privacy: .public)") - await evaluateCurrentState(at: now) - return - } - - if let snapshotDate = lastCalendarSnapshotDate, - now.timeIntervalSince(snapshotDate) < 5, - !lastCalendarEventSnapshot.isEmpty { - logger.debug("[Reminder] Using calendar snapshot (age=\(now.timeIntervalSince(snapshotDate), format: .fixed(precision: 2))s) for reason=\(reason.rawValue, privacy: .public)") - refreshFromEvents(lastCalendarEventSnapshot, referenceDate: now, reason: reason) - return - } - - let calendars = selectedCalendarIDs() - guard !calendars.isEmpty else { - deactivateReminder() - logger.debug("[Reminder] Refresh aborted; no calendars selected") - return - } - - let windowEnd = Calendar.current.date(byAdding: .hour, value: 24, to: now) ?? now.addingTimeInterval(24 * 60 * 60) - logger.debug("[Reminder] Fetching reminders (reason=\(reason.rawValue, privacy: .public), force=\(force, privacy: .public), calendars=\(calendars.count, privacy: .public))") - let fetchStart = Date() - let events = await calendarService.events(from: now, to: windowEnd, calendars: calendars) - let fetchDuration = Date().timeIntervalSince(fetchStart) - logger.debug("[Reminder] EventKit fetch completed (events=\(events.count, privacy: .public)) in \(fetchDuration, format: .fixed(precision: 2))s") - lastCalendarEventSnapshot = events - lastCalendarSnapshotDate = now - lastCalendarEventSnapshotSignature = events.map { $0.id } - await MainActor.run { - self.refreshFromEvents(events, referenceDate: now, reason: reason) - } - } - func evaluateCurrentState(at date: Date) async { guard Defaults[.enableReminderLiveActivity] else { deactivateReminder() @@ -450,13 +247,9 @@ final class ReminderLiveActivityManager: ObservableObject { } if entry.event.start <= date { - activeReminder = nil - nextReminder = nil - stopTicker() - hasShownCriticalSneakPeek = false - logger.debug("[Reminder] Reminder reached start time; requesting evaluation refresh") - reminderCompletionSuppressionDeadline = Date().addingTimeInterval(reminderCompletionSuppressionInterval) - scheduleRefresh(force: true, reason: .evaluation) + clearActiveReminderState() + logger.debug("[Reminder] Reminder reached start time; reevaluating reminders from cache") + recalculateUpcomingEntries(referenceDate: date, reason: "evaluation-complete") return } @@ -528,83 +321,6 @@ final class ReminderLiveActivityManager: ObservableObject { } } - private func handleEventStoreDrivenChange(reason: RefreshReason) { - processEventStoreChange(at: Date(), reason: reason) - } - - private func processEventStoreChange(at date: Date, reason: RefreshReason) { - if let manual = lastManualRefreshDate { - let delta = date.timeIntervalSince(manual) - if delta < manualRefreshSuppressionInterval { - logger.debug("[Reminder] Ignoring \(reason.rawValue, privacy: .public) change; manual refresh cooldown \(delta, format: .fixed(precision: 2))s") - return - } - } - - if let lastRefreshStart = lastRefreshDate { - let sinceStart = date.timeIntervalSince(lastRefreshStart) - if sinceStart >= 0 && sinceStart < eventStoreChangeNoiseInterval { - logger.debug("[Reminder] Ignoring \(reason.rawValue, privacy: .public); \(sinceStart, format: .fixed(precision: 2))s since start") - return - } - } - - if let lastCompletion = lastRefreshCompletionDate { - let sinceCompletion = abs(date.timeIntervalSince(lastCompletion)) - if sinceCompletion < eventStoreChangeNoiseInterval { - logger.debug("[Reminder] Ignoring \(reason.rawValue, privacy: .public); \(sinceCompletion, format: .fixed(precision: 2))s since completion") - return - } - } - - if reason == .eventStoreChange, - let suppressionDeadline = reminderCompletionSuppressionDeadline, - date <= suppressionDeadline { - let remaining = suppressionDeadline.timeIntervalSince(date) - logger.debug("[Reminder] Ignoring \(reason.rawValue, privacy: .public); reminder completion suppression \(remaining, format: .fixed(precision: 2))s") - return - } - - if reason == .eventStoreChange, - let noopDate = lastNoopEventStoreRefreshDate, - date.timeIntervalSince(noopDate) < noopEventStoreSuppressionInterval { - let remaining = noopEventStoreSuppressionInterval - date.timeIntervalSince(noopDate) - logger.debug("[Reminder] Ignoring \(reason.rawValue, privacy: .public); identical upcoming entries \(remaining, format: .fixed(precision: 2))s window") - return - } - - if let lastForce = lastEventStoreForceRefreshDate { - let sinceForce = date.timeIntervalSince(lastForce) - if sinceForce < self.eventStoreForceThrottleInterval { - logger.debug("[Reminder] Ignoring \(reason.rawValue, privacy: .public); throttle window remaining \(self.eventStoreForceThrottleInterval - sinceForce, format: .fixed(precision: 2))s") - return - } - } - - if refreshTask != nil { - pendingEventStoreChange = (date, reason) - logger.debug("[Reminder] Queued \(reason.rawValue, privacy: .public) change while refresh is running") - return - } - - triggerEventStoreForcedRefresh(at: date, reason: reason) - } - - private func processPendingEventStoreChangeIfNeeded() { - guard let pendingChange = pendingEventStoreChange else { return } - pendingEventStoreChange = nil - processEventStoreChange(at: pendingChange.date, reason: pendingChange.reason) - } - - private func triggerEventStoreForcedRefresh(at date: Date = Date(), reason: RefreshReason) { - lastEventStoreForceRefreshDate = date - if reason == .eventStoreChange, reminderCompletionSuppressionDeadline != nil { - reminderCompletionSuppressionDeadline = nil - } - logger.debug("[Reminder] Triggering event-store refresh for \(reason.rawValue, privacy: .public)") - scheduleRefresh(force: true, reason: reason) - } - static func additionalHeight(forRowCount rowCount: Int) -> CGFloat { guard rowCount > 0 else { return 0 } let rows = CGFloat(rowCount) diff --git a/DynamicIsland/models/Constants.swift b/DynamicIsland/models/Constants.swift index 59eaff6..97a06ee 100644 --- a/DynamicIsland/models/Constants.swift +++ b/DynamicIsland/models/Constants.swift @@ -503,6 +503,8 @@ extension Defaults.Keys { // MARK: Calendar static let calendarSelectionState = Key("calendarSelectionState", default: .all) + static let showFullEventTitles = Key("showFullEventTitles", default: false) + static let autoScrollToNextEvent = Key("autoScrollToNextEvent", default: true) // MARK: Fullscreen Media Detection static let alwaysHideInFullscreen = Key("alwaysHideInFullscreen", default: false) From f782c9d13565a6bbe811924fc0d736f5a5f6fc08 Mon Sep 17 00:00:00 2001 From: Hariharan Mudaliar Date: Mon, 1 Dec 2025 22:08:31 +0530 Subject: [PATCH 4/5] Improve animation --- DynamicIsland/ContentView.swift | 29 ++++++++++--------- .../models/DynamicIslandViewModel.swift | 22 ++++++-------- 2 files changed, 25 insertions(+), 26 deletions(-) diff --git a/DynamicIsland/ContentView.swift b/DynamicIsland/ContentView.swift index e070a19..a700f27 100644 --- a/DynamicIsland/ContentView.swift +++ b/DynamicIsland/ContentView.swift @@ -171,24 +171,27 @@ struct ContentView: View { mainLayout .conditionalModifier(!useModernCloseAnimation) { view in - let hoverAnimationAnimation = Animation.bouncy.speed(1.2) - let notchStateAnimation = Animation.spring.speed(1.2) - let viewTransitionAnimation = Animation.easeInOut(duration: 0.4) - return view - .animation(hoverAnimationAnimation, value: isHovering) - .animation(notchStateAnimation, value: vm.notchState) - .animation(viewTransitionAnimation, value: coordinator.currentView) - .animation(.smooth, value: gestureProgress) - .transition(.blurReplace.animation(.interactiveSpring(dampingFraction: 1.2))) - } - .conditionalModifier(useModernCloseAnimation) { view in - let hoverAnimationAnimation = Animation.bouncy.speed(1.2) + let hoverAnimation = Animation.bouncy.speed(1.2) let notchStateAnimation = Animation.spring.speed(1.2) let viewTransitionAnimation = Animation.easeInOut(duration: 0.4) return view - .animation(hoverAnimationAnimation, value: isHovering) + .animation(hoverAnimation, value: isHovering) .animation(notchStateAnimation, value: vm.notchState) .animation(viewTransitionAnimation, value: coordinator.currentView) + .animation(.smooth, value: gestureProgress) + .transition(.blurReplace.animation(.interactiveSpring(dampingFraction: 1.2))) + } + .conditionalModifier(useModernCloseAnimation) { view in + let hoverAnimation = Animation.bouncy.speed(1.2) + let openAnimation = Animation.spring(response: 0.42, dampingFraction: 0.8, blendDuration: 0) + let closeAnimation = Animation.spring(response: 0.45, dampingFraction: 1.0, blendDuration: 0) + let viewTransitionAnimation = Animation.easeInOut(duration: 0.4) + let notchAnimation = vm.notchState == .open ? openAnimation : closeAnimation + return view + .animation(hoverAnimation, value: isHovering) + .animation(notchAnimation, value: vm.notchState) + .animation(viewTransitionAnimation, value: coordinator.currentView) + .animation(.smooth, value: gestureProgress) } .conditionalModifier(interactionsEnabled) { view in view diff --git a/DynamicIsland/models/DynamicIslandViewModel.swift b/DynamicIsland/models/DynamicIslandViewModel.swift index b52cae1..a63464a 100644 --- a/DynamicIsland/models/DynamicIslandViewModel.swift +++ b/DynamicIsland/models/DynamicIslandViewModel.swift @@ -234,13 +234,11 @@ class DynamicIslandViewModel: NSObject, ObservableObject { DispatchQueue.main.async(execute: applyWindowResize) } - withAnimation(.bouncy) { - self.notchSize = targetSize - self.notchState = .open - } - - // Force music information update when notch is opened - MusicManager.shared.forceUpdate() + notchSize = targetSize + notchState = .open + + // Force music information update when notch is opened + MusicManager.shared.forceUpdate() } private func calculateDynamicNotchSize() -> CGSize { @@ -254,12 +252,10 @@ class DynamicIslandViewModel: NSObject, ObservableObject { } func close() { - withAnimation(.smooth) { [weak self] in - guard let self = self else { return } - self.notchSize = getClosedNotchSize(screen: self.screen) - self.closedNotchSize = self.notchSize - self.notchState = .closed - } + let targetSize = getClosedNotchSize(screen: screen) + notchSize = targetSize + closedNotchSize = targetSize + notchState = .closed // Set the current view to shelf if it contains files and the user enables openShelfByDefault // Otherwise, if the user has not enabled openLastShelfByDefault, set the view to home From 05ce48968db5d99aa62908becd52ed53d2aa6042 Mon Sep 17 00:00:00 2001 From: Hariharan Mudaliar Date: Mon, 1 Dec 2025 22:30:40 +0530 Subject: [PATCH 5/5] Add accessibility request button --- DynamicIsland/Localizable.xcstrings | 17 +++ .../components/Settings/SettingsView.swift | 105 +++++++++++++++++- .../AccessibilityPermissionStore.swift | 76 +++++++++++++ 3 files changed, 194 insertions(+), 4 deletions(-) create mode 100644 DynamicIsland/helpers/AccessibilityPermissionStore.swift diff --git a/DynamicIsland/Localizable.xcstrings b/DynamicIsland/Localizable.xcstrings index 0e3b184..d7e9074 100644 --- a/DynamicIsland/Localizable.xcstrings +++ b/DynamicIsland/Localizable.xcstrings @@ -1803,6 +1803,13 @@ } } }, + "Accessibility" : { + + }, + "Accessibility permission required" : { + "comment" : "A label explaining that accessibility permissions are required.", + "isCommentAutoGenerated" : true + }, "Actions" : { "localizations" : { "fr" : { @@ -9526,6 +9533,12 @@ } } } + }, + "Grant Accessibility permission in System Settings to control macOS HUD replacements from here." : { + + }, + "Grant Accessibility permission in System Settings to customize the on-screen display replacements here." : { + }, "Graph Visibility" : { "localizations" : { @@ -14756,6 +14769,10 @@ }, "Open Model Settings" : { + }, + "Open Settings" : { + "comment" : "A button that opens system settings when pressed.", + "isCommentAutoGenerated" : true }, "Open System Settings" : { diff --git a/DynamicIsland/components/Settings/SettingsView.swift b/DynamicIsland/components/Settings/SettingsView.swift index c1e9691..b7ce27f 100644 --- a/DynamicIsland/components/Settings/SettingsView.swift +++ b/DynamicIsland/components/Settings/SettingsView.swift @@ -1282,16 +1282,33 @@ struct HUD: View { @Default(.enableKeyboardBacklightHUD) var enableKeyboardBacklightHUD @Default(.systemHUDSensitivity) var systemHUDSensitivity @ObservedObject var coordinator = DynamicIslandViewCoordinator.shared + @ObservedObject private var accessibilityPermission = AccessibilityPermissionStore.shared private func highlightID(_ title: String) -> String { SettingsTab.hud.highlightID(for: title) } + + private var hasAccessibilityPermission: Bool { + accessibilityPermission.isAuthorized + } var body: some View { Form { + if !hasAccessibilityPermission { + Section { + SettingsPermissionCallout( + message: "Accessibility permission lets Dynamic Island replace the native volume, brightness, and keyboard HUDs.", + requestAction: { accessibilityPermission.requestAuthorizationPrompt() }, + openSettingsAction: { accessibilityPermission.openSystemSettings() } + ) + } header: { + Text("Accessibility") + } + } + Section { Toggle("Enable HUDs", isOn: $enableSystemHUD) - .disabled(Defaults[.enableCustomOSD]) + .disabled(Defaults[.enableCustomOSD] || !hasAccessibilityPermission) } header: { Text("General") } footer: { @@ -1299,6 +1316,10 @@ struct HUD: View { Text("HUDs are disabled because Custom OSD is enabled. Disable Custom OSD in the Custom OSD tab to use HUDs.") .foregroundStyle(.secondary) .font(.caption) + } else if !hasAccessibilityPermission { + Text("Grant Accessibility permission in System Settings to control macOS HUD replacements from here.") + .foregroundStyle(.secondary) + .font(.caption) } else { Text("Replaces macOS system HUD with Dynamic Island displays for volume, brightness, and keyboard backlight.") .foregroundStyle(.secondary) @@ -1306,7 +1327,7 @@ struct HUD: View { } } - if enableSystemHUD && !Defaults[.enableCustomOSD] { + if enableSystemHUD && !Defaults[.enableCustomOSD] && hasAccessibilityPermission { Section { Toggle("Volume HUD", isOn: $enableVolumeHUD) Toggle("Brightness HUD", isOn: $enableBrightnessHUD) @@ -1407,6 +1428,14 @@ struct HUD: View { } } .navigationTitle("HUDs") + .onAppear { + accessibilityPermission.refreshStatus() + } + .onChange(of: accessibilityPermission.isAuthorized) { _, granted in + if !granted { + enableSystemHUD = false + } + } } } @@ -4418,6 +4447,7 @@ struct CustomOSDSettings: View { @Default(.osdMaterial) var osdMaterial @Default(.osdIconColorStyle) var osdIconColorStyle @Default(.enableSystemHUD) var enableSystemHUD + @ObservedObject private var accessibilityPermission = AccessibilityPermissionStore.shared @State private var showAlphaWarning = false @State private var previewValue: CGFloat = 0.65 @@ -4426,13 +4456,33 @@ struct CustomOSDSettings: View { private func highlightID(_ title: String) -> String { SettingsTab.osd.highlightID(for: title) } + + private var hasAccessibilityPermission: Bool { + accessibilityPermission.isAuthorized + } var body: some View { Form { + if !hasAccessibilityPermission { + Section { + SettingsPermissionCallout( + message: "Accessibility permission is needed to intercept system controls for the Custom OSD.", + requestAction: { accessibilityPermission.requestAuthorizationPrompt() }, + openSettingsAction: { accessibilityPermission.openSystemSettings() } + ) + } header: { + Text("Accessibility") + } + } + Section { Toggle("Enable Custom OSD", isOn: Binding( get: { enableCustomOSD }, set: { newValue in + guard hasAccessibilityPermission else { + enableCustomOSD = false + return + } if newValue && !hasSeenOSDAlphaWarning { showAlphaWarning = true } else { @@ -4445,7 +4495,7 @@ struct CustomOSDSettings: View { } )) .settingsHighlight(id: highlightID("Enable Custom OSD")) - .disabled(enableSystemHUD) + .disabled(enableSystemHUD || !hasAccessibilityPermission) } header: { Text("General") } footer: { @@ -4453,6 +4503,10 @@ struct CustomOSDSettings: View { Text("Custom OSD is disabled because HUDs are enabled. Disable HUDs in the HUDs tab to use Custom OSD.") .foregroundStyle(.secondary) .font(.caption) + } else if !hasAccessibilityPermission { + Text("Grant Accessibility permission in System Settings to customize the on-screen display replacements here.") + .foregroundStyle(.secondary) + .font(.caption) } else { Text("Display custom macOS-style OSD windows at the bottom center of the screen when adjusting volume, brightness, or keyboard backlight.") .foregroundStyle(.secondary) @@ -4460,7 +4514,7 @@ struct CustomOSDSettings: View { } } - if enableCustomOSD { + if enableCustomOSD && hasAccessibilityPermission { Section { Toggle("Volume OSD", isOn: $enableOSDVolume) .settingsHighlight(id: highlightID("Volume OSD")) @@ -4572,6 +4626,49 @@ struct CustomOSDSettings: View { Text("Custom OSD is an experimental alpha feature and may contain bugs or unexpected behavior.\n\nThis feature requires macOS 15 or later and is still under active development. It's recommended to keep it disabled unless you want to help test it.") } .navigationTitle("Custom OSD") + .onAppear { + accessibilityPermission.refreshStatus() + } + .onChange(of: accessibilityPermission.isAuthorized) { _, granted in + if !granted { + enableCustomOSD = false + } + } + } +} + +struct SettingsPermissionCallout: View { + let message: String + let requestAction: () -> Void + let openSettingsAction: () -> Void + + var body: some View { + VStack(alignment: .leading, spacing: 8) { + Label("Accessibility permission required", systemImage: "exclamationmark.triangle.fill") + .font(.subheadline.weight(.semibold)) + .foregroundStyle(.orange) + + Text(message) + .font(.caption) + .foregroundStyle(.secondary) + + HStack(spacing: 8) { + Button("Request Access") { + requestAction() + } + .buttonStyle(.borderedProminent) + + Button("Open Settings") { + openSettingsAction() + } + .buttonStyle(.bordered) + } + .controlSize(.small) + } + .frame(maxWidth: .infinity, alignment: .leading) + .padding(12) + .background(Color.secondary.opacity(0.08)) + .clipShape(RoundedRectangle(cornerRadius: 12, style: .continuous)) } } diff --git a/DynamicIsland/helpers/AccessibilityPermissionStore.swift b/DynamicIsland/helpers/AccessibilityPermissionStore.swift new file mode 100644 index 0000000..bfab87f --- /dev/null +++ b/DynamicIsland/helpers/AccessibilityPermissionStore.swift @@ -0,0 +1,76 @@ +import Foundation +import Combine +import AppKit +#if canImport(ApplicationServices) +import ApplicationServices +#endif + +/// Tracks accessibility permission status and exposes helpers to request access. +@MainActor +final class AccessibilityPermissionStore: ObservableObject { + static let shared = AccessibilityPermissionStore() + + @Published private(set) var isAuthorized: Bool = AccessibilityPermissionStore.isAccessibilityAuthorized() + + private var pollingTask: Task? + + private init() {} + + deinit { + pollingTask?.cancel() + } + + func refreshStatus() { + updateAuthorizationStatus(to: Self.isAccessibilityAuthorized()) + } + + func requestAuthorizationPrompt() { +#if canImport(ApplicationServices) + let promptKey = kAXTrustedCheckOptionPrompt.takeUnretainedValue() as String + let options: CFDictionary = [promptKey: true] as CFDictionary + _ = AXIsProcessTrustedWithOptions(options) +#endif + beginPollingForStatusChanges() + } + + func openSystemSettings() { +#if os(macOS) + if let url = URL(string: "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility") { + NSWorkspace.shared.open(url) + } +#endif + } + + private func beginPollingForStatusChanges() { + pollingTask?.cancel() + pollingTask = Task { [weak self] in + for _ in 0..<30 { + try? await Task.sleep(nanoseconds: 500_000_000) + let status = Self.isAccessibilityAuthorized() + await MainActor.run { + guard let self else { return } + self.updateAuthorizationStatus(to: status) + } + if status { + break + } + } + } + } + + private func updateAuthorizationStatus(to newValue: Bool) { + guard newValue != isAuthorized else { return } + isAuthorized = newValue + if !newValue { + beginPollingForStatusChanges() + } + } + + private static func isAccessibilityAuthorized() -> Bool { +#if canImport(ApplicationServices) + return AXIsProcessTrusted() +#else + return true +#endif + } +}