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
Take out the Dock icon of an app already in the Trash
Țugui Dragoș3102adbfb540
diff --git a/GUIDE.md b/GUIDE.mdindex 67138c60..a9be6971 100644--- a/GUIDE.md+++ b/GUIDE.md@@ -64,7 +64,8 @@ and how to get it, [SAFETY.md](SAFETY.md) what it protects, [PRIVACY.md](PRIVACY- **Privacy permissions too, if you want.** Peel can also reset the permissions macOS gave the app, such as accessto the camera and the microphone. History can't undo this: the app asks again for each one.- **Its Dock icon too.** Peel takes the app's icon out of the Dock, where it would stay as a question mark,- unless you deselect it, and History puts it back where it was when you put the app back.+ unless you deselect it, and History puts it back where it was when you put the app back. An app you had already+ moved to the Trash loses its icon once the files it left behind move, and History doesn't put that icon back.- **When macOS needs more.** After a removal, Peel says when macOS keeps using what moved: an audio driver untilyou restart your Mac, and, on macOS 27, an app's login items, which macOS starts from the Trash until you empty it.- **Lines that still point to what moved.** After a removal, Peel reads the files your shell runs when it startsdiff --git a/Localization/Peel/Localizable.xcstrings b/Localization/Peel/Localizable.xcstringsindex b0724d3d..70ae0a7b 100644--- a/Localization/Peel/Localizable.xcstrings+++ b/Localization/Peel/Localizable.xcstrings@@ -182366,6 +182366,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, but an app that was already in the Trash doesn’t get its icon back." : {+ "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, ale aplikace, která už byla v koši, svou ikonu zpět nedostane."+ }+ },+ "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, aber eine App, die bereits im Papierkorb war, bekommt ihr Symbol nicht zurück."+ }+ },+ "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, pero una app que ya estaba en la papelera no recupera su icono."+ }+ },+ "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, mais une app qui était déjà dans la corbeille ne récupère pas son icône."+ }+ },+ "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, ma un’app che era già nel Cestino non recupera la sua icona."+ }+ },+ "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, maar een app die al in de prullenmand stond, krijgt zijn symbool niet terug."+ }+ },+ "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, ale aplikacja, która była już w Koszu, nie odzyskuje swojej ikony."+ }+ },+ "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, mas o ícone de um app que já estava no Lixo não volta."+ }+ },+ "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, dar o aplicație care era deja în Coș nu își recapătă pictograma."+ }+ },+ "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, men en app som redan låg i papperskorgen får inte tillbaka sin symbol."+ }+ },+ "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, ancak zaten Çöp Sepeti’nde olan bir uygulamanın simgesi geri gelmez."+ }+ },+ "uk" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Dock зберігає іконку програми у вигляді знака питання, коли самої програми вже немає. Якщо цей параметр вибрано, Peel прибирає іконку, щойно програма опиняється в Смітнику, і Dock перезапускається. Якщо повернути програму з Історії, її іконка повернеться туди, де була, але іконка програми, яка вже була в Смітнику, не повернеться."+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "App移除后,程序坞仍会以问号的形式保留它的图标。如果选择此项,Peel会在App移到废纸篓后移除它的图标,程序坞会重新启动。从“历史记录”中将App放回原处时,它的图标也会回到原来的位置,但原本就已在废纸篓中的App,它的图标不会放回原处。"+ }+ },+ "zh-Hant" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "App不在後,Dock仍會以問號保留它的圖像。若已選取此選項,Peel會在App丟到「垃圾桶」後移除該圖像,Dock也會重新啟動。從「歷史記錄」還原App時,其圖像也會放回原本的位置,但原本就已在「垃圾桶」中的App,其圖像不會放回。"+ }+ }+ }+ },"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" : {@@ -182472,6 +182578,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 files the app left behind are in the Trash, and the Dock restarts. The app was already in the Trash, so History doesn’t put its icon back." : {+ "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 budou v koši soubory, které po sobě aplikace zanechala, a Dock se restartuje. Aplikace už byla v koši, takže Historie její ikonu nevrátí."+ }+ },+ "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 von der App hinterlassenen Dateien im Papierkorb sind, und das Dock startet neu. Die App war bereits im Papierkorb, daher legt der Verlauf ihr Symbol nicht zurück."+ }+ },+ "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 los archivos que ha dejado la app ya están en la papelera, y el Dock se reinicia. La app ya estaba en la papelera, así que Historial no restaura su icono."+ }+ },+ "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 que les fichiers que l’app a laissés derrière elle sont dans la corbeille, et le Dock redémarre. L’app était déjà dans la corbeille : l’Historique ne remet donc pas son icône en 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 i file che l’app si è lasciata dietro sono nel Cestino, e il Dock si riavvia. L’app era già nel Cestino, quindi la Cronologia non ripristina la sua icona."+ }+ },+ "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 bestanden die de app heeft achtergelaten, in de prullenmand staan, en start het Dock opnieuw. De app stond al in de prullenmand, dus Geschiedenis zet het symbool niet terug."+ }+ },+ "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 pliki pozostawione przez aplikację znajdą się w Koszu, a Dock uruchamia się ponownie. Aplikacja była już w Koszu, więc Historia nie przywraca jej ikony."+ }+ },+ "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 os arquivos que o app deixou para trás estiverem no Lixo, e o Dock reinicia. O app já estava no Lixo, então o Histórico não coloca o ícone de volta."+ }+ },+ "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 fișierele lăsate în urmă de aplicație au ajuns în Coș, iar Dock‑ul repornește. Aplicația era deja în Coș, așa că nu îi puteți pune pictograma înapoi din Istoric."+ }+ },+ "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 filerna som appen lämnade kvar ligger i papperskorgen, och Dock startas om. Appen låg redan i papperskorgen, så Historik lägger inte tillbaka symbolen."+ }+ },+ "tr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Dock, bir uygulama gittikten sonra onun simgesini soru işareti olarak tutar. Bu seçiliyse, uygulamanın geride bıraktığı dosyalar Çöp Sepeti’ne taşındıktan sonra Peel simgeyi Dock’tan çıkarır ve Dock yeniden başlar. Uygulama zaten Çöp Sepeti’ndeydi, bu yüzden Geçmiş onun simgesini yerine koymaz."+ }+ },+ "uk" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Dock зберігає іконку програми у вигляді знака питання, коли самої програми вже немає. Якщо цей параметр вибрано, Peel прибирає іконку, щойно файли, які програма залишила по собі, опиняються в Смітнику, і Dock перезапускається. Програма вже була в Смітнику, тож Історія не повертає її іконку."+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "App移除后,程序坞仍会以问号的形式保留它的图标。如果选择此项,Peel会在App留下的文件移到废纸篓后移除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.swiftindex 10c36342..75a53d05 100644--- a/Packages/PeelCore/Sources/PeelCore/Apps/DockTiles.swift+++ b/Packages/PeelCore/Sources/PeelCore/Apps/DockTiles.swift@@ -112,28 +112,35 @@ public struct DockTiles: Sendable {/// Those of `apps` that have a tile in the Dock.@concurrentpublic func holding(_ apps: [URL]) async -> Set<URL> {- let lists = DockList.allCases.compactMap { store.tiles(in: $0) }- return Set(apps.filter { app in lists.contains { !indices(of: app, in: $0).isEmpty } })+ let lists = DockList.allCases.compactMap { store.tiles(in: $0) }.map(Places.init)+ return Set(apps.filter { app in lists.contains { !$0.indices(of: key(app)).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. Peel removing itself remembers nothing,- /// since its folder, where the memory is kept, has gone to the Trash.- public func takeOut(_ apps: [URL], remembering: Bool = true) async -> Bool {+ /// since its folder, where the memory is kept, has gone to the Trash, and the tile of an app in `forgotten` is not+ /// remembered either: such an app was already in the Trash, so History, which puts a tile back, never moved it.+ public func takeOut(_ apps: [URL], remembering: Bool = true, forgetting forgotten: Set<URL> = []) async -> Bool {let lists = Dictionary(uniqueKeysWithValues: DockList.allCases.compactMap { list instore.tiles(in: list).map { (list, $0) }})- let paths = lists.mapValues { $0.map(Self.path(of:)) }+ let places = lists.mapValues(Places.init)var removed: [String: [Removed]] = [:]for app in apps {- let found = lists.flatMap { list, tiles in indices(of: app, in: tiles).map { (list, tiles[$0], $0) } }+ let found = lists.flatMap { list, tiles in+ (places[list]?.indices(of: key(app)) ?? []).map { (list, tiles[$0], $0) }+ }let kept = found.compactMap { list, tile, index in(try? PropertyListSerialization.data(fromPropertyList: tile, format: .binary, options: 0))- .map { Removed(list: list, index: index, tile: $0, around: paths[list] ?? []) }+ .map { Removed(list: list, index: index, tile: $0, around: places[list]?.paths ?? []) }}if !found.isEmpty, kept.count == found.count { removed[key(app)] = kept }}- guard !removed.isEmpty, !remembering || change({ $0.merge(removed) { _, new in new } }) else { return false }+ let forgottenKeys = Set(forgotten.map(key))+ let remembered = removed.filter { !forgottenKeys.contains($0.key) }+ guard !removed.isEmpty,+ !remembering || remembered.isEmpty || change({ $0.merge(remembered) { _, new in new } })+ else { return false }var written: Set<DockList> = []for (list, tiles) in lists {let taken = Set(removed.values.flatMap { $0.filter { $0.list == list }.map(\.index) })@@ -143,9 +150,9 @@ public struct DockTiles: Sendable {}}let failed = Set(removed.values.flatMap { $0.map(\.list) }).subtracting(written)- if remembering, !failed.isEmpty {+ if remembering, !remembered.isEmpty, !failed.isEmpty {_ = change { entries in- for key in removed.keys {+ for key in remembered.keys {let left = entries[key]?.filter { !failed.contains($0.list) } ?? []entries[key] = left.isEmpty ? nil : left}@@ -202,8 +209,35 @@ public struct DockTiles: Sendable {return url.map(PathPattern.comparablePath)}- private func indices(of app: URL, in tiles: [Any]) -> [Int] {- indices(ofKey: key(app), in: tiles)+ /// Where the bookmark the Dock keeps beside a tile's path finds the tile's app, for a path that leads nowhere: the+ /// Dock keeps the place an app was kept from once the app moves, to the Trash too.+ private static func bookmarkedPath(of tile: Any, leadingNowhereFrom path: String) -> String? {+ guard URL(filePath: path).isMissing,+ let book = ((tile as? [String: Any])?["tile-data"] as? [String: Any])?["book"] as? Data+ else { return nil }+ var isStale = false+ let found = try? URL(+ resolvingBookmarkData: book, options: [.withoutUI, .withoutMounting], relativeTo: nil,+ bookmarkDataIsStale: &isStale+ )+ return found.map(PathPattern.comparablePath)+ }++ /// Where each tile of a list leads, worked out once for the list, since a bookmark is resolved on disk.+ private struct Places {+ let paths: [String?]+ let bookmarked: [String?]++ init(_ tiles: [Any]) {+ paths = tiles.map(DockTiles.path(of:))+ bookmarked = zip(tiles, paths).map { tile, path in+ path.flatMap { DockTiles.bookmarkedPath(of: tile, leadingNowhereFrom: $0) }+ }+ }++ func indices(of key: String) -> [Int] {+ paths.indices.filter { paths[$0] == key || bookmarked[$0] == key }+ }}private func indices(ofKey key: String, in tiles: [Any]) -> [Int] {diff --git a/Packages/PeelCore/Tests/PeelCoreTests/DockTilesTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/DockTilesTests.swiftindex 246296c1..8f53631d 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/DockTilesTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/DockTilesTests.swift@@ -53,6 +53,10 @@ struct DockTilesTests {["tile-data": ["file-data": ["_CFURLString": url, "_CFURLStringType": type]], "tile-type": "file-tile"]}+ private static func tile(_ url: String, book: Data) -> [String: Any] {+ ["tile-data": ["file-data": ["_CFURLString": url, "_CFURLStringType": 15], "book": book], "tile-type": "file-tile"]+ }+private static func spacer() -> [String: Any] {["tile-data": [String: Any](), "tile-type": "spacer-tile"]}@@ -90,6 +94,38 @@ struct DockTilesTests {#expect(store.paths().count == 4, "a tile was put back twice")}+ @Test func takesOutTheTileOfAnAppAlreadyInTheTrashWithoutRememberingIt() async throws {+ let directory = try TemporaryDirectory()+ let root = directory.url.resolvingSymlinksInPath()+ let kept = try directory.directory("Applications/org.example.Studio.app").resolvingSymlinksInPath()+ let tile = try Self.tile(kept.absoluteString, book: kept.bookmarkData())+ try directory.directory(".Trash")+ let trashed = root.appending(path: ".Trash/org.example.Studio.app", directoryHint: .isDirectory)+ try FileManager.default.moveItem(at: kept, to: trashed)+ let store = Store([Self.tile("file:///System/Applications/Mail.app/"), tile])+ let memory = directory.url.appending(path: "dock-tiles.json")+ let tiles = DockTiles(store: store, memory: memory)++ #expect(await tiles.holding([trashed]) == [trashed])+ #expect(await tiles.takeOut([trashed], forgetting: [trashed]))+ #expect(store.paths() == ["/System/Applications/Mail.app"])+ #expect(store.restarts.load(ordering: .relaxed) == 1)+ #expect(memory.isMissing, "a tile was remembered for an app History never moved")+ }++ @Test func aTileWhoseBookmarkFindsACopyElsewhereIsNotTheTrashedApps() async throws {+ let directory = try TemporaryDirectory()+ let root = directory.url.resolvingSymlinksInPath()+ let kept = try directory.directory("Applications/org.example.Studio.app").resolvingSymlinksInPath()+ let tile = try Self.tile(kept.absoluteString, book: kept.bookmarkData())+ try directory.directory("Elsewhere")+ try FileManager.default.moveItem(at: kept, to: root.appending(path: "Elsewhere/org.example.Studio.app"))+ let trashed = try directory.directory(".Trash/org.example.Studio.app").resolvingSymlinksInPath()+ let tiles = DockTiles(store: Store([tile]), memory: directory.url.appending(path: "dock-tiles.json"))++ #expect(await tiles.holding([trashed]).isEmpty)+ }+@Test func takesOutATileWithoutRememberingItInAFolderThatIsGone() async throws {let directory = try TemporaryDirectory()let store = Store([Self.tile("file:///Applications/org.example.Studio.app/")])diff --git a/Peel/Model/BulkRemovalPlan.swift b/Peel/Model/BulkRemovalPlan.swiftindex b5afc044..807d9e6c 100644--- a/Peel/Model/BulkRemovalPlan.swift+++ b/Peel/Model/BulkRemovalPlan.swift@@ -50,6 +50,16 @@ final class BulkRemovalPlan {var items: [BulkUninstallation.Item] { bulk?.items ?? [] }+ /// The chosen apps already in the Trash that hold a tile in the Dock and a file of their own that can be selected.+ var appsInTheTrashWithTiles: [InstalledApp] {+ appsInTheTrash(withFilesAmong: selectable).filter { appsInTheDock.contains($0.url) }+ }++ func appsInTheTrash(withFilesAmong urls: Set<URL>) -> [InstalledApp] {+ guard let bulk, !appsInTheTrash.isEmpty else { return [] }+ return apps.filter { appsInTheTrash.contains($0.url) && !bulk.files(of: $0.reference).isDisjoint(with: urls) }+ }+/// What a confirmation would ask about now: the selection, with the sizes this scan measured.var request: RemovalRequest {RemovalRequest(diff --git a/Peel/Views/AppDetailView.swift b/Peel/Views/AppDetailView.swiftindex 838bb069..fc66bd66 100644--- a/Peel/Views/AppDetailView.swift+++ b/Peel/Views/AppDetailView.swift@@ -513,8 +513,10 @@ struct AppDetailView: View {leftForAnAdministrator: left.count,shellReferences: await ShellReferences.find(naming: result.trashed.map(\.originalURL)))- if plan.removesDockTile, result.trashed.contains(where: { $0.originalURL == plan.app.url }) {- _ = await DockTiles().takeOut([plan.app.url])+ let movedTheApp = result.trashed.contains(where: { $0.originalURL == plan.app.url })+ if plan.removesDockTile, movedTheApp || plan.isAppInTheTrash && !result.trashed.isEmpty {+ let forgotten: Set<URL> = plan.isAppInTheTrash ? [plan.app.url] : []+ _ = await DockTiles().takeOut([plan.app.url], forgetting: forgotten)}if let state = AppManagement.state(after: result,@@ -553,8 +555,9 @@ private struct AppRemovalOptions: View {if !PrivacyReset.apps(among: [plan.app], moving: plan.selectable).isEmpty {PrivacyResetRow(isOn: Bindable(plan).resetsPrivacy, detail: PrivacyResetRow.beforeTheMove)}- if plan.hasDockTile, plan.selectable.contains(plan.app.url) {- DockTileRow(isOn: Bindable(plan).removesDockTile)+ if plan.hasDockTile,+ plan.selectable.contains(plan.app.url) || plan.isAppInTheTrash && !plan.selectable.isEmpty {+ DockTileRow(isOn: Bindable(plan).removesDockTile, apps: plan.isAppInTheTrash ? .alreadyInTheTrash : .moved)}}}diff --git a/Peel/Views/DockTileRow.swift b/Peel/Views/DockTileRow.swiftindex 395ba7eb..74e7522d 100644--- a/Peel/Views/DockTileRow.swift+++ b/Peel/Views/DockTileRow.swift@@ -1,13 +1,14 @@import SwiftUI/// A checkbox that also takes the removed apps' icons out of the Dock, selected unless the user deselects it: a gone-/// app's icon is only a question mark, and History puts it back with the app.+/// app's icon is only a question mark.struct DockTileRow: View {@Binding var isOn: Bool+ let apps: DockTileOption.Appsvar body: some View {HStack(spacing: 5) {- DockTileOption(isOn: $isOn)+ DockTileOption(isOn: $isOn, apps: apps)Spacer(minLength: 0)}.padding(.vertical, 8)@@ -17,7 +18,14 @@ struct DockTileRow: View {/// The checkbox and its circled i, for a row of their own or beside another option.struct DockTileOption: View {+ /// Whose icons go: the apps Peel moves, whose icons History puts back with them, the apps already in the Trash,+ /// which History never moved, or both.+ enum Apps {+ case moved, alreadyInTheTrash, both+ }+@Binding var isOn: Bool+ let apps: Appsvar body: some View {HStack(spacing: 5) {@@ -25,10 +33,18 @@ struct DockTileOption: View {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.")- )+ InfoNote(name: String(localized: "Remove from the Dock"), detail: detail)+ }+ }++ private var detail: Text {+ switch apps {+ case .moved:+ 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.")+ case .alreadyInTheTrash:+ 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 files the app left behind are in the Trash, and the Dock restarts. The app was already in the Trash, so History doesn’t put its icon back.")+ case .both:+ 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, but an app that was already in the Trash doesn’t get its icon back.")}}}diff --git a/Peel/Views/MultipleAppsView.swift b/Peel/Views/MultipleAppsView.swiftindex e1bd0e15..e1d99743 100644--- a/Peel/Views/MultipleAppsView.swift+++ b/Peel/Views/MultipleAppsView.swift@@ -401,9 +401,11 @@ struct MultipleAppsView: View {)if plan.removesDockTiles {let moved = Set(result.trashed.map(\.originalURL))- // Asked of every app that moved, since one opened after the last scan has a tile now.- let apps = plan.apps.map(\.url).filter(moved.contains).sorted { $0.path < $1.path }- _ = await DockTiles().takeOut(apps)+ // Asked of every app that moved, since one opened after the last scan has a tile now, and of every+ // app already in the Trash whose own files moved.+ let inTheTrash = plan.appsInTheTrash(withFilesAmong: moved).map(\.url)+ let apps = (plan.apps.map(\.url).filter(moved.contains) + inTheTrash).sorted { $0.path < $1.path }+ _ = await DockTiles().takeOut(apps, forgetting: Set(inTheTrash))}if let state = AppManagement.state(after: result,@@ -458,7 +460,9 @@ private struct BulkRemovalOptions: View {var body: some View {let resets = !PrivacyReset.apps(among: plan.apps, moving: plan.selectable).isEmpty- let removesTiles = !plan.appsInTheDock.isDisjoint(with: plan.selectable)+ let movesAppsWithTiles = !plan.appsInTheDock.isDisjoint(with: plan.selectable)+ let tilesInTheTrash = !plan.appsInTheTrashWithTiles.isEmpty+ let removesTiles = movesAppsWithTiles || tilesInTheTrashif resets || removesTiles {// Side by side while they fit, and the second on a line of its own when they don't.FlowLayout(spacing: 24) {@@ -466,7 +470,10 @@ private struct BulkRemovalOptions: View {PrivacyResetOption(isOn: Bindable(plan).resetsPrivacy, detail: PrivacyResetRow.beforeTheMove)}if removesTiles {- DockTileOption(isOn: Bindable(plan).removesDockTiles)+ DockTileOption(+ isOn: Bindable(plan).removesDockTiles,+ apps: movesAppsWithTiles ? (tilesInTheTrash ? .both : .moved) : .alreadyInTheTrash+ )}}.padding(.vertical, 8)diff --git a/SAFETY.md b/SAFETY.mdindex a3814018..47c2b3f8 100644--- a/SAFETY.md+++ b/SAFETY.md@@ -256,7 +256,7 @@ Some of what Peel does is not a move to the Trash. Each is here with how it is u| --- | --- || A preference domain is forgotten (`defaults delete`) once its file is in the Trash | Putting the file back from History, as described below || A launch job is stopped (`launchctl bootout`) once its file is in the Trash | Putting the file back from History, which starts the job again (`launchctl bootstrap`, a daemon through the helper) |-| An uninstalled app's icon is taken out of the Dock, which restarts the Dock | Putting the app back from History puts its icon back where it was |+| An uninstalled app's icon is taken out of the Dock, which restarts the Dock | Putting the app back from History puts its icon back where it was; the icon of an app that was already in the Trash doesn't come back || An app's privacy permissions are reset, only when you choose it | Can't be undone: the app asks again for each permission || Homebrew uninstalls a package, or cleans up its downloads, the old versions it kept, and the formulae nothing needs anymore | Can't be undone: Homebrew deletes what it removes || Homebrew upgrades a package, updates itself and its taps, or repairs its taps' links (Upgrade, Upgrade All, Update, Repair Taps) | Not through History: an upgrade replaces the version that was installed, and the earlier versions of a formula stay until you clean up |@@ -284,7 +284,8 @@ The first three happen after a move, and only for what really moved:the file back from History starts again the job Peel stopped, as the file back in place declares it (a daemonthrough the helper), and a job that was not running stays as it was.- **An uninstalled app's icon leaves the Dock**, unless you deselect Also remove from the Dock, and the Dock restarts.- Putting the app back puts its icon back where it was.+ Putting the app back puts its icon back where it was. The icon of an app that was already in the Trash goes once the+ files it left behind move, and doesn't come back.## What is selected for you