import SwiftUI import AppKit struct MenuPanelView: View { let metrics: MetricsStore let preferences: AppearancePreferences let keepAwake: KeepAwakeService let updates: ReleaseUpdates 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 = "" @State var publicIPAddress: String? @State var showVolumes = false @State private var processState = ProcessTableState() var snapshot: MetricsSnapshot { metrics.snapshot } var samples: [TrendSample] { metrics.history.samples } var chartIntervals: [TimeInterval] { samples.map(\.expectedInterval) } var chartInterval: TimeInterval { Double(metrics.effectiveMilliseconds) / 1000 } var chartBoundaries: Set { Set(samples.filter(\.breakBefore).map(\.date)) } @State private var reservedFanCount = 0 @State private var measuredCardWidth: CGFloat? var displayedFans: [FanMetrics] { let fans = snapshot.fans ?? [] guard fans.count < reservedFanCount else { return fans } let missingIDs = (0.. 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 } } func total(_ key: KeyPath) -> Double? { let rates = network.compactMap { $0[keyPath: key] } return !network.isEmpty && rates.count == network.count ? rates.reduce(0, +) : nil } var body: some View { VStack(spacing: PanelStyle.gap) { header if PanelLayout.needsDashboardScroll(size: panelSize, heights: cardHeights) { ScrollView { dashboard } .frame(maxWidth: .infinity, maxHeight: .infinity) } else { dashboard.frame(maxHeight: .infinity, alignment: .top) } footer } .padding(PanelStyle.padding) .frame(width: panelSize.width, height: panelSize.height) .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 } .onChange(of: snapshot.fans?.count) { _, count in reservedFanCount = max(reservedFanCount, count ?? 0) } .onChange(of: snapshot.network?.map(\.identity)) { _, keys in if !selectedInterface.isEmpty && !(keys ?? []).contains(selectedInterface) { selectedInterface = "" } } .background(Color("PanelBackground"), in: .rect(cornerRadius: 18)) .clipShape(.rect(cornerRadius: 18)) .transaction { $0.animation = nil } .environment(\.panelMotionActive, metrics.isPanelVisible && !metrics.isPaused && !metrics.isSystemSleeping && !metrics.isDisplaySleeping) .modifier(AppearanceStyle(preferences: preferences)) } private var dashboard: some View { VStack(spacing: PanelStyle.gap) { resourceGrid if presentation.isOpen { PanelProcessSection(metrics: metrics, state: processState) .frame(maxWidth: .infinity) .frame(height: PanelLayout.processHeight(heights: cardHeights)) } } } private var resourceGrid: some View { let rows = PanelLayout.cardRows(columns: columns) let heights = PanelLayout.rowHeights(columns: columns, heights: cardHeights) return VStack(spacing: PanelStyle.gap) { ForEach(rows.indices, id: \.self) { row in HStack(alignment: .top, spacing: PanelStyle.gap) { ForEach(rows[row], id: \.self) { card in resourceCard(card) .frame(maxWidth: .infinity) .frame(height: heights[row]) .onGeometryChange(for: CGFloat.self) { $0.size.width } action: { width in if card == .cpu { measuredCardWidth = width } } } } .frame(maxWidth: .infinity, alignment: .top) } } } @ViewBuilder private func resourceCard(_ card: PanelCard) -> some View { switch card { case .cpu: cpuCard case .battery: batteryCard case .gpu: gpuCard case .storage: diskCard case .memory: memoryCard case .network: networkCard } } private static let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String private var brand: some View { HStack(spacing: 6) { Image("BrandMark").renderingMode(.template).resizable().scaledToFit() .frame(width: 22, height: 22) HStack(alignment: .top, spacing: 3) { Text("Kymo").font(.system(size: 17, weight: .semibold)) if updates.version != nil { UpdateAction(phase: updates.phase, version: updates.version, compact: true, action: updates.performAction) .buttonStyle(.plain) .font(.system(size: 10, weight: .semibold)) .foregroundStyle(Color.accentColor) .padding(.horizontal, 5).padding(.vertical, 2) .background(Color.accentColor.opacity(0.12), in: Capsule()) .offset(y: -2) } else if let version = Self.version { Text(verbatim: "v" + version) .font(.system(size: 9, weight: .semibold)).monospacedDigit() .padding(.horizontal, 5).padding(.vertical, 1) .background(.primary.opacity(0.09), in: Capsule()) .offset(y: -2) .accessibilityLabel(Text("about.version \(version)")) } }.fixedSize() } } private var header: some View { HStack(spacing: 8) { brand Spacer(minLength: 8) controls } .frame(height: PanelLayout.headerHeight(width: panelSize.width)) .padding(.horizontal, 4) } private var footer: some View { HStack { HStack(spacing: 4) { Text("panel.uptime") let hours = (snapshot.uptime / 3600).formatted(.number.precision(.fractionLength(1)).grouping(.never).locale(locale)) Text("duration.hours \(hours)").monospacedDigit() }.fixedSize() Divider().frame(height: 14) Text(verbatim: HardwareIdentity.displayName) .lineLimit(1).truncationMode(.middle) .help(Text(verbatim: HardwareIdentity.displayName)) Spacer(minLength: 8) HStack(spacing: 4) { Image(systemName: "timer").help(Text("sampling.panel")) IntervalControl(milliseconds: Binding(get: { metrics.sampling.panelMilliseconds }, set: { metrics.sampling.panelMilliseconds = $0 }), fieldWidth: 50) } .foregroundStyle(.primary) .accessibilityLabel(Text("sampling.panel")) } .font(PanelStyle.label).foregroundStyle(.secondary) .frame(height: PanelLayout.footerHeight).padding(.horizontal, 4) } private var controls: some View { HStack(spacing: 8) { HStack(spacing: 2) { Button { presentation.isPinned.toggle() } label: { Image(systemName: presentation.isPinned ? "pin.fill" : "pin") .frame(width: 20, height: 20) .foregroundStyle(presentation.isPinned ? Color.blue : 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) .foregroundStyle(keepAwake.isEnabled ? Color.blue : Color.primary) } .help(keepAwake.didFail ? Text("awake.failed") : (keepAwake.isEnabled ? Text("awake.disable") : Text("awake.enable"))) .accessibilityLabel(keepAwake.isEnabled ? Text("awake.disable") : Text("awake.enable")) .accessibilityValue(keepAwake.isEnabled ? Text("awake.on") : Text("awake.off")) 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(action: onOpenSettings) { Image(systemName: "gearshape").frame(width: 20, height: 20) } .help(Text("action.settings")).accessibilityLabel(Text("action.settings")) Divider().frame(height: 18).padding(.horizontal, 3) Button { NSApp.terminate(nil) } label: { Image(systemName: "power").frame(width: 20, height: 20) } .help(Text("action.quit")).accessibilityLabel(Text("action.quit")) } .buttonStyle(PanelControlButtonStyle()) .padding(4) .background(.primary.opacity(0.04), in: .capsule) } .controlSize(.small) .padding(.horizontal, 2).padding(.vertical, 0) } } private struct PanelControlButtonStyle: ButtonStyle { func makeBody(configuration: Configuration) -> some View { PanelControlButtonBody(isPressed: configuration.isPressed) { configuration.label } } } private struct PanelControlButtonBody: View { let isPressed: Bool @ViewBuilder var content: () -> Content @State private var isHovered = false var body: some View { content() .frame(width: 26, height: 24) .background { Circle().fill(.primary.opacity(isPressed ? 0.16 : (isHovered ? 0.08 : 0))) } .contentShape(Circle()) .onHover { isHovered = $0 } } } /// Keep process publications out of the resource-card observation scope. private struct PanelProcessSection: View { let metrics: MetricsStore let state: ProcessTableState var body: some View { ProcessTableView(snapshot: metrics.processSnapshot, energy: metrics.energy, state: state) } }