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.

39.7 KB
Raw Blame
import AppKit
import FinderSync
import PeelCore
import ServiceManagement
import SwiftUI

/// The tabs of Settings. The one open is remembered under `SettingsKey.pane`, which is also how another page
/// opens Settings at a tab of its choosing.
enum SettingsPane: String {
    case general
    case exclusions
    case privacy
    case helper

    /// Opens Settings at this tab, where the action that sent the person there is.
    func open(with openSettings: OpenSettingsAction) {
        UserDefaults.standard.set(rawValue, forKey: SettingsKey.pane)
        openSettings()
    }
}

/// The Settings tabs, shared by the Settings window (Command-Comma) and the Settings page in Peel's sidebar.
/// The last open tab is remembered, as the Human Interface Guidelines ask of a settings window.
struct SettingsTabs: View {
    @AppStorage(SettingsKey.pane) private var pane = SettingsPane.general.rawValue
    /// Whether the tabs have the Settings window's size, the same for every tab, so the window holds still as they
    /// change. On the Settings page the tabs fill the column.
    var isInTheWindow = false

    var body: some View {
        TabView(selection: $pane) {
            Tab("General", systemImage: "gearshape", value: SettingsPane.general.rawValue) {
                fitted(GeneralSettingsView())
            }
            Tab("Exclusions", systemImage: "hand.raised", value: SettingsPane.exclusions.rawValue) {
                fitted(ExclusionsSettingsView())
            }
            Tab("Privacy", systemImage: "network", value: SettingsPane.privacy.rawValue) {
                fitted(PrivacySettingsView())
            }
            Tab("Helper", systemImage: "lock.shield", value: SettingsPane.helper.rawValue) {
                fitted(HelperSettingsView())
            }
        }
    }

    @ViewBuilder
    private func fitted(_ tab: some View) -> some View {
        if isInTheWindow {
            tab.frame(width: 680, height: SettingsView.height)
        } else {
            tab
        }
    }
}

/// The Settings window's content. The `Settings` scene sizes the window to fit it, so it keeps one size whichever tab
/// is open, and a tab with more to show scrolls.
struct SettingsView: View {
    static let height: CGFloat = 520

    var body: some View {
        if #available(macOS 27, *) {
            SettingsWindowTabs()
        } else {
            SettingsTabs(isInTheWindow: true)
        }
    }
}

/// The Settings window on macOS 27: its tabs as one capsule in the toolbar, as on the Settings page of the main
/// window, since a tab view in a settings window shows them as separate toolbar buttons whatever its style.
@available(macOS 27, *)
private struct SettingsWindowTabs: View {
    @AppStorage(SettingsKey.pane) private var pane = SettingsPane.general.rawValue

    var body: some View {
        page
            .frame(width: 760, height: SettingsView.height)
            .navigationTitle(title)
            .toolbar {
                ToolbarItem(placement: .principal) {
                    Picker("Settings", selection: $pane) {
                        Text("General").tag(SettingsPane.general.rawValue)
                        Text("Exclusions").tag(SettingsPane.exclusions.rawValue)
                        Text("Privacy").tag(SettingsPane.privacy.rawValue)
                        Text("Helper").tag(SettingsPane.helper.rawValue)
                    }
                    .pickerStyle(.tabs)
                }
            }
    }

    @ViewBuilder
    private var page: some View {
        switch SettingsPane(rawValue: pane) ?? .general {
        case .general: GeneralSettingsView()
        case .exclusions: ExclusionsSettingsView()
        case .privacy: PrivacySettingsView()
        case .helper: HelperSettingsView()
        }
    }

    private var title: Text {
        switch SettingsPane(rawValue: pane) ?? .general {
        case .general: Text("General")
        case .exclusions: Text("Exclusions")
        case .privacy: Text("Privacy")
        case .helper: Text("Helper")
        }
    }
}

