fix(menubar): 修正进程退出判断与公网刷新及风扇语言

This commit is contained in:
2026-11-03 22:12:44 +08:00
parent ea4d0e7f23
commit c8d7326a80
13 changed files with 238 additions and 49 deletions
+34 -15
View File
@@ -5,36 +5,55 @@ import Darwin
actor PublicIPAddressService {
static let shared = PublicIPAddressService()
private let session: URLSession
private let cacheLifetime: TimeInterval
private let retryInterval: TimeInterval
private let now: @Sendable () -> TimeInterval
private var cached: (route: String, expiresAt: TimeInterval, address: String?)?
init(session: URLSession = .shared) { self.session = session }
init(session: URLSession = .shared, cacheLifetime: TimeInterval = 600, retryInterval: TimeInterval = 30,
now: @escaping @Sendable () -> TimeInterval = { ProcessInfo.processInfo.systemUptime }) {
precondition(cacheLifetime.isFinite && cacheLifetime > 0 && retryInterval.isFinite && retryInterval > 0)
self.session = session
self.cacheLifetime = cacheLifetime
self.retryInterval = retryInterval
self.now = now
}
private var cached: (route: String, date: Date, address: String?)?
/// The caller owns the task lifetime; route changes and hidden views cancel both HTTP and sleep.
func refreshContinuously(route: String, onUpdate: @Sendable (String?) async -> Void) async {
while !Task.isCancelled {
let value = await address(route: route)
guard !Task.isCancelled else { return }
await onUpdate(value)
let delay = cached.flatMap { $0.route == route ? $0.expiresAt - now() : nil } ?? retryInterval
do { try await Task.sleep(for: .seconds(max(0.01, delay))) }
catch { return }
}
}
func address(route: String) async -> String? {
if let cached, cached.route == route, Date().timeIntervalSince(cached.date) < 600 {
return cached.address
}
guard !Task.isCancelled else { return nil }
if let cached, cached.route == route, now() < cached.expiresAt { return cached.address }
var request = URLRequest(url: URL(string: "https://api.ipify.org")!)
request.timeoutInterval = 5
request.cachePolicy = .reloadIgnoringLocalCacheData
let address: String?
var address: String?
do {
let (data, response) = try await session.data(for: request)
let value = String(data: data, encoding: .utf8)?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
var ipv4 = in_addr()
var ipv6 = in6_addr()
guard (response as? HTTPURLResponse)?.statusCode == 200,
value.utf8.count <= 45,
inet_pton(AF_INET, value, &ipv4) == 1 || inet_pton(AF_INET6, value, &ipv6) == 1 else {
cached = (route, Date(), nil)
return nil
if (response as? HTTPURLResponse)?.statusCode == 200,
value.utf8.count <= 45,
inet_pton(AF_INET, value, &ipv4) == 1 || inet_pton(AF_INET6, value, &ipv6) == 1 {
address = value
}
address = value
} catch {
if Task.isCancelled { return nil }
address = nil
if Task.isCancelled || (error as? URLError)?.code == .cancelled { return nil }
}
cached = (route, Date(), address)
// A cancelled old route must neither publish nor replace the cache during a route switch.
guard !Task.isCancelled else { return nil }
cached = (route, now() + (address == nil ? retryInterval : cacheLifetime), address)
return address
}
}
@@ -55,9 +55,12 @@ extension MenuPanelView {
.task(id: publicIPRoute) {
publicIPAddress = nil
guard snapshot.networkPath == .available else { return }
let address = await PublicIPAddressService.shared.address(route: publicIPRoute)
guard !Task.isCancelled else { return }
publicIPAddress = address
await PublicIPAddressService.shared.refreshContinuously(route: publicIPRoute) { address in
await MainActor.run {
guard !Task.isCancelled else { return }
publicIPAddress = address
}
}
}
}
var publicIPRoute: String {
@@ -96,8 +96,8 @@ extension MenuPanelView {
ForEach(fans) { fan in
FanSpeedIndicator(
title: fans.count == 2
? (fan.id == 0 ? "gpu.fanLeft" : "gpu.fanRight")
: LocalizedStringKey("\(String(localized: "gpu.fan")) \(fan.id + 1)"), rpm: fan.rpm)
? (fan.id == 0 ? Text("gpu.fanLeft") : Text("gpu.fanRight"))
: Text("gpu.fanNumber \(fan.id + 1)"), rpm: fan.rpm)
}
}
.modifier(CardInset())
@@ -2,6 +2,13 @@ import Foundation
/// Compute once per data/filter/sort event, never from row rendering or scroll position.
nonisolated enum ProcessTableProjection {
/// Filtering hides rows without terminating processes. A failed read proves no departure.
static func exitedSelection(_ selected: ProcessIdentity?, in snapshot: ProcessSnapshot?) -> ProcessIdentity? {
guard let selected, let snapshot, !snapshot.failed,
!snapshot.rows.contains(where: { $0.id == selected }) else { return nil }
return selected
}
static func rows(_ input: [ProcessMetrics], query: String, sorting: [ProcessSort], order: [ProcessIdentity]) -> [ProcessMetrics] {
let ranks = Dictionary(uniqueKeysWithValues: order.enumerated().map { ($0.element, $0.offset) })
return input.filter {
+3 -4
View File
@@ -14,10 +14,9 @@ struct ProcessTableView: View {
@State private var searchFocused = false
private var held: Bool { hovering || selected != nil || !search.isEmpty }
private var selectedRow: ProcessMetrics? { rows.first { $0.id == selected } }
private var selectedRow: ProcessMetrics? { snapshot?.rows.first { $0.id == selected } }
private var exitedSelection: ProcessIdentity? {
guard let selected, snapshot != nil, !rows.contains(where: { $0.id == selected }) else { return nil }
return selected
ProcessTableProjection.exitedSelection(selected, in: snapshot)
}
var body: some View {
@@ -74,7 +73,7 @@ struct ProcessTableView: View {
.task(id: exitedSelection) {
guard let id = exitedSelection else { return }
do { try await Task.sleep(for: .seconds(3)) } catch { return }
if selected == id { selected = nil; departed = nil }
if exitedSelection == id { selected = nil; departed = nil }
}
.onExitCommand {
if !search.isEmpty { search = "" }
+22
View File
@@ -1733,6 +1733,28 @@
}
}
},
"gpu.fanNumber %lld" : {
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
"value" : "Fan %lld"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
"value" : "风扇 %lld"
}
},
"zh-Hant" : {
"stringUnit" : {
"state" : "translated",
"value" : "風扇 %lld"
}
}
}
},
"gpu.memoryComparisonHelp" : {
"extractionState" : "stale",
"localizations" : {
+2 -2
View File
@@ -28,7 +28,7 @@ nonisolated struct FanRotation {
}
struct FanSpeedIndicator: View {
let title: LocalizedStringKey
let title: Text
let rpm: Double?
@Environment(\.accessibilityReduceMotion) private var reduceMotion
@State private var rotation = FanRotation()
@@ -40,7 +40,7 @@ struct FanSpeedIndicator: View {
.rotationEffect(.degrees(rotation.angle(at: context.date.timeIntervalSinceReferenceDate)))
.foregroundStyle(.secondary)
}.frame(width: 14, height: 14).accessibilityHidden(true)
Text(title).foregroundStyle(.secondary)
title.foregroundStyle(.secondary)
Spacer(minLength: 2)
AnimatedMetricText(value: rpm.map { "\(Int($0.rounded())) RPM" } ?? "-- RPM")
.monospacedDigit().fontWeight(.medium)