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 BackgroundItemList: View {
@Environment(AppLibrary.self) private var library
@Environment(BackgroundItemLibrary.self) private var backgroundItems
@State private var searchText = ""
@State private var isRescanning = false
var body: some View {
@Bindable var backgroundItems = backgroundItems
let filtered = filteredItems
List(selection: $backgroundItems.selection) {
RemovalsHeldBanner(recordsInHistory: false)
if let note = backgroundItems.missingNote, !filtered.isEmpty {
Notice(title: Text("Part of this list may be missing"), detail: Text(verbatim: note), kind: .note) {}
.padding(.vertical, 6)
.listRowSeparator(.hidden)
}
section(Text("Agents"), items: filtered.filter { $0.kind == .agent })
section(Text("Daemons"), items: filtered.filter { $0.kind == .daemon })
}
.accessibilityLabel(Text(Tool.backgroundItems.title))
.scrollBarBelowSectionHeaders(backgroundItems.items?.isEmpty == false)
.scanState(phase(filtered), isRescanning: isRescanning, scan: backgroundItems.scanRun) {
if backgroundItems.items?.isEmpty == true,
let note = backgroundItems.missingNote, let title = couldNotLook {
ContentUnavailableView {
Label {
Text(title)
} icon: {
Image(systemName: "exclamationmark.triangle")
}
} description: {
Text(verbatim: note)
}
} else if backgroundItems.items?.isEmpty == true {
ContentUnavailableView(
"No Background Items",
systemImage: "gearshape.2",
description: Text("Apps that run in the background will appear here. Apps set to open at login are in System Settings > General > Login Items & Extensions.")
)
} else {
ContentUnavailableView.search(text: searchText)
}
}
.columnSearch(text: $searchText, prompt: "Search Background Items", when: backgroundItems.items?.isEmpty == false)
.fadesInColumn(whenRowsChange: backgroundItems.items?.map(\.id))
.navigationTitle(Text(Tool.backgroundItems.title))
.announcesScan(
backgroundItems.isScanningAsAsked,
found: announcement,
couldNotLook: couldNotLook,
wasStopped: backgroundItems.scanRun.wasStopped
)
.toolbar {
ToolbarItem {
// Off during a job's action on the busy timing, so a quick one doesn't flash it.
BusyShown(isBusy: !backgroundItems.runningActionItemIDs.isEmpty) { isActing in
RescanButton(
isRunning: $isRescanning,
isDisabled: !library.hasLoaded || isActing,
scan: backgroundItems.scanRun
) {
await backgroundItems.refresh(installedApps: library.apps)
}
}
}
}
// The first scan waits for the installed apps, which it needs to trace each item to the app that owns it.
// After it, the list is read again each time it is shown and each time Peel comes forward.
.task(id: library.hasLoaded) {
guard library.hasLoaded else { return }
guard backgroundItems.items == nil else {
await backgroundItems.readAgain(installedApps: library.apps)
return
}
guard !backgroundItems.scanRun.isWaitedFor, !backgroundItems.scanRun.wasStopped else { return }
await backgroundItems.refresh(installedApps: library.apps)
}
.onReceive(NotificationCenter.default.publisher(for: NSApplication.didBecomeActiveNotification)) { _ in
guard library.hasLoaded else { return }
Task { await backgroundItems.readAgain(installedApps: library.apps) }
}
.rescanOnExclusionChange("BackgroundItemList") { await backgroundItems.refresh(installedApps: library.apps) }
.rescanAfterPutBack(.backgroundItems) { await backgroundItems.refresh(installedApps: library.apps) }
// Shown from the list, which stays on screen. An alert on the item's page would vanish with the page if
// the rescan after the action removed the item, and then show up on the next item the user opens.
.alert(alertTitle, isPresented: isShowingAlert) {
Button("OK", role: .cancel) {}
} message: {
alertMessage
}
}
/// What VoiceOver hears when a scan ends: what it found, and that part of the list may be missing when it may.
private var announcement: AttributedString? {
guard let found = backgroundItems.summary else { return nil }
guard backgroundItems.missingNote != nil else { return found }
return found + " " + AttributedString(localized: "Part of this list may be missing.")
}
private var couldNotLook: LocalizedStringResource? {
if !backgroundItems.unanswered.isEmpty { return "macOS Didn’t Answer" }
return backgroundItems.unreadableFolders.isEmpty ? nil : "Not Everything Could Be Read"
}
private func phase(_ filtered: [BackgroundItem]) -> ScanPhase {
if backgroundItems.items == nil { return backgroundItems.scanRun.wasStopped ? .stopped : .scanning(.walk) }
if backgroundItems.items?.isEmpty == true { return .message }
if filtered.isEmpty, !searchText.isEmpty { return .message }
return .content
}
private var isShowingAlert: Binding<Bool> {
Binding(
get: { backgroundItems.alerts.current != nil },
set: { if !$0 { backgroundItems.dismissAlert() } }
)
}
private var alertTitle: Text {
switch backgroundItems.alerts.current {
case .failed(let failure)?: failureTitle(failure)
case .enabledUntilLoaded(let label, _)?: Text("“\(label)” is enabled.")
case .edited(let label, _)?: Text("“\(label)” is saved.")
case .notEdited(let label, _, _)?: Text("“\(label)” couldn’t be saved.")
case nil: Text(verbatim: "")
}
}
private var alertMessage: Text {
switch backgroundItems.alerts.current {
case .failed(let failure)?: failureMessage(failure)
case .enabledUntilLoaded(_, .daemon)?:
Text("It isn’t loaded now, so it leaves this list until macOS loads it again, usually when the Mac restarts.")
case .enabledUntilLoaded?:
Text("It isn’t loaded now, so it leaves this list until macOS loads it again, usually the next time you log in.")
case .edited(_, let reload)?: reloadMessage(reload)
case .notEdited(_, let url, let problem)?: Text(verbatim: problem.explanationWithTheOldFileInTheTrash(url: url))
case nil: Text(verbatim: "")
}
}
private func reloadMessage(_ reload: LaunchAgentFile.Reload) -> Text {
switch reload {
case .notStopped(let reason):
Text("launchd didn’t stop it, so it runs as it was until you log out, and from the new file after that.\n\n\(reasonMessage(reason))")
case .notStarted(.disabled):
Text("It’s disabled, so macOS loads it from the new file once you enable it.")
case .notStarted(let reason):
Text("macOS didn’t load it again from the new file.\n\n\(reasonMessage(reason))")
}
}
private func failureTitle(_ failure: BackgroundItemLibrary.ActionFailure) -> Text {
let label = failure.label
return switch failure.action {
case .load: Text("“\(label)” couldn’t be loaded.")
case .runNow: Text("“\(label)” couldn’t be started.")
case .stop: Text("“\(label)” couldn’t be stopped.")
case .unload: Text("“\(label)” couldn’t be unloaded.")
case .restart: Text("“\(label)” couldn’t be restarted.")
case .remove: Text("“\(label)” couldn’t be removed.")
case .enable: Text("“\(label)” couldn’t be enabled.")
case .disable: Text("“\(label)” couldn’t be disabled.")
case .moveToTrash where failure.fileMoved: Text("“\(label)” is in the Trash but couldn’t be stopped.")
case .moveToTrash: Text("“\(label)” couldn’t be moved to the Trash.")
}
}
private func failureMessage(_ failure: BackgroundItemLibrary.ActionFailure) -> Text {
let reason = reasonMessage(failure.reason)
guard let stopsForGood = failure.stopsForGood else { return reason }
return Text("\(reason)\n\n\(Text(stopsForGood))")
}
private func reasonMessage(_ reason: BackgroundItemActions.Failure) -> Text {
switch reason {
case .requiresPrivileges: Text("It needs administrator access, which Peel’s helper provides.")
case .noFileToMove: Text("This one comes from the app itself, so there is no file to move. Remove the app to get rid of it.")
case .launchctl(let output): Text(verbatim: FixedSentence.translated(output))
case .trash(let reason): Text(verbatim: reason.explanation)
case .disabled: Text("macOS won’t load this while it is disabled. Enable it first, then start it.")
case .quarantinedPlist: Text("macOS won’t load this: its configuration file carries the mark macOS puts on downloads. Reinstalling the app that put it there may write it again without the mark.")
case .turnedOffInSystemSettings: Text(.keptOffBySystemSettings)
}
}
@ViewBuilder
private func section(_ title: Text, items: [BackgroundItem]) -> some View {
if !items.isEmpty {
Section {
ForEach(items) { item in
BackgroundItemRow(item: item, ownerName: ownerName(of: item))
}
} header: {
title
}
}
}
private var filteredItems: [BackgroundItem] {
let items = backgroundItems.items ?? []
guard !searchText.isEmpty else { return items }
return items.filter { item in
SearchText.matches(item.label, searchText)
|| ownerName(of: item).map { SearchText.matches($0, searchText) } == true
}
}
/// The owner's name as the item's page gives it: the name found with the owner, which knows an app outside the
/// scanned folders, and else the installed app's.
private func ownerName(of item: BackgroundItem) -> String? {
item.ownerBundleIdentifier.map { item.ownerName ?? library.name(forReference: $0) }
}
}
private struct BackgroundItemRow: View {
let item: BackgroundItem
let ownerName: String?
var body: some View {
HStack(alignment: .firstTextBaseline, spacing: 8) {
BackgroundItemStateIndicator(item: item)
VStack(alignment: .leading, spacing: 2) {
Text(item.label)
.lineLimit(1)
.truncationMode(.middle)
if item.isUnreadable {
StatusLabel(title: Text("macOS can’t load this file"))
.font(.caption)
.foregroundStyle(.secondary)
.lineLimit(1)
} else if item.isClosedToPeel, item.isNamedByItsFile {
StatusLabel(title: Text("Peel can’t read its file"))
.font(.caption)
.foregroundStyle(.secondary)
.lineLimit(1)
} else if item.isFileGone {
StatusLabel(title: Text("Its file is gone"))
.font(.caption)
.foregroundStyle(.secondary)
.lineLimit(1)
} else if item.anotherFileIsLoaded {
StatusLabel(title: Text("Another file with this name is loaded"))
.font(.caption)
.foregroundStyle(.secondary)
.lineLimit(1)
} else if item.runsFromTheTrash {
StatusLabel(title: Text("Runs from the Trash"))
.font(.caption)
.foregroundStyle(.secondary)
.lineLimit(1)
} else if item.isOrphan {
StatusLabel(title: Text("Nothing left to run"))
.font(.caption)
.foregroundStyle(.secondary)
.lineLimit(1)
} else if let ownerName {
Group {
if item.isOwnerConfirmed {
Text(ownerName)
} else {
Text("Named like \(ownerName)")
}
}
.font(.caption)
.foregroundStyle(.secondary)
.lineLimit(1)
}
if item.isExcluded {
Text("Excluded in Settings")
.font(.caption)
.foregroundStyle(.secondary)
.lineLimit(1)
}
if item.unusualCommand != nil {
StatusLabel(title: Text("Unusual command"))
.font(.caption)
.foregroundStyle(.secondary)
.lineLimit(1)
}
}
}
.padding(.vertical, 2)
.contextMenu {
// Only for a file Peel can move to the Trash. A job an app registered goes with the app, and a job
// with an Apple label is left alone.
if item.canMoveToTrash, let plist = item.plistURL {
ItemMenu(url: plist)
}
}
}
}
struct BackgroundItemStateIndicator: View {
let item: BackgroundItem
var body: some View {
let look = item.stateLook()
Image(systemName: look.symbol)
.foregroundStyle(look.tint)
.imageScale(.small)
.accessibilityLabel(look.title)
}
}
extension BackgroundItem {
/// How the job's state is shown, in the list and on its page alike. A state Peel could not read comes first,
/// since whether the job is disabled may not have been read either. `withProcess` names a running job's process.
func stateLook(withProcess: Bool = false) -> (title: Text, symbol: String, tint: Color) {
let title = Text(stateWords(withProcess: withProcess))
return switch state {
case .unknown: (title, "questionmark.circle.dashed", .secondary)
case _ where isDisabled: (title, "minus.circle.fill", .orange)
case .running: (title, "circle.fill", .green)
case .loaded: (title, "circle", .secondary)
case .notLoaded: (title, "circle.dashed", .secondary)
}
}
func stateWords(withProcess: Bool = false) -> LocalizedStringResource {
switch state {
case .unknown: .unknownBackgroundItemState
// Disabling a job keeps launchd from loading it again, and leaves what runs now running.
case .running(let pid) where isDisabled:
withProcess ? "Disabled, still running · PID \(String(pid))" : "Disabled, still running"
case _ where isDisabled: "Disabled"
case .running(let pid): withProcess ? "Running · PID \(String(pid))" : "Running"
case .loaded: "Not running"
case .notLoaded: "Not loaded"
}
}
/// Whether launchd has the job, where its state doesn't say it: one that isn't running may be loaded and waiting
/// for its time, and a disabled one may be loaded or not.
func loadWords() -> LocalizedStringResource? {
switch state {
case .loaded: "Loaded"
case .notLoaded where isDisabled: "Not loaded"
default: nil
}
}
func loadLook() -> (title: Text, symbol: String)? {
loadWords().map { (Text($0), state == .loaded ? "checkmark.circle" : "circle.dashed") }
}
}
extension LocalizedStringResource {
/// The state of a background item when `launchctl` did not say it in a form Peel can read.
static let unknownBackgroundItemState = LocalizedStringResource(
"Unknown (background item state)",
defaultValue: "Unknown"
)
static let keptOffBySystemSettings: LocalizedStringResource = "It needs approval in System Settings > General > Login Items & Extensions, or was turned off there, so macOS doesn’t run it, and Peel doesn’t start it either."
}