enum SettingsKey {
    static let pane = "settingsPane"
    static let checksForAppUpdates = "checksForAppUpdates"
    static let watchesTrash = "watchesTrash"
    static let showsInMenuBar = "showsInMenuBar"
    static let hidesFromDock = "hidesFromDock"
    static let warnsWhenDiskIsNearlyFull = "lowDiskSpace.warns"
    static let toldDiskIsNearlyFull = "lowDiskSpace.told"
    /// How many older removals History's page last said it no longer lists.
    static let toldNoLongerListed = "history.toldNoLongerListed"
    static let toldRefusalsNoLongerListed = "history.toldRefusalsNoLongerListed"
    /// The tools the person chose to show or leave out of the sidebar (`SidebarChoices`).
    static let sidebarTools = "sidebar.tools"
    /// The tools left out before each tool had a default, carried into `sidebarTools` once.
    private static let hiddenToolsBefore = "sidebar.hiddenTools"
    /// The `peel` tool reads these four keys too, so they are defined once, in PeelCore.
    static let updateSource = UpdatePreferences.Key.source
    static let ignoredUpdateApps = UpdatePreferences.Key.ignoredApps
    static let skippedUpdateVersions = UpdatePreferences.Key.skippedVersions
    static let updateMemory = UpdateMemories.key
    static let announcedUpdates = "updates.announced"

    /// Nil once the link leads to this copy's tool, and while something that may not be Peel's is where it goes.
    static func commandLineInstallCommand(
        for standing: CommandLineTool.Standing = HomeModel.commandLineStanding
    ) -> String? {
        CommandLineTool.installCommand(
            embedded: Bundle.main.bundleURL.appending(path: "Contents/Helpers/peel"),
            standing: standing
        )
    }
}

extension SettingsKey {
    /// Carries the tools a person left out before each tool had a default into their choices, once. An empty list
    /// carries no choice, so every tool starts at its default.
    static func keepSidebarChoicesAsBefore() {
        let defaults = UserDefaults.standard
        guard let hidden = defaults.string(forKey: hiddenToolsBefore) else { return }
        if defaults.string(forKey: sidebarTools) == nil {
            defaults.set(SidebarChoices(hiddenBefore: hidden).stored, forKey: sidebarTools)
        }
        defaults.removeObject(forKey: hiddenToolsBefore)
    }

    /// With no value yet, Peel shows in the menu bar exactly when it watches the Trash.
    static func showInMenuBarAsBefore() {
        let defaults = UserDefaults.standard
        guard defaults.object(forKey: showsInMenuBar) == nil else { return }
        defaults.set(defaults.bool(forKey: watchesTrash), forKey: showsInMenuBar)
    }
}

/// A small capsule that shows a state, such as On or Not installed, with a tinted symbol. Settings keeps the
/// system's plain look here rather than Peel's sticker badges.
private func state(_ title: LocalizedStringResource, _ symbol: String, _ tint: Color) -> some View {
    HStack(spacing: 4) {
        Text(title)
        Image(systemName: symbol)
            .foregroundStyle(tint)
            // The words are the whole state.
            .accessibilityHidden(true)
    }
    .font(.caption)
    .foregroundStyle(.secondary)
    .padding(.horizontal, 8)
    .padding(.vertical, 3)
    .background(.quaternary, in: .capsule)
}

private struct GeneralSettingsView: View {
    @State private var commandLine = HomeModel.commandLineStanding
    private var installCommand: String? { SettingsKey.commandLineInstallCommand(for: commandLine) }
    private static let place = CommandLineTool.place()
    private static let embeddedTool = Bundle.main.bundleURL.appending(path: "Contents/Helpers/peel")
    private var isStandardAccount: Bool { !helper.isAdministrator }
    private static let blockAhead = SelfRemoval.blockAhead(of: Bundle.main.bundleURL)

    @AppStorage(SettingsKey.checksForAppUpdates) private var checksForAppUpdates = true
    @AppStorage(SettingsKey.updateSource) private var updateSource = UpdateSource.automatic.rawValue
    @AppStorage(SettingsKey.watchesTrash) private var watchesTrash = false
    @AppStorage(SettingsKey.showsInMenuBar) private var showsInMenuBar = false
    @AppStorage(SettingsKey.hidesFromDock) private var hidesFromDock = false
    @AppStorage(SettingsKey.warnsWhenDiskIsNearlyFull) private var warnsWhenDiskIsNearlyFull = false
    @AppStorage(SettingsKey.sidebarTools) private var sidebarTools = ""
    @Environment(TrashMonitor.self) private var trashMonitor
    @Environment(AppLibrary.self) private var library
    @Environment(HomebrewLibrary.self) private var homebrew
    @Environment(HelperModel.self) private var helper
    @Environment(RemovalHistoryStore.self) private var history
    @Environment(ExclusionsStore.self) private var exclusions
    @Environment(StandingWork.self) private var background
    @Environment(HomeModel.self) private var home
    @Environment(SelfUninstall.self) private var selfUninstall
    @State private var isChoosingSidebarTools = false
    // The widest tool symbol at the body size, so the titles of the tools line up.
    @ScaledMetric(relativeTo: .body) private var toolSymbolWidth = 20.0
    @State private var isConfirmingSelfRemoval = false

