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.

12.4 KB
Raw Blame
import Foundation
import Observation
import PeelCore

@Observable
final class SpaceLibrary: RowSelection {
    private(set) var report: SpaceReport?
    /// The disk the band shows, read on its own: after each scan, when the page appears, and when Peel comes forward.
    private(set) var disk: DiskSpace?
    /// The scan this page runs, which a newer one or the Stop button ends.
    let scanRun = ScanRun()
    var isScanning: Bool { scanRun.isRunning }
    var selection: SpaceItem.ID?
    /// What is selected inside the areas' folders.
    var selectedURLs: Set<URL> = []
    var isRemoving = false
    /// Each area's last plan: what its page lists, and what a selection carried from it is counted by.
    private(set) var plans: [SpaceItem.ID: SpaceRemoval.Plan] = [:]
    /// The area as it was, and the exclusions' revision, when its plan was made.
    @ObservationIgnored private var plannedFor: [SpaceItem.ID: (item: SpaceItem, exclusions: Int)] = [:]
    @ObservationIgnored private var canUseHelper = false
    /// What the AI models and datasets the Developer page lists take, measured once the areas show; nil while there
    /// are none, and before the first measurement.
    private(set) var models: SizeTotal?
    /// Why the folders of those Peel couldn't measure weren't measured, each reason once.
    private(set) var modelsNotMeasured: Set<HoldBack> = []
    @ObservationIgnored private var modelsMeasurement = 0
    @ObservationIgnored private var quitCheck: Task<Void, Never>?
    /// How many plans of each area have started, so that a plan that started earlier and ended later is dropped: it can
    /// name folders a move has taken since.
    @ObservationIgnored private var plansStarted: [SpaceItem.ID: Int] = [:]
    private let makePlan: @Sendable (SpaceItem, Exclusions, [RunningCopies.Process]) async -> SpaceRemoval.Plan
    private let findModels: @Sendable (Exclusions) async -> [DeveloperEnvironment.Location]

    init(
        makingPlans makePlan: @escaping @Sendable (SpaceItem, Exclusions, [RunningCopies.Process]) async
            -> SpaceRemoval.Plan = { await SpaceRemoval.plan(for: $0, exclusions: $1, running: $2) },
        measuringModels findModels: @escaping @Sendable (Exclusions) async -> [DeveloperEnvironment.Location] = {
            await DeveloperCaches.models(exclusions: $0)
        }
    ) {
        self.makePlan = makePlan
        self.findModels = findModels
    }

    var selectedItem: SpaceItem? {
        report?.items.first { $0.id == selection }
    }

    func refresh() async {
        await refresh(replanning: [], keepingTheOpenArea: true)
    }

    func readDisk() async {
        disk = await DiskSpace.read()
    }

    /// Scans again and makes every area's plan again, as Rescan asks: a plan also depends on which apps are open,
    /// which the area's size does not show.
    func rescan() async {
        await refresh(replanning: Set(plans.keys), keepingTheOpenArea: false)
    }

    /// Makes the area's plan from what is on disk now, keeping what was chosen in it.
    func plan(_ item: SpaceItem) async {
        let made = await newPlan(for: item)
        // A plan cut short measured only part of the area, and would read the rest as unknown.
        guard !Task.isCancelled else { return }
        keep(made, for: item)
        await measureWhatIsLeftToDeveloper(in: item)
    }

    /// Makes the area's plan again once an app it leaves alone has quit, as its page asks the person to do.
    func followQuits(in item: SpaceItem) {
        guard let apps = plans[item.id]?.appsToQuit, !apps.isEmpty else { return }
        let running = RunningCopies.current
        quitCheck?.cancel()
        quitCheck = Task {
            guard await !SpaceRemoval.quit(of: apps, running: running).isEmpty, !Task.isCancelled else { return }
            await plan(item)
        }
    }

