Skip to content

armgit / peel

Public Imported from GitHub
0

Uninstall Mac apps with every file they leave behind, and see why each belongs. Free up space, fine-tune macOS, and set up Terminal.

Wait for an app to quit by its process's end, as the kernel tells it

Țugui Dragoșd04eb788ea4c
diff --git a/Packages/PeelCore/Sources/PeelCore/Apps/ProcessEnds.swift b/Packages/PeelCore/Sources/PeelCore/Apps/ProcessEnds.swift
new file mode 100644
index 00000000..d9c0af86
--- /dev/null
+++ b/Packages/PeelCore/Sources/PeelCore/Apps/ProcessEnds.swift
@@ -0,0 +1,33 @@
+public import Foundation
+import os
+
+/// When running programs end, as the kernel tells it. AppKit's `NSRunningApplication.isTerminated` changes only once
+/// AppKit hears of the end, which can be long after it.
+public enum ProcessEnds {
+ /// Each of `identifiers` as its process ends, at once for one that has ended already, watched from this call on.
+ /// The stream finishes once every one has ended.
+ public static func of(_ identifiers: [pid_t]) -> AsyncStream<pid_t> {
+ AsyncStream { continuation in
+ let running = Set(identifiers.filter { $0 > 0 })
+ let waiting = OSAllocatedUnfairLock(initialState: running)
+ let sources = running.map { identifier in
+ let source = DispatchSource.makeProcessSource(
+ identifier: identifier,
+ eventMask: .exit,
+ queue: .global(qos: .userInitiated)
+ )
+ source.setEventHandler {
+ continuation.yield(identifier)
+ source.cancel()
+ if waiting.withLock({ $0.remove(identifier); return $0.isEmpty }) {
+ continuation.finish()
+ }
+ }
+ return source
+ }
+ continuation.onTermination = { _ in sources.forEach { $0.cancel() } }
+ guard !sources.isEmpty else { return continuation.finish() }
+ sources.forEach { $0.resume() }
+ }
+ }
+}
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/ProcessEndsTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/ProcessEndsTests.swift
new file mode 100644
index 00000000..9c60b122
--- /dev/null
+++ b/Packages/PeelCore/Tests/PeelCoreTests/ProcessEndsTests.swift
@@ -0,0 +1,79 @@
+import Foundation
+import os
+@testable import PeelCore
+import Testing
+
+struct ProcessEndsTests {
+ /// What `ends` yields until it finishes, or nil when it has not finished within `seconds`.
+ private func collect(_ ends: AsyncStream<pid_t>, within seconds: Double = 10) async -> [pid_t]? {
+ await withTaskGroup(of: [pid_t]?.self) { group in
+ group.addTask {
+ var seen: [pid_t] = []
+ for await identifier in ends { seen.append(identifier) }
+ return seen
+ }
+ group.addTask {
+ try? await Task.sleep(for: .seconds(seconds))
+ return nil
+ }
+ let first = await group.next() ?? nil
+ group.cancelAll()
+ return first
+ }
+ }
+
+ @Test func tellsWhenARunningProgramEnds() async throws {
+ let directory = try TemporaryDirectory()
+ let program = try directory.runningProgram("Example.app/Contents/MacOS/example")
+
+ let ends = ProcessEnds.of([program.processIdentifier])
+ program.terminate()
+
+ #expect(await collect(ends) == [program.processIdentifier])
+ }
+
+ @Test func tellsAtOnceOfAProgramThatHasEndedAlready() async throws {
+ let directory = try TemporaryDirectory()
+ let program = try directory.runningProgram("Example.app/Contents/MacOS/example")
+ program.terminate()
+ program.waitUntilExit()
+
+ #expect(await collect(ProcessEnds.of([program.processIdentifier])) == [program.processIdentifier])
+ }
+
+ @Test func finishesOnlyOnceEveryProgramHasEnded() async throws {
+ let directory = try TemporaryDirectory()
+ let first = try directory.runningProgram("One.app/Contents/MacOS/one")
+ let second = try directory.runningProgram("Two.app/Contents/MacOS/two")
+ let finished = OSAllocatedUnfairLock(initialState: false)
+ let ends = ProcessEnds.of([first.processIdentifier, second.processIdentifier, first.processIdentifier, -1])
+ let collecting = Task {
+ var seen: [pid_t] = []
+ for await identifier in ends { seen.append(identifier) }
+ finished.withLock { $0 = true }
+ return seen
+ }
+
+ first.terminate()
+ first.waitUntilExit()
+ try await Task.sleep(for: .milliseconds(500))
+ #expect(!finished.withLock { $0 })
+ second.terminate()
+
+ let seen = await withTaskGroup(of: [pid_t]?.self) { group in
+ group.addTask { await collecting.value }
+ group.addTask {
+ try? await Task.sleep(for: .seconds(10))
+ return nil
+ }
+ let answer = await group.next() ?? nil
+ group.cancelAll()
+ return answer
+ }
+ #expect(seen == [first.processIdentifier, second.processIdentifier])
+ }
+
+ @Test func finishesAtOnceWithNoProgramToWatch() async {
+ #expect(await collect(ProcessEnds.of([0, -1]), within: 1) == [])
+ }
+}
diff --git a/Peel/Model/QuitBeforeRemoving.swift b/Peel/Model/QuitBeforeRemoving.swift
index 7d93f9be..dcf98774 100644
--- a/Peel/Model/QuitBeforeRemoving.swift
+++ b/Peel/Model/QuitBeforeRemoving.swift
@@ -1,5 +1,6 @@
import AppKit
import Observation
+import PeelCore
/// The processes a removal waits for, since files never move out from under a running app. It asks them to quit,
/// follows them until none runs, and then goes on with the removal. One still open after a while may be waiting for
@@ -8,6 +9,8 @@ import Observation
final class QuitBeforeRemoving {
/// The processes the alerts name.
private(set) var running: [NSRunningApplication] = []
+ /// The ones among them the kernel has seen end.
+ private var ended: Set<pid_t> = []
/// Whether the alert that asks to quit them is up.
var isAsking = false
/// Whether the alert that offers to force what did not quit is up.
@@ -23,7 +26,7 @@ final class QuitBeforeRemoving {
/// The names of what still runs, for the alerts.
var names: String {
- running.filter { !$0.isTerminated }.map { $0.localizedName ?? $0.bundleIdentifier ?? "" }
+ running.filter { !ended.contains($0.processIdentifier) }.map { $0.localizedName ?? $0.bundleIdentifier ?? "" }
.formatted(.list(type: .and))
}
@@ -32,20 +35,19 @@ final class QuitBeforeRemoving {
let open = processes.filter { !$0.isTerminated }
guard !open.isEmpty else { return goOn() }
running = open
+ ended = []
self.goOn = goOn
isAsking = true
}
/// Asks each process to quit, as Quit in its menu would, and goes on once none runs.
func quit() {
- running.forEach { $0.terminate() }
- follow()
+ follow { _ = $0.terminate() }
}
/// Ends what did not quit, as Force Quit does: whatever it had not saved is lost.
func forceQuit() {
- running.filter { !$0.isTerminated }.forEach { $0.forceTerminate() }
- follow()
+ follow { _ = $0.forceTerminate() }
}
/// Stops waiting, and nothing goes on.
@@ -57,17 +59,23 @@ final class QuitBeforeRemoving {
isOfferingToForce = false
}
- private func follow() {
+ /// Does `act` to each process still running and goes on once the kernel has seen every one end, watching from
+ /// before `act` so that no end is missed.
+ private func follow(doing act: (NSRunningApplication) -> Void) {
following?.cancel()
isWaiting = true
- let processes = running
+ let processes = running.filter { !ended.contains($0.processIdentifier) }
+ let ends = ProcessEnds.of(processes.map(\.processIdentifier))
+ processes.forEach(act)
following = Task {
let offer = Task {
try? await Task.sleep(for: Self.patience)
guard !Task.isCancelled else { return }
isOfferingToForce = true
}
- await Self.untilGone(processes)
+ for await identifier in ends {
+ ended.insert(identifier)
+ }
offer.cancel()
guard !Task.isCancelled else { return }
isWaiting = false
@@ -89,16 +97,4 @@ final class QuitBeforeRemoving {
return
}
}
-
- /// Returns once every one of `processes` has exited, or the task is canceled. `isTerminated` is followed through
- /// key-value observing, which Apple documents for it, since the workspace does not post a notice for every end.
- static func untilGone(_ processes: [NSRunningApplication]) async {
- let (changes, continuation) = AsyncStream.makeStream(of: Void.self, bufferingPolicy: .bufferingNewest(1))
- let observations = processes.map { $0.observe(\.isTerminated) { _, _ in continuation.yield() } }
- defer { observations.forEach { $0.invalidate() } }
- guard !processes.allSatisfy(\.isTerminated) else { return }
- for await _ in changes where processes.allSatisfy(\.isTerminated) {
- return
- }
- }
}
diff --git a/Peel/Model/TerminalLibrary.swift b/Peel/Model/TerminalLibrary.swift
index d421334a..4dc6b7bb 100644
--- a/Peel/Model/TerminalLibrary.swift
+++ b/Peel/Model/TerminalLibrary.swift
@@ -68,9 +68,13 @@ final class TerminalLibrary {
let running = NSRunningApplication.runningApplications(withBundleIdentifier: TerminalSettings.identifier)
isQuittingTerminal = true
defer { isQuittingTerminal = false }
+ let ends = ProcessEnds.of(running.map(\.processIdentifier))
running.forEach { $0.terminate() }
let didQuit = await withTaskGroup(of: Bool.self) { group in
- group.addTask { await QuitBeforeRemoving.untilGone(running); return true }
+ group.addTask {
+ for await _ in ends {}
+ return true
+ }
group.addTask { try? await Task.sleep(for: Self.patience); return false }
let first = await group.next() ?? false
group.cancelAll()