feat(settings): 默认启用短动效并提供独立减弱动画选项

This commit is contained in:
2026-11-04 11:53:17 +08:00
parent 40a7a55edf
commit f18f6652ff
23 changed files with 443 additions and 34 deletions
+3 -1
View File
@@ -49,7 +49,9 @@ import AppKit
menuBar = MenuPanelController(visibility: { [metrics] in metrics.setPanelVisible($0) },
menuTitle: { [language] key in
AppLocalization.string("status." + key, locale: language.locale, table: "StatusItem")
}, openSettings: { [weak self] in self?.settingsCommand() }) { [self] panel in
}, openSettings: { [weak self] in self?.settingsCommand() }, reducedMotion: { [appearance] in
appearance.reduceMotion || PanelResourceAudit.enabled
}) { [self] panel in
if PanelResourceAudit.omitted == "text" {
TextMonitoringAuditView(metrics: self.metrics, appearance: self.appearance)
} else if PanelResourceAudit.omitted == "all" {
@@ -1,5 +1,6 @@
import Foundation
import Observation
import CoreFoundation
nonisolated enum AppAppearance: String, CaseIterable, Identifiable {
case system, light, dark
@@ -11,8 +12,26 @@ final class AppearancePreferences {
@ObservationIgnored private let defaults: UserDefaults
var appearance: AppAppearance { didSet { defaults.set(appearance.rawValue, forKey: "appearance") } }
var reduceMotion: Bool {
didSet { if reduceMotion != oldValue { defaults.set(reduceMotion, forKey: "appearance.reduceMotion") } }
}
init(defaults: UserDefaults = .standard) {
self.defaults = defaults
let value = defaults.object(forKey: "appearance.reduceMotion") as? NSNumber
if defaults.volatileDomain(forName: UserDefaults.argumentDomain)["appearance.reduceMotion"] != nil {
// Foundation represents launch overrides as strings; do not persist them.
reduceMotion = defaults.bool(forKey: "appearance.reduceMotion")
} else {
reduceMotion = value.map { CFGetTypeID($0) == CFBooleanGetTypeID() && $0.boolValue } ?? false
}
appearance = AppAppearance(rawValue: defaults.string(forKey: "appearance") ?? "") ?? .system
}
}
/// Motion changes presentation only; sampling preferences are deliberately absent.
nonisolated enum MetricMotionPolicy {
static func enabled(reduced: Bool, systemReduced: Bool, visible: Bool, paused: Bool, sleeping: Bool) -> Bool {
!reduced && !systemReduced && visible && !paused && !sleeping
}
}
+2 -1
View File
@@ -21,7 +21,7 @@ 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) {
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) {
guard enabled else { return }
var payload: [String: Any] = [
"event": event, "timestamp": snapshot.date.timeIntervalSince1970,
@@ -36,6 +36,7 @@ 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
@@ -24,16 +24,19 @@ import Observation
private let visibility: (Bool) -> Void
private let menuTitle: (String) -> String
private let openSettings: () -> Void
private let reducedMotion: () -> Bool
private var showingStatusMenu = false
private var isHiding = false
init<Content: View>(installStatusItem: Bool = true, visibility: @escaping (Bool) -> Void,
menuTitle: @escaping (String) -> String = { $0 },
openSettings: @escaping () -> Void = {},
reducedMotion: @escaping () -> Bool = { false },
@ViewBuilder content: @escaping (PanelPresentation) -> Content) {
self.visibility = visibility
self.menuTitle = menuTitle
self.openSettings = openSettings
self.reducedMotion = reducedMotion
self.content = {
let host = NSHostingView(rootView: content($0))
// The controller owns the fixed panel frame; content must not negotiate window limits.
@@ -112,7 +115,12 @@ import Observation
return window.convertToScreen(button.convert(button.bounds, to: nil)).contains(screenPoint)
}
private func applyWindowMotion() {
panel.animationBehavior = reducedMotion() || NSWorkspace.shared.accessibilityDisplayShouldReduceMotion ? .none : .default
}
func show() {
applyWindowMotion()
guard !panel.isVisible else { panel.makeKeyAndOrderFront(nil); return }
place()
presentation.isOpen = true
@@ -136,6 +144,7 @@ import Observation
isHiding = true
defer { isHiding = false }
presentation.isOpen = false
applyWindowMotion()
panel.orderOut(nil)
#if DEBUG || KYMO_AUDIT
if let content = panel.contentView { lastHiddenContent = content }
@@ -75,6 +75,9 @@ struct MenuPanelView: View {
}
.background(Color("PanelBackground"), in: .rect(cornerRadius: 18))
.clipShape(.rect(cornerRadius: 18))
.environment(\.metricAnimationsEnabled, MetricMotionPolicy.enabled(
reduced: preferences.reduceMotion, systemReduced: reduceMotion, visible: metrics.isPanelVisible,
paused: metrics.isPaused, sleeping: metrics.isSystemSleeping || metrics.isDisplaySleeping))
.modifier(AppearanceStyle(preferences: preferences))
}
+15 -1
View File
@@ -30,7 +30,10 @@ 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)] })
plotBounds: views.map { [Double($0.bounds.width), Double($0.bounds.height)] },
animatedPlots: views.filter { $0.input?.animates == true }.count)
if event == "open1.10", ProcessInfo.processInfo.environment["KYMO_AUDIT_CAPTURE"] == "1",
let content = controller.panel.contentView { capture(content) }
}
func wait(_ seconds: Int) async { try? await Task.sleep(for: .seconds(seconds)) }
// Pin the test window so unrelated focus changes cannot invalidate a measurement.
@@ -59,6 +62,17 @@ import AppKit
NSApp.terminate(nil)
}
}
/// Captures only our own hosted panel, never the desktop. Excluded from normal Release.
private static func capture(_ content: NSView) {
guard content.bounds.width > 0, content.bounds.height > 0,
content.bounds.width * content.bounds.height <= 1_100_000,
let bitmap = content.bitmapImageRepForCachingDisplay(in: content.bounds) else { return }
content.cacheDisplay(in: content.bounds, to: bitmap)
guard let png = bitmap.representation(using: .png, properties: [:]),
let data = try? JSONSerialization.data(withJSONObject: ["event": "audit.capture", "png": png.base64EncodedString()]) else { return }
try? FileHandle.standardOutput.write(contentsOf: data + Data([10]))
}
/// Uses real connection lifecycle but injects local callbacks; peer auth is tested separately by RPCs.
private static func checkRequestCompletion() async {
for _ in 0..<20 {
@@ -62,12 +62,16 @@ struct AppearanceSettingsView: View {
.tint(.primary)
}
}
Section {
Toggle("motion.reduce", isOn: $preferences.reduceMotion)
Text("motion.help").font(.callout).foregroundStyle(.secondary)
}
Section {
Toggle("sampling.backgroundEnabled", isOn: $sampling.backgroundEnabled)
LabeledContent("sampling.background") {
IntervalControl(milliseconds: $sampling.backgroundMilliseconds)
}.disabled(!sampling.backgroundEnabled)
Text("sampling.backgroundHelp").font(.callout).foregroundStyle(.secondary)
Text("sampling.recordingHelp").font(.callout).foregroundStyle(.secondary)
}
}
.formStyle(.grouped)
+69
View File
@@ -4375,6 +4375,75 @@
}
}
}
},
"motion.reduce" : {
"extractionState" : "manual",
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
"value" : "Reduce animations"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
"value" : "减弱动画"
}
},
"zh-Hant" : {
"stringUnit" : {
"state" : "translated",
"value" : "減弱動畫"
}
}
}
},
"motion.help" : {
"extractionState" : "manual",
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
"value" : "Use static numbers and charts to reduce drawing work. Background recording is controlled separately. The system Reduce Motion setting takes priority."
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
"value" : "使用静态数字和曲线以减少绘制。后台记录独立控制,系统“减弱动态效果”优先。"
}
},
"zh-Hant" : {
"stringUnit" : {
"state" : "translated",
"value" : "使用靜態數字和曲線以減少繪製。背景記錄獨立控制,系統「減弱動態效果」優先。"
}
}
}
},
"sampling.recordingHelp" : {
"extractionState" : "manual",
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
"value" : "When off, hiding the panel stops recording and leaves gaps in charts. When on, recording follows the background interval. Pausing or system sleep stops recording."
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
"value" : "关闭时,隐藏面板停止记录,图表保留空档。开启后按后台间隔记录;暂停或系统睡眠期间不记录。"
}
},
"zh-Hant" : {
"stringUnit" : {
"state" : "translated",
"value" : "關閉時,隱藏面板停止記錄,圖表保留空檔。開啟後按背景間隔記錄;暫停或系統睡眠期間不記錄。"
}
}
}
}
},
"version" : "1.0"
+31 -5
View File
@@ -8,6 +8,7 @@ struct NativePanelCurve: NSViewRepresentable {
let scales: [Double]
let maximumGap: TimeInterval
var hoveredIndex: Int? = nil
@Environment(\.metricAnimationsEnabled) private var animates
func sizeThatFits(_ proposal: ProposedViewSize, nsView: PlotView, context: Context) -> CGSize? {
// Owners supply explicit geometry; do not query AppKit's intrinsic layout on every update.
@@ -17,7 +18,7 @@ struct NativePanelCurve: NSViewRepresentable {
func makeNSView(context: Context) -> PlotView { PlotView() }
func updateNSView(_ view: PlotView, context: Context) {
view.configure(Input(frame: frame, colors: colors, scales: scales, maximumGap: maximumGap, hoveredIndex: hoveredIndex))
view.configure(Input(frame: frame, colors: colors, scales: scales, maximumGap: maximumGap, hoveredIndex: hoveredIndex, animates: animates))
}
struct Input: Equatable {
@@ -26,10 +27,14 @@ struct NativePanelCurve: NSViewRepresentable {
let scales: [Double]
let maximumGap: TimeInterval
var hoveredIndex: Int? = nil
var animates = false
}
final class PlotView: NSView {
private(set) var input: Input?
private(set) var drawingFrame: PanelCurveFrame?
private let motion = MetricMotion()
var isAnimating: Bool { motion.isRunning }
override var isFlipped: Bool { true }
override func hitTest(_ point: NSPoint) -> NSView? { nil }
@@ -43,9 +48,30 @@ struct NativePanelCurve: NSViewRepresentable {
func configure(_ value: Input) {
guard input != value else { return }
let previous = input
let changedFrame = previous?.frame != value.frame
input = value
// Keep hover updates from restarting an existing transition.
drawingFrame = value.frame
if !value.animates { motion.stop() }
else if changedFrame {
motion.stop()
if window != nil, let previous, let end = value.frame.dates.last,
!value.frame.boundaryDates.contains(end),
PanelCurveGeometry.isAppend(from: previous.frame.dates, to: value.frame.dates,
maximumGap: value.maximumGap) {
motion.start(on: layer)
}
}
needsDisplay = true
}
private func settle() {
motion.stop(); drawingFrame = input?.frame
}
override func viewDidMoveToWindow() {
super.viewDidMoveToWindow()
if window == nil { settle() }
}
override func setFrameSize(_ newSize: NSSize) {
let changed = frame.size != newSize
super.setFrameSize(newSize)
@@ -71,15 +97,15 @@ struct NativePanelCurve: NSViewRepresentable {
context.move(to: CGPoint(x: 0, y: y)); context.addLine(to: CGPoint(x: bounds.width, y: y))
}
context.strokePath()
guard let input, let first = input.frame.dates.first, let last = input.frame.dates.last,
guard let input, let frame = drawingFrame, let first = input.frame.dates.first, let last = input.frame.dates.last,
!input.colors.isEmpty, !input.scales.isEmpty else { return }
let domain = PanelCurveFrame.domain(previousBegin: nil, previousEnd: nil, begin: first, end: last, progress: 1)
for index in input.frame.series.indices {
for index in frame.series.indices {
let tint = NSColor(input.colors[min(index, input.colors.count - 1)])
let proposedScale = input.scales[min(index, input.scales.count - 1)]
let scale = proposedScale.isFinite && proposedScale > 0 ? proposedScale : 1
let runs = PanelCurveGeometry.runs(dates: input.frame.dates, values: input.frame.series[index],
maximumGap: input.maximumGap, boundaryDates: input.frame.boundaryDates, intervals: input.frame.intervals)
let runs = PanelCurveGeometry.runs(dates: frame.dates, values: frame.series[index],
maximumGap: input.maximumGap, boundaryDates: frame.boundaryDates, intervals: frame.intervals)
context.setFillColor(tint.cgColor)
context.setStrokeColor(tint.cgColor)
context.setLineWidth(1.5)
+9 -3
View File
@@ -1,12 +1,18 @@
import SwiftUI
/// Static numbers avoid per-sample glyph rasterization and transition caches.
/// Short numeric transitions follow the owner-supplied motion policy.
struct AnimatedMetricText: View {
let value: String
@Environment(\.metricAnimationsEnabled) private var animates
var body: some View {
Text(verbatim: value)
.monospacedDigit()
if animates {
Text(verbatim: value).monospacedDigit()
.contentTransition(.opacity)
.animation(.easeInOut(duration: MetricMotion.duration), value: value)
} else {
Text(verbatim: value).monospacedDigit()
}
}
}
+47
View File
@@ -0,0 +1,47 @@
import SwiftUI
import QuartzCore
private struct MetricAnimationsKey: EnvironmentKey {
static let defaultValue = false
}
extension EnvironmentValues {
/// The owner supplies actual visibility and user/system motion policy.
var metricAnimationsEnabled: Bool {
get { self[MetricAnimationsKey.self] }
set { self[MetricAnimationsKey.self] = newValue }
}
}
/// A finite compositor transition; native controls never create per-frame CPU timers.
@MainActor final class MetricMotion {
static let duration: TimeInterval = 0.25
private weak var layer: CALayer?
private var deadline: DispatchSourceTimer?
// Core Animation stores every CATransition under this reserved key.
private static let key = kCATransition
var isRunning: Bool { layer?.animation(forKey: Self.key) != nil }
func start(on layer: CALayer?) {
stop()
guard let layer else { return }
self.layer = layer
let transition = CATransition()
transition.type = .fade
transition.duration = Self.duration
transition.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
transition.isRemovedOnCompletion = true
layer.add(transition, forKey: Self.key)
// AppKit backing layers can retain a finished transition; enforce a finite lifetime.
// One coalescible cleanup deadline, never a per-frame CPU callback.
let deadline = DispatchSource.makeTimerSource(queue: .main)
deadline.schedule(deadline: .now() + Self.duration, leeway: .milliseconds(10))
deadline.setEventHandler { [weak self] in MainActor.assumeIsolated { self?.stop() } }
self.deadline = deadline
deadline.resume()
}
func stop() {
deadline?.cancel(); deadline = nil
layer?.removeAnimation(forKey: Self.key); layer = nil
}
deinit { deadline?.cancel() }
}
@@ -4,6 +4,7 @@ import SwiftUI
struct MetricProgressBar: View {
let value: Double
let color: Color
@Environment(\.metricAnimationsEnabled) private var animates
private var fraction: Double { value.isFinite ? min(1, max(0, value)) : 0 }
@@ -15,6 +16,8 @@ struct MetricProgressBar: View {
}
.frame(width: proxy.size.width, height: proxy.size.height)
.clipShape(Capsule())
.animation(animates ? .easeInOut(duration: MetricMotion.duration) : nil, value: fraction)
.transaction { if !animates { $0.disablesAnimations = true } }
}
}
}
+22 -4
View File
@@ -8,6 +8,7 @@ struct NativeMetricRing: NSViewRepresentable {
let lineWidth: CGFloat
let trackOpacity: Double
let inset: CGFloat
@Environment(\.metricAnimationsEnabled) private var animates
func sizeThatFits(_ proposal: ProposedViewSize, nsView: RingView, context: Context) -> CGSize? {
// Owners supply explicit geometry; do not query AppKit's intrinsic layout on every update.
@@ -18,7 +19,7 @@ struct NativeMetricRing: NSViewRepresentable {
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))
lineWidth: lineWidth, trackOpacity: trackOpacity, inset: inset, animates: animates))
}
struct Input: Equatable {
let value: Double
@@ -26,9 +27,13 @@ struct NativeMetricRing: NSViewRepresentable {
let lineWidth: CGFloat
let trackOpacity: Double
let inset: CGFloat
var animates = false
}
final class RingView: NSView {
private(set) var input: Input?
private(set) var displayedValue = 0.0
private let motion = MetricMotion()
var isAnimating: Bool { motion.isRunning }
override var isFlipped: Bool { true }
override func hitTest(_ point: NSPoint) -> NSView? { nil }
init() {
@@ -39,7 +44,20 @@ struct NativeMetricRing: NSViewRepresentable {
required init?(coder: NSCoder) { nil }
func configure(_ value: Input) {
guard value != input else { return }
input = value; needsDisplay = true
let previous = input
input = value
displayedValue = value.value
if !value.animates { motion.stop() }
else if previous?.value != value.value {
motion.stop()
if previous != nil, window != nil { motion.start(on: layer) }
}
needsDisplay = true
}
private func settle() { motion.stop(); displayedValue = input?.value ?? 0; needsDisplay = true }
override func viewDidMoveToWindow() {
super.viewDidMoveToWindow()
if window == nil { settle() }
}
override func setFrameSize(_ newSize: NSSize) {
let changed = newSize != frame.size
@@ -59,10 +77,10 @@ struct NativeMetricRing: NSViewRepresentable {
context.setLineWidth(input.lineWidth); context.setLineCap(.round)
context.setStrokeColor(tint.withAlphaComponent(input.trackOpacity).cgColor)
context.strokeEllipse(in: CGRect(x: center.x - radius, y: center.y - radius, width: radius * 2, height: radius * 2))
guard input.value > 0 else { return }
guard displayedValue > 0 else { return }
context.setStrokeColor(tint.cgColor)
context.addArc(center: center, radius: radius, startAngle: -.pi / 2,
endAngle: -.pi / 2 + 2 * .pi * input.value, clockwise: false)
endAngle: -.pi / 2 + 2 * .pi * displayedValue, clockwise: false)
context.strokePath()
}
}