    /// Measures the folders the area's plan leaves to Developer once its list is shown, since only the page's notice
    /// reads their sizes, and with them those it keeps in place, so the notice says what the area holds now. A plan
    /// made again meanwhile takes them only if it leaves the same folders.
    private func measureWhatIsLeftToDeveloper(in item: SpaceItem) async {
        guard let plan = plans[item.id], !plan.leftToDeveloper.isEmpty else { return }
        let sizes = await SpaceRemoval.sizesLeftToDeveloper(in: plan)
        let keptSizes = await SpaceRemoval.sizesKeptInPlace(in: plan)
        guard !Task.isCancelled, plans[item.id]?.leftToDeveloper == plan.leftToDeveloper else { return }
        plans[item.id]?.developerSizes = sizes
        plans[item.id]?.keptSizes = keptSizes
    }

    private struct MadePlan {
        let plan: SpaceRemoval.Plan
        /// The exclusions' revision it was made with.
        let exclusions: Int
        let number: Int
    }

    private func newPlan(for item: SpaceItem) async -> MadePlan {
        let number = (plansStarted[item.id] ?? 0) + 1
        plansStarted[item.id] = number
        let revision = ExclusionsStore.shared.revision
        let plan = await makePlan(item, ExclusionsStore.shared.exclusions, RunningCopies.current)
        return MadePlan(plan: plan, exclusions: revision, number: number)
    }

    private func keep(_ made: MadePlan, for item: SpaceItem) {
        guard plansStarted[item.id] == made.number else { return }
        let previous = plans[item.id]
        var plan = made.plan
        // The sizes measured for the same folders stand until they are measured again, so the page's notice holds.
        if let previous, previous.leftToDeveloper == plan.leftToDeveloper {
            plan.developerSizes = previous.developerSizes
            plan.keptSizes = previous.keptSizes
        }
        let chosen = plan.selection(keeping: selectedURLs, canUseHelper: canUseHelper)
        selectedURLs.subtract(previous?.removable ?? [])
        selectedURLs.formUnion(chosen)
        plans[item.id] = plan
        plannedFor[item.id] = (item, made.exclusions)
    }

    /// Makes the plans of the areas in `items` that have none yet, as the page's scan: Rescan turns into Stop
    /// meanwhile, and a scan that was stopped keeps no plan. True once every one of them has its plan.
    func planEvery(_ items: [SpaceItem]) async -> Bool {
        let unplanned = items.filter { !$0.isReadOnly && plans[$0.id] == nil }
        guard !unplanned.isEmpty else { return true }
        let answer = await scanRun.run {
            var made: [(item: SpaceItem, plan: MadePlan)] = []
            for item in unplanned where !Task.isCancelled {
                made.append((item, await self.newPlan(for: item)))
            }
            return made
        }
        guard let made = answer else { return false }
        for (item, plan) in made {
            keep(plan, for: item)
        }
        return true
    }

    /// Brings what is selected in each area in line with the helper as it is now, without measuring again.
    func follow(canUseHelper: Bool) {
        guard canUseHelper != self.canUseHelper else { return }
        self.canUseHelper = canUseHelper
        for plan in plans.values {
            let chosen = plan.selection(keeping: selectedURLs, canUseHelper: canUseHelper)
            selectedURLs.subtract(plan.removable)
            selectedURLs.formUnion(chosen)
        }
    }

