refactor(project): 清理闲置展示链路与重复采样状态
This commit is contained in:
+9
-15
@@ -13,7 +13,7 @@ import AppKit
|
||||
}
|
||||
|
||||
@MainActor private final class ApplicationLifecycle: NSObject, NSApplicationDelegate {
|
||||
private let metrics = MetricsStore(energyEnabled: PanelResourceAudit.omitted != "energy")
|
||||
private let metrics = MetricsStore()
|
||||
private let awake = KeepAwakeService()
|
||||
private let presentation = SettingsPresentation()
|
||||
private let appearance = AppearancePreferences()
|
||||
@@ -53,20 +53,14 @@ import AppKit
|
||||
menuTitle: { [language] key in
|
||||
AppLocalization.string("status." + key, locale: language.locale, table: "StatusItem")
|
||||
}, openSettings: { [weak self] in self?.settingsCommand() }) { [self] panel in
|
||||
if PanelResourceAudit.omitted == "text" {
|
||||
TextMonitoringAuditView(metrics: self.metrics, appearance: self.appearance)
|
||||
} else if PanelResourceAudit.omitted == "all" {
|
||||
Text(verbatim: "Kymo").frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
} else {
|
||||
AppLanguageScope(preferences: language) {
|
||||
MenuPanelView(metrics: self.metrics, preferences: self.appearance, keepAwake: self.awake, settingsPresentation: self.presentation,
|
||||
presentation: panel, onOpenSettings: { [weak self] in
|
||||
self?.menuBar?.hide()
|
||||
settings.environment.openSettings()
|
||||
}, onPreferredHeight: { [weak self] height in
|
||||
self?.menuBar?.setPreferredContentHeight(height)
|
||||
})
|
||||
}
|
||||
AppLanguageScope(preferences: language) {
|
||||
MenuPanelView(metrics: self.metrics, preferences: self.appearance, keepAwake: self.awake, settingsPresentation: self.presentation,
|
||||
presentation: panel, onOpenSettings: { [weak self] in
|
||||
self?.menuBar?.hide()
|
||||
settings.environment.openSettings()
|
||||
}, onPreferredHeight: { [weak self] height in
|
||||
self?.menuBar?.setPreferredContentHeight(height)
|
||||
})
|
||||
}
|
||||
}
|
||||
if let menuBar { PanelResourceAudit.run(controller: menuBar, metrics: metrics) }
|
||||
|
||||
@@ -30,6 +30,4 @@ nonisolated enum MetricFormat {
|
||||
guard let value, value.isFinite, value >= 0 else { return "--" }
|
||||
return String(format: "%.1f W", value)
|
||||
}
|
||||
|
||||
static func decimal(_ value: Double) -> String { String(format: "%.1f", value) }
|
||||
}
|
||||
|
||||
@@ -6,7 +6,6 @@ nonisolated struct TrendSample: Sendable {
|
||||
let gpu: Double?
|
||||
let memory: Double?
|
||||
var download: Double?
|
||||
var disk: Double?
|
||||
var battery: Double?
|
||||
var batteryPower: Double?
|
||||
var upload: Double?
|
||||
@@ -45,7 +44,7 @@ nonisolated struct MetricHistory: Sendable {
|
||||
mutating func append(_ snapshot: MetricsSnapshot, breakBefore: Bool = false, expectedInterval: TimeInterval = 2) {
|
||||
samples.append(TrendSample(date: snapshot.date, cpu: snapshot.cpu?.usage,
|
||||
gpu: snapshot.gpuUsage, memory: snapshot.memory?.usage,
|
||||
download: snapshot.downloadRate, disk: snapshot.disk?.usage,
|
||||
download: snapshot.downloadRate,
|
||||
battery: snapshot.battery?.charge, batteryPower: snapshot.battery?.power,
|
||||
upload: snapshot.uploadRate,
|
||||
read: snapshot.diskIO?.read, write: snapshot.diskIO?.written,
|
||||
@@ -71,30 +70,3 @@ nonisolated struct InterfaceTrendSample: Sendable {
|
||||
/// Scheduled cadence from this point to the next interface sample.
|
||||
var expectedInterval: TimeInterval = 2
|
||||
}
|
||||
|
||||
/// Time-weighted observed utilization; never bridge failures or sleep boundaries.
|
||||
nonisolated struct GPUUtilizationSummary {
|
||||
let average: Double?
|
||||
let peak: Double?
|
||||
let coverage: TimeInterval
|
||||
|
||||
init(samples: [TrendSample], window: TimeInterval = 60) {
|
||||
guard let end = samples.last?.date else { average = nil; peak = nil; coverage = 0; return }
|
||||
let start = end.addingTimeInterval(-window)
|
||||
peak = samples.filter { $0.date >= start }.compactMap(\.gpu).max()
|
||||
var area = 0.0
|
||||
var duration = 0.0
|
||||
for (a, b) in zip(samples, samples.dropFirst()) {
|
||||
let dt = b.date.timeIntervalSince(a.date)
|
||||
guard !b.breakBefore, dt > 0, dt <= a.expectedInterval * 2.5,
|
||||
let av = a.gpu, let bv = b.gpu else { continue }
|
||||
let overlap = b.date.timeIntervalSince(max(a.date, start))
|
||||
guard overlap > 0 else { continue }
|
||||
let left = av + (bv - av) * (1 - overlap / dt)
|
||||
area += (left + bv) * 0.5 * overlap
|
||||
duration += overlap
|
||||
}
|
||||
coverage = duration
|
||||
average = duration > 0 ? area / duration : nil
|
||||
}
|
||||
}
|
||||
|
||||
@@ -35,15 +35,12 @@ nonisolated struct MetricsSnapshot: Sendable {
|
||||
var diskIO: DiskIOMetrics?
|
||||
var volumes: [VolumeMetrics]?
|
||||
var battery: BatteryMetrics?
|
||||
var load: [Double] = []
|
||||
var uptime: TimeInterval = 0
|
||||
var gpu: GPUMetrics?
|
||||
var processes: ProcessSnapshot?
|
||||
var diskHealthDate: Date?
|
||||
var batteryHealthDate: Date?
|
||||
var batteryState: BatteryAvailability = .unknown
|
||||
// GPU total is backed by validated IOAccelerator device statistics.
|
||||
var gpuUsage: Double? = nil
|
||||
var gpuUsage: Double? { gpu?.usage }
|
||||
}
|
||||
|
||||
nonisolated extension MetricsSnapshot {
|
||||
|
||||
@@ -23,19 +23,17 @@ nonisolated struct ProcessEnergyReply: Codable, Sendable {
|
||||
let readings: [ProcessEnergyReading]
|
||||
}
|
||||
nonisolated struct ProcessEnergyUsage: Identifiable, Sendable {
|
||||
let process: ProcessMetrics
|
||||
let id: ProcessIdentity
|
||||
let watts: Double
|
||||
let seconds: TimeInterval
|
||||
var id: ProcessIdentity { process.id }
|
||||
var formattedPower: String { watts >= 1 ? String(format: "%.2f W", watts) : String(format: "%.1f mW", watts * 1000) }
|
||||
}
|
||||
nonisolated struct ProcessEnergySnapshot: Sendable {
|
||||
enum State: Sendable { case waiting, available, partial, unavailable, unsupported }
|
||||
let date: Date
|
||||
let candidates: Int
|
||||
let readable: Int
|
||||
let measured: Int
|
||||
let rows: [ProcessEnergyUsage] // All valid measurements; no CPU prefilter.
|
||||
var measured: Int { rows.count }
|
||||
let state: State
|
||||
}
|
||||
|
||||
|
||||
@@ -6,9 +6,6 @@ nonisolated struct GPUMetrics: Sendable {
|
||||
let coreCount: Int?
|
||||
var renderer: Double? = nil
|
||||
var tiler: Double? = nil
|
||||
// Driver accounting, not dedicated VRAM or a capacity denominator.
|
||||
var inUseMemory: UInt64? = nil
|
||||
var allocatedMemory: UInt64? = nil
|
||||
// Independent per-core counters have not been obtained. Never split total usage.
|
||||
}
|
||||
|
||||
@@ -27,21 +24,12 @@ nonisolated enum GPUMonitor {
|
||||
let cores = (IORegistryEntryCreateCFProperty(service, "gpu-core-count" as CFString, kCFAllocatorDefault, 0)?.takeRetainedValue() as? NSNumber)?.intValue
|
||||
devices.append(GPUMetrics(usage: normalized(raw), coreCount: cores.flatMap { $0 > 0 ? $0 : nil },
|
||||
renderer: normalized((stats?["Renderer Utilization %"] as? NSNumber)?.doubleValue),
|
||||
tiler: normalized((stats?["Tiler Utilization %"] as? NSNumber)?.doubleValue),
|
||||
inUseMemory: memoryBytes(stats?["In use system memory"]),
|
||||
allocatedMemory: memoryBytes(stats?["Alloc system memory"])))
|
||||
tiler: normalized((stats?["Tiler Utilization %"] as? NSNumber)?.doubleValue)))
|
||||
}
|
||||
// Do not average incompatible utilization counters on multi-GPU machines.
|
||||
return devices.count == 1 ? devices[0] : nil
|
||||
}
|
||||
|
||||
static func memoryBytes(_ raw: Any?) -> UInt64? {
|
||||
guard let number = raw as? NSNumber else { return nil }
|
||||
let value = number.doubleValue
|
||||
guard value.isFinite, value >= 0, value < Double(UInt64.max) else { return nil }
|
||||
return UInt64(value)
|
||||
}
|
||||
|
||||
static func normalized(_ value: Double?) -> Double? {
|
||||
value.flatMap { $0.isFinite && (0...100).contains($0) ? $0 / 100 : nil }
|
||||
}
|
||||
|
||||
@@ -17,30 +17,26 @@ nonisolated struct ProcessEnergyMonitor: Sendable {
|
||||
}
|
||||
|
||||
mutating func update(processes: ProcessSnapshot, readings: [ProcessEnergyReading], capability: EnergyCapability, maximumInterval: TimeInterval = 30) -> ProcessEnergySnapshot {
|
||||
let processesByID = Dictionary(processes.rows.map { ($0.id, $0) }, uniquingKeysWith: { first, _ in first })
|
||||
let identities = Set(processes.rows.map(\.id))
|
||||
var next: [ProcessIdentity: ProcessEnergyReading] = [:]
|
||||
var usages: [ProcessEnergyUsage] = []
|
||||
var measured = 0
|
||||
if capability == .verifiedCPU && !processes.failed {
|
||||
for reading in readings where next[reading.id] == nil {
|
||||
guard let process = processesByID[reading.id], reading.status == .available,
|
||||
guard identities.contains(reading.id), reading.status == .available,
|
||||
reading.nanojoules != nil, reading.birth > 0, reading.uptime.isFinite else { continue }
|
||||
next[reading.id] = reading
|
||||
if let (power, seconds) = Self.watts(current: reading, previous: previous[reading.id], maximumInterval: maximumInterval) {
|
||||
measured += 1
|
||||
let usage = ProcessEnergyUsage(process: process, watts: power, seconds: seconds)
|
||||
usages.append(usage)
|
||||
usages.append(ProcessEnergyUsage(id: reading.id, watts: power, seconds: seconds))
|
||||
}
|
||||
}
|
||||
}
|
||||
previous = next // Failed / missing readings invalidate the old baseline.
|
||||
usages.sort { $0.watts == $1.watts ? $0.id.pid < $1.id.pid : $0.watts > $1.watts }
|
||||
let state: ProcessEnergySnapshot.State
|
||||
if capability == .unsupported { state = .unsupported }
|
||||
else if capability == .unavailable || processes.failed || (capability == .verifiedCPU && next.isEmpty) { state = .unavailable }
|
||||
else if measured == 0 { state = .waiting }
|
||||
else { state = measured < processes.enumerated ? .partial : .available }
|
||||
else if usages.isEmpty { state = .waiting }
|
||||
else { state = usages.count < processes.enumerated ? .partial : .available }
|
||||
return ProcessEnergySnapshot(date: Date(), candidates: processes.enumerated, readable: next.count,
|
||||
measured: measured, rows: usages, state: state)
|
||||
rows: usages, state: state)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,8 +24,6 @@ actor SystemSampler {
|
||||
private var batteryTask: Task<Void, Never>?
|
||||
private var diskCache: DiskHealthMetrics?
|
||||
private var batteryCache: Double?
|
||||
private var diskDate: Date?
|
||||
private var batteryDate: Date?
|
||||
private var nextDisk: TimeInterval = 0
|
||||
private var nextBattery: TimeInterval = 0
|
||||
private let processRead: @Sendable (inout ProcessMonitor) -> ProcessSnapshot
|
||||
@@ -67,7 +65,7 @@ actor SystemSampler {
|
||||
// A synchronous OS read may outlive cancellation. Keep the in-flight slot occupied.
|
||||
}
|
||||
|
||||
func sample(includeProcesses: Bool? = nil, includeSlowMetrics: Bool = true, maximumEnergyInterval: TimeInterval = 30, includeEnergy: Bool = true, demandRevision: Int? = nil,
|
||||
func sample(includeProcesses: Bool? = nil, includeSlowMetrics: Bool = true, maximumEnergyInterval: TimeInterval = 30, demandRevision: Int? = nil,
|
||||
processUpdate: (@Sendable (ProcessSnapshot) -> Void)? = nil,
|
||||
energyUpdate: (@Sendable (ProcessEnergySnapshot) -> Void)? = nil) -> MetricsSnapshot {
|
||||
guard !Task.isCancelled else { return MetricsSnapshot() }
|
||||
@@ -75,7 +73,7 @@ actor SystemSampler {
|
||||
setProcessVisible(includeProcesses ?? processVisible, revision: demandRevision)
|
||||
self.maximumEnergyInterval = min(3600, max(30, maximumEnergyInterval))
|
||||
self.processUpdate = processUpdate
|
||||
self.energyUpdate = includeEnergy ? energyUpdate : nil
|
||||
self.energyUpdate = energyUpdate
|
||||
if !didProbe {
|
||||
didProbe = true
|
||||
if ProcessInfo.processInfo.environment["KYMO_PANEL_PROBE"] == "1" { PanelCapabilityProbe.run() }
|
||||
@@ -104,7 +102,6 @@ actor SystemSampler {
|
||||
result.battery = BatteryMonitor.sample()
|
||||
result.batteryState = result.battery == nil ? BatteryMonitor.availability() : .present
|
||||
result.gpu = GPUMonitor.sample()
|
||||
result.gpuUsage = result.gpu?.usage
|
||||
if includeSlowMetrics && volumeTask == nil && start - volumeSampleTime >= 30 {
|
||||
volumeTask = Task.detached(priority: .utility) { [self] in
|
||||
let value = DiskMonitor.volumes()
|
||||
@@ -120,13 +117,9 @@ actor SystemSampler {
|
||||
startProcessesIfNeeded()
|
||||
result.processes = processVisible ? processCache : nil
|
||||
result.diskHealth = diskCache
|
||||
result.diskHealthDate = diskDate
|
||||
result.battery?.health = batteryCache
|
||||
result.batteryHealthDate = batteryDate
|
||||
result.volumes = volumes
|
||||
result.uptime = ProcessInfo.processInfo.systemUptime
|
||||
var load = [Double](repeating: 0, count: 3)
|
||||
if getloadavg(&load, 3) == 3 { result.load = load }
|
||||
if ProcessInfo.processInfo.environment["KYMO_PANEL_PROBE"] == "1" {
|
||||
let line = "{\"event\":\"sampleDuration\",\"milliseconds\":\((ProcessInfo.processInfo.systemUptime - start) * 1000)}\n"
|
||||
try? FileHandle.standardOutput.write(contentsOf: Data(line.utf8))
|
||||
@@ -146,11 +139,11 @@ actor SystemSampler {
|
||||
volumes = value; volumeSampleTime = ProcessInfo.processInfo.systemUptime; volumeTask = nil
|
||||
}
|
||||
private func finishDisk(_ value: DiskHealthMetrics?) {
|
||||
diskCache = value; diskDate = value == nil ? nil : Date()
|
||||
diskCache = value
|
||||
nextDisk = ProcessInfo.processInfo.systemUptime + (value == nil ? 600 : 3600); diskTask = nil
|
||||
}
|
||||
private func finishBattery(_ value: Double?) {
|
||||
batteryCache = value; batteryDate = value == nil ? nil : Date()
|
||||
batteryCache = value
|
||||
nextBattery = ProcessInfo.processInfo.systemUptime + (value == nil ? 600 : 3600); batteryTask = nil
|
||||
}
|
||||
private func startProcessesIfNeeded() {
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
# 核心层
|
||||
|
||||
模块职责统一见[架构](../../docs/architecture.md)。
|
||||
@@ -14,7 +14,6 @@ final class MetricsStore {
|
||||
private(set) var processUpdatesRequested = false
|
||||
private(set) var slowMetricsRequested = true
|
||||
let sampling: SamplingPreferences
|
||||
private let energyEnabled: Bool
|
||||
private var panelDemand: Bool { isPanelVisible && !isDisplaySleeping }
|
||||
private var processDemand: Bool { panelDemand && processUpdatesRequested }
|
||||
var effectiveMilliseconds: Int { panelDemand ? sampling.panelMilliseconds : sampling.backgroundMilliseconds }
|
||||
@@ -31,9 +30,8 @@ final class MetricsStore {
|
||||
@ObservationIgnored private var needsHistoryBoundary = true
|
||||
@ObservationIgnored private var lastPublishedAt: ContinuousClock.Instant?
|
||||
|
||||
init(sampling: SamplingPreferences? = nil, sampler: SystemSampler = SystemSampler(), energyEnabled: Bool = true) {
|
||||
init(sampling: SamplingPreferences? = nil, sampler: SystemSampler = SystemSampler()) {
|
||||
self.sampler = sampler
|
||||
self.energyEnabled = energyEnabled
|
||||
self.sampling = sampling ?? SamplingPreferences()
|
||||
self.sampling.onChange = { [weak self] in
|
||||
guard let self, !self.isPaused,
|
||||
@@ -78,7 +76,7 @@ final class MetricsStore {
|
||||
var next = await sampler.sample(includeProcesses: self?.processDemand == true,
|
||||
includeSlowMetrics: self?.panelDemand == true && self?.slowMetricsRequested == true,
|
||||
maximumEnergyInterval: max(30, Double(self?.effectiveMilliseconds ?? 2000) / 500),
|
||||
includeEnergy: self?.energyEnabled == true, demandRevision: visibleGeneration, processUpdate: { [weak self] processes in
|
||||
demandRevision: visibleGeneration, processUpdate: { [weak self] processes in
|
||||
Task { @MainActor [weak self] in
|
||||
guard let self, self.visibilityGeneration == visibleGeneration,
|
||||
self.processDemand, !self.isPaused, !self.isSystemSleeping else { return }
|
||||
|
||||
@@ -5,12 +5,6 @@ import Darwin
|
||||
nonisolated enum SamplingDiagnostics {
|
||||
static let enabled = ProcessInfo.processInfo.environment["KYMO_DIAGNOSTICS"] == "1"
|
||||
|
||||
static func recordTextPresentation(processes: Int, cells: Int) {
|
||||
guard enabled else { return }
|
||||
let line = "{\"event\":\"textPresentation\",\"processes\":\(processes),\"createdCells\":\(cells)}\n"
|
||||
try? FileHandle.standardOutput.write(contentsOf: Data(line.utf8))
|
||||
}
|
||||
|
||||
static func recordEnergy(_ snapshot: ProcessEnergySnapshot) {
|
||||
guard enabled else { return }
|
||||
let payload: [String: Any] = ["event": "energy", "recordedAt": Date().timeIntervalSince1970,
|
||||
@@ -21,14 +15,13 @@ nonisolated enum SamplingDiagnostics {
|
||||
try? FileHandle.standardOutput.write(contentsOf: data + Data([10]))
|
||||
}
|
||||
|
||||
static func record(_ snapshot: MetricsSnapshot, event: String = "sample", hiddenHostAlive: Bool? = nil, windowNumber: Int? = nil, hoveredPlots: Int? = nil, nativePlots: Int? = nil, pointerInsidePanel: Bool? = nil, plotBounds: [[Double]]? = nil, animatedPlots: Int? = nil) {
|
||||
static func record(_ snapshot: MetricsSnapshot, event: String = "sample", hiddenHostAlive: Bool? = nil, windowNumber: Int? = nil, hoveredPlots: Int? = nil, nativePlots: Int? = nil, pointerInsidePanel: Bool? = nil, plotBounds: [[Double]]? = nil) {
|
||||
guard enabled else { return }
|
||||
var payload: [String: Any] = [
|
||||
"event": event, "timestamp": snapshot.date.timeIntervalSince1970,
|
||||
"recordedAt": Date().timeIntervalSince1970,
|
||||
"uptime": ProcessInfo.processInfo.systemUptime,
|
||||
"pid": ProcessInfo.processInfo.processIdentifier,
|
||||
"load": snapshot.load
|
||||
"pid": ProcessInfo.processInfo.processIdentifier
|
||||
]
|
||||
payload["hiddenHostAlive"] = hiddenHostAlive
|
||||
payload["windowNumber"] = windowNumber
|
||||
@@ -36,7 +29,6 @@ nonisolated enum SamplingDiagnostics {
|
||||
payload["nativePlots"] = nativePlots
|
||||
payload["pointerInsidePanel"] = pointerInsidePanel
|
||||
payload["plotBounds"] = plotBounds
|
||||
payload["animatedPlots"] = animatedPlots
|
||||
payload["cpu"] = snapshot.cpu?.usage
|
||||
payload["cores"] = snapshot.cpu?.cores.count
|
||||
payload["cpuTemperature"] = snapshot.cpuTemperature
|
||||
|
||||
@@ -4,7 +4,6 @@ import SwiftUI
|
||||
struct CPUCoreGrid: View {
|
||||
let values: [Double]
|
||||
let kinds: [Int: CPUCoreTopology.Kind]
|
||||
let interval: TimeInterval
|
||||
|
||||
private func color(_ kind: CPUCoreTopology.Kind?) -> Color {
|
||||
switch kind {
|
||||
@@ -141,7 +140,7 @@ private struct CPUCoreGridPreviews: View {
|
||||
VStack(alignment: .leading, spacing: 4) {
|
||||
Text("\(count) cores").font(.caption)
|
||||
CPUCoreGrid(values: (0..<count).map { Double(($0 * 17) % 90 + 5) / 100 },
|
||||
kinds: Dictionary(uniqueKeysWithValues: (0..<count).map { ($0, $0 < count / 3 ? .efficiency : .performance) }), interval: 2)
|
||||
kinds: Dictionary(uniqueKeysWithValues: (0..<count).map { ($0, $0 < count / 3 ? .efficiency : .performance) }))
|
||||
}
|
||||
}
|
||||
}.padding().frame(width: width)
|
||||
|
||||
@@ -1,38 +0,0 @@
|
||||
import SwiftUI
|
||||
|
||||
/// Memory bars share a byte scale, not a used/allocated capacity ratio.
|
||||
struct GPUStatisticsView: View {
|
||||
let inUse: UInt64?
|
||||
let allocated: UInt64?
|
||||
let average: Double?
|
||||
let peak: Double?
|
||||
|
||||
private var reference: Double { max(1, Double(max(inUse ?? 0, allocated ?? 0))) }
|
||||
|
||||
var body: some View {
|
||||
HStack(spacing: 10) {
|
||||
VStack(spacing: 5) {
|
||||
memoryRow("gpu.driverMemory", bytes: inUse, color: Color("MetricMemory"))
|
||||
memoryRow("gpu.allocatedMemory", bytes: allocated, color: Color("MetricNetwork"))
|
||||
}.frame(maxWidth: .infinity)
|
||||
Divider()
|
||||
HStack(spacing: 6) {
|
||||
MetricRingGauge(title: "gpu.recentAverage", value: average, color: Color("MetricCPU"))
|
||||
MetricRingGauge(title: "gpu.peak", value: peak, color: Color("MetricGPU"))
|
||||
}.frame(maxWidth: .infinity)
|
||||
}.frame(height: 46)
|
||||
}
|
||||
|
||||
private func memoryRow(_ title: LocalizedStringKey, bytes: UInt64?, color: Color) -> some View {
|
||||
VStack(spacing: 3) {
|
||||
HStack(spacing: 4) {
|
||||
Text(title).foregroundStyle(.secondary)
|
||||
Spacer(minLength: 0)
|
||||
MetricText(value: MetricFormat.bytes(bytes)).font(PanelStyle.value)
|
||||
}.font(PanelStyle.label).lineLimit(1)
|
||||
MetricProgressBar(value: bytes.map { Double($0) / reference } ?? 0, color: color)
|
||||
.frame(height: 3)
|
||||
.accessibilityHidden(true)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -35,7 +35,7 @@ extension MenuPanelView {
|
||||
CardSeparator()
|
||||
if let cpu = snapshot.cpu {
|
||||
CPUCoreGrid(
|
||||
values: cpu.cores, kinds: CPUCoreTopology.cores, interval: chartInterval,
|
||||
values: cpu.cores, kinds: CPUCoreTopology.cores,
|
||||
availableWidth: cardContentWidth)
|
||||
|
||||
} else {
|
||||
|
||||
@@ -50,7 +50,7 @@ struct MenuPanelView: View {
|
||||
|
||||
var body: some View {
|
||||
VStack(spacing: PanelStyle.gap) {
|
||||
if PanelResourceAudit.omitted != "header" { header }
|
||||
header
|
||||
if presentation.page == .overview {
|
||||
if PanelLayout.needsResourceScroll(size: panelSize, heights: cardHeights) {
|
||||
ScrollView { resourceColumns }
|
||||
@@ -59,8 +59,8 @@ struct MenuPanelView: View {
|
||||
resourceColumns
|
||||
.frame(maxHeight: .infinity, alignment: .top)
|
||||
}
|
||||
} else if presentation.isOpen && PanelResourceAudit.omitted != "processes" {
|
||||
PanelProcessSection(metrics: metrics, state: processState, wide: panelSize.width >= 800)
|
||||
} else if presentation.isOpen {
|
||||
PanelProcessSection(metrics: metrics, state: processState)
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
}
|
||||
footer
|
||||
@@ -111,17 +111,13 @@ struct MenuPanelView: View {
|
||||
}
|
||||
|
||||
@ViewBuilder private func resourceCard(_ card: PanelCard) -> some View {
|
||||
if PanelResourceAudit.omitted == "resources" {
|
||||
Color.clear
|
||||
} else {
|
||||
switch card {
|
||||
case .cpu: cpuCard
|
||||
case .battery: batteryCard
|
||||
case .gpu: gpuCard
|
||||
case .storage: diskCard
|
||||
case .memory: memoryCard
|
||||
case .network: networkCard
|
||||
}
|
||||
switch card {
|
||||
case .cpu: cpuCard
|
||||
case .battery: batteryCard
|
||||
case .gpu: gpuCard
|
||||
case .storage: diskCard
|
||||
case .memory: memoryCard
|
||||
case .network: networkCard
|
||||
}
|
||||
}
|
||||
|
||||
@@ -254,6 +250,5 @@ private struct PanelControlButtonBody<Content: View>: View {
|
||||
private struct PanelProcessSection: View {
|
||||
let metrics: MetricsStore
|
||||
let state: ProcessTableState
|
||||
let wide: Bool
|
||||
var body: some View { ProcessTableView(snapshot: metrics.processSnapshot, energy: metrics.energy, state: state, wide: wide) }
|
||||
var body: some View { ProcessTableView(snapshot: metrics.processSnapshot, energy: metrics.energy, state: state) }
|
||||
}
|
||||
|
||||
@@ -161,7 +161,7 @@ import SwiftUI
|
||||
if cell.toolTip != tooltip { cell.toolTip = tooltip }
|
||||
}
|
||||
if key == "name" {
|
||||
let image = PanelResourceAudit.omitted == "icons" ? nil : process.path.flatMap { ProcessIconCache.shared.image(for: $0) }
|
||||
let image = process.path.flatMap { ProcessIconCache.shared.image(for: $0) }
|
||||
let desired = image ?? Self.placeholder
|
||||
if cell.imageView?.image !== desired { cell.imageView?.image = desired }
|
||||
} else if key == "threads" {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import SwiftUI
|
||||
|
||||
/// Shared by the dashboard and the text-only audit so network work is comparable.
|
||||
/// The mounted overview owns public-IP work and cancels it when demand ends.
|
||||
struct PanelPublicIPRefresh: ViewModifier {
|
||||
let metrics: MetricsStore
|
||||
@Binding var address: String?
|
||||
|
||||
@@ -4,7 +4,6 @@ import AppKit
|
||||
@MainActor enum PanelResourceAudit {
|
||||
#if DEBUG || KYMO_AUDIT
|
||||
static let enabled = ProcessInfo.processInfo.environment["KYMO_RESOURCE_AUDIT"] == "1"
|
||||
static let omitted = enabled ? ProcessInfo.processInfo.environment["KYMO_AUDIT_OMIT"] ?? "" : ""
|
||||
|
||||
static func run(controller: MenuPanelController, metrics: MetricsStore) {
|
||||
guard enabled else { return }
|
||||
@@ -30,8 +29,7 @@ import AppKit
|
||||
windowNumber: controller.panel.isVisible ? controller.panel.windowNumber : nil,
|
||||
hoveredPlots: views.filter { $0.input?.hoveredIndex != nil }.count, nativePlots: views.count,
|
||||
pointerInsidePanel: controller.panel.isVisible && controller.panel.frame.contains(NSEvent.mouseLocation),
|
||||
plotBounds: views.map { [Double($0.bounds.width), Double($0.bounds.height)] },
|
||||
animatedPlots: 0)
|
||||
plotBounds: views.map { [Double($0.bounds.width), Double($0.bounds.height)] })
|
||||
if event == "open1.10", ProcessInfo.processInfo.environment["KYMO_AUDIT_CAPTURE"] == "1",
|
||||
let content = controller.panel.contentView { capture(content) }
|
||||
}
|
||||
@@ -125,8 +123,6 @@ import AppKit
|
||||
}
|
||||
|
||||
#else
|
||||
static let enabled = false
|
||||
static let omitted = ""
|
||||
static func run(controller: MenuPanelController, metrics: MetricsStore) {}
|
||||
#endif
|
||||
|
||||
|
||||
@@ -13,7 +13,6 @@ struct ProcessTableView: View {
|
||||
let snapshot: ProcessSnapshot?
|
||||
let energy: ProcessEnergySnapshot?
|
||||
@Bindable var state: ProcessTableState
|
||||
var wide: Bool = true
|
||||
@Environment(\.locale) private var locale
|
||||
@State private var hovering = false
|
||||
@State private var rows: [ProcessMetrics] = []
|
||||
@@ -30,7 +29,7 @@ struct ProcessTableView: View {
|
||||
HStack(spacing: 10) {
|
||||
processTitle
|
||||
Spacer(minLength: 0)
|
||||
searchField.frame(maxWidth: wide ? 220 : 180)
|
||||
searchField.frame(maxWidth: 180)
|
||||
}
|
||||
HStack(spacing: 8) {
|
||||
Text("panel.processScope").lineLimit(2)
|
||||
|
||||
@@ -1,165 +0,0 @@
|
||||
import AppKit
|
||||
import SwiftUI
|
||||
|
||||
#if DEBUG || KYMO_AUDIT
|
||||
/// An opt-in comparison frontend. Sampling, history, IPC and public-IP policy remain enabled.
|
||||
struct TextMonitoringAuditView: View {
|
||||
let metrics: MetricsStore
|
||||
let appearance: AppearancePreferences
|
||||
@State private var publicAddress: String?
|
||||
var body: some View {
|
||||
TextReportHost(snapshot: metrics.snapshot, processes: metrics.processSnapshot, energy: metrics.energy,
|
||||
historyPoints: metrics.history.samples.count, publicAddress: publicAddress, appearance: appearance.appearance)
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
.modifier(PanelPublicIPRefresh(metrics: metrics, address: $publicAddress))
|
||||
}
|
||||
}
|
||||
|
||||
private struct TextReportHost: NSViewRepresentable {
|
||||
let snapshot: MetricsSnapshot
|
||||
let processes: ProcessSnapshot?
|
||||
let energy: ProcessEnergySnapshot?
|
||||
let historyPoints: Int
|
||||
let publicAddress: String?
|
||||
let appearance: AppAppearance
|
||||
func makeCoordinator() -> Coordinator { Coordinator() }
|
||||
func makeNSView(context: Context) -> ReportScrollView {
|
||||
let scroll = ReportScrollView()
|
||||
scroll.hasVerticalScroller = true
|
||||
scroll.hasHorizontalScroller = true
|
||||
scroll.autohidesScrollers = false
|
||||
scroll.scrollerStyle = .legacy
|
||||
let table = NSTableView(frame: NSRect(x: 0, y: 0, width: 3200, height: 800))
|
||||
table.headerView = nil
|
||||
table.style = .plain
|
||||
table.rowHeight = 15
|
||||
table.intercellSpacing = .zero
|
||||
table.selectionHighlightStyle = .none
|
||||
table.backgroundColor = .windowBackgroundColor
|
||||
table.columnAutoresizingStyle = .noColumnAutoresizing
|
||||
let column = NSTableColumn(identifier: NSUserInterfaceItemIdentifier("text"))
|
||||
column.width = 3200
|
||||
table.addTableColumn(column)
|
||||
table.delegate = context.coordinator
|
||||
table.dataSource = context.coordinator
|
||||
scroll.documentView = table
|
||||
return scroll
|
||||
}
|
||||
func updateNSView(_ scroll: ReportScrollView, context: Context) {
|
||||
scroll.choice = appearance
|
||||
guard let table = scroll.documentView as? NSTableView else { return }
|
||||
let c = context.coordinator
|
||||
if c.processDate != processes?.date {
|
||||
c.processDate = processes?.date
|
||||
c.rows = ProcessTableProjection.rows(processes?.rows ?? [], query: "", sorting: [ProcessSort(key: .cpu)], order: [])
|
||||
}
|
||||
let heading = Self.resourceText(snapshot) + "\nHistory points retained: \(historyPoints)\nPublic IP: \(publicAddress ?? "--")\n\n" + Self.energyText(energy)
|
||||
+ "\nProcesses: \(processes?.readable ?? 0)/\(processes?.enumerated ?? 0), failed=\(processes?.failed ?? false)\nPID\tCPU %\tFootprint bytes\tThreads\tRestricted\tName\tPath"
|
||||
c.lines = heading.components(separatedBy: "\n")
|
||||
let origin = scroll.contentView.bounds.origin
|
||||
let oldCount = table.numberOfRows
|
||||
let newCount = c.lines.count + c.rows.count
|
||||
if newCount != oldCount {
|
||||
table.beginUpdates()
|
||||
if newCount > oldCount { table.insertRows(at: IndexSet(integersIn: oldCount..<newCount), withAnimation: []) }
|
||||
else { table.removeRows(at: IndexSet(integersIn: newCount..<oldCount), withAnimation: []) }
|
||||
table.endUpdates()
|
||||
}
|
||||
let visible = table.rows(in: table.visibleRect)
|
||||
if visible.location != NSNotFound, visible.length > 0 {
|
||||
for row in visible.location..<min(newCount, visible.location + visible.length) {
|
||||
if let cell = table.view(atColumn: 0, row: row, makeIfNecessary: false) as? NSTableCellView {
|
||||
c.update(cell, row: row)
|
||||
}
|
||||
}
|
||||
}
|
||||
scroll.contentView.scroll(to: origin)
|
||||
scroll.reflectScrolledClipView(scroll.contentView)
|
||||
SamplingDiagnostics.recordTextPresentation(processes: c.rows.count, cells: c.createdCells)
|
||||
}
|
||||
/// Fixed-height native text rows format only visible records. All sampled rows remain scrollable.
|
||||
final class Coordinator: NSObject, NSTableViewDataSource, NSTableViewDelegate {
|
||||
var processDate: Date?
|
||||
var rows: [ProcessMetrics] = []
|
||||
var lines: [String] = []
|
||||
var createdCells = 0
|
||||
func numberOfRows(in tableView: NSTableView) -> Int { lines.count + rows.count }
|
||||
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
|
||||
guard row >= 0, row < lines.count + rows.count else { return nil }
|
||||
let key = NSUserInterfaceItemIdentifier("text.cell")
|
||||
let cell: NSTableCellView
|
||||
if let reused = tableView.makeView(withIdentifier: key, owner: nil) as? NSTableCellView { cell = reused }
|
||||
else {
|
||||
cell = NSTableCellView()
|
||||
cell.identifier = key
|
||||
let field = NSTextField(labelWithString: "")
|
||||
field.font = .monospacedSystemFont(ofSize: 11, weight: .regular)
|
||||
field.lineBreakMode = .byClipping
|
||||
field.translatesAutoresizingMaskIntoConstraints = false
|
||||
cell.addSubview(field)
|
||||
cell.textField = field
|
||||
NSLayoutConstraint.activate([
|
||||
field.leadingAnchor.constraint(equalTo: cell.leadingAnchor, constant: 8),
|
||||
field.trailingAnchor.constraint(equalTo: cell.trailingAnchor, constant: -4),
|
||||
field.topAnchor.constraint(equalTo: cell.topAnchor), field.bottomAnchor.constraint(equalTo: cell.bottomAnchor)
|
||||
])
|
||||
createdCells += 1
|
||||
}
|
||||
update(cell, row: row)
|
||||
return cell
|
||||
}
|
||||
func update(_ cell: NSTableCellView, row: Int) {
|
||||
guard row >= 0, row < lines.count + rows.count else { return }
|
||||
let value = row < lines.count ? lines[row] : TextReportHost.processLine(rows[row - lines.count])
|
||||
if cell.textField?.stringValue != value { cell.textField?.stringValue = value }
|
||||
}
|
||||
}
|
||||
final class ReportScrollView: NSScrollView {
|
||||
var choice = AppAppearance.system { didSet { apply() } }
|
||||
override func viewDidMoveToWindow() { super.viewDidMoveToWindow(); apply() }
|
||||
private func apply() {
|
||||
let target = choice.windowAppearance
|
||||
if window?.appearance?.name != target?.name { window?.appearance = target }
|
||||
}
|
||||
}
|
||||
private static func number(_ value: Double?) -> String { value.map { String(format: "%.3f", $0) } ?? "--" }
|
||||
private static func bytes(_ value: UInt64?) -> String { value.map(String.init) ?? "--" }
|
||||
private static func resourceText(_ s: MetricsSnapshot) -> String {
|
||||
var lines = ["Kymo — plain text comparison (no charts, icons or animation)", "Resource timestamp: \(s.date.timeIntervalSince1970)"]
|
||||
lines += ["CPU total/user/system fraction: \(number(s.cpu?.usage)) / \(number(s.cpu?.user)) / \(number(s.cpu?.system))",
|
||||
"CPU cores: \(s.cpu?.cores.map { number($0) }.joined(separator: " ") ?? "--")",
|
||||
"CPU/GPU temperature °C: \(number(s.cpuTemperature)) / \(number(s.gpuTemperature))",
|
||||
"Fans RPM: \(s.fans?.map { "\($0.id)=\(number($0.rpm))" }.joined(separator: " ") ?? "--")",
|
||||
"GPU usage/renderer/tiler/cores: \(number(s.gpu?.usage)) / \(number(s.gpu?.renderer)) / \(number(s.gpu?.tiler)) / \(s.gpu?.coreCount.map(String.init) ?? "--")",
|
||||
"GPU in-use/allocated bytes: \(bytes(s.gpu?.inUseMemory)) / \(bytes(s.gpu?.allocatedMemory))",
|
||||
"Memory total/used/available/cached/wired/compressed/swap bytes: \(bytes(s.memory?.total)) / \(bytes(s.memory?.used)) / \(bytes(s.memory?.available)) / \(bytes(s.memory?.cached)) / \(bytes(s.memory?.wired)) / \(bytes(s.memory?.compressed)) / \(bytes(s.memory?.swapUsed))",
|
||||
"Memory pressure: \(s.memory?.pressure.map(String.init) ?? "--")",
|
||||
"Disk total/available bytes: \(bytes(s.disk?.total)) / \(bytes(s.disk?.available))",
|
||||
"Disk IO read/write B/s: \(number(s.diskIO?.read)) / \(number(s.diskIO?.written))",
|
||||
"SMART remaining/hour: \(number(s.diskHealth?.remainingLife)) / \(bytes(s.diskHealth?.powerOnHours))",
|
||||
"Battery charge/health/power W/cycles: \(number(s.battery?.charge)) / \(number(s.battery?.health)) / \(number(s.battery?.power)) / \(s.battery?.cycles.map(String.init) ?? "--")",
|
||||
"Battery charging/external/minutes/state: \(String(describing: s.battery?.charging)) / \(String(describing: s.battery?.externalPower)) / \(s.battery?.minutesRemaining.map(String.init) ?? "--") / \(s.batteryState)",
|
||||
"Uptime/load: \(number(s.uptime)) / \(s.load.map { number($0) }.joined(separator: " "))",
|
||||
"Network path/default interface: \(String(describing: s.networkPath)) / \(s.defaultNetworkInterface ?? "--")"]
|
||||
for i in s.network ?? [] { lines.append("\(i.name) active=\(i.active) received/sent=\(i.received)/\(i.sent) B, down/up=\(number(i.download))/\(number(i.upload)) B/s, addresses=\(i.addresses.joined(separator: ","))") }
|
||||
for v in s.volumes ?? [] { lines.append("Volume \(v.name) \(v.path): total/available \(v.capacity.total)/\(v.capacity.available) B") }
|
||||
return lines.joined(separator: "\n")
|
||||
}
|
||||
private static func energyText(_ energy: ProcessEnergySnapshot?) -> String {
|
||||
guard let energy else { return "CPU energy: waiting\n" }
|
||||
return "CPU energy: \(energy.state), measured/readable/enumerated=\(energy.measured)/\(energy.readable)/\(energy.candidates)\n" + energy.rows.map { "\($0.id.pid) \($0.process.name): \($0.formattedPower), interval \(number($0.seconds)) s" }.joined(separator: "\n") + "\n"
|
||||
}
|
||||
private static func processLine(_ process: ProcessMetrics) -> String {
|
||||
"\(process.id.pid)\t\(number(process.cpu.map { $0 * 100 }))\t\(bytes(process.footprintBytes))\t\(process.threads.map(String.init) ?? "--")\t\(process.restricted)\t\(process.name)\t\(process.path ?? "--")"
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
#else
|
||||
/// The diagnostic renderer is excluded from distribution builds.
|
||||
struct TextMonitoringAuditView: View {
|
||||
let metrics: MetricsStore
|
||||
let appearance: AppearancePreferences
|
||||
var body: some View { EmptyView() }
|
||||
}
|
||||
#endif
|
||||
@@ -1,3 +0,0 @@
|
||||
# 业务特性
|
||||
|
||||
模块职责统一见[架构](../../docs/architecture.md)。
|
||||
@@ -70,75 +70,6 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"cpu.load.help": {
|
||||
"extractionState": "manual",
|
||||
"localizations": {
|
||||
"en": {
|
||||
"stringUnit": {
|
||||
"state": "translated",
|
||||
"value": "Average system load over the last minute. The bar is full at the number of logical CPU cores; load can exceed that number."
|
||||
}
|
||||
},
|
||||
"zh-Hans": {
|
||||
"stringUnit": {
|
||||
"state": "translated",
|
||||
"value": "最近 1 分钟的系统平均负载。进度条满格对应逻辑核心数,负载可能超过该数值。"
|
||||
}
|
||||
},
|
||||
"zh-Hant": {
|
||||
"stringUnit": {
|
||||
"state": "translated",
|
||||
"value": "最近 1 分鐘的系統平均負載。進度條滿格對應邏輯核心數,負載可能超過該數值。"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"cpu.load.oneMinute": {
|
||||
"extractionState": "manual",
|
||||
"localizations": {
|
||||
"en": {
|
||||
"stringUnit": {
|
||||
"state": "translated",
|
||||
"value": "Load · 1 min"
|
||||
}
|
||||
},
|
||||
"zh-Hans": {
|
||||
"stringUnit": {
|
||||
"state": "translated",
|
||||
"value": "负载 · 1 分钟"
|
||||
}
|
||||
},
|
||||
"zh-Hant": {
|
||||
"stringUnit": {
|
||||
"state": "translated",
|
||||
"value": "負載 · 1 分鐘"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"cpu.temperature.help": {
|
||||
"extractionState": "manual",
|
||||
"localizations": {
|
||||
"en": {
|
||||
"stringUnit": {
|
||||
"state": "translated",
|
||||
"value": "Highest valid sensor reading in the CPU core area; warning at 90°C."
|
||||
}
|
||||
},
|
||||
"zh-Hans": {
|
||||
"stringUnit": {
|
||||
"state": "translated",
|
||||
"value": "CPU 核心区域的最高有效传感器读数;达到 90°C 时提示。"
|
||||
}
|
||||
},
|
||||
"zh-Hant": {
|
||||
"stringUnit": {
|
||||
"state": "translated",
|
||||
"value": "CPU 核心區域的最高有效感測器讀數;達到 90°C 時提示。"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"cpu.temperature.high": {
|
||||
"extractionState": "manual",
|
||||
"localizations": {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,29 +1,6 @@
|
||||
{
|
||||
"sourceLanguage" : "en",
|
||||
"strings" : {
|
||||
"clearSearch" : {
|
||||
"extractionState" : "manual",
|
||||
"localizations" : {
|
||||
"en" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "Clear Search"
|
||||
}
|
||||
},
|
||||
"zh-Hans" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "清空搜索"
|
||||
}
|
||||
},
|
||||
"zh-Hant" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "清除搜尋"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"copyName" : {
|
||||
"extractionState" : "stale",
|
||||
"localizations" : {
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
# 本地化资源
|
||||
|
||||
模块职责统一见[架构](../../docs/architecture.md)。
|
||||
字符串维护与检查见[开发指南](../../docs/development.md)。
|
||||
@@ -1,36 +0,0 @@
|
||||
import SwiftUI
|
||||
|
||||
struct MiniTrendChart: View {
|
||||
let values: [Double?]
|
||||
let color: Color
|
||||
|
||||
var body: some View {
|
||||
Canvas { context, size in
|
||||
let values = Array(values.suffix(MetricHistory.capacity))
|
||||
guard values.count > 1 else { return }
|
||||
var path = Path()
|
||||
var run: [CGPoint] = []
|
||||
func appendRun() {
|
||||
guard let first = run.first, let last = run.last else { return }
|
||||
path.move(to: first)
|
||||
if run.count == 1 { path.addLine(to: CGPoint(x: first.x + 0.1, y: first.y)) }
|
||||
for index in 1..<run.count {
|
||||
let previous = run[index - 1]
|
||||
let current = run[index]
|
||||
let midpoint = CGPoint(x: (previous.x + current.x) / 2, y: (previous.y + current.y) / 2)
|
||||
path.addQuadCurve(to: midpoint, control: previous)
|
||||
}
|
||||
path.addQuadCurve(to: last, control: last)
|
||||
run.removeAll(keepingCapacity: true)
|
||||
}
|
||||
for (index, value) in values.enumerated() {
|
||||
guard let value, value.isFinite else { continue }
|
||||
let x = size.width * CGFloat(index + MetricHistory.capacity - values.count) / CGFloat(MetricHistory.capacity - 1)
|
||||
run.append(CGPoint(x: x, y: 2 + (size.height - 4) * (1 - min(1, max(0, value)))))
|
||||
}
|
||||
appendRun()
|
||||
context.stroke(path, with: .color(color.opacity(0.85)), style: StrokeStyle(lineWidth: 1.8, lineCap: .round, lineJoin: .round))
|
||||
}
|
||||
.accessibilityHidden(true)
|
||||
}
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
import Foundation
|
||||
import CoreGraphics
|
||||
|
||||
|
||||
/// Screen coordinates: prefer the parent's right side, otherwise use its left.
|
||||
nonisolated enum DetailPlacement {
|
||||
static func frame(anchor: CGRect, parent: CGRect, content: CGSize, visible: CGRect) -> CGRect {
|
||||
let gap: CGFloat = 4
|
||||
let width = min(content.width, visible.width)
|
||||
let height = min(content.height, visible.height)
|
||||
let right = parent.maxX + gap
|
||||
let left = parent.minX - gap - width
|
||||
let candidate = right + width <= visible.maxX ? right : left
|
||||
let x = max(visible.minX, min(candidate, visible.maxX - width))
|
||||
let y = max(visible.minY, min(anchor.maxY - height, visible.maxY - height))
|
||||
return CGRect(x: x, y: y, width: width, height: height)
|
||||
}
|
||||
}
|
||||
@@ -1,113 +0,0 @@
|
||||
import SwiftUI
|
||||
import AppKit
|
||||
|
||||
/// A non-activating child window: outside the parent layout, below no other app.
|
||||
struct HoverDetailPresenter<Detail: View>: NSViewRepresentable {
|
||||
@Environment(\.locale) private var locale
|
||||
let isPresented: Bool
|
||||
let detail: Detail
|
||||
let onHover: (Bool) -> Void
|
||||
let onDismiss: () -> Void
|
||||
|
||||
func makeNSView(context: Context) -> AnchorView { AnchorView() }
|
||||
func updateNSView(_ view: AnchorView, context: Context) {
|
||||
view.configure(presented: isPresented, detail: AnyView(detail.environment(\.locale, locale)), onHover: onHover, onDismiss: onDismiss)
|
||||
}
|
||||
static func dismantleNSView(_ view: AnchorView, coordinator: ()) { view.detach() }
|
||||
|
||||
final class AnchorView: NSView {
|
||||
override func hitTest(_ point: NSPoint) -> NSView? { nil }
|
||||
private var panel: DetailPanel?
|
||||
private var host: NSHostingView<AnyView>?
|
||||
private var tokens: [NSObjectProtocol] = []
|
||||
private var presented = false
|
||||
private var detail = AnyView(EmptyView())
|
||||
private var onHover: (Bool) -> Void = { _ in }
|
||||
private var onDismiss: () -> Void = {}
|
||||
|
||||
func configure(presented: Bool, detail: AnyView,
|
||||
onHover: @escaping (Bool) -> Void, onDismiss: @escaping () -> Void) {
|
||||
self.presented = presented
|
||||
self.detail = detail
|
||||
self.onHover = onHover
|
||||
self.onDismiss = onDismiss
|
||||
refresh()
|
||||
}
|
||||
|
||||
override func viewDidMoveToWindow() {
|
||||
super.viewDidMoveToWindow()
|
||||
detach()
|
||||
guard let window else { return }
|
||||
for name in [NSWindow.willCloseNotification, NSWindow.didChangeOcclusionStateNotification] {
|
||||
tokens.append(NotificationCenter.default.addObserver(forName: name, object: window, queue: .main) { [weak self, weak window] notification in
|
||||
MainActor.assumeIsolated {
|
||||
guard notification.name == NSWindow.willCloseNotification || window?.occlusionState.contains(.visible) != true else { return }
|
||||
self?.hide()
|
||||
let dismiss = self?.onDismiss
|
||||
DispatchQueue.main.async { dismiss?() }
|
||||
}
|
||||
})
|
||||
}
|
||||
refresh()
|
||||
}
|
||||
|
||||
func detach() {
|
||||
hide()
|
||||
for token in tokens { NotificationCenter.default.removeObserver(token) }
|
||||
tokens.removeAll()
|
||||
}
|
||||
|
||||
private func refresh() {
|
||||
guard presented, let parent = window, parent.isVisible, let screen = parent.screen else { hide(); return }
|
||||
let content = AnyView(detail
|
||||
.font(.caption)
|
||||
.padding(12)
|
||||
.frame(width: 280)
|
||||
.fixedSize(horizontal: false, vertical: true)
|
||||
.background(Color("PanelCard"), in: .rect(cornerRadius: 12))
|
||||
.overlay(RoundedRectangle(cornerRadius: 12).strokeBorder(.primary.opacity(0.14)))
|
||||
.onHover { [weak self] inside in self?.onHover(inside) })
|
||||
if panel == nil {
|
||||
let panel = DetailPanel(contentRect: .zero, styleMask: [.borderless, .nonactivatingPanel], backing: .buffered, defer: false)
|
||||
panel.isReleasedWhenClosed = false
|
||||
panel.isOpaque = false
|
||||
panel.backgroundColor = .clear
|
||||
panel.hasShadow = false
|
||||
panel.animationBehavior = .none
|
||||
panel.hidesOnDeactivate = false
|
||||
panel.level = parent.level
|
||||
let host = NSHostingView(rootView: content)
|
||||
panel.contentView = host
|
||||
self.panel = panel
|
||||
self.host = host
|
||||
parent.addChildWindow(panel, ordered: .above)
|
||||
}
|
||||
guard let panel, let host else { return }
|
||||
host.rootView = content
|
||||
panel.appearance = parent.appearance
|
||||
let row = parent.convertToScreen(convert(bounds, to: nil))
|
||||
let size = host.fittingSize
|
||||
panel.setFrame(DetailPlacement.frame(anchor: row, parent: parent.frame,
|
||||
content: CGSize(width: 280, height: max(40, size.height)),
|
||||
visible: screen.visibleFrame), display: true)
|
||||
panel.orderFront(nil)
|
||||
}
|
||||
|
||||
private func hide() {
|
||||
guard let panel else { return }
|
||||
panel.parent?.removeChildWindow(panel)
|
||||
panel.orderOut(nil)
|
||||
panel.contentView = nil
|
||||
panel.close()
|
||||
host = nil
|
||||
self.panel = nil
|
||||
}
|
||||
|
||||
deinit { for token in tokens { NotificationCenter.default.removeObserver(token) } }
|
||||
}
|
||||
|
||||
final class DetailPanel: NSPanel {
|
||||
override var canBecomeKey: Bool { false }
|
||||
override var canBecomeMain: Bool { false }
|
||||
}
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
import SwiftUI
|
||||
|
||||
/// A bounded percentage gauge; missing data keeps an empty track and an explicit -- label.
|
||||
struct MetricRingGauge: View {
|
||||
let title: LocalizedStringKey
|
||||
let value: Double?
|
||||
let color: Color
|
||||
|
||||
private var fraction: Double { value.flatMap { $0.isFinite ? min(1, max(0, $0)) : nil } ?? 0 }
|
||||
|
||||
var body: some View {
|
||||
VStack(spacing: 3) {
|
||||
ZStack {
|
||||
NativeMetricRing(value: fraction, color: color, lineWidth: 3, trackOpacity: 0.17, inset: 2)
|
||||
MetricText(value: MetricFormat.percent(value)).font(.system(size: 8, weight: .semibold))
|
||||
.lineLimit(1).minimumScaleFactor(0.6).frame(width: 18, height: 12)
|
||||
}.frame(width: 28, height: 28).accessibilityHidden(true)
|
||||
Text(title).font(.system(size: 8)).foregroundStyle(.secondary)
|
||||
.lineLimit(1).minimumScaleFactor(0.7)
|
||||
}
|
||||
.frame(maxWidth: .infinity)
|
||||
.accessibilityElement(children: .ignore)
|
||||
.accessibilityLabel(Text(title))
|
||||
.accessibilityValue(Text(verbatim: MetricFormat.percent(value)))
|
||||
}
|
||||
}
|
||||
@@ -1,59 +0,0 @@
|
||||
import SwiftUI
|
||||
|
||||
struct MetricRow<Detail: View>: View {
|
||||
let title: LocalizedStringKey
|
||||
let symbol: String
|
||||
let value: String
|
||||
let usage: Double?
|
||||
let history: [Double?]
|
||||
let accent: Color
|
||||
@ViewBuilder let detail: () -> Detail
|
||||
@State private var visible = false
|
||||
@State private var rowHovered = false
|
||||
@State private var detailHovered = false
|
||||
@State private var expanded = false
|
||||
private var inside: Bool { rowHovered || detailHovered }
|
||||
|
||||
private var color: Color {
|
||||
guard let usage else { return .secondary }
|
||||
return usage > 0.95 ? .red : usage >= 0.8 ? .orange : accent
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
Button { expanded.toggle() } label: {
|
||||
HStack(spacing: 10) {
|
||||
Image(systemName: symbol)
|
||||
.font(.system(size: 13, weight: .medium))
|
||||
.foregroundStyle(color)
|
||||
.frame(width: 20)
|
||||
Text(title).font(.system(size: 13, weight: .medium))
|
||||
.frame(width: 52, alignment: .leading)
|
||||
MiniTrendChart(values: history, color: color).frame(height: 24)
|
||||
Text(verbatim: value)
|
||||
.font(.system(size: 13, weight: .semibold, design: .rounded))
|
||||
.monospacedDigit()
|
||||
.frame(width: 46, alignment: .trailing)
|
||||
}
|
||||
.contentShape(Rectangle())
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.accessibilityLabel(Text(title))
|
||||
.accessibilityValue(Text(verbatim: value))
|
||||
.accessibilityHint(expanded ? Text("detail.expanded") : Text("detail.collapsed"))
|
||||
.padding(10)
|
||||
.background(expanded ? Color.primary.opacity(0.035) : .clear, in: .rect(cornerRadius: 14))
|
||||
.background(HoverDetailPresenter(isPresented: expanded && visible, detail: detail(),
|
||||
onHover: { detailHovered = $0 },
|
||||
onDismiss: { expanded = false; detailHovered = false }))
|
||||
.onHover { rowHovered = $0 }
|
||||
.task(id: inside) {
|
||||
do { try await Task.sleep(for: .milliseconds(inside ? 150 : 120)) }
|
||||
catch { return }
|
||||
guard !Task.isCancelled else { return }
|
||||
expanded = inside
|
||||
}
|
||||
.onAppear { visible = true }
|
||||
.onDisappear { visible = false; rowHovered = false; detailHovered = false; expanded = false }
|
||||
.transaction { $0.animation = nil; $0.disablesAnimations = true }
|
||||
}
|
||||
}
|
||||
@@ -1,91 +0,0 @@
|
||||
import AppKit
|
||||
import SwiftUI
|
||||
|
||||
/// Static arc geometry; sampling publishes the final value directly.
|
||||
struct NativeMetricRing: NSViewRepresentable {
|
||||
let value: Double
|
||||
let color: Color
|
||||
let lineWidth: CGFloat
|
||||
let trackOpacity: Double
|
||||
let inset: CGFloat
|
||||
|
||||
func sizeThatFits(_ proposal: ProposedViewSize, nsView: RingView, context: Context) -> CGSize? {
|
||||
CGSize(width: proposal.width.flatMap { $0.isFinite ? $0 : nil } ?? 10,
|
||||
height: proposal.height.flatMap { $0.isFinite ? $0 : nil } ?? 10)
|
||||
}
|
||||
func makeNSView(context: Context) -> RingView { RingView() }
|
||||
func updateNSView(_ view: RingView, context: Context) {
|
||||
view.configure(Input(value: value.isFinite ? min(1, max(0, value)) : 0, color: color,
|
||||
lineWidth: lineWidth, trackOpacity: trackOpacity, inset: inset))
|
||||
}
|
||||
struct Input: Equatable {
|
||||
let value: Double
|
||||
let color: Color
|
||||
let lineWidth: CGFloat
|
||||
let trackOpacity: Double
|
||||
let inset: CGFloat
|
||||
}
|
||||
final class RingView: NSView {
|
||||
private(set) var input: Input?
|
||||
let track = CAShapeLayer()
|
||||
let arc = CAShapeLayer()
|
||||
override var isFlipped: Bool { true }
|
||||
override func hitTest(_ point: NSPoint) -> NSView? { nil }
|
||||
init() {
|
||||
super.init(frame: .zero)
|
||||
wantsLayer = true
|
||||
for shape in [track, arc] {
|
||||
shape.fillColor = nil; shape.lineCap = .round
|
||||
layer?.addSublayer(shape)
|
||||
}
|
||||
setAccessibilityElement(false)
|
||||
}
|
||||
required init?(coder: NSCoder) { nil }
|
||||
func configure(_ value: Input) {
|
||||
guard value != input else { return }
|
||||
let old = input
|
||||
input = value
|
||||
CATransaction.begin(); CATransaction.setDisableActions(true)
|
||||
if old?.color != value.color || old?.trackOpacity != value.trackOpacity { updateColors() }
|
||||
if old?.inset != value.inset || old?.lineWidth != value.lineWidth { updateGeometry() }
|
||||
arc.strokeEnd = value.value
|
||||
CATransaction.commit()
|
||||
}
|
||||
private func updateColors() {
|
||||
guard let input else { return }
|
||||
effectiveAppearance.performAsCurrentDrawingAppearance {
|
||||
let color = NSColor(input.color)
|
||||
track.strokeColor = color.withAlphaComponent(input.trackOpacity).cgColor
|
||||
arc.strokeColor = color.cgColor
|
||||
}
|
||||
}
|
||||
private func updateGeometry() {
|
||||
guard let input else { return }
|
||||
let radius = max(0, min(bounds.width, bounds.height) / 2 - input.inset)
|
||||
let path = CGMutablePath()
|
||||
path.addArc(center: CGPoint(x: bounds.midX, y: bounds.midY), radius: radius,
|
||||
startAngle: -.pi / 2, endAngle: 3 * .pi / 2, clockwise: false)
|
||||
for shape in [track, arc] {
|
||||
shape.frame = bounds; shape.path = path; shape.lineWidth = input.lineWidth
|
||||
}
|
||||
}
|
||||
override func setFrameSize(_ size: NSSize) {
|
||||
let changed = frame.size != size
|
||||
super.setFrameSize(size)
|
||||
if changed {
|
||||
CATransaction.begin(); CATransaction.setDisableActions(true)
|
||||
updateGeometry(); CATransaction.commit()
|
||||
}
|
||||
}
|
||||
override func viewDidMoveToWindow() {
|
||||
super.viewDidMoveToWindow()
|
||||
CATransaction.begin(); CATransaction.setDisableActions(true)
|
||||
updateColors(); CATransaction.commit()
|
||||
}
|
||||
override func viewDidChangeEffectiveAppearance() {
|
||||
super.viewDidChangeEffectiveAppearance()
|
||||
CATransaction.begin(); CATransaction.setDisableActions(true)
|
||||
updateColors(); CATransaction.commit()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,6 @@ import SwiftUI
|
||||
/// Shared roles for the compact monitoring panel. Micro charts keep their own 8pt role.
|
||||
enum PanelStyle {
|
||||
static let title = Font.system(size: 13, weight: .semibold)
|
||||
static let section = Font.system(size: 11, weight: .semibold)
|
||||
static let label = Font.system(size: 10)
|
||||
static let value = Font.system(size: 10, weight: .medium)
|
||||
static let legend = Font.system(size: 9)
|
||||
@@ -88,19 +87,3 @@ struct CapacityField: View {
|
||||
.lineLimit(1)
|
||||
}
|
||||
}
|
||||
|
||||
struct CardSectionHeader: View {
|
||||
let title: LocalizedStringKey
|
||||
let valueLabel: LocalizedStringKey
|
||||
let value: String
|
||||
let color: Color
|
||||
|
||||
var body: some View {
|
||||
HStack {
|
||||
Text(title).font(PanelStyle.section)
|
||||
Spacer(minLength: 4)
|
||||
Text(valueLabel).font(PanelStyle.label).foregroundStyle(.secondary)
|
||||
MetricText(value: value).font(PanelStyle.value).foregroundStyle(color)
|
||||
}.frame(height: 16)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
# 可复用界面
|
||||
|
||||
模块职责统一见[架构](../../docs/architecture.md)。
|
||||
Reference in New Issue
Block a user