feat(menubar): 支持固定居中面板与独立刷新频率及图表浮层

This commit is contained in:
2026-11-03 11:30:37 +08:00
parent 906293b7c1
commit 36b8e32af3
33 changed files with 1403 additions and 118 deletions
+82 -32
View File
@@ -1,36 +1,86 @@
//
// kymoApp.swift
// kymo
//
// Created by Airnan on 2026/10/29.
//
import SwiftUI
import AppKit
/// 应用入口。
///
/// Kymo 是一款菜单栏常驻应用:平时不显示 Dock 图标与主窗口,
/// 通过 `MenuBarExtra` 场景在系统菜单栏展示状态并承载监控面板。
/// 打开设置期间临时使用常规应用激活策略,以便设置窗口正常获得焦点。
@main
struct kymoApp: App {
@State private var metrics = MetricsStore()
@State private var keepAwake = KeepAwakeService()
@State private var settingsPresentation = SettingsPresentation()
@State private var appearance = AppearancePreferences()
@State private var language = LanguagePreferences()
var body: some Scene {
MenuBarExtra("Kymo", image: "BrandMark") {
MenuPanelView(metrics: metrics, preferences: appearance, keepAwake: keepAwake, settingsPresentation: settingsPresentation)
.environment(\.locale, language.locale)
}
.menuBarExtraStyle(.window)
Settings {
AppearanceSettingsView(preferences: appearance, language: language, presentation: settingsPresentation)
.environment(\.locale, language.locale)
}
/// AppKit owns launch only; MenuBar owns windows, Core owns sampling and preferences.
@main @MainActor struct kymoApp {
static func main() {
let application = NSApplication.shared
let lifecycle = ApplicationLifecycle()
application.delegate = lifecycle
application.setActivationPolicy(.accessory)
withExtendedLifetime(lifecycle) { application.run() }
}
}
@MainActor private final class ApplicationLifecycle: NSObject, NSApplicationDelegate {
private let metrics = MetricsStore()
private let awake = KeepAwakeService()
private let presentation = SettingsPresentation()
private let appearance = AppearancePreferences()
private let language = LanguagePreferences()
private var openSettingsAction: (() -> Void)?
private var scenes: AnyObject?
private var menuBar: MenuPanelController?
func applicationWillFinishLaunching(_ notification: Notification) {
let settings = NSHostingSceneRepresentation {
Settings {
AppearanceSettingsView(preferences: appearance, language: language, sampling: metrics.sampling, presentation: presentation)
.environment(\.locale, language.locale)
.onChange(of: language.language) { _, _ in self.configureMainMenu() }
}
}
NSApp.addSceneRepresentation(settings)
scenes = settings
openSettingsAction = { settings.environment.openSettings() }
configureMainMenu()
menuBar = MenuPanelController(visibility: { [metrics] in metrics.setPanelVisible($0) }) { [self] panel in
MenuPanelView(metrics: metrics, preferences: appearance, keepAwake: awake, settingsPresentation: presentation,
presentation: panel, onOpenSettings: { [weak self] in
self?.menuBar?.hide()
settings.environment.openSettings()
})
.environment(\.locale, language.locale)
}
}
private func configureMainMenu() {
let root = NSMenu()
let application = NSMenu()
let appItem = NSMenuItem(); appItem.submenu = application; root.addItem(appItem)
let settings = NSMenuItem(title: AppLocalization.string("action.settings", locale: language.locale), action: #selector(settingsCommand), keyEquivalent: ",")
settings.target = self
application.addItem(settings)
application.addItem(.separator())
let quit = NSMenuItem(title: AppLocalization.string("action.quit", locale: language.locale), action: #selector(NSApplication.terminate(_:)), keyEquivalent: "q")
quit.target = NSApp; application.addItem(quit)
let file = NSMenu()
let fileItem = NSMenuItem(title: AppLocalization.string("action.file", locale: language.locale), action: nil, keyEquivalent: "")
fileItem.submenu = file; root.addItem(fileItem)
file.addItem(NSMenuItem(title: AppLocalization.string("action.closeWindow", locale: language.locale), action: #selector(NSWindow.performClose(_:)), keyEquivalent: "w"))
let edit = NSMenu()
let editItem = NSMenuItem(title: AppLocalization.string("action.edit", locale: language.locale), action: nil, keyEquivalent: "")
editItem.submenu = edit; root.addItem(editItem)
for (key, action, shortcut) in [("undo", "undo:", "z"), ("redo", "redo:", "Z"), ("cut", "cut:", "x"), ("copy", "copy:", "c"), ("paste", "paste:", "v"), ("selectAll", "selectAll:", "a")] {
edit.addItem(NSMenuItem(title: AppLocalization.string("action." + key, locale: language.locale), action: Selector(action), keyEquivalent: shortcut))
}
NSApp.mainMenu = root
}
@objc private func settingsCommand() {
NSApp.setActivationPolicy(.regular)
presentation.request()
menuBar?.hide()
openSettingsAction?()
}
func applicationWillTerminate(_ notification: Notification) {
menuBar?.shutdown()
awake.disable()
menuBar = nil
openSettingsAction = nil
scenes = nil
}
func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { false }
}
@@ -0,0 +1,38 @@
{
"colors": [
{
"idiom": "universal",
"color": {
"color-space": "srgb",
"components": {
"red": "0.990",
"green": "0.990",
"blue": "0.995",
"alpha": "0.970"
}
}
},
{
"idiom": "universal",
"color": {
"color-space": "srgb",
"components": {
"red": "0.130",
"green": "0.150",
"blue": "0.180",
"alpha": "0.970"
}
},
"appearances": [
{
"appearance": "luminosity",
"value": "dark"
}
]
}
],
"info": {
"author": "xcode",
"version": 1
}
}
@@ -0,0 +1,38 @@
{
"colors": [
{
"idiom": "universal",
"color": {
"color-space": "srgb",
"components": {
"red": "0.620",
"green": "0.340",
"blue": "0.000",
"alpha": "1.000"
}
}
},
{
"idiom": "universal",
"color": {
"color-space": "srgb",
"components": {
"red": "1.000",
"green": "0.760",
"blue": "0.240",
"alpha": "1.000"
}
},
"appearances": [
{
"appearance": "luminosity",
"value": "dark"
}
]
}
],
"info": {
"author": "xcode",
"version": 1
}
}
@@ -0,0 +1,38 @@
{
"colors": [
{
"idiom": "universal",
"color": {
"color-space": "srgb",
"components": {
"red": "0.700",
"green": "0.260",
"blue": "0.000",
"alpha": "1.000"
}
}
},
{
"idiom": "universal",
"color": {
"color-space": "srgb",
"components": {
"red": "1.000",
"green": "0.620",
"blue": "0.200",
"alpha": "1.000"
}
},
"appearances": [
{
"appearance": "luminosity",
"value": "dark"
}
]
}
],
"info": {
"author": "xcode",
"version": 1
}
}
@@ -0,0 +1,38 @@
{
"colors": [
{
"idiom": "universal",
"color": {
"color-space": "srgb",
"components": {
"red": "0.700",
"green": "0.040",
"blue": "0.460",
"alpha": "1.000"
}
}
},
{
"idiom": "universal",
"color": {
"color-space": "srgb",
"components": {
"red": "1.000",
"green": "0.400",
"blue": "0.750",
"alpha": "1.000"
}
},
"appearances": [
{
"appearance": "luminosity",
"value": "dark"
}
]
}
],
"info": {
"author": "xcode",
"version": 1
}
}
+3 -2
View File
@@ -13,6 +13,7 @@ nonisolated struct TrendSample: Sendable {
var write: Double?
var cpuUser: Double?
var cpuSystem: Double?
var breakBefore = false
}
/// Bounded sampling history; no timer or UI visibility dependence.
@@ -21,13 +22,13 @@ nonisolated struct MetricHistory: Sendable {
private(set) var samples: [TrendSample] = []
private(set) var interfaces: [String: [InterfaceTrendSample]] = [:]
mutating func append(_ snapshot: MetricsSnapshot) {
mutating func append(_ snapshot: MetricsSnapshot, breakBefore: Bool = false) {
samples.append(TrendSample(date: snapshot.date, cpu: snapshot.cpu?.usage,
gpu: snapshot.gpuUsage, memory: snapshot.memory?.usage,
download: snapshot.downloadRate, disk: snapshot.disk?.usage,
battery: snapshot.battery?.charge, upload: snapshot.uploadRate,
read: snapshot.diskIO?.read, write: snapshot.diskIO?.written,
cpuUser: snapshot.cpu?.user, cpuSystem: snapshot.cpu?.system))
cpuUser: snapshot.cpu?.user, cpuSystem: snapshot.cpu?.system, breakBefore: breakBefore))
let current = snapshot.network ?? []
let keys = Set(current.map(\.identity))
interfaces = interfaces.filter { keys.contains($0.key) }
+31 -11
View File
@@ -21,12 +21,18 @@ actor SystemSampler {
private var batteryDate: Date?
private var nextDisk: TimeInterval = 0
private var nextBattery: TimeInterval = 0
private let processRead: @Sendable (inout ProcessMonitor) -> ProcessSnapshot
private var processMonitor = ProcessMonitor()
private var processTask: Task<Void, Never>?
private var processCache: ProcessSnapshot?
private var processUpdate: (@Sendable (ProcessSnapshot) -> Void)?
private var processVisible = false
private var processGeneration = 0
init(processRead: @escaping @Sendable (inout ProcessMonitor) -> ProcessSnapshot = { $0.sample() }) {
self.processRead = processRead
}
func reset() { cpu = CPUMonitor(); network = NetworkMonitor(); diskIO = DiskIOMonitor() }
func setProcessVisible(_ visible: Bool) {
@@ -34,12 +40,15 @@ actor SystemSampler {
processVisible = visible
processGeneration += 1
processCache = nil
if !visible { processUpdate = nil }
processMonitor = ProcessMonitor()
// A synchronous OS read may outlive cancellation. Keep the in-flight slot occupied.
}
func sample(includeProcesses: Bool? = nil) -> MetricsSnapshot {
func sample(includeProcesses: Bool? = nil, processUpdate: (@Sendable (ProcessSnapshot) -> Void)? = nil) -> MetricsSnapshot {
guard !Task.isCancelled else { return MetricsSnapshot() }
if let includeProcesses { setProcessVisible(includeProcesses) }
self.processUpdate = processUpdate
if !didProbe {
didProbe = true
if ProcessInfo.processInfo.environment["KYMO_PANEL_PROBE"] == "1" { PanelCapabilityProbe.run() }
@@ -69,15 +78,7 @@ actor SystemSampler {
if result.battery != nil && batteryTask == nil && start >= nextBattery {
batteryTask = Task { [self, batteryHealth] in await finishBattery(batteryHealth.sample()) }
}
if processVisible && processTask == nil {
let generation = processGeneration
let monitor = processMonitor
processTask = Task.detached(priority: .utility) { [self] in
var worker = monitor
let value = worker.sample()
await finishProcesses(value, monitor: worker, generation: generation)
}
}
startProcessesIfNeeded()
result.processes = processVisible ? processCache : nil
result.diskHealth = diskCache
result.diskHealthDate = diskDate
@@ -105,9 +106,28 @@ actor SystemSampler {
batteryCache = value; batteryDate = value == nil ? nil : Date()
nextBattery = ProcessInfo.processInfo.systemUptime + (value == nil ? 600 : 3600); batteryTask = nil
}
private func startProcessesIfNeeded() {
guard processVisible, processTask == nil else { return }
let generation = processGeneration
let monitor = processMonitor
let read = processRead
processTask = Task.detached(priority: .utility) { [self] in
var worker = monitor
let value = read(&worker)
await finishProcesses(value, monitor: worker, generation: generation)
}
}
private func finishProcesses(_ value: ProcessSnapshot, monitor: ProcessMonitor, generation: Int) {
processTask = nil
guard processVisible, generation == processGeneration else { return }
guard processVisible else { return }
guard generation == processGeneration else {
// Reopening requested a new generation while the old synchronous read held its slot.
// Fulfil that deferred request now, without waiting for another polling interval.
startProcessesIfNeeded()
return
}
processMonitor = monitor; processCache = value
processUpdate?(value)
}
}
+37 -6
View File
@@ -7,30 +7,60 @@ final class MetricsStore {
private(set) var history = MetricHistory()
private(set) var isPaused = false
private(set) var isPanelVisible = false
let sampling: SamplingPreferences
var effectiveMilliseconds: Int { isPanelVisible ? sampling.panelMilliseconds : sampling.backgroundMilliseconds }
@ObservationIgnored private var generation = 0
@ObservationIgnored private var visibilityGeneration = 0
@ObservationIgnored private var task: Task<Void, Never>?
@ObservationIgnored private let sampler = SystemSampler()
@ObservationIgnored private var scheduledInterval = 0
@ObservationIgnored private var needsHistoryBoundary = true
init() { start() }
init(sampling: SamplingPreferences? = nil) {
self.sampling = sampling ?? SamplingPreferences()
self.sampling.onChange = { [weak self] in
guard let self, !self.isPaused, self.effectiveMilliseconds != self.scheduledInterval else { return }
self.reschedule(reset: false)
}
start()
}
func start() {
guard task == nil else { return }
isPaused = false
reschedule(reset: true)
}
private func reschedule(reset: Bool) {
generation += 1
task?.cancel()
needsHistoryBoundary = true
scheduledInterval = effectiveMilliseconds
let currentGeneration = generation
task = Task { [weak self, sampler] in
await sampler.reset()
await sampler.setProcessVisible(self?.isPanelVisible == true)
guard !Task.isCancelled else { return }
if reset { await sampler.reset() }
while !Task.isCancelled {
let visibleGeneration = self?.visibilityGeneration
var next = await sampler.sample(includeProcesses: self?.isPanelVisible == true)
var next = await sampler.sample(includeProcesses: self?.isPanelVisible == true, processUpdate: { [weak self] processes in
Task { @MainActor [weak self] in
guard let self, self.generation == currentGeneration, self.visibilityGeneration == visibleGeneration,
self.isPanelVisible, !self.isPaused else { return }
self.snapshot.processes = processes
}
})
guard !Task.isCancelled, self?.generation == currentGeneration else { return }
if self?.isPanelVisible != true || self?.visibilityGeneration != visibleGeneration { next.processes = nil }
else if let completed = self?.snapshot.processes, completed.date >= next.date {
// A fast detached process result may reach MainActor before this quick snapshot.
next.processes = completed
}
self?.snapshot = next
self?.history.append(next)
self?.history.append(next, breakBefore: self?.needsHistoryBoundary == true)
self?.needsHistoryBoundary = false
SamplingDiagnostics.record(next)
do { try await Task.sleep(for: .seconds(2)) }
let interval = self?.effectiveMilliseconds ?? 5_000
do { try await Task.sleep(for: .milliseconds(interval)) }
catch { return }
}
}
@@ -55,6 +85,7 @@ final class MetricsStore {
if !visible { snapshot.processes = nil }
let active = visible && !isPaused
Task { await sampler.setProcessVisible(active) }
if !isPaused { reschedule(reset: false) }
}
deinit { task?.cancel() }
@@ -0,0 +1,50 @@
import Foundation
import Observation
import CoreFoundation
/// Integer milliseconds avoid drift over repeated 100 ms steps.
@MainActor @Observable final class SamplingPreferences {
static let range = 500...1_800_000
static let step = 100
@ObservationIgnored private let defaults: UserDefaults
@ObservationIgnored var onChange: (() -> Void)?
private var panelValue: Int
private var backgroundValue: Int
var panelMilliseconds: Int {
get { panelValue }
set {
let value = Self.normalized(newValue)
guard value != panelValue else { return }
panelValue = value
defaults.set(value, forKey: "sampling.panelMilliseconds")
onChange?()
}
}
var backgroundMilliseconds: Int {
get { backgroundValue }
set {
let value = Self.normalized(newValue)
guard value != backgroundValue else { return }
backgroundValue = value
defaults.set(value, forKey: "sampling.backgroundMilliseconds")
onChange?()
}
}
init(defaults: UserDefaults = .standard) {
self.defaults = defaults
panelValue = Self.read(defaults, key: "sampling.panelMilliseconds", fallback: 2_000)
backgroundValue = Self.read(defaults, key: "sampling.backgroundMilliseconds", fallback: 5_000)
}
static func normalized(_ value: Int) -> Int {
let clamped = min(range.upperBound, max(range.lowerBound, value))
return ((clamped + step / 2) / step) * step
}
private static func read(_ defaults: UserDefaults, key: String, fallback: Int) -> Int {
guard let number = defaults.object(forKey: key) as? NSNumber,
CFGetTypeID(number) != CFBooleanGetTypeID(), number.doubleValue.isFinite else { return fallback }
return normalized(Int(min(Double(range.upperBound), max(Double(range.lowerBound), number.doubleValue))))
}
}
@@ -0,0 +1,131 @@
import AppKit
import SwiftUI
import Observation
@MainActor @Observable final class PanelPresentation {
var isPinned = false { didSet { onPinChange?(isPinned) } }
@ObservationIgnored var onPinChange: ((Bool) -> Void)?
}
/// Owns only status-item/window behavior. Sampling and settings are injected by App.
@MainActor final class MenuPanelController: NSObject {
let presentation = PanelPresentation()
let panel = MonitoringPanel(contentRect: .zero, styleMask: [.borderless, .nonactivatingPanel], backing: .buffered, defer: false)
private var statusItem: NSStatusItem?
private var localMouse: Any?
private var globalMouse: Any?
private var tokens: [NSObjectProtocol] = []
private let content: (PanelPresentation) -> NSView
private let visibility: (Bool) -> Void
init<Content: View>(installStatusItem: Bool = true, visibility: @escaping (Bool) -> Void,
@ViewBuilder content: @escaping (PanelPresentation) -> Content) {
self.visibility = visibility
self.content = { NSHostingView(rootView: content($0)) }
super.init()
panel.title = "Kymo"
panel.isReleasedWhenClosed = false
panel.isOpaque = false
panel.backgroundColor = .clear
panel.hasShadow = true
panel.hidesOnDeactivate = false
panel.collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary]
panel.dismiss = { [weak self] in self?.hide() }
presentation.onPinChange = { [weak self] pinned in self?.panel.level = pinned ? .floating : .normal }
if installStatusItem {
let item = NSStatusBar.system.statusItem(withLength: NSStatusItem.squareLength)
item.button?.image = NSImage(named: "BrandMark")
item.button?.image?.isTemplate = true
item.button?.toolTip = "Kymo"
item.button?.setAccessibilityLabel("Kymo")
item.button?.target = self
item.button?.action = #selector(togglePanel)
statusItem = item
}
tokens.append(NotificationCenter.default.addObserver(forName: NSApplication.didChangeScreenParametersNotification, object: nil, queue: .main) { [weak self] _ in
MainActor.assumeIsolated { self?.place() }
})
tokens.append(NotificationCenter.default.addObserver(forName: NSApplication.didResignActiveNotification, object: NSApp, queue: .main) { [weak self] _ in
MainActor.assumeIsolated { self?.dismissForOutsideInteraction() }
})
}
@objc func togglePanel() { panel.isVisible ? hide() : show() }
func show() {
guard !panel.isVisible else { panel.makeKeyAndOrderFront(nil); return }
place()
panel.contentView = content(presentation)
panel.level = presentation.isPinned ? .floating : .normal
panel.makeKeyAndOrderFront(nil)
panel.orderFrontRegardless()
visibility(true)
installMonitors()
}
func hide() {
panel.orderOut(nil)
panel.contentView = nil
visibility(false)
removeMonitors()
}
func dismissForOutsideInteraction() {
if panel.isVisible && !presentation.isPinned { hide() }
}
func shutdown() {
hide()
presentation.isPinned = false
if let statusItem { NSStatusBar.system.removeStatusItem(statusItem) }
statusItem = nil
tokens.forEach(NotificationCenter.default.removeObserver)
tokens.removeAll()
}
private func place() {
guard let screen = statusItem?.button?.window?.screen ?? panel.screen ?? NSScreen.main else { return }
let size = PanelLayout.contentSize(visible: screen.visibleFrame)
let initial = CGRect(x: screen.visibleFrame.midX - size.width / 2, y: screen.visibleFrame.maxY - size.height - 16,
width: size.width, height: size.height)
panel.setFrame(PanelLayout.centeredFrame(initial, visible: screen.visibleFrame), display: panel.isVisible)
}
private func installMonitors() {
removeMonitors()
let mask: NSEvent.EventTypeMask = [.leftMouseDown, .rightMouseDown, .otherMouseDown]
localMouse = NSEvent.addLocalMonitorForEvents(matching: mask) { [weak self] event in
MainActor.assumeIsolated {
guard let self else { return }
if event.window === self.statusItem?.button?.window { return }
var window = event.window
while let current = window {
if current === self.panel { return }
window = current.parent
}
// Native menus/popovers own higher-level windows. Let them handle their dismissal.
if let window = event.window, window.level > self.panel.level { return }
self.dismissForOutsideInteraction()
}
return event
}
globalMouse = NSEvent.addGlobalMonitorForEvents(matching: mask) { [weak self] _ in
Task { @MainActor in self?.dismissForOutsideInteraction() }
}
}
private func removeMonitors() {
if let localMouse { NSEvent.removeMonitor(localMouse) }
if let globalMouse { NSEvent.removeMonitor(globalMouse) }
localMouse = nil; globalMouse = nil
}
}
final class MonitoringPanel: NSPanel {
var dismiss: (() -> Void)?
override var canBecomeKey: Bool { true }
override var canBecomeMain: Bool { false }
override func cancelOperation(_ sender: Any?) { dismiss?() }
override func close() { dismiss?() }
override func performClose(_ sender: Any?) { dismiss?() }
}
+29 -12
View File
@@ -6,7 +6,8 @@ struct MenuPanelView: View {
let preferences: AppearancePreferences
let keepAwake: KeepAwakeService
let settingsPresentation: SettingsPresentation
@Environment(\.openSettings) private var openSettings
var presentation = PanelPresentation()
var onOpenSettings: () -> Void = {}
@State private var panelSize = PanelLayout.contentSize(visible: NSScreen.main?.visibleFrame ?? CGRect(x: 0, y: 0, width: 1000, height: 760))
@State private var selectedInterface = ""
@State private var showAddresses = false
@@ -14,6 +15,8 @@ struct MenuPanelView: View {
private var snapshot: MetricsSnapshot { metrics.snapshot }
private var samples: [TrendSample] { metrics.history.samples }
private var chartInterval: TimeInterval { Double(metrics.effectiveMilliseconds) / 1000 }
private var chartBoundaries: Set<Date> { Set(samples.filter(\.breakBefore).map(\.date)) }
private var columns: Int { panelSize.width >= 1160 ? 3 : panelSize.width >= 900 ? 2 : 1 }
private var network: [NetworkInterfaceMetrics] {
(snapshot.network ?? []).filter { selectedInterface.isEmpty ? $0.isIncludedInTotal : $0.identity == selectedInterface }
@@ -34,7 +37,7 @@ struct MenuPanelView: View {
LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 8, alignment: .top), count: columns), spacing: 8) {
cpuCard.frame(minHeight: 240)
gpuCard.frame(minHeight: 240)
batteryCard.aspectRatio(1, contentMode: .fit)
batteryCard.aspectRatio(4.0 / 3.0, contentMode: .fit)
memoryCard.frame(minHeight: 240)
diskCard.frame(minHeight: 250)
networkCard.frame(minHeight: 250)
@@ -48,15 +51,16 @@ struct MenuPanelView: View {
}
.padding(10)
.frame(width: panelSize.width, height: panelSize.height)
.background(PanelWindowObserver { size, visible in
.background(PanelWindowObserver { size in
if panelSize != size { panelSize = size }
if metrics.isPanelVisible != visible { metrics.setPanelVisible(visible) }
}.frame(width: 0, height: 0))
.onAppear { metrics.setPanelVisible(true) }
.onDisappear { metrics.setPanelVisible(false) }
.onChange(of: snapshot.network?.map(\.identity)) { _, keys in
if !selectedInterface.isEmpty && !(keys ?? []).contains(selectedInterface) { selectedInterface = "" }
}
.background(.ultraThinMaterial, in: .rect(cornerRadius: 18))
.clipShape(.rect(cornerRadius: 18))
.modifier(AppearanceStyle(preferences: preferences))
}
@@ -65,7 +69,7 @@ struct MenuPanelView: View {
HStack(alignment: .top, spacing: 8) {
cpuCard.frame(width: PanelLayout.firstRowWideCardWidth(size: panelSize))
gpuCard.frame(width: PanelLayout.firstRowWideCardWidth(size: panelSize))
batteryCard.frame(width: PanelLayout.resourceRowHeight(size: panelSize))
batteryCard.frame(width: PanelLayout.batteryWidth(size: panelSize))
}.frame(height: PanelLayout.resourceRowHeight(size: panelSize))
HStack(alignment: .top, spacing: 8) {
memoryCard.frame(width: (panelSize.width - 36) / 3)
@@ -91,7 +95,7 @@ struct MenuPanelView: View {
}
private func chart(_ key: KeyPath<TrendSample, Double?>, color: Color, label: LocalizedStringKey = "panel.total") -> some View {
PanelTrendChart(dates: samples.map(\.date), first: samples.map { $0[keyPath: key] }, color: color, firstLabel: label)
PanelTrendChart(dates: samples.map(\.date), first: samples.map { $0[keyPath: key] }, color: color, firstLabel: label, expectedInterval: chartInterval, boundaryDates: chartBoundaries)
}
private func line(_ key: LocalizedStringKey, _ value: String) -> some View {
HStack(alignment: .firstTextBaseline) { Text(key).foregroundStyle(.secondary); Spacer(minLength: 6); AnimatedMetricText(value: value) }
@@ -101,8 +105,8 @@ struct MenuPanelView: View {
ResourceCard(title: "metric.cpu", symbol: "cpu", color: Color("MetricCPU"), value: MetricFormat.percent(snapshot.cpu?.usage)) {
PanelTrendChart(dates: samples.map(\.date), first: samples.map(\.cpu),
second: samples.map(\.cpuUser), third: samples.map(\.cpuSystem),
color: Color("MetricCPU"), secondColor: Color("MetricNetwork"), thirdColor: Color("MetricDisk"),
firstLabel: "panel.total", secondLabel: "cpu.user", thirdLabel: "cpu.system")
color: Color("MetricCPU"), secondColor: Color("SeriesUser"), thirdColor: Color("SeriesSystem"),
firstLabel: "panel.total", secondLabel: "cpu.user", thirdLabel: "cpu.system", expectedInterval: chartInterval, boundaryDates: chartBoundaries)
if let cpu = snapshot.cpu {
HStack { line("cpu.user", MetricFormat.percent(cpu.user)); line("cpu.system", MetricFormat.percent(cpu.system)) }
LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 6), count: 7), spacing: 5) {
@@ -139,7 +143,7 @@ struct MenuPanelView: View {
PanelTrendChart(dates: samples.map(\.date),
first: samples.map { $0.memory.map { $0 * Double(snapshot.memory?.total ?? 1) } },
color: Color("MetricMemory"), fixedScale: Double(snapshot.memory?.total ?? 1),
scaleLabel: MetricFormat.bytes(snapshot.memory?.total))
scaleLabel: MetricFormat.bytes(snapshot.memory?.total), expectedInterval: chartInterval, boundaryDates: chartBoundaries)
if let m = snapshot.memory {
GeometryReader { geometry in
@@ -178,7 +182,7 @@ struct MenuPanelView: View {
Text(verbatim: "\(item.name) · \(item.addresses.first(where: { !$0.contains(":") }) ?? item.addresses.first ?? "--")")
.font(.system(size: 10)).lineLimit(1).minimumScaleFactor(0.8).textSelection(.enabled)
} else { Text("panel.addressUnknown").foregroundStyle(.secondary) }
PanelTrendChart(dates: networkDates, first: networkDownloads, second: networkUploads, color: Color("MetricNetwork"), fixedScale: nil, firstLabel: "network.download", secondLabel: "network.upload").id(selectedInterface)
PanelTrendChart(dates: networkDates, first: networkDownloads, second: networkUploads, color: Color("MetricNetwork"), secondColor: Color("SeriesUpload"), fixedScale: nil, firstLabel: "network.download", secondLabel: "network.upload", expectedInterval: chartInterval, boundaryDates: chartBoundaries).id(selectedInterface)
if !network.isEmpty && total(\.download) == nil { Text("panel.rateBaseline").foregroundStyle(.secondary) }
HStack { line("network.received", network.isEmpty ? "--" : MetricFormat.bytes(network.reduce(0) { $0 + $1.received })); line("network.sent", network.isEmpty ? "--" : MetricFormat.bytes(network.reduce(0) { $0 + $1.sent })) }
switch snapshot.networkPath {
@@ -225,7 +229,7 @@ struct MenuPanelView: View {
ResourceCard(title: "metric.disk", symbol: "internaldrive", color: Color("MetricDisk"), value: snapshot.disk.map { String(format: "%.0f / %.0f GB", Double($0.total - min($0.total, $0.available)) / 1_000_000_000, Double($0.total) / 1_000_000_000) } ?? "--") {
PanelTrendChart(dates: samples.map(\.date), first: samples.map(\.read), second: samples.map(\.write), color: Color("MetricDisk"), secondColor: Color("MetricMemory"), fixedScale: nil, firstLabel: "disk.read", secondLabel: "disk.write")
PanelTrendChart(dates: samples.map(\.date), first: samples.map(\.read), second: samples.map(\.write), color: Color("MetricDisk"), secondColor: Color("MetricMemory"), fixedScale: nil, firstLabel: "disk.read", secondLabel: "disk.write", expectedInterval: chartInterval, boundaryDates: chartBoundaries)
Text("disk.physicalIO").foregroundStyle(.secondary)
HStack { line("disk.read", MetricFormat.rate(snapshot.diskIO?.read)); line("disk.write", MetricFormat.rate(snapshot.diskIO?.written)) }
HStack { line("disk.remainingLife", MetricFormat.percent(snapshot.diskHealth?.remainingLife)); line("disk.powerOnHours", snapshot.diskHealth?.powerOnHours.map { "\($0) h" } ?? "--") }
@@ -273,6 +277,19 @@ struct MenuPanelView: View {
private var controls: some View {
HStack(spacing: 8) {
HStack(spacing: 2) {
HStack(spacing: 4) {
Image(systemName: "timer").help(Text("sampling.panel"))
IntervalControl(milliseconds: Binding(get: { metrics.sampling.panelMilliseconds }, set: { metrics.sampling.panelMilliseconds = $0 }))
}.padding(.horizontal, 6).accessibilityLabel(Text("sampling.panel"))
Divider().frame(height: 18).padding(.horizontal, 3)
Button { presentation.isPinned.toggle() } label: {
Image(systemName: presentation.isPinned ? "pin.fill" : "pin")
.frame(width: 20, height: 20)
.foregroundStyle(presentation.isPinned ? preferences.tintColor : Color.primary)
}
.help(Text(presentation.isPinned ? "panel.unpin" : "panel.pin"))
.accessibilityLabel(Text(presentation.isPinned ? "panel.unpin" : "panel.pin"))
.accessibilityValue(Text(presentation.isPinned ? "panel.pinned" : "panel.unpinned"))
Button { keepAwake.toggle() } label: {
Image(systemName: keepAwake.isEnabled ? "cup.and.saucer.fill" : "cup.and.saucer")
.frame(width: 20, height: 20)
@@ -289,7 +306,7 @@ struct MenuPanelView: View {
Button {
NSApp.setActivationPolicy(.regular)
settingsPresentation.request()
openSettings()
onOpenSettings()
} label: {
Image(systemName: "gearshape").frame(width: 20, height: 20)
}
+8 -1
View File
@@ -3,12 +3,19 @@ import CoreGraphics
nonisolated enum PanelLayout {
static func resourceRowHeight(size: CGSize) -> CGFloat { min(230, max(220, size.height - 590)) }
static func firstRowWideCardWidth(size: CGSize) -> CGFloat { (size.width - 36 - resourceRowHeight(size: size)) / 2 }
static func batteryWidth(size: CGSize) -> CGFloat { resourceRowHeight(size: size) * 4 / 3 }
static func firstRowWideCardWidth(size: CGSize) -> CGFloat { (size.width - 36 - batteryWidth(size: size)) / 2 }
static func contentSize(visible: CGRect, chrome: CGSize = .zero) -> CGSize {
CGSize(width: max(1, min(1240, visible.width - 32 - max(0, chrome.width))),
height: max(1, min(820, visible.height - 32 - max(0, chrome.height))))
}
static func centeredFrame(_ frame: CGRect, visible: CGRect) -> CGRect {
var result = constrainedFrame(frame, visible: visible)
result.origin.x = visible.midX - result.width / 2
return result
}
static func constrainedFrame(_ frame: CGRect, visible: CGRect) -> CGRect {
let safe = visible.insetBy(dx: 16, dy: 16)
let width = min(frame.width, safe.width), height = min(frame.height, safe.height)
@@ -1,25 +1,23 @@
import SwiftUI
import AppKit
/// Window geometry/lifecycle stays in the feature layer; Core receives only visibility.
/// Observes geometry only; MenuPanelController owns visibility and dismissal.
struct PanelWindowObserver: NSViewRepresentable {
var update: (CGSize, Bool) -> Void
var update: (CGSize) -> Void
func makeNSView(context: Context) -> ObserverView { ObserverView(update: update) }
func updateNSView(_ view: ObserverView, context: Context) { view.update = update }
final class ObserverView: NSView {
var update: (CGSize, Bool) -> Void
var update: (CGSize) -> Void
private var observers: [NSObjectProtocol] = []
init(update: @escaping (CGSize, Bool) -> Void) { self.update = update; super.init(frame: .zero) }
init(update: @escaping (CGSize) -> Void) { self.update = update; super.init(frame: .zero) }
required init?(coder: NSCoder) { fatalError() }
override func viewDidMoveToWindow() {
super.viewDidMoveToWindow()
observers.forEach(NotificationCenter.default.removeObserver)
observers = []
guard let window else { return }
for name in [NSWindow.didChangeScreenNotification, NSWindow.didResizeNotification, NSWindow.didMoveNotification, NSWindow.didBecomeKeyNotification,
NSWindow.didResignKeyNotification, NSWindow.willCloseNotification,
NSWindow.didChangeOcclusionStateNotification] {
for name in [NSWindow.didChangeScreenNotification, NSWindow.didResizeNotification, NSWindow.didMoveNotification] {
observers.append(NotificationCenter.default.addObserver(forName: name, object: window, queue: .main) { [weak self] _ in
MainActor.assumeIsolated { self?.report() }
})
@@ -35,15 +33,13 @@ struct PanelWindowObserver: NSViewRepresentable {
let chrome = CGSize(width: max(0, window.frame.width - window.contentLayoutRect.width),
height: max(0, window.frame.height - window.contentLayoutRect.height))
let size = PanelLayout.contentSize(visible: frame, chrome: chrome)
let visible = window.isVisible
DispatchQueue.main.async { [weak self, weak window] in
guard let self, let window else { return }
self.update(size, visible)
// SwiftUI can resize a MenuBarExtra after the system chose its anchor origin.
// Clamp after layout as well as on moves; keep the native status-item scene.
self.update(size)
// Keep the complete panel inside its screen and horizontally centered after layout.
DispatchQueue.main.async { [weak window] in
guard let window, window.isVisible else { return }
let adjusted = PanelLayout.constrainedFrame(window.frame, visible: frame)
let adjusted = PanelLayout.centeredFrame(window.frame, visible: frame)
if abs(adjusted.minX - window.frame.minX) > 0.5 || abs(adjusted.minY - window.frame.minY) > 0.5 {
window.setFrameOrigin(adjusted.origin)
}
@@ -5,6 +5,7 @@ import AppKit
struct AppearanceSettingsView: View {
@Bindable var preferences: AppearancePreferences
@Bindable var language: LanguagePreferences
@Bindable var sampling: SamplingPreferences
let presentation: SettingsPresentation
@Environment(\.locale) private var locale
@State private var colorPicker = CustomColorPicker()
@@ -24,6 +25,7 @@ struct AppearanceSettingsView: View {
switch selectedPage {
case .appearance: appearancePage
case .language: languagePage
case .monitoring: monitoringPage
case .about: aboutPage
}
}
@@ -82,6 +84,17 @@ struct AppearanceSettingsView: View {
.padding(.top, 6)
}
private var monitoringPage: some View {
Form {
Section {
LabeledContent("sampling.background") {
IntervalControl(milliseconds: $sampling.backgroundMilliseconds)
}
Text("sampling.backgroundHelp").font(.callout).foregroundStyle(.secondary)
}
}.formStyle(.grouped).padding(.horizontal, 12).padding(.top, 6)
}
private var languagePage: some View {
Form {
Section {
@@ -207,12 +220,13 @@ private extension AppAppearance {
}
private enum SettingsPage: String, CaseIterable, Identifiable {
case appearance, language, about
case appearance, language, monitoring, about
var id: String { rawValue }
var title: LocalizedStringKey {
switch self {
case .appearance: "settings.appearance"
case .language: "settings.language"
case .monitoring: "settings.monitoring"
case .about: "settings.about"
}
}
@@ -220,6 +234,7 @@ private enum SettingsPage: String, CaseIterable, Identifiable {
switch self {
case .appearance: "paintpalette"
case .language: "globe"
case .monitoring: "timer"
case .about: "info.circle"
}
}
+501 -3
View File
@@ -262,6 +262,213 @@
}
}
},
"action.file" : {
"extractionState": "manual",
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
"value": "File"
}
},
"zh-Hans": {
"stringUnit": {
"state": "translated",
"value": "文件"
}
},
"zh-Hant": {
"stringUnit": {
"state": "translated",
"value": "檔案"
}
}
}
},
"action.closeWindow" : {
"extractionState": "manual",
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
"value": "Close Window"
}
},
"zh-Hans": {
"stringUnit": {
"state": "translated",
"value": "关闭窗口"
}
},
"zh-Hant": {
"stringUnit": {
"state": "translated",
"value": "關閉視窗"
}
}
}
},
"action.edit" : {
"extractionState": "manual",
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
"value": "Edit"
}
},
"zh-Hans": {
"stringUnit": {
"state": "translated",
"value": "编辑"
}
},
"zh-Hant": {
"stringUnit": {
"state": "translated",
"value": "編輯"
}
}
}
},
"action.undo" : {
"extractionState": "manual",
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
"value": "Undo"
}
},
"zh-Hans": {
"stringUnit": {
"state": "translated",
"value": "撤销"
}
},
"zh-Hant": {
"stringUnit": {
"state": "translated",
"value": "復原"
}
}
}
},
"action.redo" : {
"extractionState": "manual",
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
"value": "Redo"
}
},
"zh-Hans": {
"stringUnit": {
"state": "translated",
"value": "重做"
}
},
"zh-Hant": {
"stringUnit": {
"state": "translated",
"value": "重做"
}
}
}
},
"action.cut" : {
"extractionState": "manual",
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
"value": "Cut"
}
},
"zh-Hans": {
"stringUnit": {
"state": "translated",
"value": "剪切"
}
},
"zh-Hant": {
"stringUnit": {
"state": "translated",
"value": "剪下"
}
}
}
},
"action.copy" : {
"extractionState": "manual",
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
"value": "Copy"
}
},
"zh-Hans": {
"stringUnit": {
"state": "translated",
"value": "复制"
}
},
"zh-Hant": {
"stringUnit": {
"state": "translated",
"value": "複製"
}
}
}
},
"action.paste" : {
"extractionState": "manual",
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
"value": "Paste"
}
},
"zh-Hans": {
"stringUnit": {
"state": "translated",
"value": "粘贴"
}
},
"zh-Hant": {
"stringUnit": {
"state": "translated",
"value": "貼上"
}
}
}
},
"action.selectAll" : {
"extractionState": "manual",
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
"value": "Select All"
}
},
"zh-Hans": {
"stringUnit": {
"state": "translated",
"value": "全选"
}
},
"zh-Hant": {
"stringUnit": {
"state": "translated",
"value": "全選"
}
}
}
},
"action.pause" : {
"extractionState" : "manual",
"localizations" : {
@@ -2400,9 +2607,24 @@
},
"panel.total" : {
"localizations" : {
"en" : { "stringUnit" : { "state" : "translated", "value" : "Total" } },
"zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "总占用" } },
"zh-Hant" : { "stringUnit" : { "state" : "translated", "value" : "總佔用" } }
"en" : {
"stringUnit" : {
"state" : "translated",
"value" : "Total"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
"value" : "总占用"
}
},
"zh-Hant" : {
"stringUnit" : {
"state" : "translated",
"value" : "總佔用"
}
}
}
},
"panel.totalNetwork" : {
@@ -2546,6 +2768,282 @@
}
}
},
"sampling.panel" : {
"extractionState": "manual",
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
"value": "Panel refresh interval"
}
},
"zh-Hans": {
"stringUnit": {
"state": "translated",
"value": "面板刷新间隔"
}
},
"zh-Hant": {
"stringUnit": {
"state": "translated",
"value": "面板重新整理間隔"
}
}
}
},
"sampling.background" : {
"extractionState": "manual",
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
"value": "Background refresh interval"
}
},
"zh-Hans": {
"stringUnit": {
"state": "translated",
"value": "后台刷新间隔"
}
},
"zh-Hant": {
"stringUnit": {
"state": "translated",
"value": "背景重新整理間隔"
}
}
}
},
"sampling.backgroundHelp" : {
"extractionState": "manual",
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
"value": "Applies while the panel is closed. Default: 5 seconds. Panel interval is adjusted in its toolbar."
}
},
"zh-Hans": {
"stringUnit": {
"state": "translated",
"value": "仅在面板关闭时生效,默认 5 秒。面板打开时的间隔在顶部工具栏单独调整。"
}
},
"zh-Hant": {
"stringUnit": {
"state": "translated",
"value": "僅在面板關閉時生效,預設 5 秒。面板開啟時的間隔在頂部工具列獨立調整。"
}
}
}
},
"sampling.seconds" : {
"extractionState": "manual",
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
"value": "Seconds"
}
},
"zh-Hans": {
"stringUnit": {
"state": "translated",
"value": "秒数"
}
},
"zh-Hant": {
"stringUnit": {
"state": "translated",
"value": "秒數"
}
}
}
},
"sampling.unit" : {
"extractionState": "manual",
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
"value": "s"
}
},
"zh-Hans": {
"stringUnit": {
"state": "translated",
"value": "秒"
}
},
"zh-Hant": {
"stringUnit": {
"state": "translated",
"value": "秒"
}
}
}
},
"sampling.interval" : {
"extractionState": "manual",
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
"value": "Refresh interval"
}
},
"zh-Hans": {
"stringUnit": {
"state": "translated",
"value": "刷新间隔"
}
},
"zh-Hant": {
"stringUnit": {
"state": "translated",
"value": "重新整理間隔"
}
}
}
},
"sampling.bounds" : {
"extractionState": "manual",
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
"value": "0.5–1800 seconds, in 0.1-second steps"
}
},
"zh-Hans": {
"stringUnit": {
"state": "translated",
"value": "0.5–1800 秒,步进 0.1 秒"
}
},
"zh-Hant": {
"stringUnit": {
"state": "translated",
"value": "0.5–1800 秒,每次 0.1 秒"
}
}
}
},
"settings.monitoring" : {
"extractionState": "manual",
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
"value": "Monitoring"
}
},
"zh-Hans": {
"stringUnit": {
"state": "translated",
"value": "监控"
}
},
"zh-Hant": {
"stringUnit": {
"state": "translated",
"value": "監控"
}
}
}
},
"panel.pin" : {
"extractionState": "manual",
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
"value": "Pin panel on top"
}
},
"zh-Hans": {
"stringUnit": {
"state": "translated",
"value": "固定面板并置顶"
}
},
"zh-Hant": {
"stringUnit": {
"state": "translated",
"value": "固定面板並置頂"
}
}
}
},
"panel.unpin" : {
"extractionState": "manual",
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
"value": "Unpin panel"
}
},
"zh-Hans": {
"stringUnit": {
"state": "translated",
"value": "取消固定面板"
}
},
"zh-Hant": {
"stringUnit": {
"state": "translated",
"value": "取消固定面板"
}
}
}
},
"panel.pinned" : {
"extractionState": "manual",
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
"value": "Pinned"
}
},
"zh-Hans": {
"stringUnit": {
"state": "translated",
"value": "已固定"
}
},
"zh-Hant": {
"stringUnit": {
"state": "translated",
"value": "已固定"
}
}
}
},
"panel.unpinned" : {
"extractionState": "manual",
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
"value": "Not pinned"
}
},
"zh-Hans": {
"stringUnit": {
"state": "translated",
"value": "未固定"
}
},
"zh-Hant": {
"stringUnit": {
"state": "translated",
"value": "未固定"
}
}
}
},
"settings.about" : {
"localizations" : {
"en" : {
+4 -4
View File
@@ -6,20 +6,20 @@ nonisolated enum PanelCurveGeometry {
let value: Double
}
static func isAppend(from old: [Date], to new: [Date]) -> Bool {
static func isAppend(from old: [Date], to new: [Date], maximumGap: TimeInterval = 5) -> Bool {
guard old.count > 1, let previous = old.last, let next = new.last,
next > previous, next.timeIntervalSince(previous) <= 5 else { return false }
next > previous, next.timeIntervalSince(previous) <= maximumGap else { return false }
if new.count == old.count + 1 { return Array(new.dropLast()) == old }
return new.count == old.count && Array(old.dropFirst()) == Array(new.dropLast())
}
static func runs(dates: [Date], values: [Double?]) -> [[Sample]] {
static func runs(dates: [Date], values: [Double?], maximumGap: TimeInterval = 5, boundaryDates: Set<Date> = []) -> [[Sample]] {
var result: [[Sample]] = []
var run: [Sample] = []
func flush() { if !run.isEmpty { result.append(run); run.removeAll(keepingCapacity: true) } }
for index in dates.indices {
guard index < values.count, let value = values[index], value.isFinite else { flush(); continue }
if index > 0 && (dates[index].timeIntervalSince(dates[index - 1]) > 5 || dates[index] <= dates[index - 1]) { flush() }
if index > 0 && (boundaryDates.contains(dates[index]) || dates[index].timeIntervalSince(dates[index - 1]) > maximumGap || dates[index] <= dates[index - 1]) { flush() }
run.append(Sample(date: dates[index], value: value))
}
flush()
+48 -14
View File
@@ -14,10 +14,13 @@ struct PanelTrendChart: View {
var firstLabel: LocalizedStringKey = "panel.total"
var secondLabel: LocalizedStringKey = "network.upload"
var thirdLabel: LocalizedStringKey = "cpu.system"
var expectedInterval: TimeInterval = 2
var boundaryDates: Set<Date> = []
@Environment(\.accessibilityReduceMotion) private var reduceMotion
@State private var retainedScale: Double = 1
@State private var smallSamples = 0
@State private var hoveredDate: Date?
@State private var hoverPoint: CGPoint?
@State private var previousBegin: Date?
@State private var previousEnd: Date?
@State private var progress: CGFloat = 1
@@ -35,18 +38,35 @@ struct PanelTrendChart: View {
if fixedScale == nil { return MetricFormat.rate(value) }
return MetricFormat.bytes(UInt64(max(0, value)))
}
private func value(_ values: [Double?]) -> String {
guard let index, index < values.count else { return "--" }
return formatted(values[index])
}
private func legend(_ label: LocalizedStringKey, values: [Double?], tint: Color) -> some View {
HStack(spacing: 3) {
RoundedRectangle(cornerRadius: 1).fill(tint).frame(width: 7, height: 7)
Text(label)
Text(verbatim: value(values)).monospacedDigit()
Text(verbatim: formatted(values.last ?? nil)).monospacedDigit()
}.font(.system(size: 9)).lineLimit(1).minimumScaleFactor(0.8)
}
private func tooltipRow(_ label: LocalizedStringKey, values: [Double?], tint: Color, index: Int) -> some View {
HStack(spacing: 6) {
RoundedRectangle(cornerRadius: 2).fill(tint).frame(width: 8, height: 8)
Text(label)
Spacer(minLength: 4)
Text(verbatim: formatted(index < values.count ? values[index] : nil)).monospacedDigit()
}
}
private func tooltip(index: Int) -> some View {
VStack(alignment: .leading, spacing: 5) {
Text(dates[index], format: .dateTime.hour().minute().second()).foregroundStyle(.secondary)
tooltipRow(firstLabel, values: first, tint: color, index: index)
if !second.isEmpty { tooltipRow(secondLabel, values: second, tint: secondColor, index: index) }
if !third.isEmpty { tooltipRow(thirdLabel, values: third, tint: thirdColor, index: index) }
}
.font(.system(size: 10)).padding(8)
.background(Color("PanelTooltip"), in: .rect(cornerRadius: 7))
.overlay(RoundedRectangle(cornerRadius: 7).strokeBorder(.primary.opacity(0.2)))
.shadow(color: .black.opacity(0.2), radius: 5, y: 2)
}
var body: some View {
VStack(spacing: 3) {
HStack(spacing: 10) {
@@ -67,7 +87,7 @@ struct PanelTrendChart: View {
GeometryReader { proxy in
ZStack(alignment: .topLeading) {
PanelCurveCanvas(dates: dates, series: [first, second, third], colors: [color, secondColor, thirdColor],
scale: scale, previousBegin: previousBegin, previousEnd: previousEnd, progress: progress)
scale: scale, maximumGap: max(5, expectedInterval * 2), boundaryDates: boundaryDates, previousBegin: previousBegin, previousEnd: previousEnd, progress: progress)
if hoveredDate != nil, let index, let begin = dates.first, let end = dates.last, end > begin {
let x = proxy.size.width * dates[index].timeIntervalSince(begin) / end.timeIntervalSince(begin)
Path { path in
@@ -87,22 +107,33 @@ struct PanelTrendChart: View {
switch phase {
case .active(let point):
if let begin = dates.first, let end = dates.last {
hoverPoint = point
hoveredDate = begin.addingTimeInterval(end.timeIntervalSince(begin) * min(1, max(0, point.x / max(1, proxy.size.width))))
}
case .ended: hoveredDate = nil
case .ended: hoveredDate = nil; hoverPoint = nil
}
}
}.frame(height: 58).clipped()
.clipped()
.overlay(alignment: .topLeading) {
if let hoverPoint, let index {
tooltip(index: index)
.frame(width: min(180, proxy.size.width))
.offset(x: min(max(0, hoverPoint.x + 12), max(0, proxy.size.width - 180)),
y: min(hoverPoint.y + 10, proxy.size.height - 12))
.allowsHitTesting(false)
.accessibilityHidden(true)
}
}
}.frame(height: 58).zIndex(10)
}
HStack {
if let date = dates.first { Text(date, style: .time) }
Spacer(minLength: 0)
if hoveredDate != nil, let index { Text(dates[index], format: .dateTime.hour().minute().second()).foregroundStyle(.primary) }
Spacer(minLength: 0)
if let date = dates.last { Text(date, style: .time) }
}.font(.system(size: 9)).foregroundStyle(.secondary).frame(height: 12)
}
.frame(maxWidth: .infinity)
.zIndex(hoveredDate == nil ? 0 : 20)
.onAppear { retainedScale = maximum }
.onChange(of: dates) { old, new in
let target = maximum
@@ -111,7 +142,7 @@ struct PanelTrendChart: View {
smallSamples += 1
if smallSamples >= 10 { retainedScale = target; smallSamples = 0 }
} else { smallSamples = 0 }
let append = PanelCurveGeometry.isAppend(from: old, to: new)
let append = PanelCurveGeometry.isAppend(from: old, to: new, maximumGap: max(5, expectedInterval * 2)) && !(new.last.map { boundaryDates.contains($0) } ?? false)
var transaction = Transaction(); transaction.disablesAnimations = true
withTransaction(transaction) {
previousBegin = append && !reduceMotion ? old.first : nil
@@ -134,6 +165,8 @@ private struct PanelCurveCanvas: View, Animatable {
let series: [[Double?]]
let colors: [Color]
let scale: Double
let maximumGap: TimeInterval
let boundaryDates: Set<Date>
let previousBegin: Date?
let previousEnd: Date?
var progress: CGFloat
@@ -157,8 +190,9 @@ private struct PanelCurveCanvas: View, Animatable {
guard let first = dates.first, let last = dates.last else { return }
let begin = (previousBegin ?? first).timeIntervalSinceReferenceDate * (1 - progress) + first.timeIntervalSinceReferenceDate * progress
let end = (previousEnd ?? last).timeIntervalSinceReferenceDate * (1 - progress) + last.timeIntervalSinceReferenceDate * progress
for (values, tint) in zip(series, colors) {
for run in PanelCurveGeometry.runs(dates: dates, values: values) {
for (seriesIndex, entry) in zip(series, colors).enumerated() {
let (values, tint) = entry
for run in PanelCurveGeometry.runs(dates: dates, values: values, maximumGap: maximumGap, boundaryDates: boundaryDates) {
let points = run.map { item in
CGPoint(x: end > begin ? size.width * (item.date.timeIntervalSinceReferenceDate - begin) / (end - begin) : size.width,
y: size.height * (1 - min(1, max(0, item.value / scale))))
@@ -176,7 +210,7 @@ private struct PanelCurveCanvas: View, Animatable {
var area = line
area.addLine(to: CGPoint(x: finish.x, y: size.height)); area.addLine(to: CGPoint(x: start.x, y: size.height)); area.closeSubpath()
context.fill(area, with: .linearGradient(Gradient(colors: [tint.opacity(0.20), tint.opacity(0.01)]), startPoint: .zero, endPoint: CGPoint(x: 0, y: size.height)))
context.stroke(line, with: .color(tint), style: StrokeStyle(lineWidth: 1.5, lineCap: .round, lineJoin: .round))
context.stroke(line, with: .color(tint), style: StrokeStyle(lineWidth: 1.5, lineCap: .round, lineJoin: .round, dash: seriesIndex == 1 ? [4, 2] : seriesIndex == 2 ? [1, 2] : []))
}
}
}
+43
View File
@@ -0,0 +1,43 @@
import SwiftUI
/// Generic millisecond interval editor; callers own persistence and scheduling.
struct IntervalControl: View {
@Binding var milliseconds: Int
var range: ClosedRange<Int> = 500...1_800_000
var step = 100
@State private var text = ""
@FocusState private var focused: Bool
var body: some View {
HStack(spacing: 3) {
TextField("sampling.seconds", text: $text)
.textFieldStyle(.roundedBorder).multilineTextAlignment(.trailing)
.frame(width: 64).focused($focused)
.onChange(of: text) { _, value in
if let seconds = Double(value.replacingOccurrences(of: ",", with: ".")), seconds.isFinite,
seconds >= Double(range.lowerBound) / 1000, seconds <= Double(range.upperBound) / 1000 {
milliseconds = quantized(seconds)
}
}
.onSubmit { commit() }
Text("sampling.unit").foregroundStyle(.secondary).fixedSize()
Stepper("sampling.interval", value: $milliseconds, in: range, step: step).labelsHidden().fixedSize()
}
.font(.system(size: 11)).monospacedDigit().controlSize(.small)
.fixedSize(horizontal: true, vertical: false)
.onAppear { synchronize() }
.onChange(of: milliseconds) { _, _ in if !focused { synchronize() } }
.onChange(of: focused) { _, value in if !value { commit() } }
.help(Text("sampling.bounds"))
}
private func quantized(_ seconds: Double) -> Int {
let clamped = min(Double(range.upperBound), max(Double(range.lowerBound), seconds * 1000))
return min(range.upperBound, max(range.lowerBound, Int((clamped / Double(step)).rounded()) * step))
}
private func synchronize() { text = String(format: "%.1f", Double(milliseconds) / 1000) }
private func commit() {
if let seconds = Double(text.replacingOccurrences(of: ",", with: ".")), seconds.isFinite { milliseconds = quantized(seconds) }
synchronize()
}
}
+3 -3
View File
@@ -15,11 +15,11 @@ struct ResourceCard<Content: View>: View {
Image(systemName: symbol).foregroundStyle(color)
}.font(.system(size: 13, weight: .semibold)).fixedSize()
Spacer(minLength: 0)
VStack(alignment: .trailing, spacing: 0) {
HStack(alignment: .firstTextBaseline, spacing: 6) {
AnimatedMetricText(value: value)
.font(.system(size: 20, weight: .semibold, design: .rounded))
.font(.system(size: 13, weight: .semibold))
if let secondaryValue {
AnimatedMetricText(value: secondaryValue).font(.system(size: 11, weight: .semibold))
AnimatedMetricText(value: secondaryValue).font(.system(size: 13, weight: .semibold))
}
}.foregroundStyle(color).lineLimit(1).minimumScaleFactor(0.65)
}