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
An app that runs quits before any file of it moves
Țugui Dragoș0a250a247a02
diff --git a/Localization/Peel/Localizable.xcstrings b/Localization/Peel/Localizable.xcstringsindex 676438fc..2c572277 100644--- a/Localization/Peel/Localizable.xcstrings+++ b/Localization/Peel/Localizable.xcstrings@@ -539,6 +539,112 @@}}},+ "%@ didn’t quit." : {+ "localizations" : {+ "cs" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Nepodařilo se ukončit: %@."+ }+ },+ "de" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Nicht beendet: %@."+ }+ },+ "es" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "No se ha podido salir de %@."+ }+ },+ "fr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Impossible de quitter %@."+ }+ },+ "it" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Uscita da %@ non riuscita."+ }+ },+ "ja" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "%@を終了できませんでした。"+ }+ },+ "ko" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "%@이(가) 종료되지 않았습니다."+ }+ },+ "nl" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Het stoppen van %@ is niet gelukt."+ }+ },+ "pl" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Nie udało się zakończyć: %@."+ }+ },+ "pt" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "O encerramento de %@ não foi concluído."+ }+ },+ "ro" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "%@ încă rulează."+ }+ },+ "ru" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Не удалось завершить %@."+ }+ },+ "sv" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "%@ avslutades inte."+ }+ },+ "tr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "%@ kapanmadı."+ }+ },+ "uk" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Не завершено: %@."+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "%@尚未退出。"+ }+ },+ "zh-Hant" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "%@尚未結束。"+ }+ }+ }+ },"%@ doesn’t say where it updates from in a way Peel can read. Peel reads an app’s update feed from the app’s own files, and asking Apple about every app instead would send Apple a list of what is installed on this Mac. Look for an update inside the app." : {"localizations" : {"cs" : {@@ -9595,6 +9701,112 @@}}},+ "An app may be waiting for you, for example to save your work. Force Quit closes what is still open at once, and what isn’t saved is lost." : {+ "localizations" : {+ "cs" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Aplikace možná čeká, až něco uděláte, například uložíte svou práci. Když kliknete na Vynutit ukončení, vše, co je stále otevřené, se okamžitě zavře a co není uložené, se ztratí."+ }+ },+ "de" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Eine App wartet möglicherweise auf dich, zum Beispiel darauf, dass du deine Arbeit sicherst. „Sofort beenden“ schließt umgehend, was noch geöffnet ist, und was nicht gesichert ist, geht dabei verloren."+ }+ },+ "es" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Puede que una app te esté esperando, por ejemplo, para que guardes tu trabajo. “Forzar salida” cierra al instante lo que sigue abierto, y lo que no se haya guardado se pierde."+ }+ },+ "fr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Une app attend peut-être une action de votre part, par exemple pour enregistrer votre travail. « Forcer à quitter » ferme immédiatement ce qui est encore ouvert, et ce qui n’a pas été enregistré est perdu."+ }+ },+ "it" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Un’app potrebbe essere in attesa di una tua risposta, ad esempio per salvare il tuo lavoro. “Uscita forzata” chiude subito ciò che è ancora aperto, e ciò che non è stato salvato va perso."+ }+ },+ "ja" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "アプリが、作業の保存などの操作を待っている可能性があります。“強制終了”をクリックすると、まだ開いているものがすぐに閉じられ、保存していない変更内容は失われます。"+ }+ },+ "ko" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "앱이 작업 저장 등 사용자의 동작을 기다리고 있을 수 있습니다. ‘강제 종료’는 아직 열려 있는 항목을 즉시 닫으며, 저장하지 않은 내용은 유실됩니다."+ }+ },+ "nl" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Een app wacht misschien op je, bijvoorbeeld om je werk te bewaren. 'Forceer stop' sluit meteen wat nog open is, en wat niet is bewaard, gaat verloren."+ }+ },+ "pl" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Aplikacja może czekać na Ciebie, na przykład aż zachowasz swoją pracę. „Wymuś koniec” natychmiast zamyka to, co jest nadal otwarte, a wszystko, czego nie zachowano, przepada."+ }+ },+ "pt" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Um app pode estar esperando por você, por exemplo, para salvar o seu trabalho. Forçar Encerrar fecha imediatamente o que ainda está aberto, e o que não estiver salvo será perdido."+ }+ },+ "ro" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "S‑ar putea ca o aplicație să aștepte ceva de la dvs., de exemplu să vă salvați lucrările. Dacă faceți clic pe Închideți forțat aplicația, ce este încă deschis se închide imediat, iar ce nu este salvat se pierde."+ }+ },+ "ru" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Возможно, приложение ждет Ваших действий, например сохранения работы. Кнопка «Завершить принудительно» сразу закрывает то, что еще открыто, и все несохраненное будет потеряно."+ }+ },+ "sv" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "En app kanske väntar på dig, till exempel på att du ska spara ditt arbete. Om du klickar på Tvångsavsluta stängs det som fortfarande är öppet direkt, och det som inte har sparats går förlorat."+ }+ },+ "tr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Bir uygulama, örneğin çalışmalarınızı kaydetmeniz için sizi bekliyor olabilir. Çıkmaya Zorla, hâlâ açık olanı hemen kapatır ve kaydedilmemiş her şey kaybolur."+ }+ },+ "uk" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Можливо, програма чекає на вас, щоб ви, наприклад, зберегли свою роботу. «Примусово завершити» відразу закриває те, що досі відкрите, і все незбережене буде втрачено."+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "某个App可能正在等待你的操作,例如保存你的工作成果。“强制退出”会立即关闭仍处于打开状态的程序,未保存的内容将会丢失。"+ }+ },+ "zh-Hant" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "App可能正在等待你的操作,例如儲存你的工作成果。「強制結束」會立即關閉仍然打開的程式,未儲存的內容將會遺失。"+ }+ }+ }+ },"An app that needs you stops jumping up and down in the Dock." : {"localizations" : {"cs" : {@@ -32180,6 +32392,112 @@}}},+ "Force Quit" : {+ "localizations" : {+ "cs" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Vynutit ukončení"+ }+ },+ "de" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Sofort beenden"+ }+ },+ "es" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Forzar salida"+ }+ },+ "fr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Forcer à quitter"+ }+ },+ "it" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Uscita forzata"+ }+ },+ "ja" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "強制終了"+ }+ },+ "ko" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "강제 종료"+ }+ },+ "nl" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Forceer stop"+ }+ },+ "pl" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Wymuś koniec"+ }+ },+ "pt" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Forçar Encerrar"+ }+ },+ "ro" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Închideți forțat aplicația"+ }+ },+ "ru" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Завершить принудительно"+ }+ },+ "sv" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Tvångsavsluta"+ }+ },+ "tr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Çıkmaya Zorla"+ }+ },+ "uk" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Примусово завершити"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "强制退出"+ }+ },+ "zh-Hant" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "強制結束"+ }+ }+ }+ },"Forget" : {"localizations" : {"cs" : {diff --git a/Peel/Model/BulkRemovalPlan.swift b/Peel/Model/BulkRemovalPlan.swiftindex 610e0bbe..6a872c84 100644--- a/Peel/Model/BulkRemovalPlan.swift+++ b/Peel/Model/BulkRemovalPlan.swift@@ -43,13 +43,14 @@ final class BulkRemovalPlan {var unreadableLocations: [SearchLocation] { bulk?.unreadableLocations ?? [] }- /// The chosen apps that are running, helpers included, with anything of theirs selected. Files never move out- /// from under a running app, so an app that stays still quits before a file of its own moves.- var runningApps: [InstalledApp] {+ /// The processes of the chosen apps with anything of theirs selected that run now, helpers included. Files never+ /// move out from under a running app, so an app that stays still quits before a file of its own moves.+ var runningProcesses: [NSRunningApplication] {let running = RunningCopies.currentlet owners = Set(items.filter { selectedURLs.contains($0.url) }.flatMap(\.apps))- return apps.filter { app in- owners.contains(app.bundleIdentifier) && !RunningCopies.belonging(to: app, among: running, installedApps: installedApps).isEmpty+ return apps.filter { owners.contains($0.bundleIdentifier) }.flatMap { app in+ RunningCopies.belonging(to: app, among: running, installedApps: installedApps)+ .compactMap { NSRunningApplication(processIdentifier: $0.identifier) }}}@@ -58,15 +59,6 @@ final class BulkRemovalPlan {bulk?.staying(selected: selectedURLs) ?? []}- func quitRunningApps() {- let running = RunningCopies.current- for app in runningApps {- for process in RunningCopies.belonging(to: app, among: running, installedApps: installedApps) {- NSRunningApplication(processIdentifier: process.identifier)?.terminate()- }- }- }-func refresh(installedApps: [InstalledApp], canUseHelper: Bool, casks: [HomebrewPackage] = [], receipts: Set<String> = []) async {self.canUseHelper = canUseHelperlet apps = appsdiff --git a/Peel/Model/QuitBeforeRemoving.swift b/Peel/Model/QuitBeforeRemoving.swiftnew file mode 100644index 00000000..fe3468bc--- /dev/null+++ b/Peel/Model/QuitBeforeRemoving.swift@@ -0,0 +1,103 @@+import AppKit+import Observation++/// 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+/// the person, to save their work for example, so forcing it is offered, never done unasked.+@Observable+final class QuitBeforeRemoving {+ /// The processes the alerts name.+ private(set) var running: [NSRunningApplication] = []+ /// 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.+ var isOfferingToForce = false+ /// True from the moment they are asked to quit until none runs or the person gives up.+ private(set) var isWaiting = false+ @ObservationIgnored private var goOn: (() -> Void)?+ @ObservationIgnored private var following: Task<Void, Never>?++ /// How long a quitting app is given before forcing it is offered. An app takes a moment to quit, and one still+ /// open after this is most likely waiting for the person.+ private static let patience: Duration = .seconds(10)++ /// The names of what still runs, for the alerts.+ var names: String {+ running.filter { !$0.isTerminated }.map { $0.localizedName ?? $0.bundleIdentifier ?? "" }.formatted(.list(type: .and))+ }++ /// Goes on at once when none of `processes` runs, and otherwise asks the person to quit them first.+ func check(_ processes: [NSRunningApplication], then goOn: @escaping () -> Void) {+ let open = processes.filter { !$0.isTerminated }+ guard !open.isEmpty else { return goOn() }+ running = open+ 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()+ }++ /// 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()+ }++ /// Stops waiting, and nothing goes on.+ func giveUp() {+ following?.cancel()+ following = nil+ goOn = nil+ isWaiting = false+ isOfferingToForce = false+ }++ private func follow() {+ following?.cancel()+ isWaiting = true+ let processes = running+ following = Task {+ let offer = Task {+ try? await Task.sleep(for: Self.patience)+ guard !Task.isCancelled else { return }+ isOfferingToForce = true+ }+ await Self.untilGone(processes)+ offer.cancel()+ guard !Task.isCancelled else { return }+ isWaiting = false+ isOfferingToForce = false+ let goOn = goOn+ self.goOn = nil+ await Self.untilNoSheet()+ goOn?()+ }+ }++ /// Returns once the sheets on Peel's windows have ended, such as the offer that has just closed. A window shows one+ /// sheet at a time, and one presented while another is still closing can fail to show.+ private static func untilNoSheet() async {+ let ends = NotificationCenter.default.notifications(named: NSWindow.didEndSheetNotification)+ let windows = NSApp.windows.filter { $0.attachedSheet != nil }+ guard !windows.isEmpty else { return }+ for await _ in ends where windows.allSatisfy({ $0.attachedSheet == nil }) {+ 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.+ private 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/RemovalPlan.swift b/Peel/Model/RemovalPlan.swiftindex eae419e1..a8f57f79 100644--- a/Peel/Model/RemovalPlan.swift+++ b/Peel/Model/RemovalPlan.swift@@ -75,10 +75,6 @@ final class RemovalPlan {}))}- var isAppRunning: Bool {- !relatedRunningApps.isEmpty- }-var privilegedURLs: Set<URL> { uninstallation?.privilegedURLs ?? [] }var requiresHelper: Bool {@@ -135,14 +131,8 @@ final class RemovalPlan {return await TrashService(exclusions: ExclusionsStore.shared.exclusions).trash(urls, usingHelperFor: uninstallation?.privilegedURLs ?? [])}- /// Quits the app and the helpers it ships, so nothing rewrites its files while they are removed.- func quitApp() {- for running in relatedRunningApps {- running.terminate()- }- }-- private var relatedRunningApps: [NSRunningApplication] {+ /// The app's processes that run now, the helpers it ships included, which quit before any of its files move.+ var runningProcesses: [NSRunningApplication] {RunningCopies.belonging(to: app, among: RunningCopies.current, installedApps: installedApps).compactMap { NSRunningApplication(processIdentifier: $0.identifier) }}diff --git a/Peel/Views/AppDetailView.swift b/Peel/Views/AppDetailView.swiftindex 965c16d6..8d21dd66 100644--- a/Peel/Views/AppDetailView.swift+++ b/Peel/Views/AppDetailView.swift@@ -8,7 +8,7 @@ struct AppDetailView: View {@Environment(RemovalHistoryStore.self) private var history@Environment(HomebrewLibrary.self) private var homebrew@State private var plan: RemovalPlan- @State private var isShowingQuitAlert = false+ @State private var quitting = QuitBeforeRemoving()@Environment(RemovalOutcome.self) private var outcome@State private var isRescanning = false@State private var resetsPrivacy = false@@ -55,10 +55,14 @@ struct AppDetailView: View {} message: {Text("macOS forgets what \(plan.app.name) was allowed to access, such as the camera, the microphone, or your files, and the app asks you again the next time it needs them. History can’t undo this.")}- .alert("Quit \(plan.app.name) before removing it.", isPresented: $isShowingQuitAlert) {- Button("Quit \(plan.app.name)") { plan.quitApp() }- Button("Cancel", role: .cancel) {}+ .alert(quitTitle, isPresented: Bindable(quitting).isAsking) {+ Button("Quit \(plan.app.name)") { quitting.quit() }+ Button("Cancel", role: .cancel) { quitting.giveUp() }+ } message: {+ Text(verbatim: quitting.names)}+ .forceQuitOffer(quitting)+ .onDisappear { quitting.giveUp() }.sheet(isPresented: $isShowingReset, onDismiss: {guard resetChangedFiles else { return }resetChangedFiles = false@@ -192,7 +196,7 @@ struct AppDetailView: View {isSelectionMeasured: selected.isComplete,isScanning: isBusy,scan: plan.scanRun,- isEnabled: !plan.selectedURLs.isEmpty && !plan.isRemoving,+ isEnabled: !plan.selectedURLs.isEmpty && !plan.isRemoving && !quitting.isWaiting,onRemove: requestRemoval)}@@ -590,12 +594,17 @@ struct AppDetailView: View {}}+ /// Asks the question once the app has quit, since none of its files moves while it runs.private func requestRemoval() {- if plan.selectedURLs.contains(plan.app.url), plan.isAppRunning {- isShowingQuitAlert = true- } else {- plan.question.ask(plan.request)- }+ let plan = plan+ quitting.check(plan.runningProcesses) { plan.question.ask(plan.request) }+ }++ /// Quitting the app before removing it, or only its files when it stays.+ private var quitTitle: Text {+ plan.selectedURLs.contains(plan.app.url)+ ? Text("Quit \(plan.app.name) before removing it.")+ : Text("Quit \(plan.app.name) before removing its files.")}/// One removal, from the privacy reset before the move to the scan after it, with the page busy throughout.diff --git a/Peel/Views/ForceQuitOffer.swift b/Peel/Views/ForceQuitOffer.swiftnew file mode 100644index 00000000..75720c8c--- /dev/null+++ b/Peel/Views/ForceQuitOffer.swift@@ -0,0 +1,13 @@+import SwiftUI++extension View {+ /// The alert that offers to force what did not quit before a removal. It closes by itself once they have.+ func forceQuitOffer(_ quitting: QuitBeforeRemoving) -> some View {+ alert(Text("\(quitting.names) didn’t quit."), isPresented: Bindable(quitting).isOfferingToForce) {+ Button("Force Quit", role: .destructive) { quitting.forceQuit() }+ Button("Cancel", role: .cancel) { quitting.giveUp() }+ } message: {+ Text("An app may be waiting for you, for example to save your work. Force Quit closes what is still open at once, and what isn’t saved is lost.")+ }+ }+}diff --git a/Peel/Views/MultipleAppsView.swift b/Peel/Views/MultipleAppsView.swiftindex 8e7b72d8..6a5df00d 100644--- a/Peel/Views/MultipleAppsView.swift+++ b/Peel/Views/MultipleAppsView.swift@@ -8,7 +8,7 @@ struct MultipleAppsView: View {@Environment(RemovalHistoryStore.self) private var history@Environment(HomebrewLibrary.self) private var homebrew@State private var plan: BulkRemovalPlan- @State private var isShowingQuitAlert = false+ @State private var quitting = QuitBeforeRemoving()@State private var resetsPrivacy = false@State private var isRescanning = false@Environment(RemovalOutcome.self) private var outcome@@ -80,7 +80,7 @@ struct MultipleAppsView: View {isSelectionMeasured: selected.isComplete,isScanning: plan.isScanning,scan: plan.scanRun,- isEnabled: !plan.selectedURLs.isEmpty && !plan.isRemoving,+ isEnabled: !plan.selectedURLs.isEmpty && !plan.isRemoving && !quitting.isWaiting,onRemove: requestRemoval)}@@ -108,12 +108,14 @@ struct MultipleAppsView: View {} message: {removalNote}- .alert("Quit these apps before removing them.", isPresented: $isShowingQuitAlert) {- Button("Quit Apps") { plan.quitRunningApps() }- Button("Cancel", role: .cancel) {}+ .alert("Quit these apps before removing them.", isPresented: Bindable(quitting).isAsking) {+ Button("Quit Apps") { quitting.quit() }+ Button("Cancel", role: .cancel) { quitting.giveUp() }} message: {- Text(verbatim: plan.runningApps.map(\.name).formatted(.list(type: .and)))+ Text(verbatim: quitting.names)}+ .forceQuitOffer(quitting)+ .onDisappear { quitting.giveUp() }.task {// Selecting apps one by one rebuilds this page after each change, and each build scans every selected// app. The short wait lets the selection settle: a newer change cancels this task before it scans.@@ -266,12 +268,10 @@ struct MultipleAppsView: View {resetsPrivacy ? PrivacyReset.apps(among: plan.apps, moving: urls) : []}+ /// Asks the question once the apps have quit, since none of their files moves while they run.private func requestRemoval() {- if !plan.runningApps.isEmpty {- isShowingQuitAlert = true- } else {- plan.question.ask(plan.request)- }+ let plan = plan+ quitting.check(plan.runningProcesses) { plan.question.ask(plan.request) }}/// One removal, from the privacy reset before the move to the scan after it, with the page busy throughout.