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
Keep File Search's selection across searches and say so
Țugui Dragoșdb6b832ab897
diff --git a/GUIDE.md b/GUIDE.mdindex c25089fe..866f7c40 100644--- a/GUIDE.md+++ b/GUIDE.md@@ -152,12 +152,13 @@ Space shows what fills your disk, area by area, and what each area is.- **Space:** what fills your disk, area by area, and which app or tool each area belongs to.- **File Search:** files by name, kind, or size, and by age along with one of them, in your home folder or across thisMac's disks, not network volumes, found through Spotlight, up to 2,000 at a time, so a folder in System Settings >- Spotlight > Search Privacy isn't searched; when nothing is found, the page names any disk Spotlight isn't indexing. A- file in a Library folder, an app's working data, is listed last and never recommended, and one that needs an+ Spotlight > Search Privacy isn't searched; when nothing is found, the page names any disk Spotlight isn't indexing.+ A file in a Library folder, an app's working data, is listed last and never recommended, and one that needs anadministrator stays where it is. The page says how many files Spotlight found that it doesn't list, and why: whatsyncs to your other devices, what you excluded, what sits where Peel never moves anything, and what macOS didn't let- Peel look at. A file's size is what moving it frees, the list goes by it, and a file that frees less than its length,- such as a copy that shares its storage, says so.+ Peel look at. A file's size is what moving it frees, the list goes by it, and a file that frees less than its+ length, such as a copy that shares its storage, says so. A file you selected that a newer search no longer lists+ stays selected, and the page says how many, with Keep Selected and Deselect.<details><summary>Developer, Build Artifacts, and Space, in detail</summary>diff --git a/Localization/Peel/Localizable.xcstrings b/Localization/Peel/Localizable.xcstringsindex 42b708df..435773d9 100644--- a/Localization/Peel/Localizable.xcstrings+++ b/Localization/Peel/Localizable.xcstrings@@ -74976,6 +74976,113 @@}}},+ "Keep Selected" : {+ "comment" : "A button in File Search beside the line that says how many selected files the current search no longer lists: they stay selected and move with the rest.",+ "localizations" : {+ "cs" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Ponechat vybrané"+ }+ },+ "de" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Auswahl behalten"+ }+ },+ "es" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Mantener selección"+ }+ },+ "fr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Conserver la sélection"+ }+ },+ "it" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Mantieni la selezione"+ }+ },+ "ja" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "選択したままにする"+ }+ },+ "ko" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "선택 유지"+ }+ },+ "nl" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Houd geselecteerd"+ }+ },+ "pl" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Pozostaw zaznaczone"+ }+ },+ "pt" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Manter Selecionados"+ }+ },+ "ro" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Păstrați selectate"+ }+ },+ "ru" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Оставить выбранными"+ }+ },+ "sv" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Behåll markeringen"+ }+ },+ "tr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Seçili Tut"+ }+ },+ "uk" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Залишити вибраними"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "保持选择"+ }+ },+ "zh-Hant" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "保持選取"+ }+ }+ }+ },"Keep connections alive" : {"localizations" : {"cs" : {@@ -158756,6 +158863,347 @@}}},+ "Selected but not in this search: ^[%lld file](inflect: true)." : {+ "comment" : "A line at the top of File Search's list. The files were selected in an earlier search and stay selected, though this search doesn't list them; Keep Selected and Deselect are beside it.",+ "localizations" : {+ "cs" : {+ "variations" : {+ "plural" : {+ "few" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Vybráno, ale mimo toto hledání: %lld soubory."+ }+ },+ "many" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Vybráno, ale mimo toto hledání: %lld souboru."+ }+ },+ "one" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Vybráno, ale mimo toto hledání: %lld soubor."+ }+ },+ "other" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Vybráno, ale mimo toto hledání: %lld souborů."+ }+ }+ }+ }+ },+ "de" : {+ "variations" : {+ "plural" : {+ "one" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Ausgewählt, aber nicht in dieser Suche: %lld Datei."+ }+ },+ "other" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Ausgewählt, aber nicht in dieser Suche: %lld Dateien."+ }+ }+ }+ }+ },+ "es" : {+ "variations" : {+ "plural" : {+ "many" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "En la selección, pero no en esta búsqueda: %lld de archivos."+ }+ },+ "one" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "En la selección, pero no en esta búsqueda: %lld archivo."+ }+ },+ "other" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "En la selección, pero no en esta búsqueda: %lld archivos."+ }+ }+ }+ }+ },+ "fr" : {+ "variations" : {+ "plural" : {+ "many" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "%lld de fichiers sélectionnés ne figurent pas dans cette recherche."+ }+ },+ "one" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "%lld fichier sélectionné ne figure pas dans cette recherche."+ }+ },+ "other" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "%lld fichiers sélectionnés ne figurent pas dans cette recherche."+ }+ }+ }+ }+ },+ "it" : {+ "variations" : {+ "plural" : {+ "many" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Selezionati ma non presenti in questa ricerca: %lld di file."+ }+ },+ "one" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Selezionato ma non presente in questa ricerca: %lld file."+ }+ },+ "other" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Selezionati ma non presenti in questa ricerca: %lld file."+ }+ }+ }+ }+ },+ "ja" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "%lld個のファイルが選択されていますが、この検索結果にはありません。"+ }+ },+ "ko" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "선택되었지만 이 검색 결과에 없음: 파일 %lld개."+ }+ },+ "nl" : {+ "variations" : {+ "plural" : {+ "one" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Geselecteerd, maar niet in deze zoekopdracht: %lld bestand."+ }+ },+ "other" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Geselecteerd, maar niet in deze zoekopdracht: %lld bestanden."+ }+ }+ }+ }+ },+ "pl" : {+ "variations" : {+ "plural" : {+ "few" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Zaznaczono %lld pliki spoza wyników tego wyszukiwania."+ }+ },+ "many" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Zaznaczono %lld plików spoza wyników tego wyszukiwania."+ }+ },+ "one" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Zaznaczono %lld plik spoza wyników tego wyszukiwania."+ }+ },+ "other" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Zaznaczono %lld pliku spoza wyników tego wyszukiwania."+ }+ }+ }+ }+ },+ "pt" : {+ "variations" : {+ "plural" : {+ "many" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Na seleção, mas fora desta busca: %lld de arquivos."+ }+ },+ "one" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Na seleção, mas fora desta busca: %lld arquivo."+ }+ },+ "other" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Na seleção, mas fora desta busca: %lld arquivos."+ }+ }+ }+ }+ },+ "ro" : {+ "variations" : {+ "plural" : {+ "few" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Selectate, dar absente din această căutare: %lld fișiere."+ }+ },+ "one" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Selectat, dar absent din această căutare: %lld fișier."+ }+ },+ "other" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Selectate, dar absente din această căutare: %lld de fișiere."+ }+ }+ }+ }+ },+ "ru" : {+ "variations" : {+ "plural" : {+ "few" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Выбрано %lld файла, которых нет в этом поиске."+ }+ },+ "many" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Выбрано %lld файлов, которых нет в этом поиске."+ }+ },+ "one" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Выбран %lld файл, которого нет в этом поиске."+ }+ },+ "other" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Выбрано %lld файла, которых нет в этом поиске."+ }+ }+ }+ }+ },+ "sv" : {+ "variations" : {+ "plural" : {+ "one" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Markerad men inte med i den här sökningen: %lld fil."+ }+ },+ "other" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Markerade men inte med i den här sökningen: %lld filer."+ }+ }+ }+ }+ },+ "tr" : {+ "variations" : {+ "plural" : {+ "one" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Seçili olup bu aramada yer almayan: %lld dosya."+ }+ },+ "other" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Seçili olup bu aramada yer almayan: %lld dosya."+ }+ }+ }+ }+ },+ "uk" : {+ "variations" : {+ "plural" : {+ "few" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Вибрано, але немає в результатах цього пошуку: %lld файли."+ }+ },+ "many" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Вибрано, але немає в результатах цього пошуку: %lld файлів."+ }+ },+ "one" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Вибрано, але немає в результатах цього пошуку: %lld файл."+ }+ },+ "other" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Вибрано, але немає в результатах цього пошуку: %lld файла."+ }+ }+ }+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "已选择但不在本次搜索结果中:%lld个文件。"+ }+ },+ "zh-Hant" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "已選取但不在此次搜尋結果中:%lld個檔案。"+ }+ }+ }+ },"Selected copies go to the Trash. A copy marked Stays has Finder tags, a Finder comment, or a resource fork the others don’t, and is never moved." : {"comment" : "The note behind the circled i of Copies in Duplicates, when one copy stays for its Finder tags, Finder comment, or resource fork. Stays is the badge on that copy's row.","localizations" : {diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/SearchSelection.swift b/Packages/PeelCore/Sources/PeelCore/Removal/SearchSelection.swiftnew file mode 100644index 00000000..86964e0c--- /dev/null+++ b/Packages/PeelCore/Sources/PeelCore/Removal/SearchSelection.swift@@ -0,0 +1,44 @@+public import Foundation++/// What stays selected in File Search when a new search lists other files. What the new list holds stays selected+/// in it, and a selected file it leaves out stays selected apart, as the search that listed it found it, so it still+/// moves with the rest until the person deselects it. The page says how many there are.+public struct SearchSelection: Sendable {+ /// The selected files the list doesn't show.+ public private(set) var outside: [URL: FoundFile] = [:]++ public init() {}++ /// The selection once `files` is the list, `known` being the list before. A file that can't be selected, or that+ /// is gone from the disk, leaves it.+ public mutating func update(_ selected: Set<URL>, was known: [FoundFile], now files: [FoundFile]) -> Set<URL> {+ let listed = Dictionary(files.map { ($0.url, $0) }, uniquingKeysWith: { first, _ in first })+ var records = outside+ for file in known { records[file.url] = file }+ var kept: Set<URL> = []+ var apart: [URL: FoundFile] = [:]+ for url in selected {+ if let file = listed[url] {+ if !file.requiresPrivileges { kept.insert(url) }+ } else if let file = records[url], !file.requiresPrivileges, !url.isMissing {+ apart[url] = file+ kept.insert(url)+ }+ }+ outside = apart+ return kept+ }++ /// `selected` without the files kept apart, which are forgotten.+ public mutating func deselectOutside(from selected: Set<URL>) -> Set<URL> {+ defer { outside = [:] }+ return selected.subtracting(outside.keys)+ }++ /// Forgets `urls`, as when they are excluded or moved.+ public mutating func forget(_ urls: some Sequence<URL>) {+ for url in urls {+ outside[url] = nil+ }+ }+}diff --git a/Packages/PeelCore/Tests/PeelCoreTests/SearchingTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/SearchingTests.swiftindex dcce4897..048f1abb 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/SearchingTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/SearchingTests.swift@@ -142,4 +142,35 @@ struct SearchingTests {#expect(moved.withLock { $0 }.isEmpty)#expect(result.failures.map(\.reason) == [.changedSinceScan])}++ /// A selected file a new search leaves out stays selected apart, as the search found it, until it is deselected+ /// or gone from the disk.+ @Test func keepsWhatANewSearchLeavesOutSelectedApart() throws {+ let directory = try TemporaryDirectory()+ let a = try directory.file("a.dmg")+ let b = try directory.file("b.dmg")+ let c = try directory.file("c.dmg")+ let found = { (url: URL) in+ FoundFile(+ url: url, size: 16, length: 16, modificationDate: .now, requiresPrivileges: false,+ identity: FileIdentity.of(url)+ )+ }+ var selection = SearchSelection()++ var selected = selection.update([a, b], was: [], now: [found(a), found(b), found(c)])+ #expect(selected == [a, b])++ selected = selection.update(selected, was: [found(a), found(b), found(c)], now: [found(c)])+ #expect(selected == [a, b])+ #expect(Set(selection.outside.keys) == [a, b])++ try FileManager.default.removeItem(at: b)+ selected = selection.update(selected, was: [found(c)], now: [found(c)])+ #expect(selected == [a])++ selected = selection.deselectOutside(from: selected.union([c]))+ #expect(selected == [c])+ #expect(selection.outside.isEmpty)+ }}diff --git a/Peel/Model/FileSearchLibrary.swift b/Peel/Model/FileSearchLibrary.swiftindex 692700fb..65fb87fe 100644--- a/Peel/Model/FileSearchLibrary.swift+++ b/Peel/Model/FileSearchLibrary.swift@@ -21,6 +21,10 @@ final class FileSearchLibrary {var chosen: URL?/// The files Peel recommends: not the ones that need an administrator, nor the ones an app keeps for itself.private(set) var recommendedURLs: Set<URL> = []+ /// The selected files a newer search no longer lists, which stay selected until the person deselects them.+ private(set) var selection = SearchSelection()+ /// True once the person chose to keep those files selected, until another search leaves out others.+ private(set) var keepsWhatIsOutside = falseprivate var sizes: [URL: Int64] = [:]private var generation = 0/// The exclusions the list is filtered by: those the search ran under, or those it was narrowed to since.@@ -59,12 +63,17 @@ final class FileSearchLibrary {if scanRun.wasStopped, current == generation, criteria != answered { forgetResults() }return}+ let known = results?.files ?? []results = foundanswered = criteriafilteredBy = exclusionsrecommendedURLs = Set(found.files.filter { !$0.requiresPrivileges && !$0.belongsToAnApp }.map(\.url))- sizes = Dictionary(found.files.map { ($0.url, $0.size) }, uniquingKeysWith: { first, _ in first })- selectedURLs.formIntersection(found.files.filter { !$0.requiresPrivileges }.map(\.url))+ let outsideBefore = Set(selection.outside.keys)+ selectedURLs = selection.update(selectedURLs, was: known, now: found.files)+ if Set(selection.outside.keys) != outsideBefore { keepsWhatIsOutside = false }+ sizes = Dictionary(+ (found.files + selection.outside.values).map { ($0.url, $0.size) }, uniquingKeysWith: { first, _ in first }+ )// The search ran under the exclusions as they were when it started, so leave out anything excluded since.await leaveOut(ExclusionsStore.shared.exclusions)}@@ -73,18 +82,38 @@ final class FileSearchLibrary {results = nilanswered = nilselectedURLs = []+ selection = SearchSelection()recommendedURLs = []sizes = [:]}+ /// Keeps selected the files no longer listed, and stops saying so until another search leaves out others.+ func keepWhatIsOutside() {+ keepsWhatIsOutside = true+ }++ /// Deselects the files no longer listed.+ func deselectWhatIsOutside() {+ let outside = selection.outside.keys+ selectedURLs = selection.deselectOutside(from: selectedURLs)+ for url in outside {+ sizes[url] = nil+ }+ }+/// Narrows the list to what `exclusions` leave. File Search runs only when asked, so without this a file/// excluded from its own row would stay listed and selected until the move refused it.func leaveOut(_ exclusions: Exclusions) async {guard let results, exclusions != filteredBy else { return }let current = generationlet kept = await Self.keeping(results.files, under: exclusions)+ let outside = Array(selection.outside.values)+ let keptOutside = await Self.keeping(outside, under: exclusions)guard current == generation else { return }filteredBy = exclusions+ let goneOutside = Set(outside.map(\.url)).subtracting(keptOutside.map(\.url))+ selection.forget(goneOutside)+ selectedURLs.subtract(goneOutside)guard kept.count < results.files.count else { return }let gone = Set(results.files.map(\.url)).subtracting(kept.map(\.url))self.results?.files = kept@@ -119,9 +148,9 @@ extension FileSearchLibrary: CarriesSelection {func move(_ part: CarriedSelection.Part, apps: AppLibrary) async -> TrashResult? {isRemoving = truedefer { isRemoving = false }- let files = results?.files.filter {+ let files = ((results?.files ?? []) + selection.outside.values).filter {selectedURLs.contains($0.url) && part.sizes.keys.contains($0.url) && !$0.requiresPrivileges- } ?? []+ }return await FileSearch.trash(files, using: TrashService(exclusions: ExclusionsStore.shared.exclusions))}diff --git a/Peel/Views/FileSearch/FileSearchList.swift b/Peel/Views/FileSearch/FileSearchList.swiftindex 960f0ff0..05e84475 100644--- a/Peel/Views/FileSearch/FileSearchList.swift+++ b/Peel/Views/FileSearch/FileSearchList.swift@@ -20,6 +20,18 @@ struct FileSearchList: View {.foregroundStyle(.secondary).listRowSeparator(.hidden)}+ if !search.selection.outside.isEmpty, !search.keepsWhatIsOutside {+ HStack(alignment: .firstTextBaseline) {+ Label("Selected but not in this search: ^[\(search.selection.outside.count) file](inflect: true).", systemImage: "checklist")+ .foregroundStyle(.secondary)+ Spacer(minLength: 8)+ Button("Keep Selected") { search.keepWhatIsOutside() }+ .buttonStyle(.borderless)+ Button("Deselect") { search.deselectWhatIsOutside() }+ .buttonStyle(.borderless)+ }+ .listRowSeparator(.hidden)+ }if let results = search.results, !results.files.isEmpty, !results.leftOut.isEmpty {Label {LeftOutLines(leftOut: results.leftOut, alignment: .leading)diff --git a/PeelTests/FileSearchLibraryTests.swift b/PeelTests/FileSearchLibraryTests.swiftindex b6d10e5f..3c87df46 100644--- a/PeelTests/FileSearchLibraryTests.swift+++ b/PeelTests/FileSearchLibraryTests.swift@@ -60,4 +60,34 @@ struct FileSearchLibraryTests {#expect(library.results?.files.map(\.url) == [invoice])#expect(library.selectedURLs == [invoice])}++ /// A selected file a newer search leaves out stays selected, and moves with the rest, until it is deselected.+ @Test func keepsSelectedWhatANewerSearchLeavesOut() async throws {+ let folder = FileManager.default.temporaryDirectory.appending(path: "PeelTests-\(UUID().uuidString)")+ try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)+ defer { try? FileManager.default.removeItem(at: folder) }+ let first = folder.appending(path: "first.dmg")+ let second = folder.appending(path: "second.dmg")+ for url in [first, second] { try Data(count: 16).write(to: url) }+ let records = [first, second].map {+ FoundFile(url: $0, size: 4_096, length: 16, modificationDate: .distantPast, requiresPrivileges: false)+ }+ let calls = OSAllocatedUnfairLock(initialState: 0)+ let library = FileSearchLibrary { _, _ in+ let call = calls.withLock { $0 += 1; return $0 }+ return FileSearchResults(files: call == 1 ? records : [records[1]])+ }+ library.criteria.name = "dmg"+ await library.search()+ library.selectedURLs = [first, second]++ library.criteria.name = "second"+ await library.search()++ #expect(library.selectedURLs == [first, second])+ #expect(Set(library.selection.outside.keys) == [first])+ #expect(library.carriedParts.first?.sizes.keys.contains(first) == true)+ library.deselectWhatIsOutside()+ #expect(library.selectedURLs == [second])+ }}