    private func readStandings() {
        commandLine = HomeModel.commandLineStanding
        SavedSettings.shared.reload()
    }

    var body: some View {
        Form {
            Section {
                // An `HStack` centers the button on a summary that takes two lines, as Saved Settings' rows do.
                HStack(spacing: 8) {
                    Text(sidebarToolsSummary)
                    Spacer(minLength: 8)
                    Button("Choose Tools…") {
                        isChoosingSidebarTools = true
                    }
                    .popover(isPresented: $isChoosingSidebarTools, arrowEdge: .bottom) {
                        sidebarToolsChoice
                    }
                }
            } header: {
                titled("Sidebar", "Turn a tool off to leave it out of the sidebar. The View menu and Shortcuts still open it.")
            }

            Section("Updates") {
                toggle("Check for app updates", isOn: $checksForAppUpdates,
                       "Peel asks each app’s update feed, the App Store, or Homebrew for the latest version. It never installs anything on its own. With this off, Peel doesn’t look for its own updates either, unless you choose Check for Updates in the Peel menu.")
                // The choices stay short, because a pop-up button that doesn't fit truncates its title. The note
                // explains what Automatic does.
                LabeledContent {
                    Picker(selection: $updateSource) {
                        Text("Automatic").tag(UpdateSource.automatic.rawValue)
                        Text("The App Store").tag(UpdateSource.appStore.rawValue)
                        Text("The app’s own feed").tag(UpdateSource.developer.rawValue)
                        Text("Homebrew").tag(UpdateSource.homebrew.rawValue)
                    } label: {
                        EmptyView()
                    }
                    .labelsHidden()
                    .accessibilityLabel(Text("Prefer updates from"))
                    .disabled(!checksForAppUpdates)
                } label: {
                    titled("Prefer updates from",
                           "Automatic asks Homebrew first about an app Homebrew installed, then the app’s own feed or the App Store. Any other choice puts the source you prefer first, then the app’s own feed, then Homebrew for an app it installed. Homebrew’s catalog answers last, for an app Homebrew didn’t install.")
                }
                .onChange(of: updateSource) { _, _ in
                    Task { await library.updateSourceChanged() }
                }
            }

            if !muted.isEmpty {
                Section {
                    ForEach(muted) { item in
                        mutedRow(item)
                    }
                } header: {
                    titled("Muted Updates",
                           "Apps Peel stays quiet about, because you chose Never Check This App or skipped a version. Checking one again brings its updates back.")
                }
            }

            AppFoldersSection()

            HomebrewSection()

            Section("While Peel Runs") {
                toggle("Show in Menu Bar", isOn: $showsInMenuBar,
                       "Peel stays in the menu bar after you close its window, with what each tool found and the updates waiting. Without it, Peel quits when you close its window.")
                toggle("Hide from the Dock while no window is open", isOn: $hidesFromDock,
                       "While Peel shows in the menu bar, its icon leaves the Dock when you close its last window, and comes back when you open Peel again from the menu bar, Finder, or Spotlight.",
                       isDisabled: !showsInMenuBar)
                toggle("Watch the Trash", isOn: $watchesTrash,
                       "When you move an app to the Trash yourself, Peel offers to remove the files it left behind. Peel watches the Trash while it is open, or while it is in the menu bar.")
                if watchesTrash, trashMonitor.status == .needsFullDiskAccess {
                    HStack {
                        StatusLabel(title: Text("Peel needs Full Disk Access to watch the Trash."), systemImage: "lock.trianglebadge.exclamationmark")
                        Spacer()
                        // Full Disk Access applies only to a new process, so once it may have been given, Peel offers
                        // to reopen.
                        if home.needsRelaunchForFullDiskAccess {
                            Button("Reopen Peel") { home.relaunch() }
                        }
                        Button("Open System Settings") {
                            home.openFullDiskAccessSettings()
                        }
                    }
                } else if watchesTrash, trashMonitor.status == .unavailable {
                    StatusLabel(title: Text("Peel isn’t watching the Trash right now. It tries again each time you come back to Peel."))
                }
                if watchesTrash, PeelNotifications.areTurnedOff(home.notificationStatus) {
                    notificationsOff(Text("Peel isn’t allowed to send notifications, so it can’t offer to remove the files an app left behind."))
                }
                toggle("Warn when the disk is almost full", isOn: $warnsWhenDiskIsNearlyFull,
                       "When less than a tenth of the disk your home folder is on is available, Peel sends a notification that opens Space. It checks only while it is running.")
                if warnsWhenDiskIsNearlyFull, PeelNotifications.areTurnedOff(home.notificationStatus) {
                    notificationsOff(Text("Peel isn’t allowed to send notifications, so it can’t warn you when the disk is almost full."))
                }
                // A binding, not `onChange`: macOS's own answer landing in the model must not register again.
                toggle("Open Peel at login", isOn: Binding(get: { home.loginItem.isOn }, set: { home.loginItem.set(on: $0) }),
                       "Starts Peel when you log in. “Watch the Trash” works only while Peel is running.",
                       isDisabled: !home.loginItem.isKnown)
                if home.loginItem.needsApproval {
                    HStack {
                        StatusLabel(title: Text("Peel is turned off in Login Items & Extensions, so macOS won’t start it."))
                        Spacer()
                        Button("Open System Settings") {
                            SMAppService.openSystemSettingsLoginItems()
                        }
                    }
                }
                if let failure = home.loginItem.failure {
                    StatusLabel(title: Text(failure))
                        .textSelection(.enabled)
                }
            }

            Section("Elsewhere on This Mac") {
                LabeledContent {
                    Button("Open System Settings") {
                        FIFinderSyncController.showExtensionManagementInterface()
                    }
                } label: {
                    // Uses `HomeModel`'s state, so Home and Settings can't show different answers.
                    let isOn = home.state(of: .finderExtension) == .on
                    HStack(spacing: 5) {
                        Text("Finder extension")
                        if home.hasChecked {
                            state(isOn ? "On" : home.isFinderExtensionFromAnotherCopy ? "On in another copy of Peel" : "Off",
                                  isOn ? "checkmark.circle" : "minus.circle",
                                  isOn ? .green : .secondary)
                        } else {
                            state("Checking…", "hourglass", .secondary)
                        }
                        InfoNote(
                            name: String(localized: "Finder extension"),
                            detail: Text("Control-click an app in Finder and choose Uninstall with Peel to see what it leaves behind.")
                        )
                    }
                }
                LabeledContent {
                    if commandLine == .installed {
                        state("Installed", "checkmark.circle", .green)
                    } else if isStandardAccount {
                        state("Needs an administrator", "person.crop.circle.badge.exclamationmark", .orange)
                    } else if let installCommand {
                        CopyButton(text: installCommand)
                    }
                } label: {
                    titled("Command-line tool",
                           "Run the command in Terminal to use `peel` from anywhere, then type `peel --help` to see what it can do.")
                }
                switch Self.place {
                case .applications:
                    EmptyView()
                case .temporaryCopy:
                    Text("Peel is running from a copy macOS made because it is still marked as downloaded. Move Peel to the Applications folder and open it from there.")
                        .font(.caption)
                        .foregroundStyle(.secondary)
                case .readOnlyVolume:
                    Text("Peel is running from a read-only disk, such as the disk image it came on. Move Peel to the Applications folder and open it from there.")
                        .font(.caption)
                        .foregroundStyle(.secondary)
                case .elsewhere:
                    if commandLine == .installed || installCommand != nil, !isStandardAccount {
                        Text("The link points at Peel where it is now, \(Text(verbatim: Bundle.main.bundleURL.abbreviatedPath)), so it breaks if Peel moves. Apps live in the Applications folder.")
                            .font(.caption)
                            .foregroundStyle(.secondary)
                    }
                }
                if [.applications, .elsewhere].contains(Self.place), commandLine != .installed {
                    if isStandardAccount {
                        if let shell = CommandLineTool.shellLine(embedded: Self.embeddedTool) {
                            CopyableLines(
                                caption: Text("Putting `peel` on the path takes an administrator. To use it from this account, add this line to \(shell.file), then open a new Terminal window."),
                                lines: [shell.line]
                            )
                        }
                    } else if let installCommand {
                        Text(verbatim: installCommand)
                            .font(.caption.monospaced())
                            .foregroundStyle(.secondary)
                            .textSelection(.enabled)
                    } else if case .somethingElse(let other) = commandLine {
                        Text(HomeModel.inTheToolsPlace(other))
                            .font(.caption)
                            .foregroundStyle(.secondary)
                    }
                }
            }

            SavedSettingsSection()

            Section {
                let way = SelfUninstall.way(
                    cask: ownCask,
                    homebrewKnowsItsApps: homebrew.knowsWhetherItInstalledPeel,
                    unanswered: homebrew.unanswered
                )
                if case .homebrew(let command) = way {
                    LabeledContent {
                        CopyButton(text: command)
                    } label: {
                        titled("Remove Peel",
                               "Homebrew installed this copy of Peel, so remove it with Homebrew, or Homebrew goes on listing it as installed. Run the command in Terminal: Homebrew deletes the app rather than moving it to the Trash, and moves Peel’s files to the Trash, its folder in Application Support among them. That folder holds History, your exclusions, App Folders, and Saved Settings, among others, and the shell and ssh settings from the Terminal page, which zsh and ssh then stop reading. Homebrew also stops Peel’s helper, asking for an administrator’s password, and deletes the helper’s record of what it moved, which History needs to put those items back.")
                    }
                    Text(verbatim: command)
                        .font(.caption.monospaced())
                        .foregroundStyle(.secondary)
                        .textSelection(.enabled)
                } else {
                    // The button is taller than a row, and `LabeledContent` would align the title with its top
                    // edge. An `HStack` centers the title and the button vertically.
                    HStack {
                        titled("Remove Peel",
                               "Peel removes its helper and login item, moves itself, the files that are certainly its own, and its folder in Application Support to the Trash, all but the Terminal settings zsh and ssh read, clears its settings, then quits. That folder holds History, your exclusions, App Folders, and Saved Settings, among others. What you set in Tweaks and on the Terminal page stays as it is. The Finder extension goes with the app.")
                        Spacer(minLength: 8)
                        Button("Remove Peel") {
                            isConfirmingSelfRemoval = true
                        }
                        .buttonStyle(.borderedProminent)
                        .tint(.red)
                        // Disabled until the app list has loaded: a file Peel shares with another app would look like
                        // Peel's alone.
                        .disabled(
                            selfUninstall.isRunning || !library.hasLoaded || way.waitsForHomebrew
                                || !history.mayMove || Self.blockAhead != nil || waitsForAnAdministrator
                        )
                    }
                    if selfUninstall.isRunning {
                        HStack(spacing: 6) {
                            ProgressView()
                                .controlSize(.small)
                            Text("Removing Peel…")
                                .font(.callout)
                                .foregroundStyle(.secondary)
                        }
                    } else if exclusions.exclusions.isUnreadable {
                        Text(verbatim: exclusions.nothingMovesUntilStartedOver)
                            .font(.callout)
                            .foregroundStyle(.secondary)
                    } else if let why = history.readProblem {
                        Text(verbatim: why.said(after: String(localized: "Peel removes nothing until you start History over, so that everything it moves can be put back."), about: history.historyFile))
                            .font(.callout)
                            .foregroundStyle(.secondary)
                    } else if let problem = history.writeProblem {
                        Text(problem.explanation())
                            .font(.callout)
                            .foregroundStyle(.secondary)
                    } else if let block = Self.blockAhead {
                        Text(SelfUninstall.explanation(of: block))
                            .font(.callout)
                            .foregroundStyle(.secondary)
                    } else if waitsForAnAdministrator {
                        Text(verbatim: SelfUninstall.onlyAnAdministrator)
                            .font(.callout)
                            .foregroundStyle(.secondary)
                    } else if way == .waitingForHomebrew {
                        Text("Peel waits for Homebrew to say whether it installed this copy, since a copy Homebrew installed is removed with Homebrew.")
                            .font(.callout)
                            .foregroundStyle(.secondary)
                    } else if case .homebrewDidNotAnswer(let why) = way {
                        HStack {
                            Group {
                                switch why {
                                case .readingFailed:
                                    Text("Homebrew didn’t say what is installed, so Peel can’t tell whether it installed this copy, which would then be removed with Homebrew.")
                                case .hasToUpdate:
                                    Text("Homebrew has to update before it can say whether it installed this copy, which would then be removed with Homebrew.")
                                case .notRun:
                                    Text("Peel doesn’t run the Homebrew on this Mac, so it can’t tell whether Homebrew installed this copy, which would then be removed with Homebrew.")
                                }
                            }
                            .font(.callout)
                            .foregroundStyle(.secondary)
                            Spacer()
                            Button("Open \(String(localized: Tool.homebrew.title))") { Navigator.shared.show(.homebrew) }
                        }
                    }
                }
                // Homebrew removes the links its cask made, and no other.
                if selfUninstall.leavesCommandLineTool(helper: helper.status),
                   ownCask?.commandLinks.contains(CommandLineTool.path) != true {
                    VStack(alignment: .leading, spacing: 4) {
                        Group {
                            if isStandardAccount {
                                Text("Removing Peel leaves the peel command in place. To remove it too, an administrator runs this command in Terminal:")
                            } else {
                                Text("Removing Peel leaves the peel command in place. To remove it too, run this command in Terminal:")
                            }
                        }
                        .font(.callout)
                        Text(verbatim: SelfUninstall.removeCommand)
                            .font(.caption.monospaced())
                    }
                    .foregroundStyle(.secondary)
                    .textSelection(.enabled)
                }
            }
        }
        .formStyle(.grouped)
        .task {
            readStandings()
            await home.loginItem.refresh()
        }
        .onReceive(NotificationCenter.default.publisher(for: NSApplication.didBecomeActiveNotification)) { _ in
            // The user may have changed the login item in System Settings, or a saved copy in Finder.
            readStandings()
            Task { await home.loginItem.refresh() }
        }
        .confirmationDialog("Remove Peel from this Mac?", isPresented: $isConfirmingSelfRemoval) {
            Button("Remove Peel", role: .destructive) {
                Task {
                    await history.moving(tool: .applications, source: "Peel") {
                        await selfUninstall.run(
                            installedApps: library.apps,
                            helper: helper,
                            pausing: background
                        ) { result in
                            await history.record(result, tool: .applications, source: "Peel", sizes: [:])
                        }
                    }
                }
            }
            Button("Cancel", role: .cancel) {}
                .keyboardShortcut(.defaultAction)
        } message: {
            Text("Peel, the files that are certainly its own, and its folder in Application Support go to the Trash, all but the Terminal settings zsh and ssh read, and its settings are cleared. That folder holds History, your exclusions, App Folders, and Saved Settings, among others. What you set in Tweaks and on the Terminal page stays as it is. The space is freed when you empty the Trash.")
        }
    }
}

