feat(menubar): 实现趋势面板外侧详情与三语外观设置
接入有界趋势、平滑滚动、菜单式外侧详情、底部操作与三语文案,装配独立外观设置和 Dock 生命周期。 合并跟随系统外观刷新、自选颜色入口与色块绘制修复,保留用户确认的配色联动、重启保存及滚动验收。 多场景视觉与长期资源验证边界仍记录于 docs。
This commit is contained in:
@@ -16,15 +16,11 @@ struct MenuBarLabel: View {
|
||||
}
|
||||
|
||||
private var title: String {
|
||||
var items = ["CPU \(percent(snapshot.cpu?.usage))"]
|
||||
var items = ["CPU \(MetricFormat.percent(snapshot.cpu?.usage))"]
|
||||
if let gpu = snapshot.gpuUsage {
|
||||
items.append("GPU \(percent(gpu))")
|
||||
items.append("GPU \(MetricFormat.percent(gpu))")
|
||||
}
|
||||
items.append("MEM \(percent(snapshot.memory?.usage))")
|
||||
items.append("MEM \(MetricFormat.percent(snapshot.memory?.usage))")
|
||||
return items.joined(separator: " · ")
|
||||
}
|
||||
|
||||
private func percent(_ value: Double?) -> String {
|
||||
value.map { "\(Int(($0 * 100).rounded()))%" } ?? "--"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,34 +1,115 @@
|
||||
//
|
||||
// MenuPanelView.swift
|
||||
// kymo
|
||||
//
|
||||
// Created by Airnan on 2026/10/29.
|
||||
//
|
||||
|
||||
import SwiftUI
|
||||
import AppKit
|
||||
|
||||
/// A 阶段临时面板:展示采样时间与暂停入口,正式面板在 B 阶段实现。
|
||||
struct MenuPanelView: View {
|
||||
let metrics: MetricsStore
|
||||
let preferences: AppearancePreferences
|
||||
@Environment(\.openSettings) private var openSettings
|
||||
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
Label("Kymo 资源监控", systemImage: "gauge")
|
||||
.font(.headline)
|
||||
|
||||
Text(metrics.snapshot.date, style: .time)
|
||||
Button(metrics.isPaused ? "继续监控" : "暂停监控") {
|
||||
metrics.togglePause()
|
||||
VStack(spacing: 4) {
|
||||
VStack(spacing: 2) {
|
||||
MetricRow(title: "metric.cpu", symbol: "cpu", value: MetricFormat.percent(metrics.snapshot.cpu?.usage),
|
||||
usage: metrics.snapshot.cpu?.usage, history: metrics.history.samples.map(\.cpu), accent: preferences.tintColor) {
|
||||
cpuDetail
|
||||
}
|
||||
MetricRow(title: "metric.gpu", symbol: "square.grid.2x2", value: MetricFormat.percent(metrics.snapshot.gpuUsage),
|
||||
usage: metrics.snapshot.gpuUsage, history: metrics.history.samples.map(\.gpu), accent: preferences.tintColor) {
|
||||
Text("gpu.unavailable").foregroundStyle(.secondary)
|
||||
}
|
||||
MetricRow(title: "metric.memory", symbol: "memorychip", value: MetricFormat.percent(metrics.snapshot.memory?.usage),
|
||||
usage: metrics.snapshot.memory?.usage, history: metrics.history.samples.map(\.memory), accent: preferences.tintColor) {
|
||||
memoryDetail
|
||||
}
|
||||
}
|
||||
Text("GPU 暂不可用")
|
||||
.font(.subheadline)
|
||||
.foregroundStyle(.secondary)
|
||||
Divider().padding(.horizontal, 10)
|
||||
HStack {
|
||||
Text("system.load")
|
||||
Text(verbatim: metrics.snapshot.load.map(MetricFormat.decimal).joined(separator: " / "))
|
||||
Spacer(minLength: 4)
|
||||
Image(systemName: "clock")
|
||||
Text(verbatim: String(format: "%.0fh", floor(metrics.snapshot.uptime / 3600)))
|
||||
}
|
||||
.font(.system(size: 10)).monospacedDigit().foregroundStyle(.secondary)
|
||||
.padding(.horizontal, 10).padding(.vertical, 8)
|
||||
footer
|
||||
}
|
||||
.padding(16)
|
||||
.frame(width: 280, alignment: .leading)
|
||||
.padding(10)
|
||||
.frame(width: 320)
|
||||
.modifier(AppearanceStyle(preferences: preferences))
|
||||
}
|
||||
|
||||
@ViewBuilder private var cpuDetail: some View {
|
||||
if let cpu = metrics.snapshot.cpu {
|
||||
VStack(alignment: .leading, spacing: 8) {
|
||||
detailLine("cpu.user", MetricFormat.percent(cpu.user))
|
||||
detailLine("cpu.system", MetricFormat.percent(cpu.system))
|
||||
LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 4), count: 7), spacing: 4) {
|
||||
ForEach(Array(cpu.cores.enumerated()), id: \.offset) { index, usage in
|
||||
RoundedRectangle(cornerRadius: 4)
|
||||
.fill(preferences.tintColor.opacity(0.12 + 0.88 * usage))
|
||||
.frame(height: 18)
|
||||
.overlay(Text(verbatim: "\(index + 1)").font(.system(size: 9)).foregroundStyle(.primary))
|
||||
.help(MetricFormat.percent(usage))
|
||||
.accessibilityLabel(Text("cpu.core"))
|
||||
.accessibilityValue(Text(verbatim: "\(index + 1): \(MetricFormat.percent(usage))"))
|
||||
}
|
||||
}
|
||||
}
|
||||
} else { Text("metric.waiting").foregroundStyle(.secondary) }
|
||||
}
|
||||
|
||||
@ViewBuilder private var memoryDetail: some View {
|
||||
if let memory = metrics.snapshot.memory {
|
||||
VStack(spacing: 6) {
|
||||
detailLine("memory.used", MetricFormat.bytes(memory.used))
|
||||
detailLine("memory.available", MetricFormat.bytes(memory.total - memory.used))
|
||||
detailLine("memory.app", MetricFormat.bytes(memory.used - min(memory.used, memory.wired + memory.compressed)))
|
||||
detailLine("memory.wired", MetricFormat.bytes(memory.wired))
|
||||
detailLine("memory.compressed", MetricFormat.bytes(memory.compressed))
|
||||
detailLine("memory.swap", MetricFormat.bytes(memory.swapUsed))
|
||||
HStack {
|
||||
Text("memory.pressure").foregroundStyle(.secondary)
|
||||
Spacer()
|
||||
switch memory.pressure {
|
||||
case 1: Text("pressure.normal")
|
||||
case 2: Text("pressure.warning").foregroundStyle(.orange)
|
||||
case 4: Text("pressure.critical").foregroundStyle(.red)
|
||||
default: Text(verbatim: "--")
|
||||
}
|
||||
}
|
||||
}
|
||||
} else { Text("metric.waiting").foregroundStyle(.secondary) }
|
||||
}
|
||||
|
||||
private func detailLine(_ key: LocalizedStringKey, _ value: String) -> some View {
|
||||
HStack { Text(key).foregroundStyle(.secondary); Spacer(); Text(verbatim: value).monospacedDigit() }
|
||||
}
|
||||
|
||||
private var footer: some View {
|
||||
HStack(spacing: 8) {
|
||||
VStack(alignment: .leading, spacing: 2) {
|
||||
Text(verbatim: "Kymo").font(.system(size: 12, weight: .semibold))
|
||||
Text(verbatim: "v\(Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "--")")
|
||||
.font(.system(size: 9)).foregroundStyle(.tertiary)
|
||||
}
|
||||
Spacer()
|
||||
Button { metrics.togglePause() } label: {
|
||||
Image(systemName: metrics.isPaused ? "play.fill" : "pause.fill").frame(width: 20, height: 20)
|
||||
}
|
||||
.help(metrics.isPaused ? Text("action.resume") : Text("action.pause"))
|
||||
.accessibilityLabel(metrics.isPaused ? Text("action.resume") : Text("action.pause"))
|
||||
Button { NSApp.activate(); openSettings() } label: {
|
||||
Image(systemName: "gearshape").frame(width: 20, height: 20)
|
||||
}
|
||||
.help(Text("action.settings")).accessibilityLabel(Text("action.settings"))
|
||||
Button { NSApp.terminate(nil) } label: {
|
||||
Image(systemName: "power").frame(width: 20, height: 20)
|
||||
}
|
||||
.help(Text("action.quit")).accessibilityLabel(Text("action.quit"))
|
||||
}
|
||||
.buttonStyle(.glass)
|
||||
.controlSize(.small)
|
||||
.padding(.horizontal, 8).padding(.vertical, 6)
|
||||
}
|
||||
}
|
||||
|
||||
#Preview {
|
||||
MenuPanelView(metrics: MetricsStore())
|
||||
}
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
import SwiftUI
|
||||
import AppKit
|
||||
|
||||
/// B-stage appearance controls; general/modules/permissions remain D-stage work.
|
||||
struct AppearanceSettingsView: View {
|
||||
@Bindable var preferences: AppearancePreferences
|
||||
@State private var colorPicker = CustomColorPicker()
|
||||
|
||||
var body: some View {
|
||||
Form {
|
||||
Section("settings.appearance") {
|
||||
Picker("appearance.title", selection: $preferences.appearance) {
|
||||
Text("appearance.system").tag(AppAppearance.system)
|
||||
Text("appearance.light").tag(AppAppearance.light)
|
||||
Text("appearance.dark").tag(AppAppearance.dark)
|
||||
}
|
||||
.pickerStyle(.segmented)
|
||||
Picker("accent.title", selection: $preferences.accent) {
|
||||
Text("accent.system").tag(AccentChoice.system)
|
||||
Text("accent.blue").tag(AccentChoice.blue)
|
||||
Text("accent.purple").tag(AccentChoice.purple)
|
||||
Text("accent.teal").tag(AccentChoice.teal)
|
||||
Text("accent.green").tag(AccentChoice.green)
|
||||
Text("accent.orange").tag(AccentChoice.orange)
|
||||
Text("accent.pink").tag(AccentChoice.pink)
|
||||
Text("accent.custom").tag(AccentChoice.custom)
|
||||
}
|
||||
if preferences.accent == .custom {
|
||||
HStack {
|
||||
Text("accent.custom")
|
||||
Spacer()
|
||||
CustomColorWell(preferences: preferences, picker: colorPicker)
|
||||
.frame(width: 44, height: 26)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
.background(SettingsWindowLifecycle(onClose: { colorPicker.close() }))
|
||||
.onChange(of: preferences.accent) { _, choice in
|
||||
if choice == .custom {
|
||||
Task { @MainActor in
|
||||
await Task.yield()
|
||||
guard preferences.accent == .custom else { return }
|
||||
colorPicker.show(for: preferences)
|
||||
}
|
||||
}
|
||||
else { colorPicker.close() }
|
||||
}
|
||||
.onAppear { NSApp.setActivationPolicy(.regular); NSApp.activate() }
|
||||
.formStyle(.grouped)
|
||||
.frame(width: 420, height: 240)
|
||||
.modifier(AppearanceStyle(preferences: preferences))
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import AppKit
|
||||
import OSLog
|
||||
|
||||
@MainActor final class CustomColorPicker: NSObject {
|
||||
private let logger = Logger(subsystem: "cn.airnan.kymo", category: "color-picker")
|
||||
private static weak var owner: CustomColorPicker?
|
||||
private var preferences: AppearancePreferences?
|
||||
|
||||
func show(for preferences: AppearancePreferences) {
|
||||
logger.info("Custom color panel requested")
|
||||
Self.owner = self
|
||||
self.preferences = preferences
|
||||
let panel = NSColorPanel.shared
|
||||
panel.appearance = preferences.appearance.windowAppearance
|
||||
panel.showsAlpha = false
|
||||
panel.isContinuous = true
|
||||
panel.color = NSColor(srgbRed: preferences.red, green: preferences.green,
|
||||
blue: preferences.blue, alpha: 1)
|
||||
panel.setTarget(self)
|
||||
panel.setAction(#selector(colorChanged(_:)))
|
||||
NSApp.activate()
|
||||
panel.level = .floating
|
||||
panel.makeKeyAndOrderFront(nil)
|
||||
panel.orderFrontRegardless()
|
||||
logger.info("Custom color panel visible: \(panel.isVisible, privacy: .public)")
|
||||
}
|
||||
|
||||
@objc private func colorChanged(_ sender: NSColorPanel) {
|
||||
guard let preferences, let rgb = sender.color.usingColorSpace(.sRGB) else { return }
|
||||
preferences.red = rgb.redComponent
|
||||
preferences.green = rgb.greenComponent
|
||||
preferences.blue = rgb.blueComponent
|
||||
}
|
||||
|
||||
func close() {
|
||||
guard Self.owner === self else { return }
|
||||
NSColorPanel.shared.setTarget(nil)
|
||||
NSColorPanel.shared.setAction(nil)
|
||||
NSColorPanel.shared.close()
|
||||
preferences = nil
|
||||
Self.owner = nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import SwiftUI
|
||||
import AppKit
|
||||
|
||||
/// A native hit target avoids Form/plain-Button hit-testing ambiguity on the swatch.
|
||||
struct CustomColorWell: NSViewRepresentable {
|
||||
let preferences: AppearancePreferences
|
||||
let picker: CustomColorPicker
|
||||
|
||||
func makeNSView(context: Context) -> SwatchButton {
|
||||
let button = SwatchButton()
|
||||
button.setAccessibilityLabel(String(localized: "accent.custom"))
|
||||
return button
|
||||
}
|
||||
|
||||
func updateNSView(_ button: SwatchButton, context: Context) {
|
||||
button.open = { picker.show(for: preferences) }
|
||||
button.swatchColor = NSColor(srgbRed: preferences.red, green: preferences.green, blue: preferences.blue, alpha: 1)
|
||||
}
|
||||
|
||||
func sizeThatFits(_ proposal: ProposedViewSize, nsView: SwatchButton, context: Context) -> CGSize? {
|
||||
CGSize(width: 44, height: 26)
|
||||
}
|
||||
|
||||
final class SwatchButton: NSButton {
|
||||
var swatchColor = NSColor.systemBlue { didSet { needsDisplay = true } }
|
||||
override var intrinsicContentSize: NSSize { NSSize(width: 44, height: 26) }
|
||||
|
||||
override func draw(_ dirtyRect: NSRect) {
|
||||
// Draw the actual RGB color inside bounds; no scalable SF Symbol/cell image.
|
||||
let shape = NSBezierPath(roundedRect: bounds.insetBy(dx: 4, dy: 4), xRadius: 4, yRadius: 4)
|
||||
(isHighlighted ? swatchColor.withAlphaComponent(0.7) : swatchColor).setFill()
|
||||
shape.fill()
|
||||
NSColor.separatorColor.setStroke()
|
||||
shape.lineWidth = 1
|
||||
shape.stroke()
|
||||
}
|
||||
|
||||
var open: () -> Void = {}
|
||||
override init(frame frameRect: NSRect) {
|
||||
super.init(frame: frameRect)
|
||||
bezelStyle = .rounded
|
||||
isBordered = false
|
||||
wantsLayer = true
|
||||
layer?.masksToBounds = true
|
||||
title = ""
|
||||
target = self
|
||||
action = #selector(openPicker)
|
||||
}
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true }
|
||||
@objc func openPicker() { open() }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import SwiftUI
|
||||
import AppKit
|
||||
|
||||
/// Keep the app discoverable while its settings window is open, including reopen.
|
||||
struct SettingsWindowLifecycle: NSViewRepresentable {
|
||||
var onClose: () -> Void = {}
|
||||
|
||||
func makeNSView(context: Context) -> WindowObserverView { WindowObserverView() }
|
||||
func updateNSView(_ nsView: WindowObserverView, context: Context) { nsView.onClose = onClose }
|
||||
|
||||
final class WindowObserverView: NSView {
|
||||
override func hitTest(_ point: NSPoint) -> NSView? { nil }
|
||||
var onClose: () -> Void = {}
|
||||
private var tokens: [NSObjectProtocol] = []
|
||||
|
||||
override func viewDidMoveToWindow() {
|
||||
super.viewDidMoveToWindow()
|
||||
for token in tokens { NotificationCenter.default.removeObserver(token) }
|
||||
tokens.removeAll()
|
||||
guard let window else { return }
|
||||
tokens.append(NotificationCenter.default.addObserver(forName: NSWindow.didBecomeKeyNotification,
|
||||
object: window, queue: .main) { _ in
|
||||
MainActor.assumeIsolated {
|
||||
if NSApp.activationPolicy() != .regular { NSApp.setActivationPolicy(.regular) }
|
||||
}
|
||||
})
|
||||
tokens.append(NotificationCenter.default.addObserver(forName: NSWindow.willCloseNotification,
|
||||
object: window, queue: .main) { [weak self] _ in
|
||||
MainActor.assumeIsolated {
|
||||
self?.onClose()
|
||||
NSApp.setActivationPolicy(.accessory)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
deinit { for token in tokens { NotificationCenter.default.removeObserver(token) } }
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user