Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
248 changes: 198 additions & 50 deletions Sources/StableBar/Bar/BarPresentation.swift

Large diffs are not rendered by default.

14 changes: 11 additions & 3 deletions Sources/StableBar/Bar/BarView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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) } }
Expand Down
63 changes: 53 additions & 10 deletions Sources/StableBar/Bar/WidgetLabel.swift
Original file line number Diff line number Diff line change
@@ -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.
Expand All @@ -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:
Expand All @@ -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<String.Index>] = []
var time: Range<String.Index>?
Expand Down Expand Up @@ -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))
}
}
}
53 changes: 39 additions & 14 deletions Sources/StableBar/Configuration/Configuration.swift
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import AppKit
import os
import SwiftUI

struct HexColor: Decodable, Equatable, Sendable {
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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)
}
}

Expand All @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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)] {
Expand All @@ -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"]) {
Expand Down Expand Up @@ -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<String> = []
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)
}
}
35 changes: 33 additions & 2 deletions Sources/StableBar/Configuration/ConfigurationLoader.swift
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,39 @@ indirect enum ConfigurationValue: Codable, Sendable, Equatable {
}

func decoded<T: Decodable>(_ 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))
}

Expand Down
11 changes: 11 additions & 0 deletions Sources/StableBar/DataSources/AudioMonitor.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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<UInt32>.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.
Expand Down
27 changes: 23 additions & 4 deletions Sources/StableBar/DataSources/DockBadges.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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? {
Expand All @@ -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
}
}
Expand Down
23 changes: 19 additions & 4 deletions Sources/StableBar/DataSources/NativeMetrics.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand All @@ -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)
Expand All @@ -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)
}
}
Expand Down
Loading
Loading