extension GeneralSettingsView {
    fileprivate struct Muted: Identifiable {
        let reference: String
        let app: InstalledApp?
        /// The listed app's name, or the Finder name of a copy macOS knows elsewhere.
        let name: String
        let isIgnored: Bool
        let skippedVersion: String?

        var id: String { reference }
    }

    fileprivate var muted: [Muted] {
        let references = library.ignoredApps.union(library.skippedVersions.keys)
        return references.map { reference in
            Muted(
                reference: reference,
                app: library.apps.first { $0.reference == reference },
                name: library.name(forReference: reference),
                isIgnored: library.ignoredApps.contains(reference),
                skippedVersion: library.skippedVersions[reference]
            )
        }
        .sorted { $0.name.localizedStandardCompare($1.name) == .orderedAscending }
    }

    @ViewBuilder
    fileprivate func mutedRow(_ item: Muted) -> some View {
        HStack(spacing: 8) {
            if let app = item.app {
                AppIcon(url: app.url)
                    .frame(width: 16, height: 16)
            } else {
                Image(systemName: "questionmark.app")
                    .foregroundStyle(.secondary)
                    .accessibilityRepresentation { Text("Not installed") }
            }
            VStack(alignment: .leading, spacing: 1) {
                Text(verbatim: item.name)
                    .lineLimit(1)
                    .truncationMode(.middle)
                if item.isIgnored {
                    Text("Never checked")
                        .font(.caption)
                        .foregroundStyle(.secondary)
                } else if let version = item.skippedVersion {
                    Text("Version \(UpdateStatus.shownVersion(of: version)) skipped")
                        .font(.caption)
                        .foregroundStyle(.secondary)
                }
            }
            Spacer(minLength: 8)
            // Checks right away, as the button's title says, rather than at the next scheduled check.
            Button {
                library.unmute(item.reference)
                if let app = item.app {
                    Task { await library.checkForUpdates([app], force: true) }
                }
            } label: {
                Text("Check Again")
                    .minimumTarget()
            }
                .buttonStyle(.borderless)
                .accessibilityLabel(Text("Check \(item.name) for updates again"))
        }
    }
}

