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