perf(menubar): 隔离卡片动效并推进 1.1 低开销版本
This commit is contained in:
@@ -18,6 +18,7 @@ nonisolated struct NetworkMonitor {
|
||||
private var previous: [String: (UInt64, UInt64)] = [:]
|
||||
private var timestamp: TimeInterval?
|
||||
private var identities: [String: String] = [:]
|
||||
private var counterBuffer: [UInt8] = []
|
||||
|
||||
static func rate(current: UInt64, previous: UInt64?, elapsed: TimeInterval) -> Double? {
|
||||
guard let previous, elapsed.isFinite, elapsed > 0, current >= previous else { return nil }
|
||||
@@ -25,7 +26,7 @@ nonisolated struct NetworkMonitor {
|
||||
}
|
||||
|
||||
mutating func sample() -> [NetworkInterfaceMetrics]? {
|
||||
guard let counters = Self.counters() else { previous = [:]; timestamp = nil; return nil }
|
||||
guard let counters = counters() else { previous = [:]; timestamp = nil; return nil }
|
||||
let now = ProcessInfo.processInfo.systemUptime
|
||||
let elapsed = timestamp.map { now - $0 } ?? 0
|
||||
let metadata = Self.interfaces()
|
||||
@@ -78,19 +79,19 @@ nonisolated struct NetworkMonitor {
|
||||
}
|
||||
|
||||
/// NET_RT_IFLIST2 exposes 64-bit counters, avoiding getifaddrs' 4 GB wrap.
|
||||
private static func counters() -> [String: (UInt64, UInt64)]? {
|
||||
private mutating func counters() -> [String: (UInt64, UInt64)]? {
|
||||
var mib: [Int32] = [CTL_NET, PF_ROUTE, 0, 0, NET_RT_IFLIST2, 0]
|
||||
// The interface list can grow between size and data queries.
|
||||
for _ in 0..<3 {
|
||||
var count = 0
|
||||
guard sysctl(&mib, u_int(mib.count), nil, &count, nil, 0) == 0 else { return nil }
|
||||
guard count > 0 else { return [:] }
|
||||
var bytes = [UInt8](repeating: 0, count: count)
|
||||
let success = bytes.withUnsafeMutableBytes { raw in
|
||||
if counterBuffer.count < count { counterBuffer = [UInt8](repeating: 0, count: count) }
|
||||
let success = counterBuffer.withUnsafeMutableBytes { raw in
|
||||
sysctl(&mib, u_int(mib.count), raw.baseAddress, &count, nil, 0)
|
||||
}
|
||||
if success != 0 { if errno == ENOMEM { continue }; return nil }
|
||||
return bytes.withUnsafeBytes { raw -> [String: (UInt64, UInt64)]? in
|
||||
return counterBuffer.withUnsafeBytes { raw -> [String: (UInt64, UInt64)]? in
|
||||
var result: [String: (UInt64, UInt64)] = [:]
|
||||
var offset = 0
|
||||
while offset < count {
|
||||
|
||||
@@ -16,6 +16,10 @@ final class MetricsStore {
|
||||
private var panelDemand: Bool { isPanelVisible && !isDisplaySleeping }
|
||||
var effectiveMilliseconds: Int { panelDemand ? sampling.panelMilliseconds : sampling.backgroundMilliseconds }
|
||||
private var hasSamplingDemand: Bool { !isSystemSleeping && (panelDemand || sampling.backgroundEnabled) }
|
||||
// Permit timer coalescing without changing the requested cadence or delta timestamps.
|
||||
private var schedulingTolerance: Duration {
|
||||
.milliseconds(min(effectiveMilliseconds / 10, panelDemand ? 200 : 1_000))
|
||||
}
|
||||
@ObservationIgnored private var generation = 0
|
||||
@ObservationIgnored private var visibilityGeneration = 0
|
||||
@ObservationIgnored private var task: Task<Void, Never>?
|
||||
@@ -59,7 +63,7 @@ final class MetricsStore {
|
||||
task = Task { [weak self, sampler] in
|
||||
guard !Task.isCancelled else { return }
|
||||
if initialDelay > .zero {
|
||||
do { try await Task.sleep(for: initialDelay) } catch { return }
|
||||
do { try await Task.sleep(for: initialDelay, tolerance: self?.schedulingTolerance) } catch { return }
|
||||
}
|
||||
if reset { await sampler.reset() }
|
||||
while !Task.isCancelled {
|
||||
@@ -98,7 +102,7 @@ final class MetricsStore {
|
||||
let interval = self?.effectiveMilliseconds ?? 5_000
|
||||
// Start-to-start cadence; missed deadlines do not trigger catch-up bursts.
|
||||
let deadline = sampledAt.advanced(by: .milliseconds(interval))
|
||||
do { try await Task.sleep(until: max(deadline, .now), clock: .continuous) }
|
||||
do { try await Task.sleep(until: max(deadline, .now), tolerance: self?.schedulingTolerance, clock: .continuous) }
|
||||
catch { return }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,7 +16,7 @@ extension EnvironmentValues {
|
||||
static let duration: TimeInterval = 0.35
|
||||
static let key = "kymo.metric.movement"
|
||||
private weak var layer: CALayer?
|
||||
private var deadline: DispatchSourceTimer?
|
||||
private static let cleanup = MotionCleanup()
|
||||
var isRunning: Bool { layer?.animation(forKey: Self.key) != nil }
|
||||
|
||||
func start(on layer: CALayer?, animation: CAAnimation) {
|
||||
@@ -28,11 +28,7 @@ extension EnvironmentValues {
|
||||
animation.isRemovedOnCompletion = true
|
||||
layer.add(animation, forKey: Self.key)
|
||||
// Backing layers may retain completed animations. Bound their lifetime explicitly.
|
||||
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()
|
||||
Self.cleanup.register(self)
|
||||
}
|
||||
/// Cubic timing curve used by the original SwiftUI easeInOut animation.
|
||||
static func easeInOut(_ time: Double) -> Double {
|
||||
@@ -48,8 +44,62 @@ extension EnvironmentValues {
|
||||
}
|
||||
|
||||
func stop() {
|
||||
deadline?.cancel(); deadline = nil
|
||||
Self.cleanup.remove(self)
|
||||
finish()
|
||||
}
|
||||
|
||||
fileprivate func finish() {
|
||||
layer?.removeAnimation(forKey: Self.key); layer = nil
|
||||
}
|
||||
deinit { deadline?.cancel() }
|
||||
}
|
||||
|
||||
/// One one-shot timer serves the whole visible batch, retaining neither views nor motions.
|
||||
@MainActor private final class MotionCleanup {
|
||||
private struct Entry {
|
||||
weak var motion: MetricMotion?
|
||||
let deadline: DispatchTime
|
||||
}
|
||||
private var entries: [ObjectIdentifier: Entry] = [:]
|
||||
private var timer: DispatchSourceTimer?
|
||||
private var scheduled: UInt64?
|
||||
|
||||
func register(_ motion: MetricMotion) {
|
||||
entries[ObjectIdentifier(motion)] = Entry(motion: motion, deadline: .now() + MetricMotion.duration)
|
||||
schedule()
|
||||
}
|
||||
|
||||
func remove(_ motion: MetricMotion) {
|
||||
guard entries.removeValue(forKey: ObjectIdentifier(motion)) != nil else { return }
|
||||
schedule()
|
||||
}
|
||||
|
||||
private func schedule() {
|
||||
guard let first = entries.values.map(\.deadline.uptimeNanoseconds).min() else {
|
||||
timer?.cancel(); timer = nil; scheduled = nil
|
||||
return
|
||||
}
|
||||
// Core Animation ends at 350 ms. Group nearby cleanup deadlines 10 ms later.
|
||||
let deadline = first + 10_000_000
|
||||
guard scheduled != deadline else { return }
|
||||
scheduled = deadline
|
||||
let newTimer = timer == nil
|
||||
if newTimer {
|
||||
let source = DispatchSource.makeTimerSource(queue: .main)
|
||||
source.setEventHandler { [weak self] in MainActor.assumeIsolated { self?.complete() } }
|
||||
timer = source
|
||||
}
|
||||
timer?.schedule(deadline: DispatchTime(uptimeNanoseconds: deadline), leeway: .milliseconds(10))
|
||||
if newTimer { timer?.resume() }
|
||||
}
|
||||
|
||||
private func complete() {
|
||||
let now = DispatchTime.now().uptimeNanoseconds
|
||||
let expired = entries.filter { $0.value.motion == nil || $0.value.deadline.uptimeNanoseconds <= now }
|
||||
for (id, entry) in expired {
|
||||
entries.removeValue(forKey: id)
|
||||
entry.motion?.finish()
|
||||
}
|
||||
scheduled = nil
|
||||
schedule()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import AppKit
|
||||
import SwiftUI
|
||||
|
||||
/// Keeps local animation rendering inside a fixed-size child host.
|
||||
struct NativeContentHost<Content: View>: NSViewRepresentable {
|
||||
let content: Content
|
||||
|
||||
func makeNSView(context: Context) -> NSHostingView<AnyView> {
|
||||
let host = NSHostingView(rootView: root(context))
|
||||
// The parent owns the card frame, including its responsive column width.
|
||||
host.sizingOptions = []
|
||||
return host
|
||||
}
|
||||
|
||||
func updateNSView(_ host: NSHostingView<AnyView>, context: Context) {
|
||||
host.rootView = root(context)
|
||||
}
|
||||
|
||||
func sizeThatFits(_ proposal: ProposedViewSize, nsView: NSHostingView<AnyView>, context: Context) -> CGSize? {
|
||||
CGSize(width: proposal.width.flatMap { $0.isFinite ? max(0, $0) : nil } ?? 10,
|
||||
height: proposal.height.flatMap { $0.isFinite ? max(0, $0) : nil } ?? 10)
|
||||
}
|
||||
|
||||
static func dismantleNSView(_ host: NSHostingView<AnyView>, coordinator: ()) {
|
||||
// AppKit may cache a detached view. Release its mounted content immediately.
|
||||
host.rootView = AnyView(EmptyView())
|
||||
}
|
||||
|
||||
private func root(_ context: Context) -> AnyView {
|
||||
AnyView(content.environment(\.self, context.environment))
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,10 @@ struct ResourceCard<Content: View>: View {
|
||||
@ViewBuilder var content: () -> Content
|
||||
|
||||
var body: some View {
|
||||
NativeContentHost(content: cardBody)
|
||||
}
|
||||
|
||||
private var cardBody: some View {
|
||||
GeometryReader { bounds in
|
||||
VStack(alignment: .leading, spacing: 4) {
|
||||
HStack(alignment: .center, spacing: 6) {
|
||||
|
||||
Reference in New Issue
Block a user