From be2099892bb29fb0f22baba139d3aa3852eea47a Mon Sep 17 00:00:00 2001 From: Steve Mendes Reis <6802086+M4n0x@users.noreply.github.com> Date: Thu, 3 Dec 2026 13:18:31 +0100 Subject: [PATCH] perf: reduce CPU use and main-thread IPCs in bar updates and polling Precompute static BarPresentation metadata for incremental per-widget updates, cache clock DateFormatters and adaptive HexColor instances, skip uncolored shadow passes, batch WindowClearance Accessibility IPCs, move MenuBarItemMirror pixel work off the main actor with zero-alloc loops, filter Spaces windows before SkyLight IPCs, add lightweight mic mute and IPv4 reads for QuickToggles, and guard no-op state writes. Fixes #995 --- Sources/StableBar/Bar/BarPresentation.swift | 248 ++++++++++++++---- Sources/StableBar/Bar/BarView.swift | 14 +- Sources/StableBar/Bar/WidgetLabel.swift | 63 ++++- .../Configuration/Configuration.swift | 53 +++- .../Configuration/ConfigurationLoader.swift | 35 ++- .../StableBar/DataSources/AudioMonitor.swift | 11 + .../StableBar/DataSources/DockBadges.swift | 27 +- .../StableBar/DataSources/NativeMetrics.swift | 23 +- .../DataSources/NetworkDetails.swift | 28 +- .../StableBar/DataSources/QuickToggles.swift | 33 ++- Sources/StableBar/MenuBar/AppMenu.swift | 17 +- .../StableBar/MenuBar/MenuBarAppearance.swift | 5 +- .../StableBar/MenuBar/MenuBarItemMirror.swift | 77 ++++-- Sources/StableBar/MenuBar/MenuBarStrip.swift | 2 + .../StableBar/MenuBar/WindowClearance.swift | 85 ++++-- Sources/StableBar/Workspaces/Spaces.swift | 56 +++- Sources/StableBar/Workspaces/Workspaces.swift | 2 +- .../PerformanceOptimizationsTests.swift | 88 +++++++ 18 files changed, 702 insertions(+), 165 deletions(-) create mode 100644 Tests/StableBarTests/PerformanceOptimizationsTests.swift diff --git a/Sources/StableBar/Bar/BarPresentation.swift b/Sources/StableBar/Bar/BarPresentation.swift index e90dd15e..2578173d 100644 --- a/Sources/StableBar/Bar/BarPresentation.swift +++ b/Sources/StableBar/Bar/BarPresentation.swift @@ -3,10 +3,34 @@ import Observation @MainActor @Observable final class BarPresentation { + private struct PreparedWidget { + let widget: WidgetConfiguration + let staticBase: WidgetStyle + let staticUsesMode: Bool + let hidesWhenEmpty: Bool + let screenEntries: [(kind: ScreenKind, widget: WidgetConfiguration, staticBase: WidgetStyle, staticUsesMode: Bool)] + } + + private struct PreparedConfiguration { + let configNeedsModeConnection: Bool + let hasWorkspaceWidgets: Bool + let screenLookKinds: [ScreenKind] + let widgets: [PreparedWidget] + let widgetIndexByID: [String: Int] + let scriptWidgetIDs: [ObjectIdentifier: [String]] + } + private weak var store: BarStore? private(set) var presentations: [String: WidgetPresentation] = [:] private(set) var barStyle = WidgetStyle() private(set) var screenBarStyles: [String: WidgetStyle] = [:] + /// Precomputed from `store.configuration` in `preparePresentations()`, which must be called whenever `configuration` changes. + @ObservationIgnored private var prepared: PreparedConfiguration? + @ObservationIgnored private var cachedOverrides = OrderedStyleOverrides(widgets: [], output: { _ in nil }) + @ObservationIgnored private var cachedScreenOverrides: [String: OrderedStyleOverrides] = [:] + @ObservationIgnored private var widgetsWithGlobalOverrides: Set = [] + @ObservationIgnored private var widgetsWithOutputMode: Set = [] + @ObservationIgnored private var lastWorkspaceConfigure: (source: WorkspaceSource, workspaces: Bool, mode: Bool)? init(store: BarStore) { self.store = store @@ -20,83 +44,207 @@ final class BarPresentation { presentations = Dictionary(uniqueKeysWithValues: (store.configuration?.widgets ?? []).map { ($0.id, presentations[$0.id] ?? WidgetPresentation()) }) + prepared = store.configuration.map { buildPrepared($0, scripts: store.widgetScripts.scripts) } for script in store.widgetScripts.scripts.values where script.onUpdate == nil { - script.onUpdate = { [weak self] in self?.updatePresentations() } + script.onUpdate = { [weak self, weak script] in + guard let script else { return } + self?.scriptDidUpdate(script) + } } updatePresentations() } - /// Resolves every widget's style and presence and the bar's style from the configuration and the - /// current outputs. Only changed values are assigned, so views of unaffected widgets stay valid. - func updatePresentations() { - guard let store, let configuration = store.configuration else { return } - let output = { (id: String) in store.widgetScripts.scripts[id]?.output } - let overrides = OrderedStyleOverrides(widgets: configuration.widgets, output: output) - let outputNeedsMode = overrides.bar.usesModeStates || overrides.widgets.values.contains(where: \.usesModeStates) - || store.widgetScripts.scripts.values.contains { $0.output.style?.usesModeStates == true || $0.output.styles?.values.contains(where: \.usesModeStates) == true } - if store.managesConnections { - store.workspaceStore.configure(source: configuration.workspaceSource, - workspaces: configuration.widgets.contains { $0.enabled && ($0.content == .workspaces || $0.display == .active) }, - mode: configuration.needsModeConnection || outputNeedsMode) - } - let mode = modePresentation - let reduceMotion = NSWorkspace.shared.accessibilityDisplayShouldReduceMotion - let screenOverrides = configuration.screenLooks.mapValues { OrderedStyleOverrides(widgets: $0.widgets, output: output) } - // A screen's own layout can also change which group a widget joins, and so its text color. + private func buildPrepared(_ configuration: Configuration, scripts: [String: ScriptWidget]) -> PreparedConfiguration { let screens = ScreenKind.allCases.filter { configuration.screenLooks[$0.rawValue] != nil || configuration.screenLayouts[$0.rawValue] != nil } + let screenLookKinds = ScreenKind.allCases.filter { configuration.screenLooks[$0.rawValue] != nil } + let screenLooks = Dictionary(uniqueKeysWithValues: screens.map { ($0, configuration.look(on: $0)) }) let screenWidgets = Dictionary(uniqueKeysWithValues: screens.map { kind in (kind, Dictionary(uniqueKeysWithValues: configuration.onScreen(kind).widgets.map { ($0.id, $0) })) }) - for widget in configuration.widgets { - let script = store.widgetScripts.scripts[widget.id] - let base = resolveStyle(widgetStyleLayers(widget, defaults: configuration.defaults, overrides: overrides, own: script?.output, - role: configuration.roleStyle(widget.role), group: configuration.groupStyle(of: widget))) - let usesMode = base.usesModeStates || configuration.usesSliderModeStates(widget) || widget.layout?.usesModeStates(roles: configuration.roles) == true + var preparedWidgets: [PreparedWidget] = [] + preparedWidgets.reserveCapacity(configuration.widgets.count) + var widgetIndexByID: [String: Int] = [:] + widgetIndexByID.reserveCapacity(configuration.widgets.count) + for (index, widget) in configuration.widgets.enumerated() { + let staticBase = resolveStyle([configuration.defaults, configuration.roleStyle(widget.role), + configuration.groupStyle(of: widget), widget.barStyle]) + let staticUsesMode = staticBase.usesModeStates || configuration.usesSliderModeStates(widget) + || widget.layout?.usesModeStates(roles: configuration.roles) == true || widget.hoverLayout?.usesModeStates(roles: configuration.roles) == true || widget.overlay?.usesModeStates(roles: configuration.roles) == true - || script?.output.styles?.values.contains(where: \.usesModeStates) == true - let animation = script?.output.animation ?? widget.animation ?? configuration.bar.animation - let states = widgetDataStates(script?.output, widget: widget, providers: configuration.providers) let hidesWhenEmpty = switch widget.content { case .script: true case let .provider(name): configuration.providers[name]?.whenVisible != true default: false } - var screenStyles: [String: ResolvedWidgetStyle] = [:] + var entries: [(kind: ScreenKind, widget: WidgetConfiguration, staticBase: WidgetStyle, staticUsesMode: Bool)] = [] for kind in screens { guard let own = screenWidgets[kind]![widget.id] else { continue } - let look = configuration.look(on: kind) - let base = resolveStyle(widgetStyleLayers(own, defaults: look.defaults, overrides: screenOverrides[kind.rawValue] ?? overrides, own: script?.output, - role: look.roleStyle(own.role), group: look.groupStyle(of: own))) - let screenStates = widgetDataStates(script?.output, widget: own, providers: configuration.providers) - let screenUsesMode = usesMode || base.usesModeStates || look.usesSliderModeStates(own) + let look = screenLooks[kind]! + let screenBase = resolveStyle([look.defaults, look.roleStyle(own.role), look.groupStyle(of: own), own.barStyle]) + let screenStaticUsesMode = staticUsesMode || screenBase.usesModeStates || look.usesSliderModeStates(own) || own.layout?.usesModeStates(roles: look.roles) == true || own.hoverLayout?.usesModeStates(roles: look.roles) == true || own.overlay?.usesModeStates(roles: look.roles) == true - screenStyles[kind.rawValue] = ResolvedWidgetStyle(base: base, state: screenStates.widget, parts: screenStates.parts, - mode: screenUsesMode ? modePresentation(on: kind) : ModePresentation()) + entries.append((kind, own, screenBase, screenStaticUsesMode)) + } + widgetIndexByID[widget.id] = index + preparedWidgets.append(PreparedWidget(widget: widget, staticBase: staticBase, staticUsesMode: staticUsesMode, + hidesWhenEmpty: hidesWhenEmpty, screenEntries: entries)) + } + var scriptWidgetIDs: [ObjectIdentifier: [String]] = [:] + for widget in configuration.widgets { + if let script = scripts[widget.id] { + scriptWidgetIDs[ObjectIdentifier(script), default: []].append(widget.id) + } + } + return PreparedConfiguration( + configNeedsModeConnection: configuration.needsModeConnection, + hasWorkspaceWidgets: configuration.widgets.contains { $0.enabled && ($0.content == .workspaces || $0.display == .active) }, + screenLookKinds: screenLookKinds, + widgets: preparedWidgets, + widgetIndexByID: widgetIndexByID, + scriptWidgetIDs: scriptWidgetIDs + ) + } + + private func scriptDidUpdate(_ script: ScriptWidget) { + guard let store, let configuration = store.configuration, let prepared else { + updatePresentations() + return + } + guard let widgetIDs = prepared.scriptWidgetIDs[ObjectIdentifier(script)], !widgetIDs.isEmpty else { + updatePresentations() + return + } + let output = script.output + let hasGlobalOverrides = !(output.widgetStyles?.isEmpty ?? true) || output.barStyle != nil + let hadGlobalOverrides = widgetIDs.contains { widgetsWithGlobalOverrides.contains($0) } + if hasGlobalOverrides || hadGlobalOverrides { + updatePresentations() + return + } + let hasOutputMode = output.style?.usesModeStates == true || output.styles?.values.contains(where: \.usesModeStates) == true + let hadOutputMode = widgetIDs.contains { widgetsWithOutputMode.contains($0) } + if hasOutputMode != hadOutputMode { + updatePresentations() + return + } + let mode = modePresentation + let reduceMotion = NSWorkspace.shared.accessibilityDisplayShouldReduceMotion + let screenModes: [ScreenKind: ModePresentation] = prepared.widgets.isEmpty ? [:] : Dictionary( + uniqueKeysWithValues: ScreenKind.allCases.compactMap { kind in + configuration.screenLooks[kind.rawValue] != nil || configuration.screenLayouts[kind.rawValue] != nil + ? (kind, modePresentation(on: kind)) : nil } - presentations[widget.id]?.update(style: ResolvedWidgetStyle(base: base, state: states.widget, parts: states.parts, - mode: usesMode ? mode : ModePresentation()), - screenStyles: screenStyles, - hidden: (script?.output.hidden == true || hidesWhenEmpty && !store.barEditing.hasContent(widget)) - && script?.error == nil, - display: script?.output.display, - visibility: visibilityAnimation(widget.transition ?? configuration.bar.motion.transition, animation: animation, - reduceMotion: reduceMotion)) - // A widget turned off has no script; its output number stays, so the parked script's last - // `temporary`, shown already, doesn't show again when the widget comes back. - if let script { - presentations[widget.id]?.show(script.output.temporary, output: script.outputNumber, - animation: reduceMotion ? nil : animation) + ) + for id in widgetIDs { + guard let index = prepared.widgetIndexByID[id] else { continue } + updateWidget(prepared.widgets[index], store: store, configuration: configuration, + overrides: cachedOverrides, screenOverrides: cachedScreenOverrides, + mode: mode, screenModes: screenModes, reduceMotion: reduceMotion) + } + } + + private func resolveDynamicStyle(staticBase: WidgetStyle, override: WidgetStyle?, own: ScriptOutput?) -> WidgetStyle { + var base = staticBase + if let override { base = override.inheriting(base) } + if let style = own?.style { base = style.inheriting(base) } + if let color = own?.color { base = WidgetStyle(foreground: color).inheriting(base) } + return base + } + + private func updateWidget(_ entry: PreparedWidget, store: BarStore, configuration: Configuration, + overrides: OrderedStyleOverrides, screenOverrides: [String: OrderedStyleOverrides], + mode: ModePresentation, screenModes: [ScreenKind: ModePresentation], reduceMotion: Bool) { + let widget = entry.widget + let script = store.widgetScripts.scripts[widget.id] + let ownOutput = script?.output + let base = resolveDynamicStyle(staticBase: entry.staticBase, override: overrides.widgets[widget.id], own: ownOutput) + let outputUsesMode = ownOutput?.style?.usesModeStates == true + || ownOutput?.styles?.values.contains(where: \.usesModeStates) == true + let usesMode = entry.staticUsesMode || outputUsesMode || overrides.widgets[widget.id]?.usesModeStates == true + let animation = ownOutput?.animation ?? widget.animation ?? configuration.bar.animation + let states = widgetDataStates(ownOutput, widget: widget, providers: configuration.providers) + var screenStyles: [String: ResolvedWidgetStyle] = [:] + if !entry.screenEntries.isEmpty { + screenStyles.reserveCapacity(entry.screenEntries.count) + for screen in entry.screenEntries { + let screenOverride = (screenOverrides[screen.kind.rawValue] ?? overrides).widgets[widget.id] + let screenBase = resolveDynamicStyle(staticBase: screen.staticBase, override: screenOverride, own: ownOutput) + let screenStates = widgetDataStates(ownOutput, widget: screen.widget, providers: configuration.providers) + let screenUsesMode = usesMode || screen.staticUsesMode || screenOverride?.usesModeStates == true + screenStyles[screen.kind.rawValue] = ResolvedWidgetStyle(base: screenBase, state: screenStates.widget, parts: screenStates.parts, + mode: screenUsesMode ? (screenModes[screen.kind] ?? modePresentation(on: screen.kind)) : ModePresentation()) } } + presentations[widget.id]?.update(style: ResolvedWidgetStyle(base: base, state: states.widget, parts: states.parts, + mode: usesMode ? mode : ModePresentation()), + screenStyles: screenStyles, + hidden: (ownOutput?.hidden == true || entry.hidesWhenEmpty && !store.barEditing.hasContent(widget)) + && script?.error == nil, + display: ownOutput?.display, + visibility: visibilityAnimation(widget.transition ?? configuration.bar.motion.transition, animation: animation, + reduceMotion: reduceMotion)) + // A widget turned off has no script; its output number stays, so the parked script's last + // `temporary`, shown already, doesn't show again when the widget comes back. + if let script { + presentations[widget.id]?.show(script.output.temporary, output: script.outputNumber, + animation: reduceMotion ? nil : animation) + } + } + + /// Resolves every widget's style and presence and the bar's style from the configuration and the + /// current outputs. Only changed values are assigned, so views of unaffected widgets stay valid. + func updatePresentations() { + guard let store, let configuration = store.configuration else { return } + let prepared = self.prepared ?? buildPrepared(configuration, scripts: store.widgetScripts.scripts) + self.prepared = prepared + let output = { (id: String) in store.widgetScripts.scripts[id]?.output } + let overrides = OrderedStyleOverrides(widgets: configuration.widgets, output: output) + cachedOverrides = overrides + widgetsWithGlobalOverrides.removeAll(keepingCapacity: true) + widgetsWithOutputMode.removeAll(keepingCapacity: true) + for widget in configuration.widgets { + guard let value = store.widgetScripts.scripts[widget.id]?.output else { continue } + if !(value.widgetStyles?.isEmpty ?? true) || value.barStyle != nil { + widgetsWithGlobalOverrides.insert(widget.id) + } + if value.style?.usesModeStates == true || value.styles?.values.contains(where: \.usesModeStates) == true { + widgetsWithOutputMode.insert(widget.id) + } + } + let outputNeedsMode = overrides.bar.usesModeStates || overrides.widgets.values.contains(where: \.usesModeStates) + || !widgetsWithOutputMode.isEmpty + if store.managesConnections { + let nextConfigure = (source: configuration.workspaceSource, + workspaces: prepared.hasWorkspaceWidgets, + mode: prepared.configNeedsModeConnection || outputNeedsMode) + if lastWorkspaceConfigure.map({ $0 != nextConfigure }) ?? true { + lastWorkspaceConfigure = nextConfigure + store.workspaceStore.configure(source: nextConfigure.source, + workspaces: nextConfigure.workspaces, + mode: nextConfigure.mode) + } + } + let mode = modePresentation + let reduceMotion = NSWorkspace.shared.accessibilityDisplayShouldReduceMotion + let screenOverrides = configuration.screenLooks.mapValues { OrderedStyleOverrides(widgets: $0.widgets, output: output) } + cachedScreenOverrides = screenOverrides + let screenModes = Dictionary(uniqueKeysWithValues: ScreenKind.allCases.compactMap { kind in + configuration.screenLooks[kind.rawValue] != nil || configuration.screenLayouts[kind.rawValue] != nil + ? (kind, modePresentation(on: kind)) : nil + }) + for entry in prepared.widgets { + updateWidget(entry, store: store, configuration: configuration, + overrides: overrides, screenOverrides: screenOverrides, + mode: mode, screenModes: screenModes, reduceMotion: reduceMotion) + } let bar = resolveStyle(barStyleLayers(configuration.bar.style, overrides: overrides), states: StyleStates(mode: mode)) if barStyle != bar { barStyle = bar } - let kinds = ScreenKind.allCases.filter { configuration.screenLooks[$0.rawValue] != nil } - let screenBars = Dictionary(uniqueKeysWithValues: kinds.map { kind in + let screenBars = Dictionary(uniqueKeysWithValues: prepared.screenLookKinds.map { kind in (kind.rawValue, resolveStyle(barStyleLayers(configuration.bar(on: kind).style, overrides: overrides), - states: StyleStates(mode: modePresentation(on: kind)))) + states: StyleStates(mode: screenModes[kind] ?? modePresentation(on: kind)))) }) if screenBarStyles != screenBars { screenBarStyles = screenBars } } diff --git a/Sources/StableBar/Bar/BarView.swift b/Sources/StableBar/Bar/BarView.swift index 0d45cf87..314c2b14 100644 --- a/Sources/StableBar/Bar/BarView.swift +++ b/Sources/StableBar/Bar/BarView.swift @@ -254,13 +254,21 @@ struct PlacedUnits: View { .onPreferenceChange(BarWidthPreference.self) { widths in let animates = BarUnit.animatesResize(units, measured: measuredUnits, from: measuredWidths, to: widths, reduceMotion: reduceMotion, providerType: config.providerType(of:)) - measuredUnits = Set(widths.keys) + let nextUnits = Set(widths.keys) + if nextUnits != measuredUnits { measuredUnits = nextUnits } let expanded = Set(units.filter { unit in unit.widgets.contains { store.barPresentation.presentations[$0.id]?.expandedDisplays.contains(display.id) == true } }.map(\.id)) + var nextMeasured = measuredWidths + nextMeasured.merge(widths) { $1 } + var nextResting = restingWidths + for (key, value) in widths where !expanded.contains(key) { + nextResting[key] = value + } + guard nextMeasured != measuredWidths || nextResting != restingWidths else { return } withAnimation(animates ? config.bar.animation.value : nil) { - measuredWidths.merge(widths) { $1 } - restingWidths.merge(widths.filter { !expanded.contains($0.key) }) { $1 } + if nextMeasured != measuredWidths { measuredWidths = nextMeasured } + if nextResting != restingWidths { restingWidths = nextResting } } } .onChange(of: visible, initial: true) { _, ids in if !preview { store.widgetScripts.setVisibleWidgets(ids: ids, displayID: display.id) } } diff --git a/Sources/StableBar/Bar/WidgetLabel.swift b/Sources/StableBar/Bar/WidgetLabel.swift index 42849b96..2c4cae9b 100644 --- a/Sources/StableBar/Bar/WidgetLabel.swift +++ b/Sources/StableBar/Bar/WidgetLabel.swift @@ -1,4 +1,5 @@ import AppKit +import os /// What a widget shows: its text and icon, and the fields its layout blocks read, which add /// `text` and `icon` to the output's own fields. @@ -21,15 +22,10 @@ extension WidgetConfiguration { case let .text(value): text = value case let .clock(format): - let formatter = DateFormatter() - formatter.dateFormat = format - formatter.timeZone = timeZone.flatMap(TimeZone.init(identifier:)) ?? .autoupdatingCurrent - text = formatter.string(from: date) - let parts = Self.clockFormatParts(format) - formatter.dateFormat = parts.date - fields["date"] = formatter.string(from: date) - formatter.dateFormat = parts.time - fields["time"] = formatter.string(from: date) + let formatted = ClockFormatterCache.shared.format(date, format: format, timeZoneID: timeZone) + text = formatted.text + fields["date"] = formatted.date + fields["time"] = formatted.time case .activeApp: text = activeApp ?? "Desktop" case .controlCenter, .menuBarItems: @@ -55,7 +51,7 @@ extension WidgetConfiguration { /// to its last, with the literal text that touches its end, such as `分`; the date is the rest, without the spaces between it and the time and the quoted text there that /// touches the time or stands apart from the date, such as `'T'` or ` 'at' `. Quoted text that touches the date, such /// as `'日'`, is part of it. - private static func clockFormatParts(_ format: String) -> (date: String, time: String) { + fileprivate static func clockFormatParts(_ format: String) -> (date: String, time: String) { var quote: String.Index? var quotes: [Range] = [] var time: Range? @@ -204,3 +200,50 @@ extension WidgetLabel { return label } } + +private final class ClockFormatterCache: @unchecked Sendable { + private struct Key: Hashable { + let format: String + let timeZoneID: String? + } + + private struct Entry { + let full: DateFormatter + let date: DateFormatter + let time: DateFormatter + } + + static let shared = ClockFormatterCache() + private let cache = OSAllocatedUnfairLock<[Key: Entry]>(uncheckedState: [:]) + + private init() { + for name in [NSLocale.currentLocaleDidChangeNotification, Notification.Name.NSSystemTimeZoneDidChange] { + NotificationCenter.default.addObserver(forName: name, object: nil, queue: nil) { [weak self] _ in + self?.cache.withLock { $0.removeAll(keepingCapacity: true) } + } + } + } + + func format(_ date: Date, format: String, timeZoneID: String?) -> (text: String, date: String, time: String) { + let key = Key(format: format, timeZoneID: timeZoneID) + return cache.withLock { entries in + let entry: Entry + if let cached = entries[key] { + entry = cached + } else { + if entries.count >= 64 { entries.removeAll(keepingCapacity: true) } + let timeZone = timeZoneID.flatMap(TimeZone.init(identifier:)) ?? .autoupdatingCurrent + let parts = WidgetConfiguration.clockFormatParts(format) + let make = { (pattern: String) -> DateFormatter in + let formatter = DateFormatter() + formatter.dateFormat = pattern + formatter.timeZone = timeZone + return formatter + } + entry = Entry(full: make(format), date: make(parts.date), time: make(parts.time)) + entries[key] = entry + } + return (entry.full.string(from: date), entry.date.string(from: date), entry.time.string(from: date)) + } + } +} diff --git a/Sources/StableBar/Configuration/Configuration.swift b/Sources/StableBar/Configuration/Configuration.swift index f37fdedd..2a413cd3 100644 --- a/Sources/StableBar/Configuration/Configuration.swift +++ b/Sources/StableBar/Configuration/Configuration.swift @@ -1,4 +1,5 @@ import AppKit +import os import SwiftUI struct HexColor: Decodable, Equatable, Sendable { @@ -41,14 +42,24 @@ struct HexColor: Decodable, Equatable, Sendable { return hex.count == 6 ? (value << 8) | 0xff : value } + private static let dynamicColorCache = OSAllocatedUnfairLock<[UInt64: NSColor]>(initialState: [:]) + var color: Color { guard light != dark else { return HexColor.color(light) } let light = light, dark = dark - return Color(nsColor: NSColor(name: nil) { appearance in - let rgba = appearance.bestMatch(from: [.darkAqua, .aqua]) == .darkAqua ? dark : light - return NSColor(srgbRed: CGFloat(rgba >> 24) / 255, green: CGFloat((rgba >> 16) & 0xff) / 255, - blue: CGFloat((rgba >> 8) & 0xff) / 255, alpha: CGFloat(rgba & 0xff) / 255) - }) + let key = (UInt64(light) << 32) | UInt64(dark) + let nsColor = HexColor.dynamicColorCache.withLock { cache -> NSColor in + if let cached = cache[key] { return cached } + if cache.count >= 512 { cache.removeAll(keepingCapacity: true) } + let created = NSColor(name: nil) { appearance in + let rgba = appearance.bestMatch(from: [.darkAqua, .aqua]) == .darkAqua ? dark : light + return NSColor(srgbRed: CGFloat(rgba >> 24) / 255, green: CGFloat((rgba >> 16) & 0xff) / 255, + blue: CGFloat((rgba >> 8) & 0xff) / 255, alpha: CGFloat(rgba & 0xff) / 255) + } + cache[key] = created + return created + } + return Color(nsColor: nsColor) } private static func color(_ rgba: UInt32) -> Color { @@ -402,8 +413,11 @@ private struct StyledShadow: ViewModifier { // Without an appearance, a clear shadow keeps the view structure: switching branches would rebuild the content. // NSView.cacheDisplay, which draws offscreen snapshots, turns a shadow's vertical offset upside down. let y = appearance?.shadowOffsetY ?? 0 - content.shadow(color: appearance?.shadowColor ?? .clear, radius: appearance?.shadowRadius ?? 0, - x: appearance?.shadowOffsetX ?? 0, y: offscreen ? -y : y) + let hasShadow = appearance?.hasShadow == true + content.shadow(color: hasShadow ? (appearance?.shadowColor ?? .clear) : .clear, + radius: hasShadow ? (appearance?.shadowRadius ?? 0) : 0, + x: hasShadow ? (appearance?.shadowOffsetX ?? 0) : 0, + y: hasShadow ? (offscreen ? -y : y) : 0) } } @@ -430,6 +444,7 @@ struct WidgetAppearance { let width: CGFloat? let shadowRadius: Double let shadowColor: Color + let hasShadow: Bool let shadowOffsetX: Double let shadowOffsetY: Double let shadowFrom: ShadowSource @@ -450,7 +465,9 @@ struct WidgetAppearance { spacing = style.spacing ?? defaults.spacing ?? 6 width = (style.width ?? defaults.width).map { CGFloat($0) } shadowRadius = style.shadowRadius ?? defaults.shadowRadius ?? 2 - shadowColor = (style.shadowColor ?? defaults.shadowColor)?.color ?? .clear + let resolvedShadowColor = style.shadowColor ?? defaults.shadowColor + shadowColor = resolvedShadowColor?.color ?? .clear + hasShadow = resolvedShadowColor != nil shadowOffsetX = style.shadowOffsetX ?? defaults.shadowOffsetX ?? 0 shadowOffsetY = style.shadowOffsetY ?? defaults.shadowOffsetY ?? 1 shadowFrom = style.shadowFrom ?? defaults.shadowFrom ?? .content @@ -963,6 +980,8 @@ struct Configuration: Decodable, Sendable { throw ConfigurationCompositionError.widgetOverrideID(id) } let definitions = try values.decode([[String: ConfigurationValue]].self, forKey: .widgets) + let widgetEncoder = JSONEncoder() + let widgetDecoder = JSONDecoder() widgets = try definitions.map { definition in var expanded = try expandWidgetTemplate(definition, templates: templates) if let id = expanded["id"], let properties = overrides[try id.decoded(String.self)] { @@ -971,7 +990,7 @@ struct Configuration: Decodable, Sendable { let id = expanded["id"].flatMap { try? $0.decoded(String.self) } ?? "?" do { var widget = try NewerConfiguration.$path.withValue(["widgets", id]) { - try JSONDecoder().decode(WidgetConfiguration.self, from: JSONEncoder().encode(expanded)) + try widgetDecoder.decode(WidgetConfiguration.self, from: widgetEncoder.encode(expanded)) } if widget.content == .workspaces { widget.workspace = try NewerConfiguration.$path.withValue(["widgets", id, "workspace"]) { @@ -1096,14 +1115,20 @@ struct Configuration: Decodable, Sendable { private func widgets(on kind: ScreenKind) -> [WidgetConfiguration] { guard let layout = screenLayouts[kind.rawValue] else { return widgets } - let listed = WidgetPosition.allCases.flatMap { position in - (layout[position.rawValue] ?? []).compactMap { id in widgets.first { $0.id == id } }.map { widget in - var widget = widget + let byID = Dictionary(widgets.map { ($0.id, $0) }, uniquingKeysWith: { first, _ in first }) + var listed: [WidgetConfiguration] = [] + listed.reserveCapacity(widgets.count) + var listedIDs: Set = [] + listedIDs.reserveCapacity(widgets.count) + for position in WidgetPosition.allCases { + for id in layout[position.rawValue] ?? [] { + guard var widget = byID[id] else { continue } widget.position = position - return widget + listed.append(widget) + listedIDs.insert(id) } } - let unlisted = widgets.filter { widget in !listed.contains { $0.id == widget.id } } + let unlisted = widgets.filter { !listedIDs.contains($0.id) } return WidgetGroupConfiguration.joining(listed + unlisted, groups: groups) } } diff --git a/Sources/StableBar/Configuration/ConfigurationLoader.swift b/Sources/StableBar/Configuration/ConfigurationLoader.swift index 59c58f98..0bf43de9 100644 --- a/Sources/StableBar/Configuration/ConfigurationLoader.swift +++ b/Sources/StableBar/Configuration/ConfigurationLoader.swift @@ -32,8 +32,39 @@ indirect enum ConfigurationValue: Codable, Sendable, Equatable { } func decoded(_ type: T.Type) throws -> T { - if case let .object(object) = self, let object = object as? T { return object } - if case let .array(array) = self, let array = array as? T { return array } + switch self { + case let .object(object): + if let value = object as? T { return value } + case let .array(array): + if let value = array as? T { return value } + if T.self == [[String: ConfigurationValue]].self { + var objects: [[String: ConfigurationValue]] = [] + objects.reserveCapacity(array.count) + var allObjects = true + for element in array { + guard case let .object(object) = element else { allObjects = false; break } + objects.append(object) + } + if allObjects, let value = objects as? T { return value } + } else if T.self == [String].self { + var strings: [String] = [] + strings.reserveCapacity(array.count) + var allStrings = true + for element in array { + guard case let .string(string) = element else { allStrings = false; break } + strings.append(string) + } + if allStrings, let value = strings as? T { return value } + } + case let .string(string): + if let value = string as? T { return value } + case let .bool(bool): + if let value = bool as? T { return value } + case let .number(number): + if let value = number as? T { return value } + case .null: + break + } return try JSONDecoder().decode(type, from: JSONEncoder().encode(self)) } diff --git a/Sources/StableBar/DataSources/AudioMonitor.swift b/Sources/StableBar/DataSources/AudioMonitor.swift index 80ef2265..c59ccc5b 100644 --- a/Sources/StableBar/DataSources/AudioMonitor.swift +++ b/Sources/StableBar/DataSources/AudioMonitor.swift @@ -67,6 +67,17 @@ final class AudioMonitor: ChangeMonitor, @unchecked Sendable { return output } + /// Reads only the default device's mute state without enumerating processes or devices. + static func isMuted(input: Bool) -> Bool? { + guard let device = try? defaultDevice(input: input), device != kAudioObjectUnknown else { return nil } + let scope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput + var address = AudioObjectPropertyAddress(mSelector: kAudioDevicePropertyMute, mScope: scope, mElement: kAudioObjectPropertyElementMain) + var muted: UInt32 = 0 + var size = UInt32(MemoryLayout.size) + guard AudioObjectGetPropertyData(device, &address, 0, nil, &size, &muted) == noErr else { return nil } + return muted != 0 + } + /// `output` with a `temporary` that shows its volume for a moment when its volume or mute state /// differs from `previous`'s, as `volumeChange` reports them. The volume is empty while muted or /// without a volume control. The first read shows nothing. diff --git a/Sources/StableBar/DataSources/DockBadges.swift b/Sources/StableBar/DataSources/DockBadges.swift index 90db57f2..a55d80a8 100644 --- a/Sources/StableBar/DataSources/DockBadges.swift +++ b/Sources/StableBar/DataSources/DockBadges.swift @@ -25,10 +25,19 @@ final class DockBadges { guard isWatching != oldValue else { return } task?.cancel() task = isWatching ? Task { [weak self] in + var bundleIDs: [URL: String] = [:] while !Task.isCancelled { - let labels = await Task.detached(priority: .utility) { readDockBadges() }.value + let cached = bundleIDs + let result = try? await BlockingWork.run { + var updated = cached + let labels = readDockBadges(bundleIDs: &updated) + return (labels, updated) + } guard !Task.isCancelled, let self else { return } - if let labels, labels != self.labels { self.labels = labels } + if let (labels, updated) = result { + bundleIDs = updated + if let labels, labels != self.labels { self.labels = labels } + } try? await Task.sleep(for: .seconds(5)) } } : nil @@ -40,7 +49,7 @@ final class DockBadges { /// Reads each app's badge from the Dock's own tiles through Accessibility: macOS has no API for another app's badge. /// Nil when the Dock can't be read right now, which says nothing about its badges; without Accessibility access /// there are none to show. -private func readDockBadges() -> [String: String]? { +private func readDockBadges(bundleIDs: inout [URL: String]) -> [String: String]? { struct Unreadable: Error {} /// An element's attribute, nil when it has none. Throws when the Dock doesn't answer. func value(_ name: String, of element: AXUIElement) throws -> CFTypeRef? { @@ -64,7 +73,17 @@ private func readDockBadges() -> [String: String]? { where try value(kAXRoleAttribute, of: list) as? String == kAXListRole { for tile in try children(of: list) where try value(kAXSubroleAttribute, of: tile) as? String == "AXApplicationDockItem" { guard let label = try value("AXStatusLabel", of: tile) as? String, !label.isEmpty, - let url = try value(kAXURLAttribute, of: tile) as? URL, let id = Bundle(url: url)?.bundleIdentifier else { continue } + let url = try value(kAXURLAttribute, of: tile) as? URL else { continue } + let id: String + if let cached = bundleIDs[url] { + id = cached + } else if let resolved = Bundle(url: url)?.bundleIdentifier { + if bundleIDs.count >= 256 { bundleIDs.removeAll(keepingCapacity: true) } + bundleIDs[url] = resolved + id = resolved + } else { + continue + } labels[id] = label } } diff --git a/Sources/StableBar/DataSources/NativeMetrics.swift b/Sources/StableBar/DataSources/NativeMetrics.swift index f3694227..2da65bd4 100644 --- a/Sources/StableBar/DataSources/NativeMetrics.swift +++ b/Sources/StableBar/DataSources/NativeMetrics.swift @@ -98,9 +98,11 @@ func processLists(_ samples: [ProcessSample], cpu: [pid_t: Double], apps: [Strin row.cpu += cpu[sample.pid] ?? 0 rows[key] = row } + let formatter = ByteCountFormatter() + formatter.countStyle = .memory let fields = { (row: Row) in ["name": row.name, "pid": String(row.pid), "path": row.path, "cpu": String(Int(row.cpu * 100)), - "memory": ByteCountFormatter.string(fromByteCount: Int64(row.memory), countStyle: .memory)] + "memory": formatter.string(fromByteCount: Int64(row.memory))] } return ["memory": rows.values.sorted { $0.memory != $1.memory ? $0.memory > $1.memory : $0.name < $1.name }.prefix(count).map(fields), "cpu": rows.values.sorted { $0.cpu != $1.cpu ? $0.cpu > $1.cpu : $0.name < $1.name }.prefix(count).map(fields)] @@ -115,6 +117,7 @@ actor ProcessMetrics { }() private var times: [pid_t: UInt64] = [:] private var time: ContinuousClock.Instant? + private var resolvedBundlePaths: [URL: String] = [:] func lists(count: Int) -> [String: [[String: String]]] { var size = proc_listpids(UInt32(PROC_UID_ONLY), getuid(), nil, 0) @@ -141,9 +144,21 @@ actor ProcessMetrics { } times = Dictionary(samples.map { ($0.pid, $0.cpuTime) }) { first, _ in first } time = now - let apps = Dictionary(NSWorkspace.shared.runningApplications.compactMap { app in - app.bundleURL.map { ($0.resolvingSymlinksInPath().path, (pid: app.processIdentifier, name: app.localizedName ?? $0.deletingPathExtension().lastPathComponent)) } - }) { first, _ in first } + var apps: [String: (pid: pid_t, name: String)] = [:] + for app in NSWorkspace.shared.runningApplications { + guard let url = app.bundleURL else { continue } + let resolved: String + if let cached = resolvedBundlePaths[url] { + resolved = cached + } else { + if resolvedBundlePaths.count >= 512 { resolvedBundlePaths.removeAll(keepingCapacity: true) } + resolved = url.resolvingSymlinksInPath().path + resolvedBundlePaths[url] = resolved + } + if apps[resolved] == nil { + apps[resolved] = (pid: app.processIdentifier, name: app.localizedName ?? url.deletingPathExtension().lastPathComponent) + } + } return processLists(samples, cpu: cpu, apps: apps, count: count) } } diff --git a/Sources/StableBar/DataSources/NetworkDetails.swift b/Sources/StableBar/DataSources/NetworkDetails.swift index c7c6fe2b..1a846f2b 100644 --- a/Sources/StableBar/DataSources/NetworkDetails.swift +++ b/Sources/StableBar/DataSources/NetworkDetails.swift @@ -10,10 +10,23 @@ enum NetworkDetails { /// The IPv4 address of the interface macOS sends traffic through, and that interface's name, such as `en0`, whether /// it's Wi-Fi or Ethernet. static func localAddress() -> (interface: String, address: String)? { - guard let global = SCDynamicStoreCopyValue(nil, "State:/Network/Global/IPv4" as CFString) as? [String: Any], - let interface = global["PrimaryInterface"] as? String else { return nil } + globalIPv4().local + } + + /// The router's IPv4 address on the network macOS sends traffic through. + static func router() -> String? { + (SCDynamicStoreCopyValue(nil, "State:/Network/Global/IPv4" as CFString) as? [String: Any])?["Router"] as? String + } + + /// Reads the primary IPv4 interface, address and router in a single SystemConfiguration lookup. + static func globalIPv4() -> (local: (interface: String, address: String)?, router: String?) { + guard let global = SCDynamicStoreCopyValue(nil, "State:/Network/Global/IPv4" as CFString) as? [String: Any] else { + return (nil, nil) + } + let router = global["Router"] as? String + guard let interface = global["PrimaryInterface"] as? String else { return (nil, router) } var first: UnsafeMutablePointer? - guard getifaddrs(&first) == 0 else { return nil } + guard getifaddrs(&first) == 0 else { return (nil, router) } defer { freeifaddrs(first) } for entry in sequence(first: first, next: { $0?.pointee.ifa_next }).compactMap({ $0?.pointee }) { guard String(cString: entry.ifa_name) == interface, let address = entry.ifa_addr, address.pointee.sa_family == UInt8(AF_INET) else { @@ -23,14 +36,9 @@ enum NetworkDetails { guard getnameinfo(address, socklen_t(address.pointee.sa_len), &host, socklen_t(host.count), nil, 0, NI_NUMERICHOST) == 0 else { continue } - return (interface, host.withUnsafeBufferPointer { String(cString: $0.baseAddress!) }) + return ((interface, host.withUnsafeBufferPointer { String(cString: $0.baseAddress!) }), router) } - return nil - } - - /// The router's IPv4 address on the network macOS sends traffic through. - static func router() -> String? { - (SCDynamicStoreCopyValue(nil, "State:/Network/Global/IPv4" as CFString) as? [String: Any])?["Router"] as? String + return (nil, router) } /// Asks `publicAddressService`, only when the person asks for the address: it's a request to the internet. diff --git a/Sources/StableBar/DataSources/QuickToggles.swift b/Sources/StableBar/DataSources/QuickToggles.swift index 827c3b45..b97b0460 100644 --- a/Sources/StableBar/DataSources/QuickToggles.swift +++ b/Sources/StableBar/DataSources/QuickToggles.swift @@ -108,21 +108,23 @@ final class QuickToggles { .darkMode: Self.preference("AppleInterfaceStyle", in: kCFPreferencesAnyApplication as String) == "Dark", .dockAutohide: Self.flag("autohide", in: "com.apple.dock") ?? false, .desktopIcons: !(Self.flag("CreateDesktop", in: "com.apple.finder") ?? true), - .hiddenFiles: Self.flag("AppleShowAllFiles", in: "com.apple.finder") ?? false + .hiddenFiles: Self.flag("AppleShowAllFiles", in: "com.apple.finder", synchronize: false) ?? false ] states[.nightShift] = PrivateAPI.nightShiftEnabled() states[.trueTone] = PrivateAPI.trueTone("available") == true ? PrivateAPI.trueTone("enabled") : nil - states[.microphone] = (try? AudioMonitor(input: true).read().fields?["muted"]).map { $0 == "true" } - bluetoothAccess = CBManager.authorization + states[.microphone] = AudioMonitor.isMuted(input: true) + let access = CBManager.authorization + if access != bluetoothAccess { bluetoothAccess = access } // Reading the power through IOBluetooth asks for access, so until it's allowed the bluetooth provider's shows. if bluetoothAccess == .allowedAlways, let power = PrivateAPI.bluetoothPowerState { states[.bluetooth] = power() == 1 } for tile in running { states[tile] = self.states[tile] } if states != self.states { self.states = states } let warmth = PrivateAPI.nightShiftStrength() if warmth != nightShiftStrength { nightShiftStrength = warmth } - let local = NetworkDetails.localAddress() + let ipv4 = NetworkDetails.globalIPv4() + let local = ipv4.local if local?.address != localAddress?.address || local?.interface != localAddress?.interface { localAddress = local } - let network = Self.network(local) + let network = Self.network(local, router: ipv4.router) if network != self.network { self.network = network publicAddress = nil @@ -132,8 +134,13 @@ final class QuickToggles { /// What tells the network through `local` apart, so a result from another one is dropped: two networks can hand out /// the same address, so the router and the Wi-Fi network's name, which Location Services allows, count too. - private static func network(_ local: (interface: String, address: String)?) -> [String?] { - [local?.interface, local?.address, NetworkDetails.router(), local.flatMap { CWWiFiClient.shared().interface(withName: $0.interface)?.ssid() }] + private static func network(_ local: (interface: String, address: String)?, router: String?) -> [String?] { + [local?.interface, local?.address, router, local.flatMap { CWWiFiClient.shared().interface(withName: $0.interface)?.ssid() }] + } + + private static func currentNetwork() -> [String?] { + let ipv4 = NetworkDetails.globalIPv4() + return network(ipv4.local, router: ipv4.router) } /// Turns `tile` off when `on`, as it shows now, or on. @@ -188,11 +195,11 @@ final class QuickToggles { func showPublicAddress() { guard acts, !fetchesPublicAddress else { return } fetchesPublicAddress = true - let started = Self.network(NetworkDetails.localAddress()) + let started = Self.currentNetwork() Task { do { let address = try await NetworkDetails.publicAddress() - if Self.network(NetworkDetails.localAddress()) == started { publicAddress = address } + if Self.currentNetwork() == started { publicAddress = address } } catch let failure { error = errorMessage(failure) } @@ -203,11 +210,11 @@ final class QuickToggles { func testSpeed() { guard acts, !testsSpeed else { return } testsSpeed = true - let started = Self.network(NetworkDetails.localAddress()) + let started = Self.currentNetwork() Task { do { let test = try await NetworkDetails.speedTest() - if Self.network(NetworkDetails.localAddress()) == started { speedTest = test } + if Self.currentNetwork() == started { speedTest = test } } catch let failure { error = errorMessage(failure) } @@ -383,8 +390,8 @@ final class QuickToggles { } /// Another app's preference as a flag, however it was written, such as `YES` by `defaults write`; nil when unset. - private static func flag(_ key: String, in domain: String) -> Bool? { - CFPreferencesAppSynchronize(domain as CFString) + private static func flag(_ key: String, in domain: String, synchronize: Bool = true) -> Bool? { + if synchronize { CFPreferencesAppSynchronize(domain as CFString) } var valid: DarwinBoolean = false let value = CFPreferencesGetAppBooleanValue(key as CFString, domain as CFString, &valid) return valid.boolValue ? value : nil diff --git a/Sources/StableBar/MenuBar/AppMenu.swift b/Sources/StableBar/MenuBar/AppMenu.swift index 0065327f..259a7499 100644 --- a/Sources/StableBar/MenuBar/AppMenu.swift +++ b/Sources/StableBar/MenuBar/AppMenu.swift @@ -272,8 +272,10 @@ final class AppMenu: NSObject { let items = await foundMenuBarItems(apps: Array(apps.keys), agent: apps.values.first { $0.bundleIdentifier == menuBarAgentID }?.processIdentifier, readAttribute: readAttribute) + let displayBounds = activeDisplayBounds() menuBarItems = items.sorted { $0.frame.midX < $1.frame.midX }.compactMap { item in - guard let app = menuBarItemApp(pid: item.pid, in: apps), let display = menuBarDisplay(of: item.frame) else { return nil } + guard let app = menuBarItemApp(pid: item.pid, in: apps), + let display = menuBarDisplay(of: item.frame, in: displayBounds) else { return nil } // Time Machine's item has neither an identifier nor a description, and SystemUIServer, which draws it, has no other such item. let timeMachine = app.bundleIdentifier == "com.apple.systemuiserver" && item.identifier == nil && item.description == nil let identifier = timeMachine ? "com.apple.menuextra.TimeMachine" : item.identifier @@ -902,14 +904,17 @@ private func showsPanel(_ pid: pid_t) -> Bool { } } -private func menuBarDisplay(of frame: CGRect) -> CGDirectDisplayID? { +private func activeDisplayBounds() -> [(id: CGDirectDisplayID, bounds: CGRect)] { var displays = [CGDirectDisplayID](repeating: 0, count: 16) var count: UInt32 = 0 CGGetActiveDisplayList(16, &displays, &count) - return displays.prefix(Int(count)).first { - let bounds = CGDisplayBounds($0) - return bounds.minX <= frame.midX && frame.midX < bounds.maxX && abs(frame.midY - bounds.minY) < frame.height * 2 - } + return displays.prefix(Int(count)).map { ($0, CGDisplayBounds($0)) } +} + +private func menuBarDisplay(of frame: CGRect, in displays: [(id: CGDirectDisplayID, bounds: CGRect)] = activeDisplayBounds()) -> CGDirectDisplayID? { + displays.first { _, bounds in + bounds.minX <= frame.midX && frame.midX < bounds.maxX && abs(frame.midY - bounds.minY) < frame.height * 2 + }?.id } /// A menu item's shortcut as Accessibility reports it. Accessibility doesn't expose `isAlternate`, and every item reports diff --git a/Sources/StableBar/MenuBar/MenuBarAppearance.swift b/Sources/StableBar/MenuBar/MenuBarAppearance.swift index 8f44931e..9267c7f2 100644 --- a/Sources/StableBar/MenuBar/MenuBarAppearance.swift +++ b/Sources/StableBar/MenuBar/MenuBarAppearance.swift @@ -24,12 +24,13 @@ final class MenuBarAppearance: NSObject { /// `BarDisplay.id` follows the screens' order, so once screens change, a remembered look could belong to another one. @objc private func screensChanged() { - schemes = [:] + if !schemes.isEmpty { schemes = [:] } windowChanged() } func record(_ appearance: NSAppearance, on displayID: Int) { - schemes[displayID] = appearance.bestMatch(from: [.darkAqua, .aqua]) == .darkAqua ? .dark : .light + let next: ColorScheme = appearance.bestMatch(from: [.darkAqua, .aqua]) == .darkAqua ? .dark : .light + if schemes[displayID] != next { schemes[displayID] = next } } /// The appearance can change a moment before the window moves to its new display, so both are read on the next turn. diff --git a/Sources/StableBar/MenuBar/MenuBarItemMirror.swift b/Sources/StableBar/MenuBar/MenuBarItemMirror.swift index e07f738b..50a5250d 100644 --- a/Sources/StableBar/MenuBar/MenuBarItemMirror.swift +++ b/Sources/StableBar/MenuBar/MenuBarItemMirror.swift @@ -71,7 +71,8 @@ final class MenuBarItemMirror { let drawn = frames.filter { !collapsed.contains($0.key) } guard let frame = drawn.values.first else { return [:] } let point = CGPoint(x: frame.midX, y: frame.midY) - let current = currentWindowFrames(listing.windows.map(\.id)) + let windowIDs = listing.windows.map(\.id) + let current = (try? await BlockingWork.run { currentWindowFrames(windowIDs) }) ?? [:] var effects = listing.handle(.refresh(point: point, current: current, at: Date())) while !effects.isEmpty { switch effects.removeFirst() { @@ -108,12 +109,16 @@ final class MenuBarItemMirror { configuration.height = Int(window.frame.height * scale) configuration.showsCursor = false configuration.backgroundColor = .clear + let windowOrigin = window.frame.origin guard let image = try? await SCScreenshotManager.captureImage(contentFilter: filter, configuration: configuration) else { return nil } - return frames.compactMapValues { frame in - let rect = frame.offsetBy(dx: -window.frame.minX, dy: -window.frame.minY) - .applying(CGAffineTransform(scaleX: scale, y: scale)).integral - return image.cropping(to: rect).flatMap { MenuBarItemImage(copying: $0, scale: scale) } - } + guard let processed = try? await BlockingWork.run({ + frames.compactMapValues { frame -> ProcessedMenuBarItemImage? in + let rect = frame.offsetBy(dx: -windowOrigin.x, dy: -windowOrigin.y) + .applying(CGAffineTransform(scaleX: scale, y: scale)).integral + return image.cropping(to: rect).flatMap { ProcessedMenuBarItemImage(copying: $0, scale: scale) } + } + }) else { return nil } + return processed.mapValues(MenuBarItemImage.init) } } @@ -172,6 +177,24 @@ struct MenuBarItemImage: Equatable { } /// Nil when `source` holds nothing, as for an item macOS isn't drawing. + init?(copying source: CGImage, scale: CGFloat) { + guard let processed = ProcessedMenuBarItemImage(copying: source, scale: scale) else { return nil } + self.init(processed) + } + + fileprivate init(_ processed: ProcessedMenuBarItemImage) { + image = NSImage(cgImage: processed.cgImage, size: processed.size) + image.isTemplate = processed.isTemplate + pixels = processed.pixels + } +} + +private struct ProcessedMenuBarItemImage: @unchecked Sendable { + let cgImage: CGImage + let pixels: Data + let size: NSSize + let isTemplate: Bool + init?(copying source: CGImage, scale: CGFloat) { let width = source.width, height = source.height let space = CGColorSpace(name: CGColorSpace.sRGB)! @@ -184,17 +207,23 @@ struct MenuBarItemImage: Equatable { let bytes = data.bindMemory(to: UInt8.self, capacity: width * height * 4) // With Reduce transparency the copy holds the menu bar's opaque background. When the corners are one opaque // color, take it out: each pixel keeps the least opacity that draws it over that color. - let corners = [0, width - 1, (height - 1) * width, height * width - 1].map { $0 * 4 } - let backdrop = (0..<4).map { bytes[$0] } - if backdrop[3] == 255, corners.allSatisfy({ corner in (0..<4).allSatisfy { bytes[corner + $0] == backdrop[$0] } }) { + let b0 = bytes[0], b1 = bytes[1], b2 = bytes[2], b3 = bytes[3] + let c1 = (width - 1) * 4, c2 = (height - 1) * width * 4, c3 = (height * width - 1) * 4 + if b3 == 255, + bytes[c1] == b0 && bytes[c1 + 1] == b1 && bytes[c1 + 2] == b2 && bytes[c1 + 3] == b3, + bytes[c2] == b0 && bytes[c2 + 1] == b1 && bytes[c2 + 2] == b2 && bytes[c2 + 3] == b3, + bytes[c3] == b0 && bytes[c3 + 1] == b1 && bytes[c3 + 2] == b2 && bytes[c3 + 3] == b3 { + let d0 = Double(b0), d1 = Double(b1), d2 = Double(b2) + let channelAlpha = { (value: Double, base: Double) -> Double in + value > base ? (value - base) / (255 - base) : value < base ? (base - value) / base : 0 + } for pixel in stride(from: 0, to: width * height * 4, by: 4) { - let alpha = (0..<3).map { channel in - let value = Double(bytes[pixel + channel]), base = Double(backdrop[channel]) - return value > base ? (value - base) / (255 - base) : value < base ? (base - value) / base : 0 - }.max()! - for channel in 0..<3 { - bytes[pixel + channel] = UInt8((Double(bytes[pixel + channel]) - (1 - alpha) * Double(backdrop[channel])).rounded()) - } + let v0 = Double(bytes[pixel]), v1 = Double(bytes[pixel + 1]), v2 = Double(bytes[pixel + 2]) + let alpha = max(channelAlpha(v0, d0), max(channelAlpha(v1, d1), channelAlpha(v2, d2))) + let inv = 1 - alpha + bytes[pixel] = UInt8((v0 - inv * d0).rounded()) + bytes[pixel + 1] = UInt8((v1 - inv * d1).rounded()) + bytes[pixel + 2] = UInt8((v2 - inv * d2).rounded()) bytes[pixel + 3] = UInt8((alpha * 255).rounded()) } } @@ -203,18 +232,19 @@ struct MenuBarItemImage: Equatable { } var left = width, right = -1, solid = 0, colored = 0, light = 0.0, opacity = 0.0 for y in 0.. 12 else { continue } - left = min(left, x) - right = max(right, x) + if x < left { left = x } + if x > right { right = x } light += brightness(pixel) opacity += Double(alpha) guard alpha > 64 else { continue } - let channels = [Int(bytes[pixel]), Int(bytes[pixel + 1]), Int(bytes[pixel + 2])] + let r = Int(bytes[pixel]), g = Int(bytes[pixel + 1]), b = Int(bytes[pixel + 2]) solid += 1 - if channels.max()! - channels.min()! > alpha / 5 { colored += 1 } + if max(r, max(g, b)) - min(r, min(g, b)) > alpha / 5 { colored += 1 } } } guard right >= left else { return nil } @@ -238,8 +268,9 @@ struct MenuBarItemImage: Equatable { let trimmed = CGImage(width: trimmedWidth, height: height, bitsPerComponent: 8, bitsPerPixel: 32, bytesPerRow: trimmedWidth * 4, space: space, bitmapInfo: CGBitmapInfo(rawValue: format), provider: provider, decode: nil, shouldInterpolate: true, intent: .defaultIntent) else { return nil } - image = NSImage(cgImage: trimmed, size: NSSize(width: CGFloat(trimmedWidth) / scale, height: CGFloat(height) / scale)) - image.isTemplate = isTemplate + cgImage = trimmed + size = NSSize(width: CGFloat(trimmedWidth) / scale, height: CGFloat(height) / scale) + self.isTemplate = isTemplate self.pixels = pixels } } diff --git a/Sources/StableBar/MenuBar/MenuBarStrip.swift b/Sources/StableBar/MenuBar/MenuBarStrip.swift index 8ff953d4..f0bb79f8 100644 --- a/Sources/StableBar/MenuBar/MenuBarStrip.swift +++ b/Sources/StableBar/MenuBar/MenuBarStrip.swift @@ -29,6 +29,7 @@ struct MenuBarStripState: Equatable { let menuBarLevel = Int(CGWindowLevelForKey(.mainMenuWindow)) for window in windows { guard let layer = window[kCGWindowLayer as String] as? Int, + layer == menuBarLevel || layer >= statusLevel, let bounds = (window[kCGWindowBounds as String] as! CFDictionary?).flatMap({ CGRect(dictionaryRepresentation: $0) }) else { continue } for (id, display) in displays @@ -142,6 +143,7 @@ final class MenuBarStrip: NSResponder { /// Reads the window list when the bar's place may change, and at least every two seconds while the pointer rests on a bar. private func tick() { + guard CGDisplayIsAsleep(CGMainDisplayID()) == 0 else { return } let pointer = CGEvent(source: nil)?.location ?? .zero let atTop = levels.strips.first { MenuBarStripState.nearsTop(pointer, of: CGDisplayBounds($0)) } if interval == 2 || ProcessInfo.processInfo.systemUptime - lastRead >= 2 || levels.reads(withPointerAtTopOf: atTop) { diff --git a/Sources/StableBar/MenuBar/WindowClearance.swift b/Sources/StableBar/MenuBar/WindowClearance.swift index b7139778..0bac6a08 100644 --- a/Sources/StableBar/MenuBar/WindowClearance.swift +++ b/Sources/StableBar/MenuBar/WindowClearance.swift @@ -200,6 +200,7 @@ final class WindowClearance: NSObject { private struct WatchedApplication { let element: AXUIElement let observer: AXObserver + var registeredNotifications = false var windows: [AXUIElement] = [] var adjustments: [AXUIElement: WindowAdjustment] = [:] } @@ -221,14 +222,17 @@ final class WindowClearance: NSObject { let timer = Timer(timeInterval: 1, repeats: true) { [weak self] _ in MainActor.assumeIsolated { self?.refreshPermission() } } + timer.tolerance = 0.25 permissionTimer = timer RunLoop.main.add(timer, forMode: .common) let center = NSWorkspace.shared.notificationCenter for name in [NSWorkspace.didLaunchApplicationNotification, NSWorkspace.didTerminateApplicationNotification, - NSWorkspace.didActivateApplicationNotification, NSWorkspace.didUnhideApplicationNotification, NSWorkspace.activeSpaceDidChangeNotification] { center.addObserver(self, selector: #selector(applicationsChanged), name: name, object: nil) } + for name in [NSWorkspace.didActivateApplicationNotification, NSWorkspace.didUnhideApplicationNotification] { + center.addObserver(self, selector: #selector(applicationActivated(_:)), name: name, object: nil) + } runningApplications = NSWorkspace.shared.observe(\.runningApplications, options: [.old, .new]) { [weak self] _, change in guard ((change.oldValue ?? []) + (change.newValue ?? [])).contains(where: { $0.bundleIdentifier == notificationCenterIdentifier @@ -253,12 +257,44 @@ final class WindowClearance: NSObject { else { removeObservers() } } + @objc private func applicationActivated(_ notification: Notification) { + guard permissionTimer != nil, isTrusted, keepsWindowsClear else { return } + guard let app = notification.userInfo?[NSWorkspace.applicationUserInfoKey] as? NSRunningApplication else { + applicationsChanged() + return + } + let pid = app.processIdentifier + guard app.activationPolicy == .regular, pid != ProcessInfo.processInfo.processIdentifier else { return } + if var application = applications[pid] { + if !application.registeredNotifications { + application.registeredNotifications = registerApplicationNotifications(for: application) + applications[pid] = application + } + if !app.isHidden { schedule(pid) } + } else { + applicationsChanged() + } + } + + private func registerApplicationNotifications(for application: WatchedApplication) -> Bool { + var allRegistered = true + for name in [kAXWindowCreatedNotification, kAXFocusedWindowChangedNotification] { + let status = AXObserverAddNotification(application.observer, application.element, name as CFString, + Unmanaged.passUnretained(self).toOpaque()) + if status != .success && status != .notificationAlreadyRegistered { + allRegistered = false + } + } + return allRegistered + } + @objc private func applicationsChanged() { guard permissionTimer != nil, isTrusted else { return } let running = NSWorkspace.shared.runningApplications.filter { keepsWindowsClear && $0.activationPolicy == .regular && $0.processIdentifier != ProcessInfo.processInfo.processIdentifier } - for (pid, application) in applications where !running.contains(where: { $0.processIdentifier == pid }) { + let runningPIDs = Set(running.map(\.processIdentifier)) + for (pid, application) in applications where !runningPIDs.contains(pid) { CFRunLoopRemoveSource(CFRunLoopGetMain(), AXObserverGetRunLoopSource(application.observer), .commonModes) applications.removeValue(forKey: pid) retries.removeValue(forKey: pid)?.task.cancel() @@ -276,13 +312,13 @@ final class WindowClearance: NSObject { }, &observer) == .success, let observer else { continue } let element = AXUIElementCreateApplication(pid) AXUIElementSetMessagingTimeout(element, 0.1) - applications[pid] = WatchedApplication(element: element, observer: observer) + var application = WatchedApplication(element: element, observer: observer) + application.registeredNotifications = registerApplicationNotifications(for: application) + applications[pid] = application CFRunLoopAddSource(CFRunLoopGetMain(), AXObserverGetRunLoopSource(observer), .commonModes) - } - let application = applications[pid]! - for name in [kAXWindowCreatedNotification, kAXFocusedWindowChangedNotification] { - AXObserverAddNotification(application.observer, application.element, name as CFString, - Unmanaged.passUnretained(self).toOpaque()) + } else if var application = applications[pid], !application.registeredNotifications { + application.registeredNotifications = registerApplicationNotifications(for: application) + applications[pid] = application } if !app.isHidden { schedule(pid) } } @@ -437,9 +473,21 @@ private func isSettable(_ name: String, of element: AXUIElement) -> Bool { return AXUIElementIsAttributeSettable(element, name as CFString, &settable) == .success && settable.boolValue } -private func windowFrame(_ window: AXUIElement) -> CGRect? { - guard let position = attribute(kAXPositionAttribute, of: window), CFGetTypeID(position) == AXValueGetTypeID(), - let size = attribute(kAXSizeAttribute, of: window), CFGetTypeID(size) == AXValueGetTypeID() else { return nil } +private func attributes(_ names: [String], of element: AXUIElement) -> [CFTypeRef?]? { + var values: CFArray? + guard AXUIElementCopyMultipleAttributeValues(element, names as CFArray, [], &values) == .success, + let array = values as? [AnyObject], array.count == names.count else { return nil } + return array.map { value in + let type = CFGetTypeID(value) + if type == CFNullGetTypeID() { return nil } + if type == AXValueGetTypeID(), AXValueGetType(value as! AXValue) == .axError { return nil } + return value + } +} + +private func frameFromValues(_ position: CFTypeRef?, _ size: CFTypeRef?) -> CGRect? { + guard let position, CFGetTypeID(position) == AXValueGetTypeID(), + let size, CFGetTypeID(size) == AXValueGetTypeID() else { return nil } var point = CGPoint.zero var dimensions = CGSize.zero guard AXValueGetValue(position as! AXValue, .cgPoint, &point), @@ -447,9 +495,16 @@ private func windowFrame(_ window: AXUIElement) -> CGRect? { return CGRect(origin: point, size: dimensions) } +private func windowFrame(_ window: AXUIElement) -> CGRect? { + guard let values = attributes([kAXPositionAttribute, kAXSizeAttribute], of: window) else { return nil } + return frameFromValues(values[0], values[1]) +} + private func ordinaryWindowFrame(_ window: AXUIElement) -> CGRect? { - guard attribute(kAXSubroleAttribute, of: window) as? String == kAXStandardWindowSubrole, - attribute(kAXMinimizedAttribute, of: window) as? Bool == false, - attribute("AXFullScreen", of: window) as? Bool != true else { return nil } - return windowFrame(window) + guard let values = attributes([kAXSubroleAttribute, kAXMinimizedAttribute, "AXFullScreen", + kAXPositionAttribute, kAXSizeAttribute], of: window), + values[0] as? String == kAXStandardWindowSubrole, + values[1] as? Bool == false, + values[2] as? Bool != true else { return nil } + return frameFromValues(values[3], values[4]) } diff --git a/Sources/StableBar/Workspaces/Spaces.swift b/Sources/StableBar/Workspaces/Spaces.swift index 51bae88e..2cdde2a9 100644 --- a/Sources/StableBar/Workspaces/Spaces.swift +++ b/Sources/StableBar/Workspaces/Spaces.swift @@ -42,8 +42,15 @@ func spacesSnapshot(displays: Data, windows: Data, windowSpaces: [Int: [UInt64]] screenUUIDs: [String], bundleIDs: [Int32: String]) throws -> [Workspace] { let windows = try PropertyListDecoder().decode([SpaceWindow].self, from: windows) .filter { $0.layer == 0 && bundleIDs[$0.pid] != nil } + let displays = try PropertyListDecoder().decode([ManagedDisplay].self, from: displays) + return spacesSnapshot(displays: displays, windows: windows, windowSpaces: windowSpaces, + activeSpace: activeSpace, screenUUIDs: screenUUIDs, bundleIDs: bundleIDs) +} + +private func spacesSnapshot(displays: [ManagedDisplay], windows: [SpaceWindow], windowSpaces: [Int: [UInt64]], + activeSpace: UInt64, screenUUIDs: [String], bundleIDs: [Int32: String]) -> [Workspace] { var number = 0 - return try PropertyListDecoder().decode([ManagedDisplay].self, from: displays).flatMap { display in + return displays.flatMap { display in let monitor = display.identifier == "Main" ? 0 : screenUUIDs.firstIndex(of: display.identifier) return display.spaces.filter { $0.type == 0 }.compactMap { space -> Workspace? in number += 1 @@ -67,6 +74,28 @@ func spacesSnapshot(displays: Data, windows: Data, windowSpaces: [Int: [UInt64]] } } +private func parseManagedSpace(_ dictionary: [String: Any]) -> ManagedSpace? { + guard let id = (dictionary["ManagedSpaceID"] as? NSNumber)?.uint64Value, + let type = (dictionary["type"] as? NSNumber)?.intValue else { return nil } + return ManagedSpace(id: id, type: type) +} + +private func parseManagedDisplays(_ raw: CFArray) -> [ManagedDisplay]? { + guard let array = raw as? [[String: Any]] else { return nil } + var displays: [ManagedDisplay] = [] + displays.reserveCapacity(array.count) + for item in array { + guard let identifier = item["Display Identifier"] as? String, + let currentRaw = item["Current Space"] as? [String: Any], + let current = parseManagedSpace(currentRaw), + let spacesRaw = item["Spaces"] as? [[String: Any]] else { return nil } + let spaces = spacesRaw.compactMap(parseManagedSpace) + guard spaces.count == spacesRaw.count else { return nil } + displays.append(ManagedDisplay(identifier: identifier, currentSpace: current, spaces: spaces)) + } + return displays +} + func currentSpaces(copyManagedDisplaySpaces: ((Int32) -> Unmanaged?)? = PrivateAPI.copyManagedDisplaySpaces) throws -> [Workspace] { guard let connection = PrivateAPI.mainConnectionID?(), let getActiveSpace = PrivateAPI.getActiveSpace, @@ -74,22 +103,33 @@ func currentSpaces(copyManagedDisplaySpaces: ((Int32) -> Unmanaged?)? = let managedDisplaySpaces = copyManagedDisplaySpaces?(connection)?.takeRetainedValue() else { throw CommandFailure(message: "This version of macOS doesn't let StableBar read its Spaces.") } - let info = CGWindowListCopyWindowInfo(.excludeDesktopElements, kCGNullWindowID) as! [[String: Any]] - let windowSpaces = info.reduce(into: [Int: [UInt64]]()) { result, window in - let id = window[kCGWindowNumber as String] as! Int - result[id] = copySpacesForWindows(connection, 7, [id] as CFArray)?.takeRetainedValue() as? [UInt64] + let bundleIDs = NSWorkspace.shared.runningApplications.reduce(into: [Int32: String]()) { result, app in + if app.activationPolicy == .regular { result[app.processIdentifier] = app.bundleIdentifier } + } + let info = CGWindowListCopyWindowInfo(.excludeDesktopElements, kCGNullWindowID) as? [[String: Any]] ?? [] + var windows: [SpaceWindow] = [] + var windowSpaces: [Int: [UInt64]] = [:] + for window in info { + guard let layer = (window[kCGWindowLayer as String] as? NSNumber)?.intValue, layer == 0, + let pid = (window[kCGWindowOwnerPID as String] as? NSNumber)?.int32Value, bundleIDs[pid] != nil, + let id = (window[kCGWindowNumber as String] as? NSNumber)?.intValue, + let app = window[kCGWindowOwnerName as String] as? String else { continue } + windows.append(SpaceWindow(id: id, pid: pid, app: app, title: window[kCGWindowName as String] as? String, layer: layer)) + windowSpaces[id] = copySpacesForWindows(connection, 7, [id] as CFArray)?.takeRetainedValue() as? [UInt64] } let screens = NSScreen.screens.map { screen in let id = (screen.deviceDescription[NSDeviceDescriptionKey("NSScreenNumber")] as! NSNumber).uint32Value return CFUUIDCreateString(nil, CGDisplayCreateUUIDFromDisplayID(id).takeRetainedValue()) as String } - let bundleIDs = NSWorkspace.shared.runningApplications.reduce(into: [Int32: String]()) { result, app in - if app.activationPolicy == .regular { result[app.processIdentifier] = app.bundleIdentifier } + let activeSpace = getActiveSpace(connection) + if let displays = parseManagedDisplays(managedDisplaySpaces) { + return spacesSnapshot(displays: displays, windows: windows, windowSpaces: windowSpaces, + activeSpace: activeSpace, screenUUIDs: screens, bundleIDs: bundleIDs) } return try spacesSnapshot( displays: PropertyListSerialization.data(fromPropertyList: managedDisplaySpaces, format: .binary, options: 0), windows: PropertyListSerialization.data(fromPropertyList: info, format: .binary, options: 0), - windowSpaces: windowSpaces, activeSpace: getActiveSpace(connection), screenUUIDs: screens, bundleIDs: bundleIDs) + windowSpaces: windowSpaces, activeSpace: activeSpace, screenUUIDs: screens, bundleIDs: bundleIDs) } struct DesktopShortcutUnavailable: LocalizedError { diff --git a/Sources/StableBar/Workspaces/Workspaces.swift b/Sources/StableBar/Workspaces/Workspaces.swift index f4853c9c..319c715e 100644 --- a/Sources/StableBar/Workspaces/Workspaces.swift +++ b/Sources/StableBar/Workspaces/Workspaces.swift @@ -512,7 +512,7 @@ final class WorkspaceStore { let previousWorkspace = workspaces.first(where: \.isFocused)?.name if workspaces != snapshot { workspaces = snapshot } if previousWorkspace != workspaces.first(where: \.isFocused)?.name { onWorkspaceChange?() } - error = nil + if reportedError != nil || failedDesktopShortcut != nil { error = nil } // Rift's subscription sends nothing when it connects, so a query that works while it runs is the first // sign it's back. Between attempts its process has exited, and the disconnect stays. if source == .rift, process?.isRunning == true { connectionError = nil } diff --git a/Tests/StableBarTests/PerformanceOptimizationsTests.swift b/Tests/StableBarTests/PerformanceOptimizationsTests.swift new file mode 100644 index 00000000..58d6985c --- /dev/null +++ b/Tests/StableBarTests/PerformanceOptimizationsTests.swift @@ -0,0 +1,88 @@ +import AppKit +import SwiftUI +import Testing +@testable import StableBar + +@Test @MainActor func incrementalScriptUpdateRefreshesOnlyAffectedWidgetAndStillAppliesAndClearsOverrides() async throws { + let json = #""" + {"widgets":[{"id":"a","type":"script","command":"true","position":"left"}, + {"id":"b","type":"script","command":"true","position":"right"}]} + """# + let configuration = try JSONDecoder().decode(Configuration.self, from: Data(json.utf8)) + let store = BarStore(configurationURL: FileManager.default.temporaryDirectory.appending(path: UUID().uuidString)) + store.configuration = configuration + let a = ScriptWidget() + let b = ScriptWidget() + store.widgetScripts.scripts = ["a": a, "b": b] + store.barPresentation.preparePresentations() + defer { store.stop() } + + let presentationA = try #require(store.barPresentation.presentations["a"]) + let presentationB = try #require(store.barPresentation.presentations["b"]) + + // Updating a's own color updates only a's presentation. + try a.accept(ScriptOutput.read(Data(##"{"text":"1","color":"#ff0000"}"##.utf8))) + #expect(presentationA.style.base.foreground == HexColor(0xff0000ff)) + #expect(presentationB.style.base.foreground == nil) + + // Emitting a cross-widget override and barStyle triggers a full update. + try a.accept(ScriptOutput.read(Data(##"{"text":"2","barStyle":{"opacity":0.5},"widgetStyles":{"b":{"foreground":"#00ff00"}}}"##.utf8))) + #expect(presentationB.style.base.foreground == HexColor(0x00ff00ff)) + #expect(store.barPresentation.barStyle.opacity == 0.5) + + // Clearing the cross-widget override and barStyle restores b and barStyle. + try a.accept(ScriptOutput.read(Data(#"{"text":"3"}"#.utf8))) + #expect(presentationB.style.base.foreground == nil) + #expect(store.barPresentation.barStyle.opacity == nil) +} + +@Test func adaptiveHexColorReusesEqualColorInstance() { + let first = HexColor(light: 0x112233ff, dark: 0xaabbccff) + let second = HexColor(light: 0x112233ff, dark: 0xaabbccff) + #expect(first.color == second.color) +} + +@Test func hardShadowsWithZeroRadiusStayEnabledWhileUncoloredShadowsSkip() { + let hardShadow = WidgetAppearance(WidgetStyle(shadowRadius: 0, shadowColor: HexColor(0x000000ff), shadowOffsetX: 2, shadowOffsetY: 2), + defaults: WidgetStyle()) + let noShadow = WidgetAppearance(WidgetStyle(), defaults: WidgetStyle()) + #expect(hardShadow.hasShadow) + #expect(!noShadow.hasShadow) +} + +@Test func configurationValueFastDecodePreservesBooleansNumbersAndCollections() throws { + let data = Data(#""" + {"flag":true,"zero":0,"one":1,"ratio":2.5,"text":"ok","nothing":null, + "names":["a","b"],"items":[{"id":"x","enabled":false}]} + """#.utf8) + let object = try JSONDecoder().decode([String: ConfigurationValue].self, from: data) + #expect(try object["flag"]?.decoded(Bool.self) == true) + #expect(try object["zero"]?.decoded(Double.self) == 0) + #expect(try object["one"]?.decoded(Double.self) == 1) + #expect(try object["ratio"]?.decoded(Double.self) == 2.5) + #expect(try object["text"]?.decoded(String.self) == "ok") + #expect(object["nothing"] == .null) + #expect(try object["names"]?.decoded([String].self) == ["a", "b"]) + let items = try object["items"]?.decoded([[String: ConfigurationValue]].self) + #expect(items?.count == 1) + #expect(try items?[0]["id"]?.decoded(String.self) == "x") + #expect(try items?[0]["enabled"]?.decoded(Bool.self) == false) +} + +@Test func cachedClockFormattersMatchAcrossFormatsAndTimeZones() throws { + let utc = try JSONDecoder().decode(WidgetConfiguration.self, from: Data(#""" + {"id":"utc","type":"clock","format":"yyyy-MM-dd HH:mm:ss","timeZone":"UTC","position":"right"} + """#.utf8)) + let tokyo = try JSONDecoder().decode(WidgetConfiguration.self, from: Data(#""" + {"id":"tokyo","type":"clock","format":"yyyy-MM-dd HH:mm:ss","timeZone":"Asia/Tokyo","position":"right"} + """#.utf8)) + let instant = Date(timeIntervalSince1970: 1_700_000_000) + let firstUTC = utc.label(output: nil, activeApp: nil, date: instant) + let secondUTC = utc.label(output: nil, activeApp: nil, date: instant) + let firstTokyo = tokyo.label(output: nil, activeApp: nil, date: instant) + #expect(firstUTC == secondUTC) + #expect(firstUTC.text == "2023-11-14 22:13:20") + #expect(firstUTC.fields["date"] == "2023-11-14") + #expect(firstUTC.fields["time"] == "22:13:20") + #expect(firstTokyo.text == "2023-11-15 07:13:20") +}