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.

Quitting waits for a removal until History has it

Țugui Dragoș0506b4108390
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md
index fdfcf0fc..ea95b079 100644
--- a/ARCHITECTURE.md
+++ b/ARCHITECTURE.md
@@ -89,8 +89,9 @@ Take the most common case, uninstalling an app. Every other page follows the sam
from and where it went, so it can be put back; History keeps the most recent 20,000 items. A removal is one
entry, even when it moved what was selected on several pages. Each item is also written down the moment it
moves (`removals.journal`, through `RemovalJournal`), so what a removal cut short moved reaches History the
- next time it is read, as an interrupted removal. What Peel refused to move is recorded too (`refusals.json`),
- and History lists it under Not Moved, one removal to an entry.
+ next time it is read, as an interrupted removal, and quitting the app waits for a removal until History has it
+ (`QuitGuard`). What Peel refused to move is recorded too (`refusals.json`), and History lists it under Not
+ Moved, one removal to an entry.
8. **Put back.** History's Put Back reads its record as a request, not as a fact: an item returns only from a
real Trash, only to a place the guard allows, and, through the helper, only if the helper's own ledger says
it moved that very item from that very place.
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index d0781f4c..d26ad815 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -9,13 +9,15 @@ from happening, and they are not up for negotiation.
## The rule everything else serves
**Nothing of the user's is ever deleted for good.** Every removal goes to the Trash through `TrashService` and is
-recorded, so History can put it back. No code path in Peel deletes anything of the user's, and a change that adds one
-won't be accepted; the one file Peel deletes outright is its own list of refusals, when `peel history --refused --clear`
-is asked to forget it. Three things Peel starts can't be undone by History, and each says so where the user confirms it:
-Homebrew's own uninstall and clean up, and resetting an app's privacy permissions. `defaults delete` for an app's
-preferences runs only once their file is in the Trash, and a reset exports the domain first, so putting the file back
-undoes it; putting saved settings back clears a domain only once it has been saved as a copy of its own, and asks first.
-Every `brew` call runs with `HOMEBREW_NO_INSTALL_CLEANUP`, so an upgrade never cleans up on its own.
+recorded, so History can put it back; in the app it runs inside `QuitGuard.shared.run` from its first move until History
+has it, and so does a Put Back, so that quitting waits for them. No code path in Peel deletes anything of the user's,
+and a change that adds one won't be accepted; the one file Peel deletes outright is its own list of refusals, when
+`peel history --refused --clear` is asked to forget it. Three things Peel starts can't be undone by History, and each
+says so where the user confirms it: Homebrew's own uninstall and clean up, and resetting an app's privacy permissions.
+`defaults delete` for an app's preferences runs only once their file is in the Trash, and a reset exports the domain
+first, so putting the file back undoes it; putting saved settings back clears a domain only once it has been saved as a
+copy of its own, and asks first. Every `brew` call runs with `HOMEBREW_NO_INSTALL_CLEANUP`, so an upgrade never cleans
+up on its own.
## What you need
diff --git a/Peel/Model/BackgroundItemLibrary.swift b/Peel/Model/BackgroundItemLibrary.swift
index e7fedc57..9770383c 100644
--- a/Peel/Model/BackgroundItemLibrary.swift
+++ b/Peel/Model/BackgroundItemLibrary.swift
@@ -59,8 +59,11 @@ final class BackgroundItemLibrary {
case .disable: try await BackgroundItemActions.setEnabled(false, for: item)
case .moveToTrash:
let exclusions = ExclusionsStore.shared.exclusions
- let result = try await BackgroundItemActions.moveToTrash(item, exclusions: exclusions)
- await record(result)
+ let result = try await QuitGuard.shared.run { () async throws(BackgroundItemActions.Failure) -> TrashResult in
+ let result = try await BackgroundItemActions.moveToTrash(item, exclusions: exclusions)
+ await record(result)
+ return result
+ }
if let refusal = result.failures.first {
failure = ActionFailure(action: action, reason: .trash(refusal.reason))
}
diff --git a/Peel/Model/HomeModel.swift b/Peel/Model/HomeModel.swift
index b7e88d54..b7a2c3fc 100644
--- a/Peel/Model/HomeModel.swift
+++ b/Peel/Model/HomeModel.swift
@@ -271,7 +271,7 @@ final class HomeModel {
self.couldNotRelaunch = true
return
}
- NSApp.terminate(nil)
+ QuitGuard.quit()
}
}
}
diff --git a/Peel/Model/PackageLibrary.swift b/Peel/Model/PackageLibrary.swift
index 412f445a..bc36a9ec 100644
--- a/Peel/Model/PackageLibrary.swift
+++ b/Peel/Model/PackageLibrary.swift
@@ -34,9 +34,12 @@ final class PackageLibrary {
defer { isWorking = false }
let items = selectedReceipt?.items.filter { selectedURLs.contains($0.url) } ?? []
let privileged = Set(items.filter(\.requiresPrivileges).map(\.url))
- let result = await TrashService(exclusions: ExclusionsStore.shared.exclusions).trash(items.map(\.url), usingHelperFor: privileged)
- // Written down before the rescan, which can take a while: History is the way back for what just moved.
- await record(result)
+ let result = await QuitGuard.shared.run {
+ let result = await TrashService(exclusions: ExclusionsStore.shared.exclusions).trash(items.map(\.url), usingHelperFor: privileged)
+ // Written down before the rescan, which can take a while: History is the way back for what just moved.
+ await record(result)
+ return result
+ }
await refresh()
return result
}
@@ -44,8 +47,11 @@ final class PackageLibrary {
func forget(_ receipt: PackageReceipt, recording record: (TrashResult) async -> Void) async -> TrashResult {
isWorking = true
defer { isWorking = false }
- let result = await PackageActions.forget(receipt, exclusions: ExclusionsStore.shared.exclusions)
- await record(result)
+ let result = await QuitGuard.shared.run {
+ let result = await PackageActions.forget(receipt, exclusions: ExclusionsStore.shared.exclusions)
+ await record(result)
+ return result
+ }
await refresh()
return result
}
diff --git a/Peel/Model/PluginLibrary.swift b/Peel/Model/PluginLibrary.swift
index 389aec64..79076bf2 100644
--- a/Peel/Model/PluginLibrary.swift
+++ b/Peel/Model/PluginLibrary.swift
@@ -27,9 +27,12 @@ final class PluginLibrary {
isRemoving = true
defer { isRemoving = false }
let privileged: Set<URL> = plugin.requiresPrivileges ? [plugin.url] : []
- let result = await TrashService(exclusions: ExclusionsStore.shared.exclusions).trash([plugin.url], usingHelperFor: privileged)
- // Written down before the rescan, which can take a while: History is the way back for what just moved.
- await record(result)
+ let result = await QuitGuard.shared.run {
+ let result = await TrashService(exclusions: ExclusionsStore.shared.exclusions).trash([plugin.url], usingHelperFor: privileged)
+ // Written down before the rescan, which can take a while: History is the way back for what just moved.
+ await record(result)
+ return result
+ }
await refresh()
return result
}
diff --git a/Peel/Model/QuitGuard.swift b/Peel/Model/QuitGuard.swift
new file mode 100644
index 00000000..b1126107
--- /dev/null
+++ b/Peel/Model/QuitGuard.swift
@@ -0,0 +1,52 @@
+import AppKit
+
+/// What a quit waits for: a removal from its first move until History has it, and a Put Back until it is done.
+/// Quitting halfway would leave what already moved in History as an interrupted removal, without its name or sizes,
+/// skip what follows a move (stopping a job whose file went, forgetting its settings), and leave items put back
+/// listed as still in the Trash.
+@MainActor
+final class QuitGuard {
+ static let shared = QuitGuard()
+
+ private var running = 0
+ private var refusing = 0
+ private var isQuitWaiting = false
+
+ /// Runs `work`, and a quit asked meanwhile waits for it to end.
+ func run<T, Failure: Error>(_ work: () async throws(Failure) -> T) async throws(Failure) -> T {
+ running += 1
+ defer {
+ running -= 1
+ if running == 0, isQuitWaiting {
+ isQuitWaiting = false
+ NSApp.reply(toApplicationShouldTerminate: true)
+ }
+ }
+ return try await work()
+ }
+
+ /// Runs Peel's removal of itself, which ends Peel its own way, so a quit asked meanwhile is refused. Quitting
+ /// through AppKit would write the window's place and Peel's settings again, just after they went to the Trash.
+ func runRefusingQuit<T>(_ work: () async -> T) async -> T {
+ refusing += 1
+ defer { refusing -= 1 }
+ return await work()
+ }
+
+ /// The answer to a quit: now when nothing is under way, otherwise once the last of it ends.
+ func replyToQuit() -> NSApplication.TerminateReply {
+ guard refusing == 0 else { return .terminateCancel }
+ guard running > 0 else { return .terminateNow }
+ isQuitWaiting = true
+ return .terminateLater
+ }
+
+ /// Asks Peel to quit from the run loop rather than from inside the task that asks. The loop AppKit runs while a
+ /// quit waits takes the main queue's next block only once the running one returns, so a quit asked from inside
+ /// one would hold back the very work it waits for.
+ static func quit() {
+ RunLoop.main.perform {
+ MainActor.assumeIsolated { NSApp.terminate(nil) }
+ }
+ }
+}
diff --git a/Peel/Model/RemovalHistoryStore.swift b/Peel/Model/RemovalHistoryStore.swift
index 824e567e..2353538a 100644
--- a/Peel/Model/RemovalHistoryStore.swift
+++ b/Peel/Model/RemovalHistoryStore.swift
@@ -228,21 +228,23 @@ final class RemovalHistoryStore {
isRestoring = true
defer { isRestoring = false }
let service = TrashService()
- var restored: Set<UUID> = []
- var problems: [RemovalRecord.ID: RestoreFailure] = [:]
- // Shallowest first, so a folder is put back before anything that was inside it. A child put back first
- // would make a new folder at its parent's path, and the parent could then not be put back.
- for record in records.sorted(by: { $0.originalURL.pathComponents.count < $1.originalURL.pathComponents.count }) {
- if let failure = await service.restore(record.trashedItem, canUseHelper: canUseHelper) {
- problems[record.id] = failure
- } else {
- restored.insert(record.id)
+ await QuitGuard.shared.run {
+ var restored: Set<UUID> = []
+ var problems: [RemovalRecord.ID: RestoreFailure] = [:]
+ // Shallowest first, so a folder is put back before anything that was inside it. A child put back first
+ // would make a new folder at its parent's path, and the parent could then not be put back.
+ for record in records.sorted(by: { $0.originalURL.pathComponents.count < $1.originalURL.pathComponents.count }) {
+ if let failure = await service.restore(record.trashedItem, canUseHelper: canUseHelper) {
+ problems[record.id] = failure
+ } else {
+ restored.insert(record.id)
+ }
+ }
+ failures = problems
+ selectedIDs.subtract(restored)
+ if !restored.isEmpty {
+ apply(await log.remove(restored))
}
- }
- failures = problems
- selectedIDs.subtract(restored)
- if !restored.isEmpty {
- apply(await log.remove(restored))
}
}
diff --git a/Peel/Model/ResetPlan.swift b/Peel/Model/ResetPlan.swift
index 0b51c547..9d11b503 100644
--- a/Peel/Model/ResetPlan.swift
+++ b/Peel/Model/ResetPlan.swift
@@ -119,9 +119,9 @@ final class ResetPlan {
func putSettingsBack() async -> Bool {
refreshRunningState()
guard let backup, !isAppRunning else { return false }
- return await PreferenceBackup.restore(
- from: backup, of: app.bundleIdentifier, exclusions: ExclusionsStore.shared.exclusions
- ).isComplete
+ return await QuitGuard.shared.run {
+ await PreferenceBackup.restore(from: backup, of: app.bundleIdentifier, exclusions: ExclusionsStore.shared.exclusions)
+ }.isComplete
}
/// Quits the app and the helpers it ships, so nothing writes its settings again while they are cleared.
diff --git a/Peel/Model/SelectionCarrier.swift b/Peel/Model/SelectionCarrier.swift
index 5b4fe0dc..09fbd569 100644
--- a/Peel/Model/SelectionCarrier.swift
+++ b/Peel/Model/SelectionCarrier.swift
@@ -90,13 +90,15 @@ final class SelectionCarrier {
defer { isMoving = false }
var removal = RemovalInProgress()
var appsToQuit: [String] = []
- let pass = await CarriedSelection.pass(parts) { part in
- guard let tool = tool(of: part), let result = await tool.move(part, apps: apps) else {
- appsToQuit.append(tool(of: part)?.appToQuit(for: part) ?? part.title)
- return nil
+ let pass = await QuitGuard.shared.run {
+ await CarriedSelection.pass(parts) { part in
+ guard let tool = tool(of: part), let result = await tool.move(part, apps: apps) else {
+ appsToQuit.append(tool(of: part)?.appToQuit(for: part) ?? part.title)
+ return nil
+ }
+ await history.record(result, part: part.removalPart, sizes: part.measuredSizes, in: &removal)
+ return result
}
- await history.record(result, part: part.removalPart, sizes: part.measuredSizes, in: &removal)
- return result
}
history.finish(removal)
outcome.report(pass.result, appsToQuit: appsToQuit)
diff --git a/Peel/Model/SelfUninstall.swift b/Peel/Model/SelfUninstall.swift
index 5a1667f4..93bcba91 100644
--- a/Peel/Model/SelfUninstall.swift
+++ b/Peel/Model/SelfUninstall.swift
@@ -24,11 +24,17 @@ final class SelfUninstall {
}
/// Removes Peel. The plan is made first, and the steps nothing can undo (unregistering the helper and the
- /// login item) come after, so a plan that cannot be made leaves Peel as it was.
+ /// login item) come after, so a plan that cannot be made leaves Peel as it was. A quit is refused meanwhile,
+ /// since Peel ends itself once it has gone.
func run(installedApps: [InstalledApp], helper: HelperModel, recording record: (TrashResult) async -> Void = { _ in }) async {
isRunning = true
defer { isRunning = false }
+ await QuitGuard.shared.runRefusingQuit {
+ await remove(installedApps: installedApps, helper: helper, recording: record)
+ }
+ }
+ private func remove(installedApps: [InstalledApp], helper: HelperModel, recording record: (TrashResult) async -> Void) async {
let bundleURL = Bundle.main.bundleURL
guard let app = await AppLibrary.inspect(bundleURL) else {
failure = String(localized: "Peel couldn’t read its own files.")
diff --git a/Peel/PeelApp.swift b/Peel/PeelApp.swift
index 80a2e8bb..b3ff82d2 100644
--- a/Peel/PeelApp.swift
+++ b/Peel/PeelApp.swift
@@ -1,14 +1,18 @@
import PeelCore
import SwiftUI
-/// Decides whether Peel quits when its window closes. SwiftUI's documentation for `Window` says an app whose
-/// primary scene is a single window quits when that window closes. Peel keeps running in the menu bar while it
-/// watches the Trash, so it quits only when that setting is off.
+/// Decides whether Peel quits when its window closes, and when a quit goes ahead (`QuitGuard`). SwiftUI's
+/// documentation for `Window` says an app whose primary scene is a single window quits when that window closes.
+/// Peel keeps running in the menu bar while it watches the Trash, so it quits only when that setting is off.
@MainActor
final class PeelAppDelegate: NSObject, NSApplicationDelegate {
func applicationShouldTerminateAfterLastWindowClosed(_ application: NSApplication) -> Bool {
!UserDefaults.standard.bool(forKey: SettingsKey.watchesTrash)
}
+
+ func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply {
+ QuitGuard.shared.replyToQuit()
+ }
}
@main
diff --git a/Peel/Views/AppDetailView.swift b/Peel/Views/AppDetailView.swift
index 6df8ad8d..2f50e2b0 100644
--- a/Peel/Views/AppDetailView.swift
+++ b/Peel/Views/AppDetailView.swift
@@ -613,14 +613,17 @@ struct AppDetailView: View {
let plan = plan
defer { plan.question.finish() }
guard plan.runningProcesses.isEmpty else { return requestRemoval() }
- // The one step that goes before the move: `tccutil` only finds an app that is still in its place.
- let privacy = await PrivacyReset.reset(resetting(request.urls))
- let result = await plan.move(request)
- outcome.report(result, privacy: privacy)
- if let state = AppManagement.state(after: result, appBundles: [plan.app.url], movedByTheHelper: plan.privilegedURLs) {
- home.record(appManagement: state)
- }
- await history.record(result, tool: .applications, source: plan.app.name, sizes: request.sizes)
+ let result = await QuitGuard.shared.run {
+ // The one step that goes before the move: `tccutil` only finds an app that is still in its place.
+ let privacy = await PrivacyReset.reset(resetting(request.urls))
+ let result = await plan.move(request)
+ outcome.report(result, privacy: privacy)
+ if let state = AppManagement.state(after: result, appBundles: [plan.app.url], movedByTheHelper: plan.privilegedURLs) {
+ home.record(appManagement: state)
+ }
+ await history.record(result, tool: .applications, source: plan.app.name, sizes: request.sizes)
+ return result
+ }
if result.trashed.contains(where: { $0.originalURL == plan.app.url }) {
await library.load()
diff --git a/Peel/Views/MenuBarPanel.swift b/Peel/Views/MenuBarPanel.swift
index ab0756b1..17f4209b 100644
--- a/Peel/Views/MenuBarPanel.swift
+++ b/Peel/Views/MenuBarPanel.swift
@@ -47,7 +47,7 @@ struct MenuBarPanel: View {
SettingsLink { Text("Settings…") }
Button("About Peel") { openWindow(id: AboutView.windowID) }
Divider()
- Button("Quit Peel") { NSApp.terminate(nil) }
+ Button("Quit Peel") { QuitGuard.quit() }
.keyboardShortcut("q")
} label: {
Image(systemName: "gearshape")
diff --git a/Peel/Views/MultipleAppsView.swift b/Peel/Views/MultipleAppsView.swift
index 3a058ecc..9bb6c215 100644
--- a/Peel/Views/MultipleAppsView.swift
+++ b/Peel/Views/MultipleAppsView.swift
@@ -280,14 +280,17 @@ struct MultipleAppsView: View {
let plan = plan
defer { plan.question.finish() }
guard plan.runningProcesses.isEmpty else { return requestRemoval() }
- // The privacy reset runs before the move, because `tccutil` only finds an app that is still in its place.
- let privacy = await PrivacyReset.reset(resetting(request.urls))
- let result = await plan.move(request)
- outcome.report(result, privacy: privacy)
- if let state = AppManagement.state(after: result, appBundles: Set(plan.apps.map(\.url)), movedByTheHelper: plan.privilegedURLs) {
- home.record(appManagement: state)
+ let result = await QuitGuard.shared.run {
+ // The privacy reset runs before the move, because `tccutil` only finds an app that is still in its place.
+ let privacy = await PrivacyReset.reset(resetting(request.urls))
+ let result = await plan.move(request)
+ outcome.report(result, privacy: privacy)
+ if let state = AppManagement.state(after: result, appBundles: Set(plan.apps.map(\.url)), movedByTheHelper: plan.privilegedURLs) {
+ home.record(appManagement: state)
+ }
+ await history.record(result, tool: .applications, source: plan.historySource, sourceKey: plan.historySourceKey, sizes: request.sizes)
+ return result
}
- await history.record(result, tool: .applications, source: plan.historySource, sourceKey: plan.historySourceKey, sizes: request.sizes)
// When an app bundle moved, reloading the library changes the selection, which rebuilds this page. When
// only files moved, the plan is refreshed here: otherwise they would stay listed, and moving them again
// would fail for each one.
diff --git a/Peel/Views/ResetSheet.swift b/Peel/Views/ResetSheet.swift
index 1e923478..d73bd3d4 100644
--- a/Peel/Views/ResetSheet.swift
+++ b/Peel/Views/ResetSheet.swift
@@ -37,11 +37,13 @@ struct ResetSheet: View {
.confirmationDialog("Reset \(plan.app.name)?", isPresented: $isConfirming) {
Button("Reset", role: .destructive) {
Task {
- let result = await plan.performReset()
- if !result.trashed.isEmpty {
- changedFiles = true
+ await QuitGuard.shared.run {
+ let result = await plan.performReset()
+ if !result.trashed.isEmpty {
+ changedFiles = true
+ }
+ await history.record(result, tool: .applications, source: plan.app.name, sizes: sizes)
}
- await history.record(result, tool: .applications, source: plan.app.name, sizes: sizes)
}
}
Button("Cancel", role: .cancel) {}
diff --git a/Peel/Views/Settings/SavedSettingsSection.swift b/Peel/Views/Settings/SavedSettingsSection.swift
index 3fcbfff8..3ac59a0b 100644
--- a/Peel/Views/Settings/SavedSettingsSection.swift
+++ b/Peel/Views/Settings/SavedSettingsSection.swift
@@ -115,9 +115,9 @@ struct SavedSettingsSection: View {
}
workingOn = copy.id
defer { workingOn = nil }
- let restored = await PreferenceBackup.restore(
- from: copy.folder, of: copy.bundleIdentifier, exclusions: ExclusionsStore.shared.exclusions
- )
+ let restored = await QuitGuard.shared.run {
+ await PreferenceBackup.restore(from: copy.folder, of: copy.bundleIdentifier, exclusions: ExclusionsStore.shared.exclusions)
+ }
// The settings the app had until now may have become a copy of their own.
reload()
switch restored {
@@ -140,11 +140,13 @@ struct SavedSettingsSection: View {
defer { workingOn = nil }
// Measured before the move, since nothing is left at that path after it.
let size = await FileSize.allocatedSize(of: copy.folder)
- let result = await TrashService(exclusions: ExclusionsStore.shared.exclusions).trash([copy.folder])
- if let reason = result.failures.first?.reason {
- failure = Failure(title: String(localized: "The copy couldn’t be moved to the Trash."), message: reason.explanation)
+ await QuitGuard.shared.run {
+ let result = await TrashService(exclusions: ExclusionsStore.shared.exclusions).trash([copy.folder])
+ if let reason = result.failures.first?.reason {
+ failure = Failure(title: String(localized: "The copy couldn’t be moved to the Trash."), message: reason.explanation)
+ }
+ await history.record(result, tool: .applications, source: name, sizes: [URL: Int64](measured: [(copy.folder, size)]))
}
- await history.record(result, tool: .applications, source: name, sizes: [URL: Int64](measured: [(copy.folder, size)]))
reload()
}
diff --git a/Peel/Views/VendorNotes.swift b/Peel/Views/VendorNotes.swift
index df82f891..27ba989d 100644
--- a/Peel/Views/VendorNotes.swift
+++ b/Peel/Views/VendorNotes.swift
@@ -132,8 +132,11 @@ struct PackageReceiptSection: View {
private func forget(_ receipt: PackageReceipt, recording record: (TrashResult) async -> Void) async -> TrashResult {
isForgetting = true
defer { isForgetting = false }
- let result = await PackageActions.forget(receipt, exclusions: ExclusionsStore.shared.exclusions)
- await record(result)
+ let result = await QuitGuard.shared.run {
+ let result = await PackageActions.forget(receipt, exclusions: ExclusionsStore.shared.exclusions)
+ await record(result)
+ return result
+ }
await load()
return result
}
diff --git a/SAFETY.md b/SAFETY.md
index 3a69d3bd..5a0a30c6 100644
--- a/SAFETY.md
+++ b/SAFETY.md
@@ -107,10 +107,10 @@ link moves the link.
Peel never deletes anything of yours. Everything it removes goes to the Trash, and everything is recorded so
History can put it back; History keeps the most recent 20,000 items, and what it forgets is still in the Trash.
That includes an installer receipt you ask Peel to forget: the two files that make it up go to the Trash
-through the helper, where `pkgutil --forget` would have discarded them for good. Each item is written down the
-moment it moves, so a removal cut short by a quit or a crash still reaches History, as an interrupted removal,
-the next time Peel or `peel` opens it. The space is freed when *you* empty the Trash: Peel never does
-that for you.
+through the helper, where `pkgutil --forget` would have discarded them for good. Quitting Peel waits for a
+removal until History has it, and each item is written down the moment it moves, so one cut short by a crash
+or Force Quit still reaches History, as an interrupted removal, the next time Peel or `peel` opens it. The
+space is freed when *you* empty the Trash: Peel never does that for you.
The one file Peel deletes outright is its own list of refusals, and only when `peel history --refused --clear` is
asked to forget it.