extension GeneralSettingsView {
    /// A switch row. `isDisabled` disables the switch alone: disabling the whole row would disable the circled i beside
    /// the title too, so its note couldn't be read while it explains why the switch is off.
    fileprivate func toggle(
        _ title: LocalizedStringResource,
        isOn: Binding<Bool>,
        _ detail: LocalizedStringResource,
        isDisabled: Bool = false
    ) -> some View {
        LabeledContent {
            Toggle(isOn: isOn) { EmptyView() }
                .labelsHidden()
                .accessibilityLabel(Text(title))
                .disabled(isDisabled)
        } label: {
            titled(title, detail)
        }
    }

    fileprivate func notificationsOff(_ title: Text) -> some View {
        HStack {
            StatusLabel(title: title, systemImage: "bell.slash")
            Spacer()
            Button("Open System Settings") {
                home.openNotificationSettings()
            }
        }
    }
}

extension GeneralSettingsView {
    private var sidebarToolsSummary: String {
        let hidden = Tool.hidden(by: SidebarChoices(stored: sidebarTools), homebrew: homebrew)
        let left = Tool.Group.allCases.flatMap(\.tools).filter(hidden.contains).map { String(localized: $0.title) }
        guard !left.isEmpty else { return String(localized: "Every tool is in the sidebar.") }
        return String(localized: "Left out: \(left.formatted(.list(type: .and))).")
    }