    /// Scans again, and makes again the plans of the areas in `replanning` and of every area that changed since
    /// its plan was made, so what is carried from them follows what is on disk. The plans are part of the scan, so
    /// an area's page stays busy until it shows what is there now. The area open on its page stays listed, however
    /// small a move left it, until the person asks for a Rescan.
    private func refresh(replanning: Set<SpaceItem.ID>, keepingTheOpenArea: Bool) async {
        let exclusions = ExclusionsStore.shared.exclusions
        let keeping = keepingTheOpenArea ? Set([selection].compactMap(\.self)) : []
        let answer = await scanRun.run {
            let result = await SpaceInventory.scan(keeping: keeping, exclusions: exclusions)
            var made: [(item: SpaceItem, plan: MadePlan)] = []
            for item in result.items where self.plans[item.id] != nil && !Task.isCancelled {
                let planned = self.plannedFor[item.id]
                let changed = planned?.item != item || planned?.exclusions != ExclusionsStore.shared.revision
                guard replanning.contains(item.id) || changed else { continue }
                made.append((item, await self.newPlan(for: item)))
            }
            return (result, made, await DiskSpace.read())
        }
        guard let (result, made, disk) = answer else { return }
        // Together, so the page never shows the areas without the disk's band.
        report = result
        self.disk = disk
        for id in plans.keys.filter({ id in !result.items.contains { $0.id == id } }) {
            selectedURLs.subtract(plans[id]?.removable ?? [])
            plans[id] = nil
            plannedFor[id] = nil
        }
        if let selection, !result.items.contains(where: { $0.id == selection }) {
            self.selection = nil
        }
        for (item, plan) in made {
            keep(plan, for: item)
        }
        for (item, _) in made {
            await measureWhatIsLeftToDeveloper(in: item)
        }
        await measureModels()
    }

    /// Measures the AI models and datasets after the areas, keeping the newest answer: a measurement that ends after
    /// a newer one began, or is stopped, changes nothing.
    func measureModels() async {
        modelsMeasurement += 1
        let measurement = modelsMeasurement
        let found = await findModels(ExclusionsStore.shared.exclusions)
        guard !Task.isCancelled, measurement == modelsMeasurement else { return }
        models = found.isEmpty ? nil : SizeTotal(found.map(\.size))
        modelsNotMeasured = Set(found.compactMap(\.whyNotMeasured))
    }
}

extension SpaceItem {
    var page: CarriedSelection.Page { Tool.space.page(id) }
}

extension SpaceLibrary: CarriesSelection {
    var carriedParts: [CarriedSelection.Part] {
        (report?.items ?? []).compactMap { item in
            guard let plan = plans[item.id] else { return nil }
            let selected = plan.removable.filter(selectedURLs.contains)
            guard !selected.isEmpty else { return nil }
            return CarriedSelection.Part(
                page: item.page,
                title: String(localized: item.words.title),
                source: item.words.title.inEnglish,
                sourceKey: "space.\(item.id)",
                sizes: Dictionary(selected.map { ($0, plan.sizes[$0]) }, uniquingKeysWith: { first, _ in first })
            )
        }
    }

    /// Asks the area again rather than trusting its plan: an app opened since may be writing to some of these
    /// folders, and they stay where they are, each told as in use by that app.
    func move(_ part: CarriedSelection.Part, apps: AppLibrary) async -> TrashResult? {
        guard let item = report?.items.first(where: { $0.page == part.page }) else { return TrashResult() }
        let exclusions = ExclusionsStore.shared.exclusions
        let chosen = selectedURLs.intersection(part.sizes.keys)
        let now = await SpaceRemoval.movableNow(in: item, exclusions: exclusions, running: RunningCopies.current)
        let removable = now.removable.filter(chosen.contains)
        var result = await TrashService(exclusions: exclusions)
            .trash(removable, usingHelperFor: Set(removable.filter(FileAccess.requiresPrivilegesToRemove)))
        result.failures += now.inUse.filter { chosen.contains($0.url) }.map {
            TrashFailure(url: $0.url, reason: .heldOpen(by: [$0.name]))
        }
        return result
    }

    func refresh(after parts: [CarriedSelection.Part], apps: AppLibrary) async {
        await refresh(replanning: Set(parts.map(\.page.scope)), keepingTheOpenArea: true)
    }

    func choose(_ page: CarriedSelection.Page) {
        selection = page.scope
    }
}

extension SpaceItem.Category {
    var title: LocalizedStringResource {
        switch self {
        case .development: "Development"
        case .virtualMachines: "Virtual Machines"
        case .media: "Media"
        case .cloud: "Cloud Storage"
        case .library: "Library"
        }
    }

    var systemImage: String {
        switch self {
        case .development: "hammer"
        case .virtualMachines: "server.rack"
        case .media: "play.rectangle"
        case .cloud: "cloud"
        case .library: "books.vertical"
        }
    }
}