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.

7.5 KB
Raw Blame
import AppKit
import Foundation
import Observation
import PeelCore

@Observable
final class ResetPlan {
    let app: InstalledApp
    private(set) var reset: AppReset?
    /// The scan the sheet runs. A new scan, such as the one after the exclusions change, replaces the one before.
    let scanRun = ScanRun()
    private(set) var isResetting = false
    private(set) var outcome: AppReset.Outcome?
    /// Off until chosen: History can't bring the permissions back.
    var resetsPrivacy = false
    /// Stored rather than computed, so the sheet can observe it: reading the workspace in a computed property
    /// gives Observation nothing to track. `refreshRunningState()` keeps it current.
    private(set) var isAppRunning = false
    /// Every installed app as of the last scan. It tells this app's running helpers apart from another app's.
    private var installedApps: [InstalledApp] = []
    var selectedURLs: Set<URL> = []
    private var choices = KeptSelection()

    init(app: InstalledApp) {
        self.app = app
        refreshRunningState()
    }

    var items: [AppReset.Item] {
        reset?.items ?? []
    }

    func items(in group: AppReset.Group) -> [AppReset.Item] {
        reset?.items(in: group) ?? []
    }

    var suggested: Set<URL> {
        reset?.suggestedSelection ?? []
    }

    var selected: SizeTotal {
        reset?.size(of: selectedURLs) ?? SizeTotal(known: 0, isComplete: true)
    }

    var keepsAppData: Bool {
        reset?.keepsAppData ?? false
    }

    var needsFullDiskAccess: Bool {
        reset?.needsFullDiskAccess ?? false
    }

    /// Read from the exclusions, not the scan, so an app excluded while the sheet is open shows at once.
    var isExcluded: Bool {
        ExclusionsStore.shared.exclusions.excludes(app)
    }

    var canResetPrivacy: Bool {
        PrivacyReset.isAllowed(for: app) && !isExcluded
    }

    var didReset: Bool {
        outcome.map { $0.stop == nil } ?? false
    }

    /// Why the settings could not be backed up, so nothing was moved, or nil. The backup is what restores them once
    /// the app has written new ones, which History cannot do.
    var whySettingsNotSaved: PreferenceBackup.NotSaved? {
        if case .settingsNotSaved(let why) = outcome?.stop { why } else { nil }
    }

    var backup: URL? {
        outcome?.settingsToPutBack
    }

    var failures: [TrashFailure] {
        outcome?.result.failures ?? []
    }

    var movedCount: Int {
        outcome?.result.trashed.count ?? 0
    }

    /// How many files the reset asked to move: a reset of privacy permissions alone asks for none.
    var askedToMove: Int {
        outcome?.askedToMove ?? 0
    }

    var didClearSettings: Bool {
        outcome?.clearedSettings ?? false
    }

    var privacy: PrivacyReset.Result? {
        outcome?.privacy
    }

    /// Whether resetting the selection copies settings first, as it does for each preference domain it clears. It
    /// reads the disk, so it is asked when Reset is pressed, not while the sheet draws.
    func selectionCopiesSettings() -> Bool {
        reset.map { $0.clearsSettings(moving: $0.selected(selectedURLs)) } ?? false
    }

    /// Nothing is, until the scan has said what the reset would take: `performReset()` has nothing to go on before.
    var hasAnythingToReset: Bool {
        reset != nil && !isExcluded && (!selectedURLs.isEmpty || (resetsPrivacy && canResetPrivacy))
    }

    /// Updates `isAppRunning`. Called when the sheet opens and whenever an app launches or quits.
    func refreshRunningState() {
        isAppRunning = !relatedRunningApps.isEmpty
    }

    func refresh(installedApps: [InstalledApp]) async {
        let app = app
        guard let result = await scanRun.run({
            await AppReset.prepare(app, installedApps: installedApps, exclusions: ExclusionsStore.shared.exclusions)
        }) else { return }
        selectedURLs = choices.update(
            selectedURLs,
            selectable: Set(result.items.map(\.url)),
            suggested: result.suggestedSelection
        )
        reset = result
        self.installedApps = installedApps
        refreshRunningState()
    }

    /// Backs up the app's settings, then moves the selection to the Trash, which also makes cfprefsd forget the
    /// app's preference domains. The app must be closed before the copy and still be after it: an app opened
    /// meanwhile would have its files moved from under it, and would write its settings back when it quits.
    func performReset() async -> TrashResult {
        refreshRunningState()
        guard let reset, !isAppRunning else { return TrashResult() }
        isResetting = true
        defer { isResetting = false }

        let outcome = await reset.run(
            selectedURLs,
            resettingPrivacy: resetsPrivacy && canResetPrivacy,
            exclusions: ExclusionsStore.shared.exclusions
        ) { @MainActor in
            self.refreshRunningState()
            return self.isAppRunning
        }
        self.outcome = outcome
        SavedSettings.shared.reload()
        return outcome.result
    }

    /// Why the saved settings can't be put back now, or nil when they can, read from the exclusions as they stand.
    var putBackRefusal: PreferenceBackup.Restored? {
        app.bundleIdentifier.flatMap {
            PreferenceBackup.refusal(ofPuttingBack: $0, exclusions: ExclusionsStore.shared.exclusions)
        }
    }

    /// Puts the settings saved in `backup` back, unless the app is open, which would write its own over them.
    func putSettingsBack(from backup: URL) async -> PreferenceBackup.Restored {
        // A copy is saved under the app's identifier, so an app with none has no copy to put back.
        guard let identifier = app.bundleIdentifier else { return .notSaved(.noUsableIdentifier) }
        let restored = await QuitGuard.shared.run {
            await PreferenceBackup.restore(
                from: backup,
                of: identifier,
                exclusions: ExclusionsStore.shared.exclusions
            ) { @MainActor in
                self.refreshRunningState()
                return self.isAppRunning
            }
        }
        // The settings the app had until now may have become a copy of their own.
        SavedSettings.shared.reload()
        return restored
    }

    /// Quits the app and the helpers it ships, so nothing writes its settings again while they are cleared.
    func quitApp() {
        for running in relatedRunningApps {
            running.terminate()
        }
    }

    private var relatedRunningApps: [NSRunningApplication] {
        RunningCopies.belonging(
            to: app,
            among: RunningCopies.current,
            installedApps: installedApps,
            sharingItsSettings: true
        )
            .compactMap { NSRunningApplication(processIdentifier: $0.identifier) }
    }
}

extension AppReset.Group {
    var title: LocalizedStringResource {
        switch self {
        case .settings: "Settings"
        case .webData: "Cookies and Website Data"
        case .appData: "What the App Keeps for You"
        }
    }

    var explanation: LocalizedStringResource {
        switch self {
        case .settings: "The app writes all of this again the next time it opens. An app may also keep what it remembers about you here, such as a license key or an account you stayed signed in to, and then those go too."
        case .webData: "Removing this signs you out of websites the app kept you signed in to."
        case .appData: "This is what the app keeps for you, which can include your own work. Peel never selects it for you."
        }
    }
}