    private var sidebarToolsChoice: some View {
        VStack(alignment: .leading, spacing: 8) {
            ForEach(Tool.Group.allCases.flatMap(\.tools).filter(\.canBeHidden)) { tool in
                Toggle(isOn: showsInSidebar(tool)) {
                    Label { Text(tool.title) } icon: { Image(systemName: tool.systemImage) }
                }
                .toggleStyle(.checkbox)
            }
        }
        .labelReservedIconWidth(toolSymbolWidth)
        .padding(16)
    }

    fileprivate func showsInSidebar(_ tool: Tool) -> Binding<Bool> {
        Binding(
            get: {
                !Tool.hidden(by: SidebarChoices(stored: sidebarTools), homebrew: homebrew).contains(tool)
            },
            set: { shows in
                var choices = SidebarChoices(stored: sidebarTools)
                choices.choose(tool.rawValue, shows: shows)
                sidebarTools = choices.stored
            }
        )
    }

    private var waitsForAnAdministrator: Bool {
        SelfUninstall.waitsForAnAdministrator(isAdministrator: helper.isAdministrator, status: helper.status)
    }

    /// The cask Homebrew installed this copy of Peel from, found by the rule the Applications list follows.
    fileprivate var ownCask: HomebrewPackage? {
        guard let app = library.apps.first(where: \.isTheRunningCopy) else { return nil }
        return CaskEvidence.installedCask(for: app, in: (homebrew.packages ?? []).filter { $0.kind == .cask })
    }
}

