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.

Read and change the login item away from the main thread

Țugui Dragoș77b68d49abf7
diff --git a/Packages/PeelCore/Sources/PeelCore/Home/LoginItem.swift b/Packages/PeelCore/Sources/PeelCore/Home/LoginItem.swift
new file mode 100644
index 00000000..9a07d3ca
--- /dev/null
+++ b/Packages/PeelCore/Sources/PeelCore/Home/LoginItem.swift
@@ -0,0 +1,95 @@
+import Observation
+public import ServiceManagement
+
+/// Peel's own login item, as macOS reports it, read and changed away from the main actor, since `SMAppService` asks
+/// `smd` over XPC. The switch keeps the value it was set to until macOS answers, and a read that overlaps a change
+/// shows nothing.
+@MainActor
+@Observable
+public final class LoginItem {
+ public struct Answer: Sendable {
+ public var status: SMAppService.Status
+ public var error: String?
+
+ public init(status: SMAppService.Status, error: String? = nil) {
+ self.status = status
+ self.error = error
+ }
+ }
+
+ public typealias Read = @MainActor () async -> SMAppService.Status
+ public typealias Change = @MainActor (_ on: Bool) async -> Answer
+
+ public private(set) var status: SMAppService.Status?
+ /// Why the last change left the item other than asked. Nil when the status says the change took, since
+ /// registering an item that is registered already throws too (`SMAppService.h`).
+ public private(set) var failure: String?
+ private var asked: Bool?
+ private var checks = OverlappingChecks()
+ private let changes = OneAtATime<Bool>()
+ private let read: Read
+ private let change: Change
+
+ public init(read: @escaping Read, change: @escaping Change) {
+ self.read = read
+ self.change = change
+ }
+
+ public static func ofTheMainApp() -> LoginItem {
+ LoginItem(read: { await status() }, change: { await set(on: $0) })
+ }
+
+ public var isOn: Bool {
+ asked ?? Self.isOn(status)
+ }
+
+ public var needsApproval: Bool {
+ status == .requiresApproval
+ }
+
+ public func refresh() async {
+ let check = checks.start()
+ let status = await read()
+ guard checks.mayShow(check) else { return }
+ self.status = status
+ }
+
+ public func set(on: Bool) {
+ asked = on
+ Task {
+ await changes.ask(on) { [self] on, anotherWaits in
+ checks.changeStarts()
+ let answer = await change(on)
+ checks.changeEnds()
+ status = answer.status
+ failure = Self.isOn(answer.status) == on ? nil : answer.error
+ if !anotherWaits() {
+ asked = nil
+ }
+ }
+ }
+ }
+
+ private static func isOn(_ status: SMAppService.Status?) -> Bool {
+ status == .enabled || status == .requiresApproval
+ }
+
+ @concurrent
+ public static func status() async -> SMAppService.Status {
+ SMAppService.mainApp.status
+ }
+
+ @concurrent
+ private static func set(on: Bool) async -> Answer {
+ do {
+ if on {
+ try SMAppService.mainApp.register()
+ } else {
+ try await SMAppService.mainApp.unregister()
+ }
+ } catch {
+ return Answer(status: SMAppService.mainApp.status, error: error.localizedDescription)
+ }
+ return Answer(status: SMAppService.mainApp.status)
+ }
+}
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/LoginItemTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/LoginItemTests.swift
new file mode 100644
index 00000000..34ed5c10
--- /dev/null
+++ b/Packages/PeelCore/Tests/PeelCoreTests/LoginItemTests.swift
@@ -0,0 +1,85 @@
+@testable import PeelCore
+import ServiceManagement
+import Testing
+
+@MainActor
+struct LoginItemTests {
+ @Test func keepsWhatTheSwitchWasSetToUntilMacOSAnswers() async {
+ var release: CheckedContinuation<Void, Never>?
+ let item = LoginItem(read: { .notRegistered }) { on in
+ await withCheckedContinuation { release = $0 }
+ return LoginItem.Answer(status: on ? .enabled : .notRegistered)
+ }
+ await item.refresh()
+ #expect(!item.isOn)
+
+ item.set(on: true)
+ #expect(item.isOn)
+ while release == nil { await Task.yield() }
+ #expect(item.isOn && item.status == .notRegistered)
+ release?.resume()
+ while item.status != .enabled { await Task.yield() }
+
+ #expect(item.isOn && item.failure == nil)
+ }
+
+ @Test func runsOnlyTheLatestOfChangesFlippedQuickly() async {
+ var release: CheckedContinuation<Void, Never>?
+ var changes: [Bool] = []
+ let item = LoginItem(read: { .notRegistered }) { on in
+ changes.append(on)
+ if changes.count == 1 {
+ await withCheckedContinuation { release = $0 }
+ return LoginItem.Answer(status: .enabled)
+ }
+ return LoginItem.Answer(status: .enabled, error: "already registered")
+ }
+
+ item.set(on: true)
+ item.set(on: false)
+ item.set(on: true)
+ #expect(item.isOn)
+ while release == nil { await Task.yield() }
+ release?.resume()
+ while changes.count < 2 { await Task.yield() }
+
+ #expect(changes == [true, true])
+ #expect(item.isOn && item.status == .enabled && item.failure == nil)
+ }
+
+ @Test func dropsAReadThatOverlappedAChange() async {
+ var release: CheckedContinuation<Void, Never>?
+ let item = LoginItem(
+ read: {
+ await withCheckedContinuation { release = $0 }
+ return .notRegistered
+ },
+ change: { _ in LoginItem.Answer(status: .enabled) }
+ )
+ let reading = Task { await item.refresh() }
+ while release == nil { await Task.yield() }
+
+ item.set(on: true)
+ while item.status != .enabled { await Task.yield() }
+ release?.resume()
+ await reading.value
+
+ #expect(item.status == .enabled && item.isOn)
+ }
+
+ @Test func saysWhyAChangeFailedOnlyWhileTheItemIsNotAsAsked() async {
+ let refused = LoginItem(read: { .notRegistered }) { _ in
+ LoginItem.Answer(status: .notRegistered, error: "not allowed")
+ }
+ refused.set(on: true)
+ while refused.failure == nil { await Task.yield() }
+ #expect(!refused.isOn && refused.failure == "not allowed")
+
+ let approved = LoginItem(read: { .notRegistered }) { _ in
+ LoginItem.Answer(status: .requiresApproval, error: "already registered")
+ }
+ approved.set(on: true)
+ while approved.status == nil { await Task.yield() }
+ #expect(approved.isOn && approved.needsApproval && approved.failure == nil)
+ }
+}
diff --git a/Peel/Model/HomeModel.swift b/Peel/Model/HomeModel.swift
index bc1d9d39..ea2cbdd8 100644
--- a/Peel/Model/HomeModel.swift
+++ b/Peel/Model/HomeModel.swift
@@ -168,7 +168,7 @@ final class HomeModel {
let fullDisk = await access
needsRelaunchForFullDiskAccess = fullDisk == .missing && hasOpenedFullDiskAccessSettings
- let opensAtLogin = await Self.opensAtLogin()
+ let opensAtLogin = await LoginItem.status() == .enabled
found = [
.fullDiskAccess: state(for: fullDisk),
.appManagement: state(for: appManagementSeenThisLaunch ?? appManagement),
@@ -266,12 +266,6 @@ final class HomeModel {
FIFinderSyncController.isExtensionEnabled
}
- /// Off the main thread: `SMAppService` asks `smd` over XPC.
- @concurrent
- private static func opensAtLogin() async -> Bool {
- SMAppService.mainApp.status == .enabled
- }
-
private static func finderExtensionRunsFromAnotherCopy() async -> Bool {
guard let own = Bundle.main.builtInPlugInsURL.flatMap({ Bundle(url: $0.appending(path: "PeelFinder.appex")) }),
let identifier = own.bundleIdentifier
diff --git a/Peel/Views/Settings/SettingsView.swift b/Peel/Views/Settings/SettingsView.swift
index ab0eb43a..0d4cb7aa 100644
--- a/Peel/Views/Settings/SettingsView.swift
+++ b/Peel/Views/Settings/SettingsView.swift
@@ -216,36 +216,10 @@ private struct GeneralSettingsView: View {
// 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
- // The login item's state is read when the page appears (`readStandings()`), not as an initial value:
- // initial values run on every `init` of the view, and each read is a synchronous call to a daemon.
- @State private var opensAtLogin = false
- @State private var needsApprovalToOpenAtLogin = false
- @State private var loginItemFailure: String?
-
- /// Registers or unregisters Peel as a login item, then shows the status macOS reports. After `register()`,
- /// a login item the user turned off in Login Items still needs approval, so the toggle stays on and a note
- /// says why. An error is shown, not ignored.
- private func setOpensAtLogin(_ shouldOpen: Bool) {
- loginItemFailure = nil
- do {
- if shouldOpen {
- try SMAppService.mainApp.register()
- } else {
- try SMAppService.mainApp.unregister()
- }
- } catch {
- loginItemFailure = error.localizedDescription
- }
- let status = SMAppService.mainApp.status
- opensAtLogin = status == .enabled || status == .requiresApproval
- needsApprovalToOpenAtLogin = status == .requiresApproval
- }
+ @State private var loginItem = LoginItem.ofTheMainApp()
private func readStandings() {
commandLine = HomeModel.commandLineStanding
- let status = SMAppService.mainApp.status
- opensAtLogin = status == .enabled || status == .requiresApproval
- needsApprovalToOpenAtLogin = status == .requiresApproval
SavedSettings.shared.reload()
}
@@ -312,11 +286,10 @@ private struct GeneralSettingsView: View {
}
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.")
- // A binding, not `onChange`: setting `opensAtLogin` to macOS's answer must not register or
- // unregister again.
- toggle("Open Peel at login", isOn: Binding(get: { opensAtLogin }, set: setOpensAtLogin),
+ // A binding, not `onChange`: macOS's own answer landing in the model must not register again.
+ toggle("Open Peel at login", isOn: Binding(get: { loginItem.isOn }, set: { loginItem.set(on: $0) }),
"Starts Peel when you log in. “Watch the Trash” works only while Peel is running.")
- if needsApprovalToOpenAtLogin {
+ if loginItem.needsApproval {
HStack {
StatusLabel(title: Text("Peel is turned off in Login Items & Extensions, so macOS won’t start it."))
Spacer()
@@ -325,8 +298,8 @@ private struct GeneralSettingsView: View {
}
}
}
- if let loginItemFailure {
- StatusLabel(title: Text(loginItemFailure))
+ if let failure = loginItem.failure {
+ StatusLabel(title: Text(failure))
.textSelection(.enabled)
}
}
@@ -468,10 +441,14 @@ private struct GeneralSettingsView: View {
guard isChecking else { return }
Task { await library.checkForUpdates(library.apps) }
}
- .task { readStandings() }
+ .task {
+ readStandings()
+ await 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 loginItem.refresh() }
}
.confirmationDialog("Remove Peel from this Mac?", isPresented: $isConfirmingSelfRemoval) {
Button("Remove Peel", role: .destructive) {