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.

Uninstalling can take the app's icon out of the Dock, and History puts it back

Țugui Dragoș2e6b57649327
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md
index c3375f63..ea4626a9 100644
--- a/ARCHITECTURE.md
+++ b/ARCHITECTURE.md
@@ -199,6 +199,7 @@ where a Homebrew install takes them from.
| `~/Library/Application Support/Peel/digests.bin` | What Duplicates already read, so an unchanged file isn't read again. |
| `~/Library/Application Support/Peel/apps.json`, `teams.json` | What Peel remembers about apps and their signing teams between launches. |
| `~/Library/Application Support/Peel/orphan-owners.json` | The orphaned files the user said belong to an installed app. |
+| `~/Library/Application Support/Peel/dock-tiles.json` | The Dock icons an uninstall took out, and where each was, so History puts them back with their app. |
| `~/Library/Application Support/Peel/app-folders.json` | The folders the user chose for Peel to look for apps in, beside the Applications folders. |
| `/private/var/db/com.tuguidragos.Peel.Helper/` | The helper's ledger of what it moved. |
| Peel's preferences | Settings, the totals Home shows, what each tool found the last time it looked, and the last answer of each update check. |
diff --git a/Localization/Peel/Localizable.xcstrings b/Localization/Peel/Localizable.xcstrings
index 95f0f0ff..bc8850f1 100644
--- a/Localization/Peel/Localizable.xcstrings
+++ b/Localization/Peel/Localizable.xcstrings
@@ -9807,6 +9807,112 @@
}
}
},
+ "Also remove from the Dock" : {
+ "localizations" : {
+ "cs" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Odstranit také z Docku"
+ }
+ },
+ "de" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Auch aus dem Dock entfernen"
+ }
+ },
+ "es" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Eliminar también del Dock"
+ }
+ },
+ "fr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Supprimer aussi du Dock"
+ }
+ },
+ "it" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Rimuovi anche dal Dock"
+ }
+ },
+ "ja" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Dockからも削除"
+ }
+ },
+ "ko" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Dock에서도 제거"
+ }
+ },
+ "nl" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Verwijder ook uit Dock"
+ }
+ },
+ "pl" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Usuń też z Docka"
+ }
+ },
+ "pt" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Remover também do Dock"
+ }
+ },
+ "ro" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Eliminați și din Dock"
+ }
+ },
+ "ru" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Также удалить из Dock"
+ }
+ },
+ "sv" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Ta även bort från Dock"
+ }
+ },
+ "tr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Dock’tan da çıkar"
+ }
+ },
+ "uk" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Також вилучити з Dock"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "同时从程序坞中移除"
+ }
+ },
+ "zh-Hant" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "一併從Dock中移除"
+ }
+ }
+ }
+ },
"Also reset privacy permissions" : {
"localizations" : {
"cs" : {
@@ -96262,6 +96368,112 @@
}
}
},
+ "Remove from the Dock" : {
+ "localizations" : {
+ "cs" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Odstranit z Docku"
+ }
+ },
+ "de" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Aus dem Dock entfernen"
+ }
+ },
+ "es" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Eliminar del Dock"
+ }
+ },
+ "fr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Supprimer du Dock"
+ }
+ },
+ "it" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Rimuovi dal Dock"
+ }
+ },
+ "ja" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Dockから削除"
+ }
+ },
+ "ko" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Dock에서 제거"
+ }
+ },
+ "nl" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Verwijder uit Dock"
+ }
+ },
+ "pl" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Usuń z Docka"
+ }
+ },
+ "pt" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Remover do Dock"
+ }
+ },
+ "ro" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Eliminați din Dock"
+ }
+ },
+ "ru" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Удалить из Dock"
+ }
+ },
+ "sv" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Ta bort från Dock"
+ }
+ },
+ "tr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Dock’tan çıkar"
+ }
+ },
+ "uk" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Вилучити з Dock"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "从程序坞中移除"
+ }
+ },
+ "zh-Hant" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "從Dock中移除"
+ }
+ }
+ }
+ },
"Remove the downloads from this Mac?" : {
"localizations" : {
"cs" : {
@@ -115694,6 +115906,112 @@
}
}
},
+ "The Dock keeps an app’s icon after the app is gone, as a question mark. If this is selected, Peel takes the icon out once the app is in the Trash, and the Dock restarts. Putting the app back from History puts its icon back where it was." : {
+ "localizations" : {
+ "cs" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Když aplikace zmizí, Dock její ikonu ponechá jako otazník. Pokud je tato volba vybraná, Peel ikonu odstraní, jakmile bude aplikace v koši, a Dock se restartuje. Když aplikaci vrátíte zpět z Historie, vrátí se i její ikona tam, kde byla."
+ }
+ },
+ "de" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Ist eine App nicht mehr da, behält das Dock ihr Symbol als Fragezeichen. Ist diese Option ausgewählt, entfernt Peel das Symbol, sobald die App im Papierkorb ist, und das Dock startet neu. Legst du die App im Verlauf zurück, kommt auch ihr Symbol wieder an seine alte Stelle."
+ }
+ },
+ "es" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "El Dock conserva el icono de una app cuando la app ya no está, como un signo de interrogación. Si esta opción está seleccionada, Peel quita el icono cuando la app ya está en la papelera, y el Dock se reinicia. Al restaurar la app desde Historial, su icono vuelve a donde estaba."
+ }
+ },
+ "fr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Le Dock conserve l’icône d’une app après sa disparition, sous la forme d’un point d’interrogation. Si cette option est cochée, Peel supprime l’icône une fois l’app dans la corbeille, et le Dock redémarre. Si vous remettez l’app depuis l’Historique, son icône revient à sa place."
+ }
+ },
+ "it" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Il Dock mantiene l’icona di un’app dopo che l’app non c’è più, come un punto interrogativo. Se questa opzione è selezionata, Peel rimuove l’icona una volta che l’app è nel Cestino, e il Dock si riavvia. Se ripristini l’app dalla Cronologia, la sua icona torna dov’era."
+ }
+ },
+ "ja" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Dockは、アプリがなくなった後もそのアイコンを疑問符として残します。これを選択すると、アプリがゴミ箱に入った時点でPeelがアイコンを取り除き、Dockが再起動します。“履歴”からアプリを戻すと、アイコンも元の場所に戻ります。"
+ }
+ },
+ "ko" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Dock은 앱이 사라진 후에도 앱의 아이콘을 물음표로 남겨 둡니다. 이 항목을 선택하면 앱이 휴지통으로 이동된 후 Peel이 아이콘을 제거하고, Dock이 다시 시작됩니다. 기록에서 앱을 되돌려 놓으면 아이콘도 원래 있던 자리로 되돌아갑니다."
+ }
+ },
+ "nl" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Het Dock bewaart het symbool van een app nadat de app weg is, als een vraagteken. Als dit is geselecteerd, haalt Peel het symbool weg zodra de app in de prullenmand staat, en start het Dock opnieuw. Als je de app vanuit Geschiedenis terugzet, komt het symbool terug op de plek waar het stond."
+ }
+ },
+ "pl" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Dock zachowuje ikonę aplikacji po jej zniknięciu, jako znak zapytania. Jeśli ta opcja jest zaznaczona, Peel usuwa ikonę, gdy aplikacja znajdzie się w Koszu, a Dock uruchamia się ponownie. Przywrócenie aplikacji z Historii przywraca jej ikonę tam, gdzie była."
+ }
+ },
+ "pt" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "O Dock mantém o ícone de um app depois que o app deixa de existir, como um ponto de interrogação. Se esta opção estiver selecionada, o Peel remove o ícone assim que o app estiver no Lixo, e o Dock reinicia. Ao colocar o app de volta pelo Histórico, o ícone volta para onde estava."
+ }
+ },
+ "ro" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Dock‑ul păstrează pictograma unei aplicații după ce aplicația dispare, sub forma unui semn de întrebare. Dacă această opțiune este selectată, Peel elimină pictograma după ce aplicația a ajuns în Coș, iar Dock‑ul repornește. Dacă puneți aplicația înapoi din Istoric, pictograma ei revine unde era."
+ }
+ },
+ "ru" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Dock сохраняет значок приложения и после его удаления, в виде вопросительного знака. Если этот параметр выбран, Peel убирает значок, как только приложение окажется в Корзине, и Dock перезапускается. Если восстановить приложение из Истории, его значок вернется на прежнее место."
+ }
+ },
+ "sv" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Dock behåller en apps symbol som ett frågetecken när appen är borta. Om det här är markerat tar Peel bort symbolen när appen ligger i papperskorgen, och Dock startas om. Om du lägger tillbaka appen från Historik läggs symbolen tillbaka där den var."
+ }
+ },
+ "tr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Dock, bir uygulama gittikten sonra onun simgesini soru işareti olarak tutar. Bu seçiliyse, uygulama Çöp Sepeti’ne taşındıktan sonra Peel simgeyi Dock’tan çıkarır ve Dock yeniden başlar. Uygulamayı Geçmiş’ten yerine koyduğunuzda simgesi de eski yerine döner."
+ }
+ },
+ "uk" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Dock зберігає іконку програми у вигляді знака питання, коли самої програми вже немає. Якщо цей параметр вибрано, Peel прибирає іконку, щойно програма опиняється в Смітнику, і Dock перезапускається. Якщо повернути програму з Історії, її іконка повернеться туди, де була."
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "App删除后,程序坞仍会以问号的形式保留它的图标。如果选择此项,Peel会在App移到废纸篓后移除它的图标,程序坞会重新启动。从“历史记录”中将App放回原处时,它的图标也会回到原来的位置。"
+ }
+ },
+ "zh-Hant" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "App不在後,Dock仍會以問號保留它的圖像。若已選取此選項,Peel會在App丟到「垃圾桶」後移除該圖像,Dock也會重新啟動。從「歷史記錄」還原App時,其圖像也會放回原本的位置。"
+ }
+ }
+ }
+ },
"The Dock restarts" : {
"localizations" : {
"cs" : {
diff --git a/Packages/PeelCore/Sources/PeelCore/Apps/DockTiles.swift b/Packages/PeelCore/Sources/PeelCore/Apps/DockTiles.swift
new file mode 100644
index 00000000..ce2b6198
--- /dev/null
+++ b/Packages/PeelCore/Sources/PeelCore/Apps/DockTiles.swift
@@ -0,0 +1,135 @@
+public import Foundation
+
+/// Where the Dock keeps its tiles. Tests stand in for it, so they never change the Dock.
+public protocol DockTileStore: Sendable {
+ func tiles() -> [Any]?
+ func setTiles(_ tiles: [Any]) -> Bool
+ func restartTheDock() async
+}
+
+/// The Dock's own list of apps, read and written through CFPreferences as the Tweaks are, never in its file:
+/// cfprefsd keeps its own copy of the domain. The Dock reads the list again when it starts.
+public struct DockPreferences: DockTileStore {
+ private static var domain: CFString { "com.apple.dock" as CFString }
+ private static var key: CFString { "persistent-apps" as CFString }
+
+ public init() {}
+
+ public func tiles() -> [Any]? {
+ CFPreferencesAppSynchronize(Self.domain)
+ return CFPreferencesCopyAppValue(Self.key, Self.domain) as? [Any]
+ }
+
+ public func setTiles(_ tiles: [Any]) -> Bool {
+ guard !CFPreferencesAppValueIsForced(Self.key, Self.domain) else { return false }
+ CFPreferencesSetAppValue(Self.key, tiles as CFArray, Self.domain)
+ return CFPreferencesAppSynchronize(Self.domain)
+ }
+
+ public func restartTheDock() async {
+ await TweakRestart.run(.dock)
+ }
+}
+
+/// An app's tiles in the Dock, which keeps a gone app's tile as a question mark. An uninstall can take them out,
+/// and History putting the app back puts them back where they were.
+public struct DockTiles: Sendable {
+ private struct Removed: Codable {
+ let index: Int
+ let tile: Data
+ }
+
+ private let store: any DockTileStore
+ private let memory: URL
+
+ public init(
+ store: any DockTileStore = DockPreferences(),
+ memory: URL = PeelFolder.url.appending(path: "dock-tiles.json")
+ ) {
+ self.store = store
+ self.memory = memory
+ }
+
+ /// Those of `apps` that have a tile in the Dock.
+ @concurrent
+ public func holding(_ apps: [URL]) async -> Set<URL> {
+ let tiles = store.tiles() ?? []
+ return Set(apps.filter { !indices(of: $0, in: tiles).isEmpty })
+ }
+
+ /// Takes the tiles of `apps` out of the Dock, remembering where each was, and restarts the Dock once. False
+ /// when none had a tile, or when that could not be remembered or written.
+ public func takeOut(_ apps: [URL]) async -> Bool {
+ guard var tiles = store.tiles() else { return false }
+ var removed: [String: [Removed]] = [:]
+ for app in apps {
+ let found = indices(of: app, in: tiles)
+ let kept = found.compactMap { index in
+ (try? PropertyListSerialization.data(fromPropertyList: tiles[index], format: .binary, options: 0))
+ .map { Removed(index: index, tile: $0) }
+ }
+ if !found.isEmpty, kept.count == found.count { removed[key(app)] = kept }
+ }
+ guard !removed.isEmpty, change({ $0.merge(removed) { _, new in new } }) else { return false }
+ let taken = Set(removed.values.flatMap { $0.map(\.index) })
+ tiles = tiles.indices.filter { !taken.contains($0) }.map { tiles[$0] }
+ guard store.setTiles(tiles) else {
+ _ = change { entries in removed.keys.forEach { entries[$0] = nil } }
+ return false
+ }
+ await store.restartTheDock()
+ return true
+ }
+
+ /// Puts back the tiles taken out for the app at `app`, unless the Dock holds one for it again.
+ public func putBack(_ app: URL) async {
+ guard let removed = FileLock.whileHeld(beside: memory, { read()?[key(app)] }) else { return }
+ guard var tiles = store.tiles() else { return }
+ if indices(of: app, in: tiles).isEmpty {
+ for entry in removed.sorted(by: { $0.index < $1.index }) {
+ if let tile = try? PropertyListSerialization.propertyList(from: entry.tile, format: nil) {
+ tiles.insert(tile, at: min(entry.index, tiles.count))
+ }
+ }
+ guard store.setTiles(tiles) else { return }
+ await store.restartTheDock()
+ }
+ _ = change { $0[key(app)] = nil }
+ }
+
+ /// The path a tile leads to, from the URL or the path it keeps for its file.
+ static func path(of tile: Any) -> String? {
+ guard
+ let data = (tile as? [String: Any])?["tile-data"] as? [String: Any],
+ let file = data["file-data"] as? [String: Any],
+ let text = file["_CFURLString"] as? String
+ else { return nil }
+ let url = (file["_CFURLStringType"] as? Int) == 0 ? URL(filePath: text) : URL(string: text)
+ return url.map(PathPattern.comparablePath)
+ }
+
+ private func indices(of app: URL, in tiles: [Any]) -> [Int] {
+ tiles.indices.filter { Self.path(of: tiles[$0]) == key(app) }
+ }
+
+ private func key(_ app: URL) -> String {
+ PathPattern.comparablePath(of: app)
+ }
+
+ private func change(_ edit: (inout [String: [Removed]]) -> Void) -> Bool {
+ FileLock.whileHeld(beside: memory) {
+ guard var entries = read() ?? (memory.isMissing ? [:] : nil) else { return false }
+ edit(&entries)
+ guard let data = try? JSONEncoder().encode(entries) else { return false }
+ try? FileManager.default.createDirectory(
+ at: memory.deletingLastPathComponent(), withIntermediateDirectories: true
+ )
+ return (try? data.write(to: memory, options: .atomic)) != nil
+ }
+ }
+
+ private func read() -> [String: [Removed]]? {
+ guard let data = BoundedRead.data(at: memory) else { return nil }
+ return try? JSONDecoder().decode([String: [Removed]].self, from: data)
+ }
+}
diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/TrashService.swift b/Packages/PeelCore/Sources/PeelCore/Removal/TrashService.swift
index 1763cd82..00d5176f 100644
--- a/Packages/PeelCore/Sources/PeelCore/Removal/TrashService.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Removal/TrashService.swift
@@ -158,12 +158,14 @@ public struct TrashService: Sendable {
typealias StopJobs = @Sendable ([LaunchdCleanup.Job], _ canUseHelper: Bool) async -> Void
typealias ForgetDomains = @Sendable ([URL], _ owner: String?) async -> Void
typealias MoveThroughHelper = @Sendable ([URL]) async -> TrashResult
+ typealias PutBackDockTiles = @Sendable (URL) async -> Void
private let environment: SearchEnvironment
private let removalGuard: RemovalGuard
private let stopJobs: StopJobs
private let forgetDomains: ForgetDomains
private let moveThroughHelper: MoveThroughHelper
+ private let putBackDockTiles: PutBackDockTiles
private let moveToTrash: @Sendable (URL) throws -> URL
private let ownMoves: OwnTrashMoves
/// Where each item is written down as soon as it moves, so a removal cut short still reaches History.
@@ -177,6 +179,7 @@ public struct TrashService: Sendable {
stopJobs: LaunchdCleanup.stop,
forgetDomains: { await PreferenceCleanup.forgetDomains(for: $0, ownedBy: $1) },
moveThroughHelper: Self.moveThroughTheHelper,
+ putBackDockTiles: { await DockTiles().putBack($0) },
moveToTrash: { try Self.moveToSystemTrash($0, isAllowed: removalGuard.allowsRemoval(of:)) },
ownMoves: .shared,
journal: RemovalJournal(beside: RemovalHistory.defaultURL)
@@ -184,13 +187,14 @@ public struct TrashService: Sendable {
}
/// For tests. Unless a test passes its own, it stops no launchd job, forgets no preference domain, acts as if
- /// there were no helper, and writes no journal.
+ /// there were no helper, changes no Dock, and writes no journal.
init(
environment: SearchEnvironment,
exclusions: Exclusions = .none,
stopJobs: @escaping StopJobs = { _, _ in },
forgetDomains: @escaping ForgetDomains = { _, _ in },
moveThroughHelper: @escaping MoveThroughHelper = Self.asIfThereWereNoHelper,
+ putBackDockTiles: @escaping PutBackDockTiles = { _ in },
ownMoves: OwnTrashMoves = OwnTrashMoves(),
journal: RemovalJournal? = nil,
moveToTrash: @escaping @Sendable (URL) throws -> URL
@@ -201,6 +205,7 @@ public struct TrashService: Sendable {
stopJobs: stopJobs,
forgetDomains: forgetDomains,
moveThroughHelper: moveThroughHelper,
+ putBackDockTiles: putBackDockTiles,
moveToTrash: moveToTrash,
ownMoves: ownMoves,
journal: journal
@@ -213,6 +218,7 @@ public struct TrashService: Sendable {
stopJobs: @escaping StopJobs,
forgetDomains: @escaping ForgetDomains,
moveThroughHelper: @escaping MoveThroughHelper,
+ putBackDockTiles: @escaping PutBackDockTiles,
moveToTrash: @escaping @Sendable (URL) throws -> URL,
ownMoves: OwnTrashMoves,
journal: RemovalJournal?
@@ -222,6 +228,7 @@ public struct TrashService: Sendable {
self.stopJobs = stopJobs
self.forgetDomains = forgetDomains
self.moveThroughHelper = moveThroughHelper
+ self.putBackDockTiles = putBackDockTiles
self.moveToTrash = moveToTrash
self.ownMoves = ownMoves
self.journal = journal
@@ -374,9 +381,17 @@ public struct TrashService: Sendable {
}
/// Moves an item from the Trash back where it came from, through the helper when the folder needs
- /// administrator rights.
+ /// administrator rights, and puts back the Dock tiles an uninstall took out for it.
@concurrent
public func restore(_ item: TrashedItem, canUseHelper: Bool = false) async -> RestoreFailure? {
+ let failure = await moveBack(item, canUseHelper: canUseHelper)
+ if failure == nil {
+ await putBackDockTiles(item.originalURL)
+ }
+ return failure
+ }
+
+ private func moveBack(_ item: TrashedItem, canUseHelper: Bool) async -> RestoreFailure? {
// The record comes from a file any process of the user can rewrite, so it is a request, not a fact.
// Putting an item back must not write where removal is refused, or move a file that is not in a Trash.
guard removalGuard.allowsPuttingBack(item.trashedURL, at: item.originalURL), isInATrash(item.trashedURL) else { return .notAllowed }
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/DockTilesTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/DockTilesTests.swift
new file mode 100644
index 00000000..75c8b9b2
--- /dev/null
+++ b/Packages/PeelCore/Tests/PeelCoreTests/DockTilesTests.swift
@@ -0,0 +1,120 @@
+import Foundation
+@testable import PeelCore
+import Synchronization
+import Testing
+
+struct DockTilesTests {
+ /// Keeps the tiles as a property list, as cfprefsd does.
+ private final class Store: DockTileStore {
+ let saved = Mutex(Data())
+ let restarts = Atomic(0)
+
+ init(_ tiles: [Any]) {
+ _ = setTiles(tiles)
+ }
+
+ func tiles() -> [Any]? {
+ try? PropertyListSerialization.propertyList(from: saved.withLock { $0 }, format: nil) as? [Any]
+ }
+
+ func setTiles(_ tiles: [Any]) -> Bool {
+ guard let data = try? PropertyListSerialization.data(fromPropertyList: tiles, format: .binary, options: 0)
+ else { return false }
+ saved.withLock { $0 = data }
+ return true
+ }
+
+ func restartTheDock() async {
+ restarts.add(1, ordering: .relaxed)
+ }
+
+ var paths: [String] {
+ (tiles() ?? []).compactMap { DockTiles.path(of: $0) }
+ }
+ }
+
+ private static func tile(_ url: String, type: Int = 15) -> [String: Any] {
+ ["tile-data": ["file-data": ["_CFURLString": url, "_CFURLStringType": type]], "tile-type": "file-tile"]
+ }
+
+ private let studio = URL(filePath: "/Applications/org.example.Studio.app", directoryHint: .isDirectory)
+
+ /// The Dock keeps a gone app's tile as a question mark. Peel takes out only the tiles of that copy, and History
+ /// putting the app back puts its tile back where it was.
+ @Test func takesOutTheAppsTileAndPutsItBackWhereItWas() async throws {
+ let directory = try TemporaryDirectory()
+ let store = Store([
+ Self.tile("file:///System/Applications/Mail.app/"),
+ Self.tile("file:///Applications/org.example.Studio.app/"),
+ Self.tile("/Volumes/Other/org.example.Studio.app", type: 0),
+ Self.tile("file:///Applications/org.example.Notes.app/"),
+ ])
+ let tiles = DockTiles(store: store, memory: directory.url.appending(path: "dock-tiles.json"))
+
+ #expect(await tiles.holding([studio]) == [studio])
+ #expect(await tiles.takeOut([studio]))
+ #expect(store.paths == [
+ "/System/Applications/Mail.app", "/Volumes/Other/org.example.Studio.app",
+ "/Applications/org.example.Notes.app",
+ ])
+ #expect(await tiles.holding([studio]).isEmpty)
+
+ await tiles.putBack(studio)
+ #expect(store.paths == [
+ "/System/Applications/Mail.app", "/Applications/org.example.Studio.app",
+ "/Volumes/Other/org.example.Studio.app", "/Applications/org.example.Notes.app",
+ ])
+ #expect(store.restarts.load(ordering: .relaxed) == 2)
+
+ await tiles.putBack(studio)
+ #expect(store.paths.count == 4, "a tile was put back twice")
+ }
+
+ /// Several apps removed together restart the Dock once, and each comes back to its own place.
+ @Test func takesOutSeveralAppsTilesWithOneRestart() async throws {
+ let directory = try TemporaryDirectory()
+ let tools = URL(filePath: "/Applications/org.example.Tools.app", directoryHint: .isDirectory)
+ let store = Store([
+ Self.tile("file:///System/Applications/Mail.app/"),
+ Self.tile("file:///Applications/org.example.Studio.app/"),
+ Self.tile("file:///Applications/org.example.Notes.app/"),
+ Self.tile("file:///Applications/org.example.Tools.app/"),
+ ])
+ let tiles = DockTiles(store: store, memory: directory.url.appending(path: "dock-tiles.json"))
+
+ #expect(await tiles.takeOut([studio, tools]))
+ #expect(store.paths == ["/System/Applications/Mail.app", "/Applications/org.example.Notes.app"])
+ #expect(store.restarts.load(ordering: .relaxed) == 1)
+
+ await tiles.putBack(studio)
+ await tiles.putBack(tools)
+ #expect(store.paths == [
+ "/System/Applications/Mail.app", "/Applications/org.example.Studio.app",
+ "/Applications/org.example.Notes.app", "/Applications/org.example.Tools.app",
+ ])
+ }
+
+ @Test func leavesTheDockAsItIsForAnAppWithNoTile() async throws {
+ let directory = try TemporaryDirectory()
+ let store = Store([Self.tile("file:///Applications/org.example.Notes.app/")])
+ let tiles = DockTiles(store: store, memory: directory.url.appending(path: "dock-tiles.json"))
+
+ #expect(!(await tiles.takeOut([studio])))
+ await tiles.putBack(studio)
+ #expect(store.paths == ["/Applications/org.example.Notes.app"])
+ #expect(store.restarts.load(ordering: .relaxed) == 0)
+ }
+
+ /// A tile the person added again meanwhile is not doubled when History puts the app back.
+ @Test func neverDoublesATileThePersonAddedAgain() async throws {
+ let directory = try TemporaryDirectory()
+ let store = Store([Self.tile("file:///Applications/org.example.Studio.app/")])
+ let tiles = DockTiles(store: store, memory: directory.url.appending(path: "dock-tiles.json"))
+
+ #expect(await tiles.takeOut([studio]))
+ _ = store.setTiles([Self.tile("file:///Applications/org.example.Studio.app/")])
+ await tiles.putBack(studio)
+
+ #expect(store.paths == ["/Applications/org.example.Studio.app"])
+ }
+}
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/TrashServiceTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/TrashServiceTests.swift
index 7871299e..a6861cb1 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/TrashServiceTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/TrashServiceTests.swift
@@ -218,6 +218,31 @@ struct TrashServiceTests {
#expect(await forgotten.calls.last == ["home/Library/Preferences/com.example.app.plist", "com.example.app"])
}
+ /// Putting an app back puts back the Dock tiles an uninstall took out for it, and only once it is back.
+ @Test func puttingAnItemBackPutsBackItsDockTiles() async throws {
+ let directory = try TemporaryDirectory()
+ let app = try directory.directory("home/Applications/org.example.Studio.app")
+ let trash = try directory.directory("home/.Trash")
+ let asked = Mutex<[String]>([])
+ let service = TrashService(
+ environment: SearchEnvironment(
+ homeDirectory: directory.url.appending(path: "home", directoryHint: .isDirectory),
+ rootDirectory: directory.url.appending(path: "root", directoryHint: .isDirectory)
+ ),
+ putBackDockTiles: { url in asked.withLock { $0.append(url.lastPathComponent) } }
+ ) { url in
+ let destination = trash.appending(path: url.lastPathComponent)
+ try FileManager.default.moveItem(at: url, to: destination)
+ return destination
+ }
+
+ let moved = try #require(await service.trash([app]).trashed.first)
+ #expect(asked.withLock { $0 }.isEmpty)
+ #expect(await service.restore(moved) == nil)
+ #expect(await service.restore(moved) != nil)
+ #expect(asked.withLock { $0 } == ["org.example.Studio.app"])
+ }
+
@Test func movesItemsToTrashAndRestoresThem() async throws {
let directory = try TemporaryDirectory()
let item = try directory.file("home/Library/Caches/com.example.app/cache.db")
diff --git a/Peel/Views/AppDetailView.swift b/Peel/Views/AppDetailView.swift
index 0fbbb585..3b208616 100644
--- a/Peel/Views/AppDetailView.swift
+++ b/Peel/Views/AppDetailView.swift
@@ -12,6 +12,8 @@ struct AppDetailView: View {
@Environment(RemovalOutcome.self) private var outcome
@State private var isRescanning = false
@State private var resetsPrivacy = false
+ @State private var removesDockTile = false
+ @State private var hasDockTile = false
@State private var isConfirmingPrivacyReset = false
/// The result of the last privacy reset started from the More menu, shown under the buttons.
@State private var privacyReset: PrivacyReset.Result?
@@ -82,6 +84,9 @@ struct AppDetailView: View {
guard !Task.isCancelled, !(plan.scan == nil && plan.scanRun.wasStopped) else { return }
await rescan()
}
+ .task(id: plan.app.url) {
+ hasDockTile = !(await DockTiles().holding([plan.app.url])).isEmpty
+ }
.rescanOnExclusionChange("AppDetailView") { await rescan() }
.onChange(of: helper.canAct) { _, canAct in
plan.follow(canUseHelper: canAct)
@@ -179,6 +184,9 @@ struct AppDetailView: View {
if PrivacyReset.isAllowed(bundleIdentifier: plan.app.bundleIdentifier), !plan.isAppInTheTrash {
PrivacyResetRow(isOn: $resetsPrivacy, detail: PrivacyResetRow.beforeTheMove)
}
+ if hasDockTile, !plan.isPeel {
+ DockTileRow(isOn: $removesDockTile)
+ }
defaultsSection
PackageReceiptSection(app: plan.app, isExcluded: plan.isExcluded)
}
@@ -635,6 +643,9 @@ struct AppDetailView: View {
let privacy = await PrivacyReset.reset(resetting(request.urls))
let result = await plan.move(request)
outcome.report(result, privacy: privacy)
+ if removesDockTile, result.trashed.contains(where: { $0.originalURL == plan.app.url }) {
+ _ = await DockTiles().takeOut([plan.app.url])
+ }
if let state = AppManagement.state(after: result, appBundles: [plan.app.url], movedByTheHelper: plan.privilegedURLs) {
home.record(appManagement: state)
}
diff --git a/Peel/Views/DockTileRow.swift b/Peel/Views/DockTileRow.swift
new file mode 100644
index 00000000..b3d73947
--- /dev/null
+++ b/Peel/Views/DockTileRow.swift
@@ -0,0 +1,23 @@
+import SwiftUI
+
+/// A checkbox that also takes the removed apps' icons out of the Dock. It is off until the user selects it,
+/// because it changes the Dock.
+struct DockTileRow: View {
+ @Binding var isOn: Bool
+
+ var body: some View {
+ HStack(spacing: 5) {
+ Toggle(isOn: $isOn) {
+ Text("Also remove from the Dock")
+ }
+ .toggleStyle(.checkbox)
+ InfoNote(
+ name: String(localized: "Remove from the Dock"),
+ detail: Text("The Dock keeps an app’s icon after the app is gone, as a question mark. If this is selected, Peel takes the icon out once the app is in the Trash, and the Dock restarts. Putting the app back from History puts its icon back where it was.")
+ )
+ Spacer(minLength: 0)
+ }
+ .padding(.vertical, 8)
+ .listRowSeparator(.hidden)
+ }
+}
diff --git a/Peel/Views/MultipleAppsView.swift b/Peel/Views/MultipleAppsView.swift
index b8203cea..b79bc52c 100644
--- a/Peel/Views/MultipleAppsView.swift
+++ b/Peel/Views/MultipleAppsView.swift
@@ -10,6 +10,8 @@ struct MultipleAppsView: View {
@State private var plan: BulkRemovalPlan
@State private var quitting = QuitBeforeRemoving()
@State private var resetsPrivacy = false
+ @State private var removesDockTiles = false
+ @State private var appsInTheDock: Set<URL> = []
@State private var isRescanning = false
@Environment(RemovalOutcome.self) private var outcome
@@ -68,6 +70,9 @@ struct MultipleAppsView: View {
if plan.apps.contains(where: { PrivacyReset.isAllowed(bundleIdentifier: $0.bundleIdentifier) && !plan.appsInTheTrash.contains($0.url) }) {
PrivacyResetRow(isOn: $resetsPrivacy, detail: PrivacyResetRow.beforeTheMove)
}
+ if !appsInTheDock.isEmpty {
+ DockTileRow(isOn: $removesDockTiles)
+ }
}
}
.disabled(plan.isRemoving)
@@ -123,6 +128,9 @@ struct MultipleAppsView: View {
guard !Task.isCancelled, !(plan.bulk == nil && plan.scanRun.wasStopped) else { return }
await rescan()
}
+ .task(id: plan.apps.map(\.url)) {
+ appsInTheDock = await DockTiles().holding(plan.apps.map(\.url))
+ }
.rescanOnExclusionChange("MultipleAppsView") { await rescan() }
.onChange(of: helper.canAct) { _, canAct in
plan.follow(canUseHelper: canAct)
@@ -288,6 +296,10 @@ struct MultipleAppsView: View {
let privacy = await PrivacyReset.reset(resetting(request.urls))
let result = await plan.move(request)
outcome.report(result, privacy: privacy)
+ if removesDockTiles {
+ let moved = Set(result.trashed.map(\.originalURL))
+ _ = await DockTiles().takeOut(appsInTheDock.filter(moved.contains).sorted { $0.path < $1.path })
+ }
if let state = AppManagement.state(after: result, appBundles: Set(plan.apps.map(\.url)), movedByTheHelper: plan.privilegedURLs) {
home.record(appManagement: state)
}
diff --git a/README.md b/README.md
index 8a125ccc..c131f3b4 100644
--- a/README.md
+++ b/README.md
@@ -96,6 +96,8 @@ Peel is free and open source, and it speaks English and 17 other languages.
put them back, and never selects your own work.
- **Privacy permissions too, if you want.** Peel can also reset the permissions macOS gave the app, such as access
to the camera and the microphone.
+- **Its Dock icon too, if you want.** Peel can take the app's icon out of the Dock, where it would stay as a
+ question mark, and History puts it back where it was when you put the app back.
- **Updates for your apps.** Peel checks your apps for new versions, through the update feed each app names or the
App Store for apps bought there. Skip This Version and Never Check This App keep it quiet about the ones you
want left alone.