feat(menubar): 支持固定居中面板与独立刷新频率及图表浮层
This commit is contained in:
@@ -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) }
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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))))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user