private struct HelperSettingsView: View {
    @Environment(HelperModel.self) private var helper
    @State private var failure: HelperModel.Failure?
    @State private var isConfirmingUninstall = false

    var body: some View {
        Form {
            Section {
                ViewThatFits(in: .horizontal) {
                    HStack(spacing: 8) {
                        status
                        Spacer(minLength: 8)
                        actions
                    }
                    VStack(alignment: .leading, spacing: 8) {
                        HStack(spacing: 8) { status }
                        ActionRow { actions }
                    }
                }
                if let explanation {
                    explanation
                        .font(.callout)
                }
            }
        }
        .formStyle(.grouped)
        .task {
            await helper.checkConnection()
        }
        .helperFailureAlert($failure)
        .confirmationDialog("Uninstall Peel’s helper?", isPresented: $isConfirmingUninstall) {
            Button("Uninstall Helper", role: .destructive) {
                Task { failure = await helper.uninstall() }
            }
            Button("Cancel", role: .cancel) {}
                .keyboardShortcut(.defaultAction)
        } message: {
            Text("The helper serves every account on this Mac, so this removes it for all of them. Until it is installed again, Peel can’t move what only an administrator can change.")
        }
    }

    /// The state with its word and its note, which stay together wherever the buttons go.
    @ViewBuilder
    private var status: some View {
        InfoNote(
            name: String(localized: "Helper"),
            detail: Text("A small tool with administrator rights. It moves items to the Trash and puts them back, starts, stops, enables, or disables background items, and forgets installer receipts. It takes no other orders."),
            symbol: "lock.shield"
        )
        Text("Status")
        statusBadge
    }

