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.

Give a background job one Start or Stop button and say if launchd has it

Țugui Dragoșde4593a5e8a7
diff --git a/Localization/Peel/Localizable.xcstrings b/Localization/Peel/Localizable.xcstrings
index 72b08240..615055c5 100644
--- a/Localization/Peel/Localizable.xcstrings
+++ b/Localization/Peel/Localizable.xcstrings
@@ -91552,6 +91552,112 @@
}
}
},
+ "Loaded" : {
+ "localizations" : {
+ "cs" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Načteno"
+ }
+ },
+ "de" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Geladen"
+ }
+ },
+ "es" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Cargado"
+ }
+ },
+ "fr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Chargé"
+ }
+ },
+ "it" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Caricato"
+ }
+ },
+ "ja" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "読み込み済み"
+ }
+ },
+ "ko" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "로드됨"
+ }
+ },
+ "nl" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Geladen"
+ }
+ },
+ "pl" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Wczytany"
+ }
+ },
+ "pt" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Carregado"
+ }
+ },
+ "ro" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Încărcat"
+ }
+ },
+ "ru" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Загружено"
+ }
+ },
+ "sv" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Inläst"
+ }
+ },
+ "tr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Yüklü"
+ }
+ },
+ "uk" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Завантажено"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "已载入"
+ }
+ },
+ "zh-Hant" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "已載入"
+ }
+ }
+ }
+ },
"Loaded from a file elsewhere" : {
"localizations" : {
"cs" : {
diff --git a/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItem.swift b/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItem.swift
index 9a3653c7..05743468 100644
--- a/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItem.swift
+++ b/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItem.swift
@@ -168,6 +168,30 @@ public struct BackgroundItem: Sendable, Hashable, Identifiable {
return !isSeenOnlyWhileLoaded || isDisabled || mayBeDisabled
}
+ public enum StartOrStop: Sendable {
+ case start
+ case stop
+ /// Stop under the name macOS 27's page gives it for a job its gone app left loaded.
+ case remove
+ }
+
+ /// The one button that starts or stops the job, as launchd has it: Stop while launchd has it, running or waiting
+ /// for its time, and Start while it doesn't. A job Peel sees only while it is loaded has Stop only while it runs.
+ public var startOrStop: StartOrStop? {
+ guard offersControls else { return nil }
+ if canOnlyBeStopped { return .stop }
+ if #available(macOS 27, *), isLeftByAGoneApp { return .remove }
+ if isSeenOnlyWhileLoaded { return isRunning ? .stop : nil }
+ return state == .notLoaded ? .start : .stop
+ }
+
+ /// Enable and Disable, which a job Peel can only stop, and on macOS 27 one its gone app left, don't have.
+ public var offersEnableOrDisable: Bool {
+ guard offersControls, !canOnlyBeStopped, isDisabled || mayBeDisabled else { return false }
+ if #available(macOS 27, *), isLeftByAGoneApp { return false }
+ return true
+ }
+
/// Whether the helper would let Peel do more with the job than it can without it: a control the page offers, or the
/// move of its file.
public var waitsForTheHelper: Bool {
diff --git a/Packages/PeelCore/Sources/PeelCore/Support/ActionRowPlan.swift b/Packages/PeelCore/Sources/PeelCore/Support/ActionRowPlan.swift
index bd6fc282..24f77b22 100644
--- a/Packages/PeelCore/Sources/PeelCore/Support/ActionRowPlan.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Support/ActionRowPlan.swift
@@ -1,7 +1,9 @@
public import CoreGraphics
/// Where the buttons of a page go: together at the right edge, the last, its main action, at the edge itself. When a
-/// language's words leave no room on one line, the first ones take a line above, also at the right edge.
+/// language's words leave no room on one line, the first ones take a line above, also at the right edge. Buttons that
+/// lead, those that keep what the page is about, such as Start and Disable, stand at the left edge instead, on the
+/// line of the others while there is room, and on the lines above them otherwise.
public struct ActionRowPlan: Equatable, Sendable {
public let frames: [CGRect]
public let size: CGSize
@@ -9,35 +11,43 @@ public struct ActionRowPlan: Equatable, Sendable {
/// - Parameters:
/// - sizes: Each button's own size. What has no width, a group with nothing to show, takes no room.
/// - top: The space above the buttons, left out with them when none shows.
- public init(sizes: [CGSize], width: CGFloat?, spacing: CGFloat = 8, lineSpacing: CGFloat = 6, top: CGFloat = 0) {
+ /// - leading: Which buttons lead, by their place in `sizes`.
+ public init(
+ sizes: [CGSize], width: CGFloat?, spacing: CGFloat = 8, lineSpacing: CGFloat = 6, top: CGFloat = 0,
+ leading: [Bool] = []
+ ) {
let shown = sizes.indices.filter { sizes[$0].width > 0 }
- let needed = shown.reduce(0) { $0 + sizes[$1].width } + spacing * CGFloat(max(shown.count - 1, 0))
- let room = width.flatMap { $0.isFinite ? $0 : nil } ?? needed
-
- var lines: [[Int]] = []
- var used: CGFloat = 0
- for index in shown.reversed() {
- let width = min(sizes[index].width, room)
- if let line = lines.first, !line.isEmpty, used + spacing + width <= room {
- lines[0].insert(index, at: 0)
- used += spacing + width
- } else {
- lines.insert([index], at: 0)
- used = width
- }
+ let leads = shown.filter { leading.indices.contains($0) && leading[$0] }
+ let follows = shown.filter { !leads.contains($0) }
+ func needed(_ indices: [Int]) -> CGFloat {
+ indices.reduce(0) { $0 + sizes[$1].width } + spacing * CGFloat(max(indices.count - 1, 0))
}
+ let room = width.flatMap { $0.isFinite ? $0 : nil } ?? needed(shown)
+
+ let oneLine = !leads.isEmpty && !follows.isEmpty && needed(shown) <= room
+ var lines = oneLine ? [] : Self.lines(of: leads, sizes, room: room, spacing: spacing, fromTheRight: false)
+ let trailing = Self.lines(of: follows, sizes, room: room, spacing: spacing, fromTheRight: true)
+ lines += oneLine ? [Line(leading: leads, trailing: follows)] : trailing
var frames = [CGRect](repeating: .zero, count: sizes.count)
var y = top
for line in lines {
- let height = line.reduce(0) { max($0, sizes[$1].height) }
- var x = room
- for index in line.reversed() {
- let width = min(sizes[index].width, room)
- x -= width
+ let height = (line.leading + line.trailing).reduce(0) { max($0, sizes[$1].height) }
+ func place(_ index: Int, at x: CGFloat) {
frames[index] = CGRect(
- x: x, y: y + (height - sizes[index].height) / 2, width: width, height: sizes[index].height
+ x: x, y: y + (height - sizes[index].height) / 2, width: min(sizes[index].width, room),
+ height: sizes[index].height
)
+ }
+ var x: CGFloat = 0
+ for index in line.leading {
+ place(index, at: x)
+ x += min(sizes[index].width, room) + spacing
+ }
+ x = room
+ for index in line.trailing.reversed() {
+ x -= min(sizes[index].width, room)
+ place(index, at: x)
x -= spacing
}
y += height + lineSpacing
@@ -45,4 +55,30 @@ public struct ActionRowPlan: Equatable, Sendable {
self.frames = frames
size = CGSize(width: room, height: lines.isEmpty ? 0 : y - lineSpacing)
}
+
+ private struct Line {
+ var leading: [Int] = []
+ var trailing: [Int] = []
+ }
+
+ /// The lines `indices` take, as many as fit on each: from the right edge, the first ones on the line above, or
+ /// from the left edge, the last ones on the line below.
+ private static func lines(
+ of indices: [Int], _ sizes: [CGSize], room: CGFloat, spacing: CGFloat, fromTheRight: Bool
+ ) -> [Line] {
+ var lines: [[Int]] = []
+ var used: CGFloat = 0
+ for index in fromTheRight ? indices.reversed() : indices {
+ let width = min(sizes[index].width, room)
+ let line = fromTheRight ? lines.first : lines.last
+ if let line, !line.isEmpty, used + spacing + width <= room {
+ if fromTheRight { lines[0].insert(index, at: 0) } else { lines[lines.count - 1].append(index) }
+ used += spacing + width
+ } else {
+ if fromTheRight { lines.insert([index], at: 0) } else { lines.append([index]) }
+ used = width
+ }
+ }
+ return lines.map { fromTheRight ? Line(trailing: $0) : Line(leading: $0) }
+ }
}
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/ActionRowPlanTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/ActionRowPlanTests.swift
index 8a4b0607..c7a7536f 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/ActionRowPlanTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/ActionRowPlanTests.swift
@@ -51,6 +51,26 @@ struct ActionRowPlanTests {
#expect(ActionRowPlan(sizes: [.zero], width: 400, top: 8).size.height == 0)
}
+ @Test func leadingActionsStandAtTheLeftEdgeOnTheLineOfTheOthers() {
+ let plan = ActionRowPlan(sizes: [small, small, small], width: 400, spacing: 8, leading: [true, true, false])
+ #expect(plan.frames.map(\.minX) == [0, 108, 300])
+ #expect(plan.frames.map(\.minY) == [0, 0, 0])
+ #expect(plan.size == CGSize(width: 400, height: 28))
+ }
+
+ @Test func leadingActionsWithoutRoomBesideTheOthersTakeTheLineAbove() {
+ let plan = ActionRowPlan(sizes: [wide, small], width: 380, spacing: 8, lineSpacing: 6, leading: [true, false])
+ #expect(plan.frames[0] == CGRect(x: 0, y: 0, width: 300, height: 28))
+ #expect(plan.frames[1] == CGRect(x: 280, y: 34, width: 100, height: 28))
+ #expect(plan.size == CGSize(width: 380, height: 62))
+ }
+
+ @Test func aLeadingActionThatIsNotShownTakesNoRoom() {
+ let plan = ActionRowPlan(sizes: [.zero, small], width: 400, leading: [true, false])
+ #expect(plan.frames[1] == CGRect(x: 300, y: 0, width: 100, height: 28))
+ #expect(plan.size.height == 28)
+ }
+
@Test func anActionWiderThanTheRowIsGivenTheWholeRow() {
let plan = ActionRowPlan(sizes: [CGSize(width: 500, height: 28)], width: 400)
#expect(plan.frames == [CGRect(x: 0, y: 0, width: 400, height: 28)])
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/BackgroundItemActionsTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/BackgroundItemActionsTests.swift
index 2b57d2ea..fc126409 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/BackgroundItemActionsTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/BackgroundItemActionsTests.swift
@@ -139,6 +139,35 @@ struct BackgroundItemActionsTests {
#expect(rows.map(\.canMoveToTrash) == [false, true])
}
+ @Test func oneButtonStopsAJobLaunchdHasAndStartsOneItDoesNot() {
+ let file = URL(filePath: "/Users/me/Library/LaunchAgents/job.plist")
+ #expect(item(state: .running(pid: 42), plist: file).startOrStop == .stop)
+ #expect(item(state: .loaded, plist: file).startOrStop == .stop)
+ #expect(item(state: .notLoaded, plist: file).startOrStop == .start)
+ #expect(item(state: .unknown, plist: file).startOrStop == nil)
+
+ var registered = BackgroundItem(
+ label: "com.example.agent", kind: .agent, source: .app, plistURL: nil, program: "/Applications/App.app/x",
+ runsAtLoad: nil, keepsAlive: nil, ownerBundleIdentifier: "com.example", ownerName: "App",
+ ownerURL: URL(filePath: "/Applications/App.app"), isOrphan: false, state: .running(pid: 42), isDisabled: false
+ )
+ registered.isManagedByServiceManagement = true
+ #expect(registered.startOrStop == .stop)
+ registered.state = .loaded
+ #expect(registered.startOrStop == nil)
+
+ var elsewhere = item(state: .loaded, plist: URL(filePath: "/tmp/org.example.job.plist"))
+ elsewhere.source = .otherFile
+ #expect(elsewhere.startOrStop == .stop)
+ #expect(!elsewhere.offersEnableOrDisable)
+
+ var excluded = item(state: .running(pid: 42), plist: file)
+ excluded.isExcluded = true
+ #expect(excluded.startOrStop == nil)
+ #expect(!excluded.offersEnableOrDisable)
+ #expect(item(state: .loaded, plist: file).offersEnableOrDisable)
+ }
+
@Test func startRunsALoadedJobAtOnceAndLoadsOneThatIsNot() {
let file = URL(filePath: "/Users/me/Library/LaunchAgents/job.plist")
diff --git a/Peel/Model/BackgroundItemLibrary.swift b/Peel/Model/BackgroundItemLibrary.swift
index 3bcebbff..7b294ded 100644
--- a/Peel/Model/BackgroundItemLibrary.swift
+++ b/Peel/Model/BackgroundItemLibrary.swift
@@ -32,6 +32,7 @@ final class BackgroundItemLibrary {
/// could be traced to the app that owns it.
private var installedApps: [InstalledApp] = []
private let scan: @MainActor ([InstalledApp], Exclusions) async -> BackgroundItems.Scan
+ private let control: @MainActor (Action, BackgroundItem) async throws(BackgroundItemActions.Failure) -> Void
/// The reads of the list started so far, so that a job just enabled is judged by a read started after it.
private var readsStarted = 0
private var enabledJobs: [(job: BackgroundItem, readsBefore: Int)] = []
@@ -39,9 +40,23 @@ final class BackgroundItemLibrary {
init(
scan: @escaping @MainActor ([InstalledApp], Exclusions) async -> BackgroundItems.Scan = {
await BackgroundItems.scan(installedApps: $0, exclusions: $1)
- }
+ },
+ control: @escaping @MainActor (Action, BackgroundItem) async throws(BackgroundItemActions.Failure) -> Void =
+ BackgroundItemLibrary.control
) {
self.scan = scan
+ self.control = control
+ }
+
+ /// Starts, stops, enables or disables a job through launchd.
+ private static func control(_ action: Action, _ item: BackgroundItem) async throws(BackgroundItemActions.Failure) {
+ switch action {
+ case .start: try await BackgroundItemActions.start(item)
+ case .stop, .remove: try await BackgroundItemActions.stop(item)
+ case .enable: try await BackgroundItemActions.setEnabled(true, for: item)
+ case .disable: try await BackgroundItemActions.setEnabled(false, for: item)
+ case .moveToTrash: return
+ }
}
func refresh(installedApps: [InstalledApp]) async {
@@ -70,6 +85,20 @@ final class BackgroundItemLibrary {
show(result, read: read)
}
+ /// The read that follows an action, which only the action's own buttons show. While a scan runs, a newer one takes
+ /// its place, so that what is shown was read after the action.
+ private func readAfterAction() async {
+ guard !isScanning else { return await refresh(installedApps: installedApps) }
+ readsStarted += 1
+ let read = readsStarted
+ let scan = scan
+ let installedApps = installedApps
+ guard
+ let result = await scanRun.runQuietly({ await scan(installedApps, ExclusionsStore.shared.exclusions) })
+ else { return }
+ show(result, read: read)
+ }
+
/// Notes a job just enabled. The first read of the list started after now says whether it left the list, whoever
/// asked for that read: the action's own scan may be overtaken by another.
func noteEnabled(_ item: BackgroundItem) {
@@ -140,17 +169,16 @@ final class BackgroundItemLibrary {
func perform(
_ action: Action, on item: BackgroundItem, recording record: (TrashResult) async -> Void = { _ in }
) async {
- runningActionItemIDs.insert(item.id)
+ // A second action on the job while one runs does nothing: its buttons turn off only once the work shows.
+ guard runningActionItemIDs.insert(item.id).inserted else { return }
defer { runningActionItemIDs.remove(item.id) }
var failed = false
do {
switch action {
- case .start: try await BackgroundItemActions.start(item)
- case .stop, .remove: try await BackgroundItemActions.stop(item)
+ case .start, .stop, .remove, .disable: try await control(action, item)
case .enable:
- try await BackgroundItemActions.setEnabled(true, for: item)
+ try await control(action, item)
noteEnabled(item)
- case .disable: try await BackgroundItemActions.setEnabled(false, for: item)
case .moveToTrash:
let exclusions = ExclusionsStore.shared.exclusions
let moved = try await QuitGuard.shared.run {
@@ -176,7 +204,7 @@ final class BackgroundItemLibrary {
alerts.add(.failed(ActionFailure(label: item.label, action: action, reason: error)))
}
let shown = scans
- await refresh(installedApps: installedApps)
+ await readAfterAction()
// History tells of a move to the Trash, and an alert of a failure.
if action != .moveToTrash, !failed, scans > shown, let words = Self.announcement(for: item, in: items) {
AccessibilityNotification.Announcement(words).post()
diff --git a/Peel/Views/ActionRow.swift b/Peel/Views/ActionRow.swift
index 3959cf44..79ca5600 100644
--- a/Peel/Views/ActionRow.swift
+++ b/Peel/Views/ActionRow.swift
@@ -29,7 +29,20 @@ struct ActionRow: Layout {
guard let width, size.width > width else { return size }
return subview.sizeThatFits(ProposedViewSize(width: width, height: nil))
}
- return ActionRowPlan(sizes: fitted, width: width, top: top)
+ let leading = subviews.map { $0[LeadsActionRow.self] }
+ return ActionRowPlan(sizes: fitted, width: width, top: top, leading: leading)
+ }
+}
+
+nonisolated private struct LeadsActionRow: LayoutValueKey {
+ static let defaultValue = false
+}
+
+extension View {
+ /// Stands at the left edge of its `ActionRow`: a button that keeps what the page is about, such as Start or
+ /// Disable, apart from the one that removes it.
+ func leadsActionRow() -> some View {
+ layoutValue(key: LeadsActionRow.self, value: true)
}
}
diff --git a/Peel/Views/BackgroundItems/BackgroundItemDetailView.swift b/Peel/Views/BackgroundItems/BackgroundItemDetailView.swift
index 457fda40..6818155e 100644
--- a/Peel/Views/BackgroundItems/BackgroundItemDetailView.swift
+++ b/Peel/Views/BackgroundItems/BackgroundItemDetailView.swift
@@ -271,9 +271,11 @@ struct BackgroundItemDetailView: View {
}
if hasOwnControls || item.canMoveToTrash {
- PageActions {
- if hasOwnControls { ownControls }
- moveToTrash
+ BusyShown(isBusy: isBusy) { isShown in
+ PageActions {
+ if hasOwnControls { ownControls(busyShown: isShown) }
+ moveToTrash(busyShown: isShown)
+ }
}
}
}
@@ -327,7 +329,11 @@ struct BackgroundItemDetailView: View {
}
private var isBusy: Bool {
- backgroundItems.runningActionItemIDs.contains(item.id) || backgroundItems.isScanning
+ isActing || backgroundItems.isScanning
+ }
+
+ private var isActing: Bool {
+ backgroundItems.runningActionItemIDs.contains(item.id)
}
/// Returns the job's status in System Settings (Login Items & Extensions), or nil when it has no plist file in a
@@ -370,6 +376,10 @@ struct BackgroundItemDetailView: View {
.help(Text(verbatim: item.label))
FlowLayout(spacing: 6) {
stateBadge
+ if let load = item.loadLook() {
+ Badge(title: load.title, systemImage: load.symbol)
+ .contentTransition(.opacity)
+ }
if item.isOrphan, !item.isUnreadable {
NoteBadge(
title: Text("Nothing left to run"), systemImage: "questionmark.circle", tint: .orange,
@@ -398,9 +408,14 @@ struct BackgroundItemDetailView: View {
}
}
Spacer(minLength: 0)
- if isBusy {
- ProgressView()
- .controlSize(.small)
+ // The job's own action shows its work beside its buttons.
+ BusyShown(isBusy: backgroundItems.isScanning && !isActing) { isShown in
+ ZStack {
+ if isShown {
+ ProgressView()
+ .controlSize(.small)
+ }
+ }
}
}
.padding(.vertical, 4)
@@ -417,53 +432,40 @@ struct BackgroundItemDetailView: View {
private var hasOwnControls: Bool { item.offersControls }
- private var ownControls: some View {
+ private func ownControls(busyShown: Bool) -> some View {
Group {
- // Stopping takes the job out of launchd, and nothing else removes one whose file or app is gone.
- if item.canOnlyBeStopped {
- Button("Stop") {
- Task { await backgroundItems.perform(.stop, on: item) }
- }
- .help(item.isFileGone ? Text(verbatim: "") : Text("Takes it out of launchd. Its file stays where it is, and it runs again only if something loads it again."))
- } else if #available(macOS 27, *), item.isLeftByAGoneApp {
- Button("Remove") {
- Task { await backgroundItems.perform(.remove, on: item) }
- }
- .help(removeHelp)
- } else {
- // A job Peel sees only while it is loaded has no Start, since once stopped it leaves the list, and has
- // Stop only while it runs, to let go of what it holds.
- if item.isSeenOnlyWhileLoaded {
- if item.isRunning {
- Button("Stop") {
- Task { await backgroundItems.perform(.stop, on: item) }
- }
- .help(Text("Takes it out of launchd for now. It leaves this list until macOS or its app adds it again."))
- }
- } else {
- if !item.isRunning {
- Button("Start") {
- Task { await backgroundItems.perform(.start, on: item) }
- }
- .help(startHelp)
- }
- // A job that waits for its schedule is loaded too, and only this takes it out for now.
- if item.state != .notLoaded {
- Button("Stop") {
- Task { await backgroundItems.perform(.stop, on: item) }
- }
- .help(Text("Takes it out of launchd until the next login or restart. Its file stays where it is."))
- }
+ if let control = item.startOrStop {
+ Button(control.title) {
+ Task { await backgroundItems.perform(control.action, on: item) }
}
- if item.isDisabled || item.mayBeDisabled {
- Button(item.isDisabled ? "Enable" : "Disable") {
- Task { await backgroundItems.perform(item.isDisabled ? .enable : .disable, on: item) }
- }
- .help(item.isDisabled ? Text(verbatim: "") : Text("macOS won’t load it again from the next login or restart. If it’s running now, it may keep running until then."))
+ .help(help(for: control))
+ }
+ if item.offersEnableOrDisable {
+ Button(item.isDisabled ? "Enable" : "Disable") {
+ Task { await backgroundItems.perform(item.isDisabled ? .enable : .disable, on: item) }
}
+ .help(item.isDisabled ? Text(verbatim: "") : Text("macOS won’t load it again from the next login or restart. If it’s running now, it may keep running until then."))
+ }
+ if busyShown, isActing {
+ ProgressView()
+ .controlSize(.small)
}
}
- .disabled(isBusy || item.requiresPrivileges && !helper.canAct)
+ .leadsActionRow()
+ .disabled(busyShown || item.requiresPrivileges && !helper.canAct)
+ }
+
+ private func help(for control: BackgroundItem.StartOrStop) -> Text {
+ switch control {
+ case .start: startHelp
+ case .remove: removeHelp
+ case .stop where item.canOnlyBeStopped:
+ item.isFileGone ? Text(verbatim: "") : Text("Takes it out of launchd. Its file stays where it is, and it runs again only if something loads it again.")
+ case .stop where item.isSeenOnlyWhileLoaded:
+ Text("Takes it out of launchd for now. It leaves this list until macOS or its app adds it again.")
+ case .stop:
+ Text("Takes it out of launchd until the next login or restart. Its file stays where it is.")
+ }
}
private var startHelp: Text {
@@ -483,20 +485,38 @@ struct BackgroundItemDetailView: View {
}
@ViewBuilder
- private var moveToTrash: some View {
+ private func moveToTrash(busyShown: Bool) -> some View {
if item.canMoveToTrash {
Button("Move to Trash") {
isConfirmingTrash = true
}
.buttonStyle(.borderedProminent)
.disabled(
- isBusy || item.removalRequiresPrivileges && !helper.canAct || !history.mayMove
+ busyShown || item.removalRequiresPrivileges && !helper.canAct || !history.mayMove
)
}
}
}
+private extension BackgroundItem.StartOrStop {
+ var title: LocalizedStringKey {
+ switch self {
+ case .start: "Start"
+ case .stop: "Stop"
+ case .remove: "Remove"
+ }
+ }
+
+ var action: BackgroundItemLibrary.Action {
+ switch self {
+ case .start: .start
+ case .stop: .stop
+ case .remove: .remove
+ }
+ }
+}
+
extension UnusualCommand {
var explanation: LocalizedStringResource {
switch self {
diff --git a/Peel/Views/BackgroundItems/BackgroundItemList.swift b/Peel/Views/BackgroundItems/BackgroundItemList.swift
index 431d63d6..e6c2c3f6 100644
--- a/Peel/Views/BackgroundItems/BackgroundItemList.swift
+++ b/Peel/Views/BackgroundItems/BackgroundItemList.swift
@@ -311,6 +311,20 @@ extension BackgroundItem {
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 {
diff --git a/PeelTests/BackgroundItemLibraryTests.swift b/PeelTests/BackgroundItemLibraryTests.swift
index 8dbdd5b2..effc89ce 100644
--- a/PeelTests/BackgroundItemLibraryTests.swift
+++ b/PeelTests/BackgroundItemLibraryTests.swift
@@ -40,6 +40,63 @@ struct BackgroundItemLibraryTests {
#expect(reads.wereShownAsAScan == [true, false], "a read again is announced to nobody")
}
+ private final class HeldAction {
+ var calls = 0
+ private var waiting: CheckedContinuation<Void, Never>?
+ let (started, starting) = AsyncStream<Void>.makeStream()
+
+ func run() async {
+ calls += 1
+ guard calls == 1 else { return }
+ starting.yield()
+ await withCheckedContinuation { waiting = $0 }
+ }
+
+ func release() {
+ waiting?.resume()
+ waiting = nil
+ }
+ }
+
+ @Test func aSecondActionOnAJobDoesNothingWhileTheFirstRuns() async {
+ let held = HeldAction()
+ let job = job
+ let library = BackgroundItemLibrary(
+ scan: { _, _ in BackgroundItems.Scan(items: [job]) },
+ control: { _, _ in await held.run() }
+ )
+
+ let first = Task { await library.perform(.start, on: job) }
+ for await _ in held.started { break }
+ await library.perform(.stop, on: job)
+ #expect(held.calls == 1)
+ held.release()
+ await first.value
+
+ #expect(held.calls == 1)
+ #expect(library.runningActionItemIDs.isEmpty)
+ }
+
+ @Test func theReadAfterAnActionIsNotShownAsAScan() async {
+ let reads = Reads()
+ let job = job
+ let library = BackgroundItemLibrary(
+ scan: { _, _ in
+ reads.count += 1
+ reads.wereShownAsAScan.append(reads.library?.isScanning == true)
+ return BackgroundItems.Scan(items: [job])
+ },
+ control: { _, _ in }
+ )
+ reads.library = library
+
+ await library.refresh(installedApps: [])
+ await library.perform(.start, on: job)
+
+ #expect(reads.wereShownAsAScan == [true, false])
+ #expect(library.scans == 2)
+ }
+
/// A scan whose answers the test gives, call by call, and which holds the calls in `held` until it lets them go.
private final class Script {
var calls = 0
diff --git a/PeelTests/BackgroundItemStateLookTests.swift b/PeelTests/BackgroundItemStateLookTests.swift
index f64b8df0..0d657472 100644
--- a/PeelTests/BackgroundItemStateLookTests.swift
+++ b/PeelTests/BackgroundItemStateLookTests.swift
@@ -17,4 +17,13 @@ struct BackgroundItemStateLookTests {
#expect(String(localized: job(.loaded, disabled: true).stateWords()) == String(localized: "Disabled"))
#expect(String(localized: job(.running(pid: 4_242), disabled: false).stateWords()) == String(localized: "Running"))
}
+
+ @Test func whetherLaunchdHasTheJobIsSaidWhereTheStateDoesNotSayIt() {
+ #expect(job(.loaded, disabled: false).loadWords().map { String(localized: $0) } == String(localized: "Loaded"))
+ #expect(job(.loaded, disabled: true).loadWords().map { String(localized: $0) } == String(localized: "Loaded"))
+ #expect(job(.notLoaded, disabled: true).loadWords().map { String(localized: $0) } == String(localized: "Not loaded"))
+ #expect(job(.notLoaded, disabled: false).loadWords() == nil)
+ #expect(job(.running(pid: 4_242), disabled: false).loadWords() == nil)
+ #expect(job(.unknown, disabled: false).loadWords() == nil)
+ }
}