perf: don't compute diffs of running-apps; directly get new/old

This commit is contained in:
lwouis committed 2026-01-03 18:09:18 +01:00
1 parent a45361321d
commit 7ded01c277
2 files changed
+10 -14

No files matched your search

+1 -1
View File
@@ -315,7 +315,7 @@ extension DispatchTimeInterval {
} }
extension NSRunningApplication { extension NSRunningApplication {
var id: String { "pid:\(String(describing: processIdentifier)) app:\(bundleIdentifier ?? bundleURL?.absoluteString ?? executableURL?.absoluteString ?? localizedName ?? "nil")" } func debugId() -> String { "pid:\(String(describing: processIdentifier)) app:\(bundleIdentifier ?? bundleURL?.absoluteString ?? executableURL?.absoluteString ?? localizedName ?? "nil")" }
} }
// 250ms is similar to human delay in processing changes on screen // 250ms is similar to human delay in processing changes on screen
@@ -2,26 +2,22 @@ import Cocoa
class RunningApplicationsEvents { class RunningApplicationsEvents {
private static var appsObserver: NSKeyValueObservation! private static var appsObserver: NSKeyValueObservation!
private static var previousValueOfRunningApps: Set<NSRunningApplication>!
static func observe() { static func observe() {
previousValueOfRunningApps = Set(NSWorkspace.shared.runningApplications)
// we can't observe NSWorkspace.didLaunchApplicationNotification or NSWorkspace.didTerminateApplicationNotification // we can't observe NSWorkspace.didLaunchApplicationNotification or NSWorkspace.didTerminateApplicationNotification
// these only trigger for some apps, mostly GUI app. We need to track all processes as any could spawn a window // these only trigger for some apps, mostly GUI app. We need to track all processes as any could spawn a window
appsObserver = NSWorkspace.shared.observe(\.runningApplications, options: [.old, .new], changeHandler: { (_, _) in handleEvent() }) appsObserver = NSWorkspace.shared.observe(\.runningApplications, options: [.old, .new], changeHandler: { (_, change) in handleEvent(change) })
} }
private static func handleEvent() { private static func handleEvent(_ change: NSKeyValueObservedChange<[NSRunningApplication]>) {
let workspaceApps = Set(NSWorkspace.shared.runningApplications) let added = change.newValue
let added = workspaceApps.subtracting(previousValueOfRunningApps) let removed = change.oldValue
let removed = previousValueOfRunningApps.subtracting(workspaceApps) Logger.debug("added:", added?.map { $0.debugId() }, "removed:", removed?.map { $0.debugId() })
Logger.info("added:", added.map { $0.id }, "removed:", removed.map { $0.id }) if let added {
if !added.isEmpty { Applications.addRunningApplications(added)
Applications.addRunningApplications(Array(added))
} }
if !removed.isEmpty { if let removed {
Applications.removeRunningApplications(Array(removed)) Applications.removeRunningApplications(removed)
} }
previousValueOfRunningApps = workspaceApps
} }
} }