    /// What can be done about the state, the step it asks for last.
    @ViewBuilder
    private var actions: some View {
        switch helper.standing {
        case .notInstalled:
            if helper.standing.offersInstall(registeredByAnotherCopy: helper.isRegisteredByAnotherCopy) {
                Button("Install Helper") {
                    Task { failure = await helper.install() }
                }
                .buttonStyle(.borderedProminent)
                .disabled(helper.isChanging)
            }
        case .waitingForApproval:
            uninstallButton
            // Opens System Settings instead of registering again, which returns an error in this state
            // (`SMAppService.h`).
            Button("Open System Settings") {
                PrivilegedHelper.openLoginItemsSettings()
            }
            .buttonStyle(.borderedProminent)
        case .notThisAccount:
            EmptyView()
        case .notAnswering:
            uninstallButton
            Button("Repair Helper") {
                Task { failure = await helper.repair() }
            }
            .buttonStyle(.borderedProminent)
            .disabled(helper.isChanging)
        case .ready:
            uninstallButton
        }
    }

    /// What the helper's state asks of the person, said under its row.
    private var explanation: Text? {
        switch helper.standing {
        case .notInstalled:
            helper.standing.offersInstall(registeredByAnotherCopy: helper.isRegisteredByAnotherCopy)
                ? nil : Text(helper.standing.whyItCannotAct(registeredByAnotherCopy: true))
        case .waitingForApproval:
            Text("Allow Peel in System Settings under Login Items & Extensions.")
        case .notThisAccount:
            Text("Only an administrator can install, allow, or repair the helper. Once it works, Peel asks for an administrator’s name and password each time this account needs it.")
        case .notAnswering:
            // Several causes share this message: an older or newer helper, a signature that doesn't
            // match, or a helper that didn't start.
            Text("Peel’s helper isn’t answering. Repairing it installs the one this version of Peel works with.")
        case .ready:
            helper.isAdministrator
                ? nil : Text("Peel asks for an administrator’s name and password each time this account needs the helper.")
        }
    }

    private var uninstallButton: some View {
        Button("Uninstall Helper", role: .destructive) {
            isConfirmingUninstall = true
        }
        .disabled(helper.isChanging)
    }

    @ViewBuilder
    private var statusBadge: some View {
        if let changing = helper.changing {
            state(changing.progress, "hourglass", .secondary)
        } else if !helper.hasChecked {
            state("Checking…", "hourglass", .secondary)
        } else {
            switch helper.standing {
            case .notThisAccount:
                state("Needs an administrator", "person.crop.circle.badge.exclamationmark", .orange)
            case .notAnswering:
                state("Not answering", "exclamationmark.triangle", .orange)
            case .ready:
                state("Installed", "checkmark.circle", .green)
            case .waitingForApproval:
                state("Needs approval, or was turned off", "clock", .orange)
            case .notInstalled where helper.isRegisteredByAnotherCopy:
                state("Installed by another copy of Peel", "exclamationmark.triangle", .orange)
            case .notInstalled:
                state("Not installed", "minus.circle", .secondary)
            }
        }
    }
}