feat(menubar): 实现紧凑独立双列与按内容定高

This commit is contained in:
2026-11-08 18:47:01 +08:00
parent 8821089872
commit 8d3891966a
22 changed files with 259 additions and 128 deletions
+5 -6
View File
@@ -1,6 +1,6 @@
import SwiftUI
/// Keep cores in two balanced rows when they fit, otherwise use at most three.
/// Keep two balanced rows when possible; add rows to preserve readable core values.
struct CPUCoreGrid: View {
let values: [Double]
let kinds: [Int: CPUCoreTopology.Kind]
@@ -66,7 +66,7 @@ struct CPUCoreGrid: View {
}
}
.frame(height: 15 + CGFloat(maxRows(groups: groups)) * 22 + CGFloat(max(0, maxRows(groups: groups) - 1)) * 4)
.padding(.vertical, 4)
.padding(.vertical, 1)
}
// Match the content width so row reservation agrees with placement.
@@ -102,10 +102,9 @@ struct CPUCoreGridLayout: Layout {
static func rowCounts(count: Int, width: CGFloat) -> [Int] {
guard count > 0 else { return [] }
guard count > 1 else { return [1] }
let twoColumns = (count + 1) / 2
let availableForCells = width - CGFloat(twoColumns - 1) * columnSpacing
let twoRowCellWidth = availableForCells / CGFloat(twoColumns)
let rows = count > 2 && twoRowCellWidth < minimumTwoRowCellWidth ? 3 : 2
let usableWidth = width.isFinite ? max(0, width) : 0
let capacity = max(1, Int(min(CGFloat(count), (usableWidth + columnSpacing) / (minimumTwoRowCellWidth + columnSpacing))))
let rows = max(2, (count + capacity - 1) / capacity)
let quotient = count / rows, remainder = count % rows
return (0..<rows).map { quotient + ($0 < remainder ? 1 : 0) }
}
@@ -9,8 +9,6 @@ struct MemoryDetailsView: View {
var body: some View {
VStack(alignment: .leading, spacing: 4) {
CardSeparator()
CardSectionHeader(title: "memory.distribution", valueLabel: "gpu.totalUtilization",
value: MetricFormat.percent(memory.usage), color: Color("MemoryApplication"))
CapacityBar(values: values.map { Double($0) }, colors: colors, total: Double(memory.total))
HStack(spacing: 4) {
ForEach(0..<4) { index in
@@ -30,6 +28,8 @@ struct MemoryDetailsView: View {
}
}.font(PanelStyle.label).lineLimit(1)
}
.accessibilityElement(children: .contain)
.accessibilityLabel(Text("memory.distribution"))
}
@ViewBuilder private var pressure: some View {
@@ -30,6 +30,7 @@ enum PanelPage: Hashable { case overview, processes }
private let openSettings: () -> Void
private var showingStatusMenu = false
private var isHiding = false
private var preferredContentHeight = PanelLayout.defaultHeight
init<Content: View>(installStatusItem: Bool = true, visibility: @escaping (Bool) -> Void,
pageChanged: @escaping (PanelPage) -> Void = { _ in },
@@ -168,9 +169,22 @@ enum PanelPage: Hashable { case overview, processes }
visibilityObservation = nil
}
func setPreferredContentHeight(_ height: CGFloat) {
guard height.isFinite, height > 0 else { return }
let height = min(PanelLayout.maximumHeight, max(360, height))
guard preferredContentHeight != height else { return }
preferredContentHeight = height
#if DEBUG || KYMO_AUDIT
// An explicit diagnostic viewport must not be overridden by automatic sizing.
if ProcessInfo.processInfo.environment["KYMO_AUDIT_INTERACTIVE"] == "1",
ProcessInfo.processInfo.environment["KYMO_AUDIT_SIZE"] != nil { return }
#endif
if presentation.isOpen { place() }
}
private func place() {
guard let screen = statusItem?.button?.window?.screen ?? panel.screen ?? NSScreen.main else { return }
let size = PanelLayout.contentSize(visible: screen.visibleFrame)
let size = PanelLayout.contentSize(visible: screen.visibleFrame, preferredHeight: preferredContentHeight)
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)
@@ -24,8 +24,8 @@ extension MenuPanelView {
symbol: "arrow.up", color: Color("SeriesUpload"))
Divider().frame(height: 32)
VStack(alignment: .leading, spacing: 4) {
HStack {
Text("network.status").foregroundStyle(.secondary)
HStack(spacing: 4) {
Circle().fill(networkStatusColor).frame(width: 5, height: 5)
Picker("panel.interface", selection: $selectedInterface) {
Text("network.all").tag("")
ForEach(snapshot.network ?? [], id: \.identity) { item in
@@ -33,33 +33,29 @@ extension MenuPanelView {
}
}.labelsHidden().controlSize(.mini).fixedSize()
}
HStack(spacing: 4) {
Circle().fill(networkStatusColor).frame(width: 5, height: 5)
Text(networkStatusLabel)
}
Text(networkStatusLabel).help(Text(networkStatusLabel))
}.frame(maxWidth: .infinity, alignment: .leading)
}.font(PanelStyle.label).lineLimit(1)
CardSeparator()
VStack(alignment: .leading, spacing: 5) {
Text("network.addresses").font(PanelStyle.section)
HStack(spacing: 8) {
networkAddress("network.public", address: publicIPAddress)
Divider().frame(height: 15)
networkAddress(
"network.local",
address: addressInterface?.addresses.first(where: { !$0.contains(":") }) ?? addressInterface?.addresses.first)
}
HStack(spacing: 8) {
networkAddress("network.public", address: publicIPAddress)
Divider().frame(height: 15)
networkAddress(
"network.local",
address: addressInterface?.addresses.first(where: { !$0.contains(":") }) ?? addressInterface?.addresses.first)
}.font(PanelStyle.label)
.modifier(CardInset())
.accessibilityElement(children: .contain)
.accessibilityLabel(Text("network.addresses"))
}
.modifier(PanelPublicIPRefresh(metrics: metrics, address: $publicIPAddress))
}
func networkAddress(_ title: LocalizedStringKey, address: String?) -> some View {
HStack(spacing: 4) {
HStack(spacing: 3) {
Text(title).foregroundStyle(.secondary)
Text(verbatim: address ?? "--").font(PanelStyle.value).monospacedDigit().textSelection(.enabled)
.help(Text(verbatim: address ?? "--"))
Spacer(minLength: 0)
.frame(maxWidth: .infinity, alignment: .leading)
if let address {
Button {
NSPasteboard.general.clearContents()
@@ -34,7 +34,6 @@ extension MenuPanelView {
boundaryDates: chartBoundaries, intervals: chartIntervals)
CardSeparator()
if let cpu = snapshot.cpu {
Spacer(minLength: 0)
CPUCoreGrid(
values: cpu.cores, kinds: CPUCoreTopology.cores, interval: chartInterval,
availableWidth: cardContentWidth)
@@ -57,18 +56,24 @@ extension MenuPanelView {
color: Color("MetricGPU"), secondColor: Color("MetricCPU"), thirdColor: Color("SeriesSystem"),
firstLabel: "gpu.totalUtilization", secondLabel: "gpu.renderer", thirdLabel: "gpu.tiler",
expectedInterval: chartInterval, boundaryDates: chartBoundaries, intervals: chartIntervals)
CardSeparator()
let fans = displayedFans
if !fans.isEmpty {
LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 10), count: min(2, fans.count)), spacing: 5) {
CardSeparator()
LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 10), count: min(2, fans.count)), spacing: 4) {
ForEach(fans) { fan in
FanSpeedIndicator(
title: fans.count == 2
? (fan.id == 0 ? Text("gpu.fanLeft") : Text("gpu.fanRight"))
: Text("gpu.fanNumber \(fan.id + 1)"), rpm: fan.rpm)
.frame(height: 16)
}
}
.modifier(CardInset())
} else if snapshot.fans == nil {
CardSeparator()
Text("metric.waiting").font(PanelStyle.label)
.frame(maxWidth: .infinity, alignment: .leading).frame(height: 16)
.modifier(CardInset())
}
}
}
@@ -78,7 +83,8 @@ extension MenuPanelView {
title: "metric.memory", symbol: "memorychip", color: Color("MemoryApplication"),
value: snapshot.memory.map {
String(format: "%.1f / %.0f GiB", Double($0.used) / 1_073_741_824, Double($0.total) / 1_073_741_824)
} ?? "--"
} ?? "--",
status: snapshot.memory.map { MetricFormat.percent($0.usage) }
) {
PanelTrendChart(
dates: samples.map(\.date),
@@ -134,6 +140,7 @@ extension MenuPanelView {
Text("panel.apfsScope").font(.system(size: 9)).foregroundStyle(.secondary)
}
}.padding(12).frame(width: 330)
.environment(\.locale, locale)
}
}
@@ -163,7 +170,7 @@ extension MenuPanelView {
batteryDetails(battery)
} else {
Text(snapshot.batteryState == .absent ? "panel.noBattery" : "panel.batteryFailed").foregroundStyle(.secondary)
.frame(maxWidth: .infinity, maxHeight: .infinity)
.font(PanelStyle.label).frame(maxWidth: .infinity).frame(height: 32)
}
}
}
@@ -199,7 +206,7 @@ extension MenuPanelView {
.lineLimit(1)
.frame(height: 32)
}.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
}.frame(maxWidth: .infinity, alignment: .topLeading)
}
}
+35 -25
View File
@@ -8,6 +8,7 @@ struct MenuPanelView: View {
let settingsPresentation: SettingsPresentation
var presentation = PanelPresentation()
var onOpenSettings: () -> Void = {}
var onPreferredHeight: (CGFloat) -> Void = { _ in }
@Environment(\.locale) var locale
@State private var panelSize = PanelLayout.contentSize(visible: NSScreen.main?.visibleFrame ?? CGRect(x: 0, y: 0, width: 1000, height: 760))
@State var selectedInterface = ""
@@ -30,13 +31,15 @@ struct MenuPanelView: View {
}
var cardContentWidth: CGFloat { max(0, (measuredCardWidth ?? PanelLayout.cardWidth(size: panelSize)) - 20) }
var columns: Int { PanelLayout.columns(width: panelSize.width) }
private var rowHeights: [CGFloat] {
let groups = CPUCoreGrid.groups(count: snapshot.cpu?.cores.count ?? 0, kinds: CPUCoreTopology.cores)
let widths = CPUCoreGrid.groupWidths(groups: groups, width: max(0, (measuredCardWidth ?? PanelLayout.cardWidth(size: panelSize)) - 20))
private var cardHeights: [PanelCard: CGFloat] {
let coreCount = max(CPUCoreTopology.cores.count, ProcessInfo.processInfo.processorCount, snapshot.cpu?.cores.count ?? 0)
let groups = CPUCoreGrid.groups(count: coreCount, kinds: CPUCoreTopology.cores)
let widths = CPUCoreGrid.groupWidths(groups: groups, width: cardContentWidth)
let coreRows = zip(groups, widths).map { CPUCoreGridLayout.rowCounts(count: $0.0.count, width: $0.1).count }.max() ?? 0
return PanelLayout.rowHeights(columns: columns, coreRows: coreRows,
fanCount: max(reservedFanCount, snapshot.fans?.count ?? 0))
let fanCount = reservedFanCount > 0 ? max(reservedFanCount, snapshot.fans?.count ?? 0) : snapshot.fans?.count
return PanelLayout.cardHeights(coreRows: coreRows, fanCount: fanCount)
}
private var preferredHeight: CGFloat { PanelLayout.preferredHeight(width: panelSize.width, heights: cardHeights) }
var network: [NetworkInterfaceMetrics] {
(snapshot.network ?? []).filter { selectedInterface.isEmpty ? $0.isIncludedInTotal : $0.identity == selectedInterface }
}
@@ -49,11 +52,11 @@ struct MenuPanelView: View {
VStack(spacing: PanelStyle.gap) {
if PanelResourceAudit.omitted != "header" { header }
if presentation.page == .overview {
if PanelLayout.needsResourceScroll(size: panelSize, rows: rowHeights) {
ScrollView { resourceRows }
if PanelLayout.needsResourceScroll(size: panelSize, heights: cardHeights) {
ScrollView { resourceColumns }
.frame(maxWidth: .infinity, maxHeight: .infinity)
} else {
resourceRows
resourceColumns
.frame(maxHeight: .infinity, alignment: .top)
}
} else if presentation.isOpen && PanelResourceAudit.omitted != "processes" {
@@ -67,6 +70,12 @@ struct MenuPanelView: View {
.background(PanelWindowObserver { size in
if panelSize != size { panelSize = size }
}.frame(width: 0, height: 0))
.task(id: preferredHeight) {
// Resize only for structural changes, outside the current layout pass.
await Task.yield()
guard !Task.isCancelled else { return }
onPreferredHeight(preferredHeight)
}
.onAppear {
reservedFanCount = snapshot.fans?.count ?? 0
}
@@ -82,35 +91,36 @@ struct MenuPanelView: View {
.modifier(AppearanceStyle(preferences: preferences))
}
private var resourceRows: some View {
VStack(spacing: PanelStyle.gap) {
ForEach(rowHeights.indices, id: \.self) { row in
HStack(spacing: PanelStyle.gap) {
ForEach(0..<columns, id: \.self) { column in
resourceCard(at: row * columns + column)
private var resourceColumns: some View {
let groups = PanelLayout.cardColumns(columns: columns)
return HStack(alignment: .top, spacing: PanelStyle.gap) {
ForEach(groups.indices, id: \.self) { column in
VStack(spacing: PanelStyle.gap) {
ForEach(groups[column], id: \.self) { card in
resourceCard(card)
.frame(maxWidth: .infinity)
.frame(height: rowHeights[row])
.frame(height: cardHeights[card])
.onGeometryChange(for: CGFloat.self) { $0.size.width } action: { width in
if row == 0 && column == 0 { measuredCardWidth = width }
if card == .cpu { measuredCardWidth = width }
}
}
}
.frame(maxWidth: .infinity, alignment: .top)
}
}
}
@ViewBuilder private func resourceCard(at index: Int) -> some View {
@ViewBuilder private func resourceCard(_ card: PanelCard) -> some View {
if PanelResourceAudit.omitted == "resources" {
Color.clear
} else {
switch index {
case 0: cpuCard
case 1: batteryCard
case 2: gpuCard
case 3: diskCard
case 4: memoryCard
case 5: networkCard
default: EmptyView()
switch card {
case .cpu: cpuCard
case .battery: batteryCard
case .gpu: gpuCard
case .storage: diskCard
case .memory: memoryCard
case .network: networkCard
}
}
}
+44 -19
View File
@@ -1,36 +1,61 @@
import Foundation
import CoreGraphics
nonisolated enum PanelCard: Int, CaseIterable {
case cpu, battery, gpu, storage, memory, network
}
nonisolated enum PanelLayout {
static let baseCardHeight: CGFloat = 204
static let footerHeight: CGFloat = 26
static let maximumHeight: CGFloat = 800
static func headerHeight(width: CGFloat) -> CGFloat { width >= 560 ? 32 : 64 }
static func columns(width: CGFloat) -> Int { width >= 560 ? 2 : 1 }
static func cardWidth(size: CGSize) -> CGFloat {
let count = columns(width: size.width)
return max(0, (size.width - 20 - CGFloat(count - 1) * 8) / CGFloat(count))
}
/// Physical order: CPU/battery, GPU/storage, memory/network.
static func rowHeights(columns: Int, coreRows: Int, fanCount: Int) -> [CGFloat] {
let cpu: CGFloat = 220 + CGFloat(max(0, coreRows - 2)) * 26
let gpu = baseCardHeight + CGFloat(max(0, (fanCount + 1) / 2 - 1)) * 26
let heights = [cpu, baseCardHeight, gpu, baseCardHeight, 260, 260]
let count = max(1, min(2, columns))
return stride(from: 0, to: heights.count, by: count).map {
heights[$0..<min($0 + count, heights.count)].max() ?? baseCardHeight
}
}
static func resourceHeight(rows: [CGFloat]) -> CGFloat {
rows.reduce(0, +) + CGFloat(max(0, rows.count - 1)) * 8
}
static func needsResourceScroll(size: CGSize, rows: [CGFloat]) -> Bool {
// Outer padding, common toolbar/footer, and two gaps. Process page is separate.
resourceHeight(rows: rows) > size.height - 20 - headerHeight(width: size.width) - footerHeight - 16
/// Preserve location and order; never rebalance columns when values change.
static func cardColumns(columns: Int) -> [[PanelCard]] {
columns > 1 ? [[.cpu, .gpu, .memory], [.battery, .storage, .network]] : [PanelCard.allCases]
}
static func contentSize(visible: CGRect, chrome: CGSize = .zero) -> CGSize {
/// Fixed content rows with a 48pt plot. Nil fans reserve a discovery row.
static func cardHeights(coreRows: Int, fanCount: Int?) -> [PanelCard: CGFloat] {
let fanRows = fanCount.map { (max(0, $0) + 1) / 2 } ?? 1
return [.cpu: 152 + CGFloat(max(1, coreRows)) * 26,
.gpu: fanRows == 0 ? 124 : 144 + CGFloat(fanRows) * 20,
.memory: 228, .battery: 170, .storage: 170, .network: 208]
}
static func columnHeights(columns: Int, heights: [PanelCard: CGFloat]) -> [CGFloat] {
cardColumns(columns: columns).map { cards in
cards.reduce(0) { $0 + (heights[$1] ?? 0) } + CGFloat(max(0, cards.count - 1)) * 8
}
}
static func resourceHeight(columns: Int, heights: [PanelCard: CGFloat]) -> CGFloat {
columnHeights(columns: columns, heights: heights).max() ?? 0
}
static func preferredHeight(width: CGFloat, heights: [PanelCard: CGFloat]) -> CGFloat {
min(maximumHeight, resourceHeight(columns: columns(width: width), heights: heights)
+ 20 + headerHeight(width: width) + footerHeight + 16)
}
static var defaultHeight: CGFloat {
preferredHeight(width: 640, heights: cardHeights(coreRows: 2, fanCount: nil))
}
static func needsResourceScroll(size: CGSize, heights: [PanelCard: CGFloat]) -> Bool {
resourceHeight(columns: columns(width: size.width), heights: heights)
> size.height - 20 - headerHeight(width: size.width) - footerHeight - 16
}
static func contentSize(visible: CGRect, chrome: CGSize = .zero, preferredHeight: CGFloat? = nil) -> CGSize {
CGSize(width: max(1, min(640, visible.width - 32 - max(0, chrome.width))),
height: max(1, min(800, visible.height - 32 - max(0, chrome.height))))
height: max(1, min(maximumHeight, preferredHeight ?? defaultHeight,
visible.height - 32 - max(0, chrome.height))))
}
static func centeredFrame(_ frame: CGRect, visible: CGRect) -> CGRect {
var result = constrainedFrame(frame, visible: visible)
@@ -32,7 +32,7 @@ struct PanelWindowObserver: NSViewRepresentable {
let frame = (window.screen ?? NSScreen.main)?.visibleFrame ?? NSRect(x: 0, y: 0, width: 1000, height: 760)
let chrome = CGSize(width: max(0, window.frame.width - window.contentLayoutRect.width),
height: max(0, window.frame.height - window.contentLayoutRect.height))
let maximum = PanelLayout.contentSize(visible: frame, chrome: chrome)
let maximum = PanelLayout.contentSize(visible: frame, chrome: chrome, preferredHeight: PanelLayout.maximumHeight)
let size = CGSize(width: min(maximum.width, window.contentLayoutRect.width),
height: min(maximum.height, window.contentLayoutRect.height))
DispatchQueue.main.async { [weak self, weak window] in
+22 -16
View File
@@ -8,29 +8,35 @@ struct StorageDetailsView: View {
var body: some View {
VStack(alignment: .leading, spacing: 4) {
CardSeparator()
HStack(alignment: .top, spacing: 8) {
CardField(title: "memory.available") {
MetricText(value: MetricFormat.bytes(disk?.available))
HStack(spacing: 8) {
VStack(spacing: 4) {
field("memory.available", value: MetricFormat.bytes(disk?.available))
field("disk.powerOnHours", value: health?.powerOnHours.map { "\($0) h" } ?? "--")
}
Divider().frame(height: 32)
CardField(title: "disk.remainingLife") {
MetricText(value: MetricFormat.percent(health?.remainingLife))
}
Divider().frame(height: 32)
CardField(title: "disk.powerOnHours") {
MetricText(value: health?.powerOnHours.map { "\($0) h" } ?? "--")
}
Divider().frame(height: 32)
CardField(title: "disk.localVolumes") {
VStack(spacing: 4) {
field("disk.remainingLife", value: MetricFormat.percent(health?.remainingLife))
Button(action: showVolumes) {
HStack(spacing: 2) {
Text("disk.viewDetails")
HStack(spacing: 3) {
Text("disk.localVolumes")
Spacer(minLength: 3)
Image(systemName: "chevron.right").font(.system(size: 8))
}
}.buttonStyle(.plain)
}.contentShape(.rect)
}
.buttonStyle(.plain).help(Text("disk.viewDetails"))
.frame(height: 14)
}
}.font(PanelStyle.label).lineLimit(1)
}
}
private func field(_ title: LocalizedStringKey, value: String) -> some View {
HStack(spacing: 3) {
Text(title).foregroundStyle(.secondary).help(Text(title))
Spacer(minLength: 3)
MetricText(value: value).font(PanelStyle.value)
}
.frame(height: 14)
.frame(maxWidth: .infinity)
}
}