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
File Search can be stopped like every other page
Țugui Dragoș0406a6f34b44
diff --git a/Packages/PeelCore/Sources/PeelCore/Search/FileSearch.swift b/Packages/PeelCore/Sources/PeelCore/Search/FileSearch.swiftindex 2b7edb78..ca20f189 100644--- a/Packages/PeelCore/Sources/PeelCore/Search/FileSearch.swift+++ b/Packages/PeelCore/Sources/PeelCore/Search/FileSearch.swift@@ -55,6 +55,9 @@ public struct FileSearchResults: Sendable {public enum FileSearch {public static let maximumResults = 2_000+ /// Runs a Spotlight query and returns the paths it found, or nil when it could not run or was stopped.+ typealias Gather = @concurrent @Sendable (sending MDQuery) async -> [String]?+/// Moves `files` to the Trash. A file written again under the same name after it was listed is a different/// file, so it fails with `changedSinceScan` instead.@concurrent@@ -74,19 +77,23 @@ public enum FileSearch {/// Returns up to `maximumResults` regular files from the Spotlight index that match `criteria` and that the/// removal guard allows. Files in a Library folder come after the rest, and each part is sorted largest first.+ /// Stopping the task stops the query.@concurrentpublic static func run(_ criteria: FileSearchCriteria, environment: SearchEnvironment = .current, exclusions: Exclusions = .none) async -> FileSearchResults {+ await run(criteria, environment: environment, exclusions: exclusions) { await SpotlightGathering($0).paths() }+ }++ /// The same, with the query run by `gather`, so a test can stand in for one that never finishes.+ static func run(+ _ criteria: FileSearchCriteria,+ environment: SearchEnvironment = .current,+ exclusions: Exclusions = .none,+ gather: Gather+ ) async -> FileSearchResults {guard criteria.isSearchable, let query = makeQuery(for: criteria) else { return FileSearchResults(didRun: false) }let scope = criteria.scope == .home ? kMDQueryScopeHome : kMDQueryScopeComputerMDQuerySetSearchScope(query, [scope] as CFArray, 0)-- guard MDQueryExecute(query, CFOptionFlags(kMDQuerySynchronous.rawValue)) else { return FileSearchResults(didRun: false) }-- let count = MDQueryGetResultCount(query)- let paths = (0..<count).compactMap { index -> String? in- guard let pointer = MDQueryGetResultAtIndex(query, index) else { return nil }- return MDItemCopyAttribute(Unmanaged<MDItem>.fromOpaque(pointer).takeUnretainedValue(), kMDItemPath) as? String- }+ guard let paths = await gather(query), !Task.isCancelled else { return FileSearchResults(didRun: false) }return results(from: paths, environment: environment, exclusions: exclusions)}@@ -101,6 +108,8 @@ public enum FileSearch {let allows = allows ?? RemovalGuard(environment: environment, exclusions: exclusions).allowsRemoval(of:)var candidates: [(url: URL, info: stat, belongsToAnApp: Bool)] = []for path in paths {+ // A stopped search reads nothing more; nobody will look at what it would have found.+ guard !Task.isCancelled else { return FileSearchResults(didRun: false) }var info = stat()guard lstat(path, &info) == 0, info.st_mode & S_IFMT == S_IFREG else { continue }let url = URL(filePath: path)@@ -198,3 +207,69 @@ public enum FileSearch {return "(\(clause))"}}++/// One Spotlight query, run without blocking a thread and stopped when the task that waits for it is. Everything+/// about the query happens on its own serial queue, where Spotlight delivers its results and notifications, so+/// the query is never touched from two threads at once.+private final class SpotlightGathering: @unchecked Sendable {+ private let query: MDQuery+ private let queue = DispatchQueue(label: "com.tuguidragos.Peel.FileSearch")+ // Touched only on `queue`.+ private var continuation: CheckedContinuation<[String]?, Never>?+ private var observer: (any NSObjectProtocol)?+ private var isOver = false++ init(_ query: MDQuery) {+ self.query = query+ }++ /// The paths the query found, or nil when it could not run or the task was canceled.+ func paths() async -> [String]? {+ await withTaskCancellationHandler {+ await withCheckedContinuation { continuation in+ queue.async { self.start(continuation) }+ }+ } onCancel: {+ queue.async { self.end(with: nil) }+ }+ }++ private func start(_ continuation: CheckedContinuation<[String]?, Never>) {+ // Canceled before it started.+ guard !isOver else { return continuation.resume(returning: nil) }+ self.continuation = continuation+ MDQuerySetDispatchQueue(query, queue)+ observer = NotificationCenter.default.addObserver(+ forName: Notification.Name(kMDQueryDidFinishNotification as String), object: query, queue: nil+ ) { [weak self] _ in+ guard let self else { return }+ end(with: foundPaths())+ }+ if !MDQueryExecute(query, 0) {+ end(with: nil)+ }+ }++ /// Reads each result's path from the result itself: Spotlight does not carry `kMDItemPath` in a query's value+ /// lists, which `MDQueryGetAttributeValueOfResultAtIndex` reads, so a query built to gather it finds no paths.+ private func foundPaths() -> [String] {+ MDQueryDisableUpdates(query)+ return (0..<MDQueryGetResultCount(query)).compactMap { index in+ guard let pointer = MDQueryGetResultAtIndex(query, index) else { return nil }+ let item = Unmanaged<MDItem>.fromOpaque(pointer).takeUnretainedValue()+ return MDItemCopyAttribute(item, kMDItemPath) as? String+ }+ }++ /// Stops the query and answers the waiting task, once.+ private func end(with paths: [String]?) {+ guard !isOver else { return }+ isOver = true+ MDQueryStop(query)+ if let observer {+ NotificationCenter.default.removeObserver(observer)+ }+ continuation?.resume(returning: paths)+ continuation = nil+ }+}diff --git a/Packages/PeelCore/Tests/PeelCoreTests/FileSearchTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/FileSearchTests.swiftindex 1d5f850a..51b0b5fb 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/FileSearchTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/FileSearchTests.swift@@ -15,6 +15,23 @@ struct FileSearchTests {#expect(!FileSearch.isAppData(URL(filePath: "/Users/x/Libraryish/cache.db"), home: home))}+ /// A Spotlight query over the whole Mac can take seconds, so a search is stopped like any scan: it comes back+ /// at once and reads nothing more.+ @Test func aStoppedSearchStops() async throws {+ let unanswered = Unanswered()+ var search = FileSearchCriteria()+ search.name = "report"+ let criteria = search++ let stop = try await unanswered.stop {+ _ = await FileSearch.run(criteria, gather: unanswered.gather)+ }++ #expect(stop.took < .seconds(1))+ #expect(stop.askedBefore == 1)+ #expect(stop.askedAfter == 0)+ }+@Test func buildsQueryFromCriteria() {var criteria = FileSearchCriteria()criteria.name = " Budget "diff --git a/Packages/PeelCore/Tests/PeelCoreTests/Unanswered.swift b/Packages/PeelCore/Tests/PeelCoreTests/Unanswered.swiftindex 0aa9009d..1a846034 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/Unanswered.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/Unanswered.swift@@ -25,6 +25,13 @@ final class Unanswered: Sendable {}}+ var gather: FileSearch.Gather {+ { [self] _ in+ await wait()+ return nil+ }+ }+private func wait() async {asked.withLock { $0 += 1 }try? await Task.sleep(for: .seconds(3_600))diff --git a/Peel/Model/FileSearchLibrary.swift b/Peel/Model/FileSearchLibrary.swiftindex 9a08d314..98e34ffa 100644--- a/Peel/Model/FileSearchLibrary.swift+++ b/Peel/Model/FileSearchLibrary.swift@@ -7,7 +7,9 @@ final class FileSearchLibrary {var criteria = FileSearchCriteria()private(set) var results: FileSearchResults?private(set) var searchedCriteria: FileSearchCriteria?- private(set) var isSearching = false+ /// The search this page runs, which a newer one or the Stop button ends.+ let scanRun = ScanRun()+ var isSearching: Bool { scanRun.isRunning }private(set) var isRemoving = falsevar selectedURLs: Set<URL> = []/// The file the detail shows, chosen in the list. Checking a file for the Trash is `selectedURLs`, apart.@@ -34,23 +36,26 @@ final class FileSearchLibrary {let criteria = criteriasearchedCriteria = criteriaguard criteria.isSearchable else {+ // Nothing is asked of Spotlight anymore, so a search still running for the old words is stopped.+ scanRun.stop()results = nilselectedURLs = []selectableURLs = []sizes = [:]- isSearching = falsereturn}- isSearching = truelet exclusions = ExclusionsStore.shared.exclusions- let found = await FileSearch.run(criteria, exclusions: exclusions)- guard current == generation else { return }+ guard let found = await scanRun.run({ await FileSearch.run(criteria, exclusions: exclusions) }) else {+ // Canceled with the task that asked for it, as when the page goes away, the search answered nothing,+ // so the page asks again when it comes back. Stopped or replaced by a newer search, it counts as asked.+ if !scanRun.wasStopped, current == generation { searchedCriteria = nil }+ return+ }results = foundfilteredBy = exclusionsselectableURLs = 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))- isSearching = false// The search ran under the exclusions as they were when it started, so leave out anything excluded since.await leaveOut(ExclusionsStore.shared.exclusions)}diff --git a/Peel/Views/FileSearch/FileSearchList.swift b/Peel/Views/FileSearch/FileSearchList.swiftindex ce54651c..289906ba 100644--- a/Peel/Views/FileSearch/FileSearchList.swift+++ b/Peel/Views/FileSearch/FileSearchList.swift@@ -53,7 +53,7 @@ struct FileSearchList: View {.disabled(search.isSearching || search.isRemoving)}}- .scanState(phase, isRescanning: search.isSearching) {+ .scanState(phase, isRescanning: search.isSearching, scan: search.scanRun) {if search.results == nil {ContentUnavailableView("Search for Files",@@ -94,7 +94,11 @@ struct FileSearchList: View {}}ToolbarItem {- RescanButton(isRunning: $isRescanning, isDisabled: !search.criteria.isSearchable || search.isSearching || search.isRemoving) {+ RescanButton(+ isRunning: $isRescanning,+ isDisabled: !search.criteria.isSearchable || search.isRemoving,+ scan: search.scanRun+ ) {await search.search()}}@@ -133,6 +137,8 @@ struct FileSearchList: View {private var phase: ScanPhase {if search.isSearching, search.results?.files.isEmpty ?? true { return .scanning(.spotlight) }+ // A first search stopped before it answered says so; one left behind by words since cleared does not.+ if search.results == nil, search.scanRun.wasStopped, search.criteria.isSearchable { return .stopped }if search.results == nil { return .message }if search.results?.files.isEmpty == true { return .message }return .contentdiff --git a/Peel/Views/RescanButton.swift b/Peel/Views/RescanButton.swiftindex 48a24b2b..511eebf6 100644--- a/Peel/Views/RescanButton.swift+++ b/Peel/Views/RescanButton.swift@@ -7,9 +7,8 @@ struct RescanButton: View {var isDisabled = falsevar title: LocalizedStringResource = "Rescan"/// The page's scan. While it runs, the button turns into Stop, as Safari's Reload does. Nil where the work- /// can't be stopped halfway, such as a Spotlight query or reading one file. Stop is not offered while the- /// button is disabled: the scan after a move to the Trash takes the moved rows off the list, and stopping- /// it would leave them listed.+ /// can't be stopped halfway, such as reading one file. Stop is not offered while the button is disabled: the+ /// scan after a move to the Trash takes the moved rows off the list, and stopping it would leave them listed.var scan: (any StoppableWork)?let action: () async -> Void