Uninstall Mac apps with every file they leave behind, and see why each belongs. Free up space, fine-tune macOS, and set up Terminal.
Swift cache-cleanercleanerclideveloper-toolsdisk-cleanupdisk-spaceduplicate-finderhomebrewliquid-glassmac-cleanermacosmacos-appmacos-golden-gatemacos-tahoemacos-tweaksswiftswiftuiterminal-themesuninstalluninstaller
A removal moves what its question asked about
Țugui Dragoșcc3d357f3b14
diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/RemovalQuestion.swift b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalQuestion.swiftnew file mode 100644index 00000000..49cd1628--- /dev/null+++ b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalQuestion.swift@@ -0,0 +1,62 @@+public import Foundation+public import Observation++/// A page's removal, from the question that asks about it to its end, held by the page's model.+///+/// What the question asks about is frozen when it appears, and the move takes exactly that. The question stands for+/// what it showed, so a selection that changes under it closes it. One removal runs at a time, and it counts as+/// running from the moment it is confirmed until the page has recorded it and scanned again. A scan the page asks+/// for meanwhile waits: it runs once the question is closed, and the scan that ends a removal covers one asked for+/// during it.+@MainActor+@Observable+public final class RemovalQuestion {+ /// Whether the question is up. The page shows it from this, and closing it sets this back.+ public var isAsking = false+ /// What the question asks about, as it was when it appeared.+ public private(set) var request: RemovalRequest?+ public private(set) var isRemoving = false+ @ObservationIgnored private var isScanWaiting = false++ public init() {}++ public func ask(_ request: RemovalRequest) {+ self.request = request+ isAsking = true+ }++ /// Closes the question once the selection is no longer what it asks about.+ public func selectionChanged(to selected: Set<URL>) {+ if isAsking, !isRemoving, selected != request?.urls {+ isAsking = false+ }+ }++ /// Starts the removal the question asked about, or answers nil while one is running.+ public func start() -> RemovalRequest? {+ guard !isRemoving, let request else { return nil }+ isRemoving = true+ return request+ }++ /// Ends the removal once it has moved, recorded and scanned again.+ public func finish() {+ isRemoving = false+ isScanWaiting = false+ }++ /// True when a scan the page asks for may run now. Otherwise it waits for the question to close.+ public func mayScan() -> Bool {+ guard !isAsking, !isRemoving else {+ isScanWaiting = true+ return false+ }+ isScanWaiting = false+ return true+ }++ /// True when a scan waited for the question, which has closed without starting a removal.+ public var hasWaitingScan: Bool {+ isScanWaiting && !isAsking && !isRemoving+ }+}diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/RemovalRequest.swift b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalRequest.swiftnew file mode 100644index 00000000..fe580718--- /dev/null+++ b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalRequest.swift@@ -0,0 +1,18 @@+public import Foundation++/// What a confirmation asks about: the selection as it was when the question appeared, and the sizes the scan+/// measured for it. The move takes exactly that, and History records those sizes.+public struct RemovalRequest: Sendable, Equatable {+ public let urls: Set<URL>+ /// The size of each item the scan measured. An item missing here was not measured.+ public let sizes: [URL: Int64]++ public init(urls: Set<URL>, sizes: [URL: Int64]) {+ self.urls = urls+ self.sizes = sizes+ }++ public var total: SizeTotal {+ SizeTotal(urls.map { sizes[$0] })+ }+}diff --git a/Packages/PeelCore/Tests/PeelCoreTests/RemovalQuestionTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/RemovalQuestionTests.swiftnew file mode 100644index 00000000..0145ed50--- /dev/null+++ b/Packages/PeelCore/Tests/PeelCoreTests/RemovalQuestionTests.swift@@ -0,0 +1,78 @@+import Foundation+@testable import PeelCore+import Testing++@MainActor+struct RemovalQuestionTests {+ private let first = RemovalRequest(urls: [URL(filePath: "/Users/me/Library/Caches/a")], sizes: [:])++ /// The question asks about the selection as it was when it appeared, and the move takes exactly that.+ @Test func startsTheRemovalItAskedAbout() {+ let question = RemovalQuestion()+ question.ask(first)++ #expect(question.isAsking)+ #expect(question.start() == first)+ }++ /// The question stands for what it showed: a selection that changes under it closes it, and one that stays+ /// the same leaves it up.+ @Test func closesWhenTheSelectionChangesUnderIt() {+ let question = RemovalQuestion()+ question.ask(first)++ question.selectionChanged(to: first.urls)+ #expect(question.isAsking)+ question.selectionChanged(to: [])+ #expect(!question.isAsking)+ }++ /// A second confirmation while a removal runs starts nothing, and the removal counts as running until it ends.+ @Test func runsOneRemovalAtATime() {+ let question = RemovalQuestion()+ question.ask(first)++ #expect(question.start() == first)+ #expect(question.isRemoving)+ #expect(question.start() == nil)+ question.finish()+ #expect(!question.isRemoving)+ }++ /// A scan the page asks for while the question is up waits, and runs once the question is closed.+ @Test func aScanAskedForWhileTheQuestionIsUpWaitsUntilItCloses() {+ let question = RemovalQuestion()+ question.ask(first)++ #expect(!question.mayScan())+ #expect(!question.hasWaitingScan)+ question.isAsking = false+ #expect(question.hasWaitingScan)+ #expect(question.mayScan())+ #expect(!question.hasWaitingScan)+ }++ /// A scan asked for during a removal waits too, and the scan that ends the removal covers it.+ @Test func aScanAskedForDuringARemovalIsCoveredByTheScanThatEndsIt() {+ let question = RemovalQuestion()+ question.ask(first)+ _ = question.start()+ question.isAsking = false++ #expect(!question.mayScan())+ #expect(!question.hasWaitingScan)+ question.selectionChanged(to: [])+ #expect(question.isRemoving)+ question.finish()+ #expect(!question.hasWaitingScan)+ #expect(question.mayScan())+ }++ @Test func totalsWhatWasMeasuredAndSaysWhenSomethingWasNot() {+ let measured = URL(filePath: "/Users/me/Library/Caches/measured")+ let unknown = URL(filePath: "/Users/me/Library/Caches/unknown")++ #expect(RemovalRequest(urls: [measured], sizes: [measured: 100]).total == SizeTotal(known: 100, isComplete: true))+ #expect(RemovalRequest(urls: [measured, unknown], sizes: [measured: 100]).total == SizeTotal(known: 100, isComplete: false))+ }+}diff --git a/Peel/Model/BulkRemovalPlan.swift b/Peel/Model/BulkRemovalPlan.swiftindex 11f8a200..22d5bccb 100644--- a/Peel/Model/BulkRemovalPlan.swift+++ b/Peel/Model/BulkRemovalPlan.swift@@ -11,7 +11,9 @@ final class BulkRemovalPlan {/// The scan this page runs, which a newer one or the Stop button ends.let scanRun = ScanRun()var isScanning: Bool { scanRun.isRunning }- private(set) var isRemoving = false+ /// The question before a removal, and the removal it starts.+ let question = RemovalQuestion()+ var isRemoving: Bool { question.isRemoving }/// Every installed app as of the last scan, to tell a chosen app's processes from another installed app's.private var installedApps: [InstalledApp] = []var selectedURLs: Set<URL> = []@@ -25,13 +27,12 @@ final class BulkRemovalPlan {var items: [BulkUninstallation.Item] { bulk?.items ?? [] }- /// False when a selected item's size is unknown, so the bar reads "Over" the sum.- var isSelectionMeasured: Bool {- items.allSatisfy { !selectedURLs.contains($0.url) || $0.isMeasured }- }-- var selectedSize: Int64 {- items.filter { selectedURLs.contains($0.url) }.reduce(0) { $0 + $1.size }+ /// What a confirmation would ask about now: the selection, with the sizes this scan measured.+ var request: RemovalRequest {+ RemovalRequest(+ urls: selectedURLs,+ sizes: [URL: Int64](measured: items.filter { selectedURLs.contains($0.url) }.map { ($0.url, $0.isMeasured ? $0.size : nil) })+ )}var total: SizeTotal { bulk?.total ?? SizeTotal(known: 0, isComplete: true) }@@ -82,19 +83,14 @@ final class BulkRemovalPlan {selectedURLs = choices.update(selectedURLs, in: bulk, canUseHelper: canUseHelper)}- func removeSelected() async -> TrashResult {+ /// Moves what `request` asked about, whatever has been selected since.+ func move(_ request: RemovalRequest) async -> TrashResult {guard let bulk else { return TrashResult() }- isRemoving = true- defer { isRemoving = false }- let urls = bulk.removalOrder(of: selectedURLs)+ let urls = bulk.removalOrder(of: request.urls)return await TrashService(exclusions: ExclusionsStore.shared.exclusions).trash(urls, usingHelperFor: bulk.privilegedURLs)}- var sizes: [URL: Int64] {- [URL: Int64](measured: items.map { ($0.url, $0.isMeasured ? $0.size : nil) })- }-/// The source History records: up to three app names, or a count in English that History shows in the/// user's language through `historySourceKey`.var historySource: String {diff --git a/Peel/Model/RemovalPlan.swift b/Peel/Model/RemovalPlan.swiftindex f324e1fc..eae419e1 100644--- a/Peel/Model/RemovalPlan.swift+++ b/Peel/Model/RemovalPlan.swift@@ -10,7 +10,9 @@ final class RemovalPlan {/// The scan this page runs, which a newer one or the Stop button ends.let scanRun = ScanRun()var isScanning: Bool { scanRun.isRunning }- private(set) var isRemoving = false+ /// The question before a removal, and the removal it starts.+ let question = RemovalQuestion()+ var isRemoving: Bool { question.isRemoving }/// The kinds of files and links this app opens by default, so the page can say which app opens them once/// it is gone.private(set) var defaultRoles: [DefaultRole] = []@@ -66,13 +68,11 @@ final class RemovalPlan {app.isPeelItself}- /// False when the size of something selected is unknown, so the bar shows the sum as "Over" that amount.- var isSelectionMeasured: Bool {- (!selectedURLs.contains(app.url) || isAppMeasured) && selectedURLs.allSatisfy { leftoverSizes[$0]?.isMeasured ?? true }- }-- var selectedSize: Int64 {- selectedURLs.reduce(0) { $0 + (leftoverSizes[$1]?.size ?? 0) } + (selectedURLs.contains(app.url) ? appSize : 0)+ /// What a confirmation would ask about now: the selection, with the sizes this scan measured.+ var request: RemovalRequest {+ RemovalRequest(urls: selectedURLs, sizes: [URL: Int64](measured: selectedURLs.map { url in+ (url, url == app.url ? (isAppMeasured ? appSize : nil) : leftoverSizes[url].flatMap { $0.isMeasured ? $0.size : nil })+ }))}var isAppRunning: Bool {@@ -127,10 +127,9 @@ final class RemovalPlan {(VendorRemoval.uninstaller(for: app), VendorRemoval.systemExtensions(in: app))}- func removeSelected() async -> TrashResult {- isRemoving = true- defer { isRemoving = false }- let urls = uninstallation?.removalOrder(of: selectedURLs) ?? []+ /// Moves what `request` asked about, whatever has been selected since.+ func move(_ request: RemovalRequest) async -> TrashResult {+ let urls = uninstallation?.removalOrder(of: request.urls) ?? []// These paths are about to hold something else, or nothing, so their cached icons are dropped.IconCache.forget(urls)return await TrashService(exclusions: ExclusionsStore.shared.exclusions).trash(urls, usingHelperFor: uninstallation?.privilegedURLs ?? [])diff --git a/Peel/Views/AppDetailView.swift b/Peel/Views/AppDetailView.swiftindex b86d636b..297a2d86 100644--- a/Peel/Views/AppDetailView.swift+++ b/Peel/Views/AppDetailView.swift@@ -8,7 +8,6 @@ struct AppDetailView: View {@Environment(RemovalHistoryStore.self) private var history@Environment(HomebrewLibrary.self) private var homebrew@State private var plan: RemovalPlan- @State private var isConfirmingRemoval = false@State private var isShowingQuitAlert = false@Environment(RemovalOutcome.self) private var outcome@State private var isRescanning = false@@ -34,11 +33,12 @@ struct AppDetailView: View {var body: some View {page.confirmationDialog(- Text.movingToTrash(plan.selectedURLs.count, SizeTotal(known: plan.selectedSize, isComplete: plan.isSelectionMeasured)),- isPresented: $isConfirmingRemoval+ Text.movingToTrash(plan.question.request?.urls.count ?? 0, plan.question.request?.total ?? SizeTotal([])),+ isPresented: Bindable(plan.question).isAsking) {Button("Move to Trash") {- Task { await remove() }+ guard let request = plan.question.start() else { return }+ Task { await remove(request) }}Button("Cancel", role: .cancel) {}} message: {@@ -77,6 +77,14 @@ struct AppDetailView: View {.onChange(of: helper.canAct) { _, canAct inplan.follow(canUseHelper: canAct)}+ .onChange(of: plan.selectedURLs) { _, selected in+ plan.question.selectionChanged(to: selected)+ }+ .onChange(of: plan.question.isAsking) {+ if plan.question.hasWaitingScan {+ Task { await rescan() }+ }+ }}private var phase: ScanPhase {@@ -165,17 +173,18 @@ struct AppDetailView: View {defaultsSectionPackageReceiptSection(app: plan.app, isExcluded: plan.isExcluded)}- .opacity(isBusy ? Busy.dimmed : 1)- .disabled(isBusy)- .motion(value: isBusy)+ .opacity(isAtWork ? Busy.dimmed : 1)+ .disabled(isAtWork)+ .motion(value: isAtWork)}}.scanState(phase, fadesInResults: false, scan: plan.scanRun).safeAreaBar(edge: .bottom) {if plan.scan != nil {+ let selected = plan.request.totalRemovalBar(- selectedSize: plan.selectedSize,- isSelectionMeasured: plan.isSelectionMeasured,+ selectedSize: selected.known,+ isSelectionMeasured: selected.isComplete,isScanning: isBusy,scan: plan.scanRun,isEnabled: !plan.selectedURLs.isEmpty && !plan.isRemoving && !isBusy,@@ -435,8 +444,9 @@ struct AppDetailView: View {}/// A reset moves files to the Trash, and an exclusion changes what may be listed at all, so after either- /// one the tables are out of date.+ /// one the tables are out of date. A scan asked for while the question is up or a removal runs waits for them.private func rescan() async {+ guard plan.question.mayScan() else { return }await plan.refresh(installedApps: library.apps, canUseHelper: helper.canAct, casks: homebrew.caskEvidence, receipts: homebrew.receipts)}@@ -546,15 +556,20 @@ struct AppDetailView: View {isRescanning || (plan.isScanning && plan.scan != nil)}- /// The app, when this removal resets its privacy permissions.- private var resetting: [InstalledApp] {- resetsPrivacy ? PrivacyReset.apps(among: [plan.app], moving: plan.selectedURLs) : []+ /// True while the page scans again or a removal runs, when its rows take no clicks.+ private var isAtWork: Bool {+ isBusy || plan.isRemoving+ }++ /// The app, when a removal of `urls` resets its privacy permissions.+ private func resetting(_ urls: Set<URL>) -> [InstalledApp] {+ resetsPrivacy ? PrivacyReset.apps(among: [plan.app], moving: urls) : []}/// The confirmation's message: the privacy reset, which History can't undo, and Homebrew's own record/// of the app, which the move doesn't touch.private var removalNote: Text? {- let privacy = resetting.isEmpty+ let privacy = resetting(plan.question.request?.urls ?? []).isEmpty? nil: Text("The app’s privacy permissions are cleared first, and History can’t bring them back.")// Homebrew keeps its own record of what it installed, and moving the bundle does not touch it.@@ -573,21 +588,22 @@ struct AppDetailView: View {if plan.selectedURLs.contains(plan.app.url), plan.isAppRunning {isShowingQuitAlert = true} else {- isConfirmingRemoval = true+ plan.question.ask(plan.request)}}- private func remove() async {+ /// One removal, from the privacy reset before the move to the scan after it, with the page busy throughout.+ private func remove(_ request: RemovalRequest) async {+ let plan = plan+ defer { plan.question.finish() }// 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)- let result = await plan.removeSelected()+ 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)}- let sizes = [URL: Int64](measured: [(plan.app.url, plan.isAppMeasured ? plan.appSize : nil)]- + (plan.scan?.leftovers ?? []).map { ($0.url, $0.isMeasured ? $0.size : nil) })- await history.record(result, tool: .applications, source: plan.app.name, sizes: sizes)+ await history.record(result, tool: .applications, source: plan.app.name, sizes: request.sizes)if result.trashed.contains(where: { $0.originalURL == plan.app.url }) {await library.load()diff --git a/Peel/Views/MultipleAppsView.swift b/Peel/Views/MultipleAppsView.swiftindex 3c9c1f2d..cb45fcd4 100644--- a/Peel/Views/MultipleAppsView.swift+++ b/Peel/Views/MultipleAppsView.swift@@ -8,7 +8,6 @@ struct MultipleAppsView: View {@Environment(RemovalHistoryStore.self) private var history@Environment(HomebrewLibrary.self) private var homebrew@State private var plan: BulkRemovalPlan- @State private var isConfirmingRemoval = false@State private var isShowingQuitAlert = false@State private var resetsPrivacy = false@State private var isRescanning = false@@ -57,12 +56,14 @@ struct MultipleAppsView: View {}}}- .scanState(phase, isRescanning: isRescanning, fadesInResults: false, scan: plan.scanRun)+ .disabled(plan.isRemoving)+ .scanState(phase, isRescanning: isRescanning || plan.isRemoving, fadesInResults: false, scan: plan.scanRun).safeAreaBar(edge: .bottom) {if plan.bulk != nil {+ let selected = plan.request.totalRemovalBar(- selectedSize: plan.selectedSize,- isSelectionMeasured: plan.isSelectionMeasured,+ selectedSize: selected.known,+ isSelectionMeasured: selected.isComplete,isScanning: plan.isScanning,scan: plan.scanRun,isEnabled: !plan.selectedURLs.isEmpty && !plan.isRemoving && !plan.isScanning,@@ -82,15 +83,16 @@ struct MultipleAppsView: View {}}.confirmationDialog(- Text.movingToTrash(plan.selectedURLs.count, SizeTotal(known: plan.selectedSize, isComplete: plan.isSelectionMeasured)),- isPresented: $isConfirmingRemoval+ Text.movingToTrash(plan.question.request?.urls.count ?? 0, plan.question.request?.total ?? SizeTotal([])),+ isPresented: Bindable(plan.question).isAsking) {Button("Move to Trash") {- Task { await remove() }+ guard let request = plan.question.start() else { return }+ Task { await remove(request) }}Button("Cancel", role: .cancel) {}} message: {- if !resetting.isEmpty {+ if !resetting(plan.question.request?.urls ?? []).isEmpty {Text("The selected apps’ privacy permissions are cleared first, and History can’t bring them back.")}}@@ -105,14 +107,26 @@ struct MultipleAppsView: View {// app. The short wait lets the selection settle: a newer change cancels this task before it scans.try? await Task.sleep(for: .milliseconds(300))guard !Task.isCancelled, !(plan.bulk == nil && plan.scanRun.wasStopped) else { return }- await plan.refresh(installedApps: library.apps, canUseHelper: helper.canAct, casks: homebrew.caskEvidence, receipts: homebrew.receipts)- }- .rescanOnExclusionChange("MultipleAppsView") {- await plan.refresh(installedApps: library.apps, canUseHelper: helper.canAct, casks: homebrew.caskEvidence, receipts: homebrew.receipts)+ await rescan()}+ .rescanOnExclusionChange("MultipleAppsView") { await rescan() }.onChange(of: helper.canAct) { _, canAct inplan.follow(canUseHelper: canAct)}+ .onChange(of: plan.selectedURLs) { _, selected in+ plan.question.selectionChanged(to: selected)+ }+ .onChange(of: plan.question.isAsking) {+ if plan.question.hasWaitingScan {+ Task { await rescan() }+ }+ }+ }++ /// A scan asked for while the question is up or a removal runs waits for them.+ private func rescan() async {+ guard plan.question.mayScan() else { return }+ await plan.refresh(installedApps: library.apps, canUseHelper: helper.canAct, casks: homebrew.caskEvidence, receipts: homebrew.receipts)}private var phase: ScanPhase {@@ -194,28 +208,31 @@ struct MultipleAppsView: View {return lines.isEmpty ? nil : lines.joined(separator: "\n\n")}- /// The apps whose privacy permissions this removal resets.- private var resetting: [InstalledApp] {- resetsPrivacy ? PrivacyReset.apps(among: plan.apps, moving: plan.selectedURLs) : []+ /// The apps whose privacy permissions a removal of `urls` resets.+ private func resetting(_ urls: Set<URL>) -> [InstalledApp] {+ resetsPrivacy ? PrivacyReset.apps(among: plan.apps, moving: urls) : []}private func requestRemoval() {if !plan.runningApps.isEmpty {isShowingQuitAlert = true} else {- isConfirmingRemoval = true+ plan.question.ask(plan.request)}}- private func remove() async {+ /// One removal, from the privacy reset before the move to the scan after it, with the page busy throughout.+ private func remove(_ request: RemovalRequest) async {+ let plan = plan+ defer { plan.question.finish() }// 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)- let result = await plan.removeSelected()+ 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: plan.sizes)+ 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.