perf: don't compute diffs of running-apps; directly get new/old
This commit is contained in:
1 parent
a45361321d
commit
7ded01c277
2 files changed
+10
-14
No files matched your search
@@ -315,7 +315,7 @@ extension DispatchTimeInterval {
|
||||
}
|
||||
|
||||
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
|
||||
|
||||
@@ -2,26 +2,22 @@ import Cocoa
|
||||
|
||||
class RunningApplicationsEvents {
|
||||
private static var appsObserver: NSKeyValueObservation!
|
||||
private static var previousValueOfRunningApps: Set<NSRunningApplication>!
|
||||
|
||||
static func observe() {
|
||||
previousValueOfRunningApps = Set(NSWorkspace.shared.runningApplications)
|
||||
// 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
|
||||
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() {
|
||||
let workspaceApps = Set(NSWorkspace.shared.runningApplications)
|
||||
let added = workspaceApps.subtracting(previousValueOfRunningApps)
|
||||
let removed = previousValueOfRunningApps.subtracting(workspaceApps)
|
||||
Logger.info("added:", added.map { $0.id }, "removed:", removed.map { $0.id })
|
||||
if !added.isEmpty {
|
||||
Applications.addRunningApplications(Array(added))
|
||||
private static func handleEvent(_ change: NSKeyValueObservedChange<[NSRunningApplication]>) {
|
||||
let added = change.newValue
|
||||
let removed = change.oldValue
|
||||
Logger.debug("added:", added?.map { $0.debugId() }, "removed:", removed?.map { $0.debugId() })
|
||||
if let added {
|
||||
Applications.addRunningApplications(added)
|
||||
}
|
||||
if !removed.isEmpty {
|
||||
Applications.removeRunningApplications(Array(removed))
|
||||
if let removed {
|
||||
Applications.removeRunningApplications(removed)
|
||||
}
|
||||
previousValueOfRunningApps = workspaceApps
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user