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
import PeelCore
import SwiftUI
struct MultipleAppsView: View {
@Environment(AppLibrary.self) private var library
@Environment(HelperModel.self) private var helper
@Environment(HomeModel.self) private var home
@Environment(RemovalHistoryStore.self) private var history
@Environment(HomebrewLibrary.self) private var homebrew
@State private var plan: BulkRemovalPlan
@State private var quitting = QuitBeforeRemoving()
@State private var progress = MoveProgress()
@State private var isRescanning = false
@State private var questionTitle = Text(verbatim: "")
@State private var questionNote = Text(verbatim: "")
@State private var quitTitle = Text(verbatim: "")
@Environment(RemovalOutcome.self) private var outcome
init(apps: [InstalledApp]) {
_plan = State(initialValue: BulkRemovalPlan(apps: apps))
}
var body: some View {
ScrollViewReader { proxy in
List {
header
.listRowSeparator(.hidden)
RemovalsHeldBanner()
if plan.bulk != nil {
if plan.bulk?.needsFullDiskAccess == true || !plan.unreadableLocations.isEmpty {
UnreadableFoldersNotice(
folders: plan.unreadableLocations.map(\.url),
needsFullDiskAccess: plan.bulk?.needsFullDiskAccess == true
)
}
if plan.rowsWaitingForTheHelper > 0, !helper.canAct {
HelperRequiredBanner(need: .moving(plan.rowsWaitingForTheHelper))
}
// Here, above the lists, so they are seen before Move to Trash however long the lists run.
BulkRemovalOptions(plan: plan)
ListJumps(
toFiles: !plan.recommendedFiles.isEmpty,
toReview: !plan.filesToReview.isEmpty,
proxy: proxy
)
Section {
RemovalColumnHeaders()
ForEach(Array(plan.applications.enumerated()), id: \.element.id) { index, item in
row(item, isFirst: index == 0)
}
.listRowSeparator(.hidden)
} header: {
SectionHeaderLine {
Text("Apps")
} actions: {
SelectMenu(list: list(of: plan.applications), place: Text("Apps"), selection: plan)
}
}
if !plan.recommendedFiles.isEmpty {
Section {
RemovalColumnHeaders()
.id(ListJumps.Target.files)
ForEach(Array(plan.recommendedFiles.enumerated()), id: \.element.id) { index, item in
row(item, isFirst: index == 0)
}
.listRowSeparator(.hidden)
} header: {
SectionHeaderLine {
Text("Files They Leave Behind")
} actions: {
SelectMenu(
list: list(of: plan.recommendedFiles),
place: Text("Files They Leave Behind"),
selection: plan
)
}
}
}
if !plan.filesToReview.isEmpty {
Section {
RemovalColumnHeaders()
.id(ListJumps.Target.review)
ForEach(Array(plan.filesToReview.enumerated()), id: \.element.id) { index, item in
row(item, isFirst: index == 0)
}
.listRowSeparator(.hidden)
} header: {
SectionHeaderLine {
heading(
"Review Before Removing",
"These are here because Peel is less sure about them, another app on this Mac uses them too, or Peel held them back for the reason each row gives. Nothing here is selected for you: read each one and select only what you recognize."
)
} actions: {
SelectMenu(
list: list(of: plan.filesToReview),
place: Text("Review Before Removing"),
selection: plan
)
}
}
}
}
}
}
.scrollBarBelowSectionHeaders()
.dimmedWhileBusy(plan.isRemoving)
.disabled(plan.isRemoving)
.scanState(phase, isRescanning: isRescanning, fadesInResults: false, scan: plan.scanRun)
.announcesScan(
plan.isScanning,
found: plan.total.spoken,
couldNotLook: "Nothing here can be moved. Each file’s note says why.",
wasStopped: plan.scanRun.wasStopped
)
.edgeBar(.bottom) {
if plan.bulk != nil {
let selected = plan.request.total
RemovalBar(
selectedSize: selected.known,
isSelectionMeasured: selected.isComplete,
isScanning: plan.isScanning,
scan: plan.scanRun,
isEnabled: !plan.selectedURLs.isEmpty && !plan.isRemoving && !quitting.isWaiting,
onRemove: requestRemoval,
progress: progress,
waitingToQuit: quitting.isWaiting ? quitting.names : nil
)
}
}
.navigationTitle(Text("^[\(plan.apps.count) app](inflect: true)"))
.toolbar(removing: .title)
// Like an app's own page, this page has Rescan, which turns into Stop while a scan runs: scanning
// several apps can take a while.
.toolbar {
ToolbarItem {
RescanButton(isRunning: $isRescanning, isDisabled: plan.isRemoving, scan: plan.scanRun) {
await plan.refresh(
installedApps: library.apps,
canUseHelper: helper.canAct,
casks: homebrew.caskEvidence,
receipts: homebrew.receipts
)
}
}
}
.confirmationDialog(questionTitle, isPresented: Bindable(plan.question).isAsking) {
Button("Move to Trash") {
guard let request = plan.question.start() else { return }
Task { await remove(request) }
}
Button("Cancel", role: .cancel) {}
} message: {
questionNote
}
.alert(quitTitle, isPresented: Bindable(quitting).isAsking) {
Button(quitting.namesSeveral ? "Quit Apps" : "Quit \(quitting.names)") { quitting.quit() }
Button("Cancel", role: .cancel) { quitting.giveUp() }
} message: {
Text(verbatim: quitting.names)
}
.forceQuitOffer(quitting)
.onDisappear { quitting.giveUp() }
// Keyed to what Homebrew knows: evidence that arrives after the page opened is a reason to look again.
.task(id: homebrew.evidenceRevision) {
// 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.
try? await Task.sleep(for: .milliseconds(300))
guard !Task.isCancelled, !(plan.bulk == nil && plan.scanRun.wasStopped) else { return }
await rescan()
}
.rescanOnExclusionChange(scannedUnder: plan.exclusionsRevision) { await rescan() }
.onChange(of: helper.canAct) { _, canAct in
plan.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 {
if plan.bulk != nil { return .content }
return plan.scanRun.wasStopped ? .stopped : .scanning(.walk)
}
private var header: some View {
HStack(alignment: .center, spacing: 18) {
AppStack(apps: plan.apps)
VStack(alignment: .leading, spacing: 6) {
Text("^[\(plan.apps.count) app](inflect: true)")
.pageHeading()
Text(verbatim: plan.apps.map(\.name).formatted(.list(type: .and)))
.font(.callout)
.foregroundStyle(.secondary)
.lineLimit(2)
if plan.bulk != nil {
Badge(title: Text("^[\(plan.items.count) item](inflect: true)"), systemImage: "doc.on.doc")
.padding(.top, 2)
}
}
Spacer(minLength: 8)
if !plan.total.isNothing {
TotalLabel(total: plan.total, caption: Text("to remove"))
.accessibilityLabel(Text("\(plan.total.text) can be moved to the Trash"))
}
}
.padding(.vertical, 8)
}
private func list(of items: [BulkUninstallation.Item]) -> SelectableRows<URL> {
let rows = items.map(\.url)
return SelectableRows(
rows: rows,
selectable: rows.filter(plan.selectable.contains),
recommended: rows.filter(plan.suggested.contains)
)
}
private func row(_ item: BulkUninstallation.Item, isFirst: Bool) -> some View {
RemovalRow(
url: item.url,
icon: item.isApplication ? .file(item.url) : .symbol(item.kind?.symbolName ?? "doc"),
detail: item.isApplication ? nil : item.match?.reason.title,
kind: item.isApplication ? "Application" : item.kind?.title,
warning: warning(for: item),
foundFor: item.isApplication ? nil : names(of: item.apps),
size: item.size,
isMeasured: item.isMeasured,
isLocked: item.requiresPrivileges && !helper.canAct,
isExcluded: item.isApplication && item.isExcluded,
isLeftAlone: item.match?.heldBack?.cannotBeMoved == true || item.isBeyondTheHelper
|| (item.isApplication && item.isKeptByMacOS)
|| item.removedElsewhere != nil || item.isInTheTrash || item.enclosingPackage != nil,
appIdentifier: item.isApplication ? item.apps.first : nil,
isFirst: isFirst,
selection: plan, isSelected: plan.isSelected(item.url)
)
}
/// The names of the apps with these bundle identifiers, as a list.
private func names(of identifiers: [String]) -> String {
identifiers.map(library.name(forReference:)).formatted(.list(type: .and))
}
/// The warning in a row's note, in the same words an app's own page uses: which other apps use the item,
/// and why Peel did not select it or leaves it where it is.
private func warning(for item: BulkUninstallation.Item) -> String? {
var lines: [String] = []
let keptBy = item.apps.filter(plan.staying.contains)
if !item.isApplication, !keptBy.isEmpty, !item.isKeptByMacOS, item.removedElsewhere == nil, !item.isExcluded {
lines.append(String(localized: "Not selected: it stays with \(names(of: keptBy))."))
}
let users =
item.sharedWithOthers.map(library.name(forReference:)) + item.otherCopies.map(\.abbreviatedPath)
if !users.isEmpty {
lines.append(String(localized: "Also used by \(users.formatted(.list(type: .and)))."))
}
if let heldBack = item.match?.heldBack {
lines.append(String(localized: heldBack.explanation(keptInStepBy: item.syncedBy)))
}
if item.holdsDamagedSettings {
lines.append(String(localized: "Can’t be read as a property list, so nothing can read these settings."))
}
if item.isApplication, item.isBeyondTheHelper {
lines.append(String(localized: HoldBack.beyondTheHelper.explanation))
}
if let removedElsewhere = item.removedElsewhere {
lines.append(String(localized: removedElsewhere.explanation))
}
if item.isInTheTrash {
lines.append(String(localized: "Already in the Trash. What it left behind can still go."))
}
if let package = item.enclosingPackage {
let name = AppInspector.displayName(of: package)
lines.append(String(localized: "Part of \(name), so it stays where it is."))
}
if item.isKeptByMacOS {
// Two literals, so the string catalog finds both.
lines.append(item.isApplication
? String(localized: "macOS keeps this app, so it stays where it is.")
: String(localized: "Not selected: it belongs to an app macOS keeps, so it is in use."))
}
if item.isApplication, let app = plan.apps.first(where: { $0.url == item.url }) {
if case .browser(let identifier) = app.webApp {
let browser = library.name(forReference: identifier)
lines.append(String(localized: "Moving it to the Trash takes away only this shortcut, and the app stays in \(browser), which can make the shortcut again. To remove the app itself, uninstall it in \(browser), which takes the shortcut away too."))
}
if let change = app.bundleIdentifier.flatMap({ library.teamChanges[$0] }) {
if change.current.isEmpty {
lines.append(String(localized: "No developer signs this app anymore."))
lines.append(String(localized: "It was first seen signed by \(change.previous). A copy someone has changed looks like this, and so does one built from source."))
} else {
lines.append(String(localized: "It was first seen signed by \(change.previous), and is signed by \(change.current) now."))
}
}
}
return lines.isEmpty ? nil : lines.joined(separator: "\n\n")
}
/// Under the question: which of the chosen apps go and which stay, the privacy reset, which History can't undo, a
/// root certificate an app that goes leaves trusted, and Homebrew's record of an app that goes while its record
/// stays.
private func note(about urls: Set<URL>) -> Text {
let going = plan.apps.filter { urls.contains($0.url) }
let staying = plan.apps.filter { !urls.contains($0.url) && !plan.appsInTheTrash.contains($0.url) }
var lines: [Text] = []
if !going.isEmpty {
lines.append(Text("Apps that go: \(list(going))"))
}
if !staying.isEmpty {
lines.append(Text("Apps that stay: \(list(staying))"))
}
if !resetting(urls).isEmpty {
lines.append(Text("The selected apps’ privacy permissions are cleared first, and History can’t bring them back."))
}
lines += UninstallsItself.when(moving: urls, among: plan.apps).map(\.warning)
for app in going {
guard let root = TrustedRoot.of(app) else { continue }
lines.append(Text("\(app.name)’s root certificate stays trusted on this Mac after the app goes."))
lines.append(root.step(in: app.name))
}
for app in going {
let movesItsReceipt = plan.items.contains {
$0.kind == .homebrewReceipt && $0.apps.contains(app.reference) && urls.contains($0.url)
}
if !movesItsReceipt, let cask = library.cask(for: app) {
let record = Text("Homebrew installed this app and will keep listing it as installed. To take it off that list, run `brew uninstall --cask \(cask.name)`: Homebrew then carries out the cask’s own uninstall steps, which can delete files for good.")
lines.append(Text("\(list([app])): \(record)"))
}
}
return lines.dropFirst().reduce(lines.first ?? Text(verbatim: "")) { Text("\($0)\n\n\($1)") }
}
/// These chosen apps as a list, the first ones only, as an alert lists them: each by its name, or by where it is
/// when another chosen app has the same name.
private func list(_ apps: [InstalledApp]) -> String {
RemovalFailureAlert.listed(apps.map { app in
plan.apps.contains { $0.name == app.name && $0.url != app.url } ? app.url.abbreviatedPath : app.name
})
}
/// The apps whose privacy permissions a removal of `urls` resets.
private func resetting(_ urls: Set<URL>) -> [InstalledApp] {
guard !urls.isEmpty, plan.resetsPrivacy else { return [] }
return PrivacyReset.apps(among: plan.apps, moving: urls)
}
/// Asks the question once the apps have quit, since none of their files moves while they run, and after scanning
/// again if any had to quit: what they wrote until then was not there when the page scanned. Its words are worked
/// out here, once, rather than with every change of the page: the note compares every chosen app with every other.
private func requestRemoval() {
let plan = plan
Task {
let (apps, running) = await plan.toQuit()
if !running.isEmpty {
quitTitle = Text(BulkRemovalPlan.quitTitle(running: apps, going: plan.selectedURLs))
}
quitting.check(running) {
Task {
if !running.isEmpty {
await rescan()
guard !plan.scanRun.wasStopped else { return }
}
let request = plan.request
questionTitle = Text.movingToTrash(request.urls.count, request.total)
questionNote = note(about: request.urls)
plan.question.ask(request)
}
}
}
}
/// One removal, from the privacy reset before the move to the scan after it, with the page busy throughout.
/// An app opened since the question moves nothing: it is asked to quit again.
private func remove(_ request: RemovalRequest) async {
let plan = plan
defer { plan.question.finish() }
guard await plan.toQuit().processes.isEmpty else { return requestRemoval() }
let result = await progress.run(toMove: request.urls.count) {
await QuitGuard.shared.run {
// The privacy reset runs before the move, because `tccutil` only finds an app that is still in its
// place.
let service = TrashService(exclusions: ExclusionsStore.shared.exclusions)
let privacy = await PrivacyReset.reset(resetting(request.urls), beforeMovingWith: service)
let result = await history.moving(
plan.part(naming: []), sizes: request.sizes, sharingStorage: request.sharingStorage
) { await plan.move(request) }
let kept = plan.bulk?.appsThatKeptTheirFiles(after: result, selection: request.urls) ?? []
let left = plan.bulk?.leftForAnAdministrator(after: result) ?? []
await LeftForAnAdministrator().record(left)
outcome.report(
result,
privacy: privacy,
keptTheirFiles: kept.map(\.name),
startingFromTheTrash: plan.apps.filter { result.startsFromTheTrash.contains($0.url) }.map(\.name),
leftForAnAdministrator: left.count,
shellReferences: await ShellReferences.find(naming: result.trashed.map(\.originalURL))
)
if plan.removesDockTiles {
let moved = Set(result.trashed.map(\.originalURL))
// Asked of every app that moved, since one opened after the last scan has a tile now, and of every
// app already in the Trash whose own files moved.
let inTheTrash = plan.appsInTheTrash(withFilesAmong: moved).map(\.url)
let apps = (plan.apps.map(\.url).filter(moved.contains) + inTheTrash).sorted { $0.path < $1.path }
_ = await DockTiles().takeOut(apps, foundAt: result.trashedAt, forgetting: Set(inTheTrash))
}
if let state = AppManagement.state(
after: result,
appBundles: Set(plan.apps.map(\.url)),
movedByTheHelper: plan.privilegedURLs
) {
home.record(appManagement: state)
}
await plan.record(result, sizes: request.sizes, sharingStorage: request.sharingStorage, in: history)
return result
}
}
// 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.
let bundles = Set(plan.apps.map(\.url))
if result.trashed.contains(where: { bundles.contains($0.originalURL) }) {
await library.refresh()
} else {
await plan.refresh(
installedApps: library.apps,
canUseHelper: helper.canAct,
casks: homebrew.caskEvidence,
receipts: homebrew.receipts
)
}
}
}
/// The icons of the first three chosen apps, stacked with small offsets.
private struct AppStack: View {
let apps: [InstalledApp]
var body: some View {
ZStack {
ForEach(Array(apps.prefix(3).enumerated()).reversed(), id: \.offset) { index, app in
AppIcon(url: app.url)
.frame(width: 58, height: 58)
.offset(x: [0, 9, -10][index], y: [0, -4, 6][index])
.zIndex(Double(3 - index))
}
}
.frame(width: 86, height: 76)
.accessibilityHidden(true)
}
}
/// The options of the apps' removal, in a view of their own: a binding reads its value where it is made, so one made
/// in the page's body would build the whole page, every row of its lists, again with every click.
private struct BulkRemovalOptions: View {
let plan: BulkRemovalPlan
var body: some View {
let resets = !PrivacyReset.apps(among: plan.apps, moving: plan.selectable).isEmpty
let movesAppsWithTiles = !plan.appsInTheDock.isDisjoint(with: plan.selectable)
let tilesInTheTrash = !plan.appsInTheTrashWithTiles.isEmpty
let removesTiles = movesAppsWithTiles || tilesInTheTrash
if resets || removesTiles {
// Side by side while they fit, and the second on a line of its own when they don't.
FlowLayout(spacing: 24) {
if resets {
PrivacyResetOption(isOn: Bindable(plan).resetsPrivacy, detail: PrivacyResetRow.beforeTheMove)
}
if removesTiles {
DockTileOption(
isOn: Bindable(plan).removesDockTiles,
apps: movesAppsWithTiles ? (tilesInTheTrash ? .both : .moved) : .alreadyInTheTrash
)
}
}
.padding(.vertical, 8)
.listRowSeparator(.hidden)
}
}
}
/// Buttons that scroll to the lists further down, which with many apps chosen start far below the top of the page.
private struct ListJumps: View {
enum Target { case files, review }
let toFiles: Bool
let toReview: Bool
let proxy: ScrollViewProxy
var body: some View {
if toFiles || toReview {
FlowLayout(spacing: 16) {
if toFiles {
Button {
proxy.scrollTo(Target.files, anchor: .top)
} label: {
Label("Files They Leave Behind", systemImage: "arrow.down")
.minimumTarget()
}
}
if toReview {
Button {
proxy.scrollTo(Target.review, anchor: .top)
} label: {
Label("Review Before Removing", systemImage: "arrow.down")
.minimumTarget()
}
}
}
.buttonStyle(.borderless)
.padding(.bottom, 4)
.listRowSeparator(.hidden)
}
}
}