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 AppKit
import PeelCore
import SwiftUI
/// Makes an app forget its settings without uninstalling it. What is selected goes to the Trash, and the
/// preference domains are saved first, because cfprefsd is told to forget them afterwards.
struct ResetSheet: View {
@Environment(\.dismiss) private var dismiss
@Environment(AppLibrary.self) private var library
@Environment(RemovalHistoryStore.self) private var history
@Environment(ExclusionsStore.self) private var exclusions
@State private var plan: ResetPlan
/// Set once the sheet has moved files to the Trash or put settings back, so the page behind it knows that what
/// it lists has changed.
@Binding var changedFiles: Bool
@State private var isConfirming = false
@State private var copiesSettings = false
@State private var isPuttingBack = false
/// The result of Put Settings Back, or nil before it is pressed. A result is shown either way, so a success
/// doesn't look like a click that did nothing.
@State private var putBack: PreferenceBackup.Restored?
init(app: InstalledApp, changedFiles: Binding<Bool>) {
_plan = State(initialValue: ResetPlan(app: app))
_changedFiles = changedFiles
}
var body: some View {
VStack(spacing: 0) {
if plan.didReset {
outcome
} else {
choices
}
}
.frame(width: 560, height: 520)
// Escape closes a sheet even while its buttons are off.
.interactiveDismissDisabled(plan.isResetting || isPuttingBack)
.motion(value: plan.didReset)
.confirmationDialog("Reset \(plan.app.name)?", isPresented: $isConfirming) {
Button("Reset", role: .destructive) {
Task {
await QuitGuard.shared.run {
let result = await history.moving(
tool: .applications, source: "Reset of \(plan.app.name)", sourceKey: "reset.\(plan.app.name)",
sizes: sizes
) {
await plan.performReset()
}
if !result.trashed.isEmpty {
changedFiles = true
}
await history.record(
result,
tool: .applications,
source: "Reset of \(plan.app.name)",
sourceKey: "reset.\(plan.app.name)",
sizes: sizes
)
}
}
}
Button("Cancel", role: .cancel) {}
} message: {
confirmation
}
// The question stands for what it showed, so a change under it, such as an exclusion, closes it.
.onChange(of: plan.selectedURLs) { isConfirming = false }
.onChange(of: plan.canResetPrivacy) { isConfirming = false }
// Runs again when the exclusions change, because an item the user excludes must drop out of the reset.
.task(id: exclusions.revision) {
await plan.refresh(installedApps: library.apps)
}
// A reset needs the app quit, so the sheet follows the apps that run. The workspace reports every change
// to them through key-value observing, while it posts no notice for a menu bar or background app.
.onReceive(NSWorkspace.shared.publisher(for: \.runningApplications)) { _ in
plan.refreshRunningState()
}
}
private var phase: ScanPhase {
if plan.reset == nil { return .scanning(.walk) }
return plan.items.isEmpty && !plan.canResetPrivacy ? .message : .content
}
/// What the reset moves and how much, what the chosen groups cost, and what History can't undo.
private var confirmation: Text {
guard !plan.selectedURLs.isEmpty else {
return Text("\(plan.app.name) asks you again for what it was allowed to access. History can’t undo this.")
}
var sentences = [
copiesSettings
? Text("Peel moves ^[\(plan.selectedURLs.count) item](inflect: true), \(plan.selected.text), to the Trash and copies the settings first. \(plan.app.name) opens without them.")
: Text("Peel moves ^[\(plan.selectedURLs.count) item](inflect: true), \(plan.selected.text), to the Trash. \(plan.app.name) opens without them."),
]
let groups = plan.reset?.groups(in: plan.selectedURLs) ?? []
if groups.contains(.webData) {
sentences.append(Text(AppReset.Group.webData.explanation))
}
if groups.contains(.appData) {
sentences.append(Text("What the app keeps for you is selected too, and it can include your own work."))
}
if plan.resetsPrivacy && plan.canResetPrivacy {
sentences.append(Text("Its privacy permissions are reset too, and History can’t bring them back."))
}
return sentences.dropFirst().reduce(sentences[0]) { Text("\($0)\n\n\($1)") }
}
private var choices: some View {
List {
header
.listRowSeparator(.hidden)
RemovalsHeldBanner()
if plan.needsFullDiskAccess {
UnreadableFoldersNotice(folders: [], needsFullDiskAccess: true)
}
if let why = plan.whySettingsNotSaved {
Notice(
title: Text("Nothing was reset"),
detail: Text(verbatim: [String(localized: "Peel couldn’t save a copy of the settings first, so it moved nothing."), why.sentence].joined(separator: " "))
) { EmptyView() }
.listRowSeparator(.hidden)
}
if plan.isAppRunning {
Section {
HStack(spacing: 10) {
Text("\(plan.app.name) is open. Quit it first, or it can write its settings again.")
.font(.callout)
Spacer(minLength: 8)
Button("Quit \(plan.app.name)") { plan.quitApp() }
.buttonStyle(.bordered)
}
.listRowSeparator(.hidden)
}
}
ForEach(AppReset.Group.allCases, id: \.self) { group in
let items = plan.items(in: group)
if !items.isEmpty {
Section {
ForEach(Array(items.enumerated()), id: \.element.id) { index, item in
RemovalRow(
url: item.url,
icon: .symbol(item.kind.symbolName),
detail: nil,
size: item.size,
isFirst: index == 0,
hasNoteColumn: false,
selection: plan, isSelected: plan.isSelected(item.url)
)
}
.listRowSeparator(.hidden)
} header: {
SectionHeaderLine {
heading(group.title, group.explanation)
} actions: {
SelectMenu(
list: SelectableRows(
rows: items.map(\.url),
selectable: items.map(\.url),
recommended: items.map(\.url).filter(plan.suggested.contains)
),
place: Text(group.title),
selection: plan
)
}
}
}
}
if plan.canResetPrivacy {
PrivacyResetRow(
isOn: $plan.resetsPrivacy,
detail: Text("macOS remembers what an app was allowed to access, such as the camera or the microphone. If this is selected, Peel clears that too, so \(plan.app.name) asks you again the next time it needs them. History can’t bring them back.")
)
}
if plan.keepsAppData {
Section {
Text("Peel never offers to remove what \(plan.app.name) keeps for you, whether that is mail, messages, notes, or photos.")
.font(.callout)
.foregroundStyle(.secondary)
.listRowSeparator(.hidden)
} header: {
Text("What Stays")
}
}
}
.dimmedWhileBusy(plan.isResetting)
.disabled(plan.isResetting)
.scrollBarBelowSectionHeaders()
.scanState(phase, scan: plan.scanRun) {
if plan.isExcluded {
ContentUnavailableView(
"This app is excluded",
systemImage: "hand.raised",
description: Text("Peel leaves it and its files alone. Change that in Settings.")
)
} else {
ContentUnavailableView(
"Nothing to Reset",
systemImage: "sparkles",
description: Text("Peel found no settings on this Mac that are certainly \(plan.app.name)’s own.")
)
}
}
.announcesScan(
plan.scanRun.isRunning,
found: plan.items.isEmpty ? nil : AttributedString(localized: "^[\(plan.items.count) item](inflect: true)."),
couldNotLook: phase != .message ? nil : plan.isExcluded ? "This app is excluded" : "Nothing to Reset",
wasStopped: plan.scanRun.wasStopped
)
.edgeBar(.bottom) { bar }
}
private var header: some View {
HStack(alignment: .center, spacing: 18) {
Image(nsImage: IconCache.icon(for: plan.app.url))
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 64, height: 64)
.accessibilityIgnoresInvertColors()
.accessibilityHidden(true)
VStack(alignment: .leading, spacing: 4) {
Text("Reset \(plan.app.name)")
.font(.title.bold())
.headsThePage()
Text("\(plan.app.name) stays installed and forgets what is selected below. What is selected goes to the Trash, and any settings in it are copied first.")
.font(.callout)
.foregroundStyle(.secondary)
}
Spacer(minLength: 8)
}
.padding(.vertical, 6)
}
private var bar: some View {
HStack(spacing: 12) {
VStack(alignment: .leading, spacing: 1) {
Text(plan.selected.text)
.font(.title3.weight(.bold))
.monospacedDigit()
Text("^[\(plan.selectedURLs.count) item](inflect: true)")
.font(.caption)
.foregroundStyle(.secondary)
}
Spacer(minLength: 8)
// Closing the sheet during the reset would lose the Put Settings Back button that follows it.
Button("Cancel") { dismiss() }
.buttonStyle(.bordered)
.keyboardShortcut(.cancelAction)
.disabled(plan.isResetting)
// Reset is not the default action, so pressing Return can't start the one step here that changes
// something.
Button("Reset") {
copiesSettings = plan.selectionCopiesSettings()
isConfirming = true
}
.buttonStyle(.borderedProminent)
.disabled(
!plan.hasAnythingToReset || plan.isResetting || plan.isAppRunning
|| !history.mayMove
)
}
.padding(.horizontal, 20)
.padding(.vertical, 14)
}
private var outcome: some View {
List {
VStack(alignment: .leading, spacing: 10) {
outcomeTitle
.font(.title.bold())
.headsThePage()
// Two paragraphs, not one sentence joined in code: languages build sentences differently.
Group {
if plan.askedToMove > 0 {
filesDetail
}
if let privacyDetail {
privacyDetail
}
}
.font(.callout)
.foregroundStyle(.secondary)
}
.padding(.vertical, 6)
.listRowSeparator(.hidden)
if !plan.failures.isEmpty {
Section {
ForEach(plan.failures, id: \.url) { failure in
VStack(alignment: .leading, spacing: 1) {
Text(failure.url.abbreviatedPath)
.lineLimit(1)
.truncationMode(.middle)
.font(.callout)
Text(verbatim: failure.reason.explanation)
.font(.caption)
.foregroundStyle(.secondary)
}
}
} header: {
Text("Not Moved")
}
}
if let backup = plan.backup {
Section {
VStack(alignment: .leading, spacing: 10) {
if plan.isAppRunning {
HStack(spacing: 10) {
Text("Quit \(plan.app.name) first, or it can write its own settings over these.")
.font(.callout)
Spacer(minLength: 8)
Button("Quit \(plan.app.name)") { plan.quitApp() }
.buttonStyle(.bordered)
}
}
if let refusal = plan.putBackRefusal {
putBackResult(refusal, from: backup)
} else if let putBack {
putBackResult(putBack, from: backup)
}
}
.padding(.vertical, 2)
.listRowSeparator(.hidden)
} header: {
HeadingWithActions {
heading(
"If You Change Your Mind",
"The old settings were saved before they were cleared. Put them back from here: once the app opens again, it writes new settings where the old ones were, and History won’t put the old files back over them."
)
} actions: {
Button("Show in Finder") {
NSWorkspace.shared.activateFileViewerSelecting([backup])
}
Button("Put Settings Back") {
isPuttingBack = true
Task {
let restored = await plan.putSettingsBack(from: backup)
putBack = restored
switch restored {
case .complete, .incomplete: changedFiles = true
case .notSaved, .appIsOpen, .exclusionsNotKnown, .excluded, .copyUnreadable: break
}
isPuttingBack = false
}
}
.buttonStyle(.borderedProminent)
.disabled(isPuttingBack || plan.isAppRunning || plan.putBackRefusal != nil)
}
}
}
}
.scrollBarBelowSectionHeaders()
.edgeBar(.bottom) {
HStack {
Spacer()
// Closed while the settings go back, the sheet would let the page scan again before they are back.
Button("Done") { dismiss() }
.buttonStyle(.borderedProminent)
.keyboardShortcut(.defaultAction)
.disabled(isPuttingBack)
}
.padding(.horizontal, 20)
.padding(.vertical, 14)
}
}
/// What Put Settings Back did, each way it can end.
@ViewBuilder
private func putBackResult(_ restored: PreferenceBackup.Restored, from copy: URL) -> some View {
switch restored {
case .complete:
Text("The settings are back as they were.")
.font(.callout)
.foregroundStyle(.secondary)
case .incomplete(let clearedSome):
VStack(alignment: .leading, spacing: 2) {
StatusLabel(title: Text("Not all of the saved settings could be put back."), tint: .red)
if clearedSome {
Text("The settings that didn’t go back were cleared first, so the app starts them from scratch. The copy is still here to try again.")
}
}
.font(.callout)
.foregroundStyle(.secondary)
case .notSaved(let why):
let said = String(localized: "Peel couldn’t save the settings \(plan.app.name) has now, so it put nothing back.")
StatusLabel(title: Text(verbatim: [said, why.sentence].joined(separator: " ")), tint: .red)
.font(.callout)
.foregroundStyle(.secondary)
case .copyUnreadable(let why):
let said = String(localized: "Peel couldn’t read the settings saved for \(plan.app.name), so it put nothing back.")
StatusLabel(title: Text(verbatim: [said, why.sentence(about: copy)].joined(separator: " ")), tint: .red)
.font(.callout)
.foregroundStyle(.secondary)
case .appIsOpen:
StatusLabel(title: Text("Quit \(plan.app.name) first, or it can write its own settings over these."), tint: .red)
.font(.callout)
.foregroundStyle(.secondary)
case .exclusionsNotKnown:
VStack(alignment: .leading, spacing: 2) {
StatusLabel(title: Text("Peel couldn’t read your exclusions"), tint: .red)
Text(verbatim: exclusions.nothingMovesUntilStartedOver)
}
.font(.callout)
.foregroundStyle(.secondary)
case .excluded:
VStack(alignment: .leading, spacing: 2) {
StatusLabel(title: Text("This app is excluded"), tint: .red)
Text("Peel leaves it and its files alone. Change that in Settings.")
}
.font(.callout)
.foregroundStyle(.secondary)
}
}
/// The outcome's title, based on what really happened: reset, partly reset, or nothing reset.
private var outcomeTitle: Text {
let privacyWasReset = plan.privacy == .reset
let privacyFailed = plan.privacy.map { $0 != .reset } ?? false
if plan.movedCount == 0, !privacyWasReset { return Text("Nothing was reset.") }
return plan.failures.isEmpty && !privacyFailed ? Text("\(plan.app.name) was reset.") : Text("\(plan.app.name) was partly reset.")
}
private var privacyDetail: Text? {
guard let privacy = plan.privacy else { return nil }
guard let problem = privacy.explanation else {
return Text("Its privacy permissions were reset, so it asks you again the next time it needs them.")
}
return Text("Its privacy permissions weren’t reset. \(problem)")
}
private var filesDetail: Text {
guard plan.movedCount > 0 else {
return Text("None of what you selected could be moved to the Trash. The reasons are below.")
}
switch (plan.failures.isEmpty, plan.didClearSettings) {
case (true, false):
return Text("Everything went to the Trash. History can put it back until the app writes new files in its place.")
case (true, true):
return Text("Everything went to the Trash. History can put it back until the app writes new files in its place. Peel also told macOS to drop any copy of these settings it still held.")
case (false, false):
return Text("What could be moved went to the Trash. History can put it back until the app writes new files in its place.")
case (false, true):
return Text("What could be moved went to the Trash. History can put it back until the app writes new files in its place. Peel also told macOS to drop any copy of these settings it still held.")
}
}
private var sizes: [URL: Int64] {
Dictionary(plan.items.map { ($0.url, $0.size) }, uniquingKeysWith: { first, _ in first })
}
}