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.

Keep Installers' reasons current, and its list true to its pages

Țugui Dragoș8dea3414aa25
diff --git a/Localization/Peel/Localizable.xcstrings b/Localization/Peel/Localizable.xcstrings
index 084b30b7..a5a7ea34 100644
--- a/Localization/Peel/Localizable.xcstrings
+++ b/Localization/Peel/Localizable.xcstrings
@@ -16512,108 +16512,108 @@
}
}
},
- "Almost all of a device’s data and settings, backed up to this Mac. Peel shows what is here and leaves the rest to Finder." : {
+ "Almost all of a device’s data and settings, backed up to this Mac. Peel shows what is here. A backup is deleted in System Settings > General > Storage > iOS Files, or in Finder." : {
"localizations" : {
"cs" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Téměř všechna data a nastavení zařízení zálohovaná do tohoto Macu. Peel ukazuje, co tu je, a zbytek nechává na Finderu."
+ "value" : "Téměř všechna data a nastavení zařízení zálohovaná do tohoto Macu. Peel ukazuje, co tu je. Záloha se maže v Nastavení systému > Obecné > Úložiště > iOS soubory nebo ve Finderu."
}
},
"de" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Fast alle Daten und Einstellungen eines Geräts, auf diesem Mac gesichert. Peel zeigt, was hier ist, und überlässt den Rest dem Finder."
+ "value" : "Fast alle Daten und Einstellungen eines Geräts, auf diesem Mac gesichert. Peel zeigt, was hier ist. Ein Backup wird unter „Systemeinstellungen“ > „Allgemein“ > „Speicher“ > „iOS-Dateien“ oder im Finder gelöscht."
}
},
"es" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Casi todos los datos y ajustes de un dispositivo, con copia de seguridad en este Mac. Peel muestra lo que hay aquí y deja el resto al Finder."
+ "value" : "Casi todos los datos y ajustes de un dispositivo, con copia de seguridad en este Mac. Peel muestra lo que hay aquí. Una copia de seguridad se elimina en Ajustes del Sistema > General > Almacenamiento > Archivos de iOS, o en el Finder."
}
},
"fr" : {
"stringUnit" : {
"state" : "translated",
- "value" : "La quasi-totalité des données et des réglages d’un appareil, sauvegardés sur ce Mac. Peel montre ce qui s’y trouve et laisse le reste au Finder."
+ "value" : "La quasi-totalité des données et des réglages d’un appareil, sauvegardés sur ce Mac. Peel montre ce qui s’y trouve. Une sauvegarde se supprime dans Réglages Système > Général > Stockage > Fichiers iOS, ou dans le Finder."
}
},
"it" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Quasi tutti i dati e le impostazioni di un dispositivo, salvati con un backup su questo Mac. Peel mostra cosa c’è e lascia il resto al Finder."
+ "value" : "Quasi tutti i dati e le impostazioni di un dispositivo, salvati con un backup su questo Mac. Peel mostra cosa c’è. Un backup si elimina in Impostazioni di Sistema > Generali > Spazio > File iOS, oppure nel Finder."
}
},
"ja" : {
"stringUnit" : {
"state" : "translated",
- "value" : "このMacにバックアップされた、デバイスのほぼすべてのデータと設定です。Peelはここにあるものを表示するだけで、それ以外はFinderに任せます。"
+ "value" : "このMacにバックアップされた、デバイスのほぼすべてのデータと設定です。Peelはここにあるものを表示します。バックアップの削除は、“システム設定”>“一般”>“ストレージ”>“iOSファイル”またはFinderで行います。"
}
},
"ko" : {
"stringUnit" : {
"state" : "translated",
- "value" : "기기의 거의 모든 데이터와 설정을 이 Mac에 백업한 것입니다. Peel은 여기에 무엇이 있는지 보여 주고 나머지는 Finder에 맡깁니다."
+ "value" : "기기의 거의 모든 데이터와 설정을 이 Mac에 백업한 것입니다. Peel은 여기에 무엇이 있는지 보여 줍니다. 백업은 시스템 설정 > 일반 > 저장 공간 > iOS 파일 또는 Finder에서 삭제합니다."
}
},
"nl" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Bijna alle gegevens en instellingen van een apparaat, als back-up bewaard op deze Mac. Peel toont wat er staat en laat de rest over aan Finder."
+ "value" : "Bijna alle gegevens en instellingen van een apparaat, als back-up bewaard op deze Mac. Peel toont wat er staat. Een back-up wordt verwijderd in Systeeminstellingen > Algemeen > Opslag > iOS-bestanden, of in Finder."
}
},
"pl" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Prawie wszystkie dane i ustawienia urządzenia, zachowane w backupie na tym Macu. Peel pokazuje, co tu jest, a resztę zostawia Finderowi."
+ "value" : "Prawie wszystkie dane i ustawienia urządzenia, zachowane w backupie na tym Macu. Peel pokazuje, co tu jest. Backup usuwa się w Ustawieniach systemowych > Ogólne > Miejsce > Pliki iOS albo w Finderze."
}
},
"pt" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Quase todos os dados e ajustes de um dispositivo, guardados em backup neste Mac. O Peel mostra o que está aqui e deixa o resto para o Finder."
+ "value" : "Quase todos os dados e ajustes de um dispositivo, guardados em backup neste Mac. O Peel mostra o que está aqui. Um backup é apagado em Ajustes do Sistema > Geral > Armazenamento > Arquivos do iOS ou no Finder."
}
},
"ro" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Aproape toate datele și configurările unui dispozitiv, salvate prin backup pe acest Mac. Peel arată ce se află aici și lasă restul în seama Finder."
+ "value" : "Aproape toate datele și configurările unui dispozitiv, salvate prin backup pe acest Mac. Peel arată ce se află aici. Un backup se șterge din Configurări sistem > General > Stocare > Fișiere iOS sau din Finder."
}
},
"ru" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Почти все данные и настройки устройства, сохраненные в резервной копии на этом Mac. Peel показывает, что здесь есть, а остальное оставляет для Finder."
+ "value" : "Почти все данные и настройки устройства, сохраненные в резервной копии на этом Mac. Peel показывает, что здесь есть. Резервные копии удаляют в разделе «Системные настройки» > «Основные» > «Хранилище» > «Файлы iOS» или в Finder."
}
},
"sv" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Nästan alla data och inställningar från en enhet, säkerhetskopierade till den här datorn. Peel visar vad som finns här och lämnar resten åt Finder."
+ "value" : "Nästan alla data och inställningar från en enhet, säkerhetskopierade till den här datorn. Peel visar vad som finns här. En säkerhetskopia raderas i Systeminställningar > Allmänt > Lagring > iOS-filer, eller i Finder."
}
},
"tr" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Bu Mac’e yedeklenmiş, bir aygıtın verilerinin ve ayarlarının neredeyse tamamı. Peel burada ne olduğunu gösterir, gerisini Finder’a bırakır."
+ "value" : "Bu Mac’e yedeklenmiş, bir aygıtın verilerinin ve ayarlarının neredeyse tamamı. Peel burada ne olduğunu gösterir. Bir yedekleme, Sistem Ayarları > Genel > Saklama Alanı > iOS Dosyaları bölümünde veya Finder’da silinir."
}
},
"uk" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Майже всі дані й налаштування пристрою, збережені в резервній копії на цьому Mac. Peel показує, що тут є, а решту залишає для Finder."
+ "value" : "Майже всі дані й налаштування пристрою, збережені в резервній копії на цьому Mac. Peel показує, що тут є. Резервну копію видаляють у розділі Системні параметри > Загальні > Сховище > Файли iOS або у Finder."
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "设备几乎所有的数据和设置,备份在这台Mac上。Peel只显示这里有什么,其余的交给“访达”处理。"
+ "value" : "设备几乎所有的数据和设置,备份在这台Mac上。Peel会显示这里有什么。备份可在“系统设置”>“通用”>“储存空间”>“iOS文件”中或在“访达”中删除。"
}
},
"zh-Hant" : {
"stringUnit" : {
"state" : "translated",
- "value" : "裝置幾乎所有的資料和設定,已備份到這部Mac上。Peel會顯示這裡有什麼,其餘交由Finder處理。"
+ "value" : "裝置幾乎所有的資料和設定,已備份到這部Mac上。Peel會顯示這裡有什麼。備份可在「系統設定」>「一般」>「儲存空間」>「iOS檔案」中或在Finder中刪除。"
}
}
}
@@ -47301,108 +47301,108 @@
}
}
},
- "Firmware for restoring Apple devices, such as an iPhone, an iPad, or a Mac. It is downloaded again when a device needs it." : {
+ "Firmware for restoring Apple devices, such as an iPhone, an iPad, or a Mac. It is downloaded again when a device needs it. What Apple Configurator keeps stays in its own container, and is deleted in System Settings > General > Storage > iOS Files." : {
"localizations" : {
"cs" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Firmware pro obnovu zařízení Apple, jako je iPhone, iPad nebo Mac. Když ho zařízení potřebuje, stáhne se znovu."
+ "value" : "Firmware pro obnovu zařízení Apple, jako je iPhone, iPad nebo Mac. Když ho zařízení potřebuje, stáhne se znovu. Co uchovává Apple Configurator, zůstává v jeho vlastním kontejneru a maže se v Nastavení systému > Obecné > Úložiště > iOS soubory."
}
},
"de" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Firmware zum Wiederherstellen von Apple-Geräten wie iPhone, iPad oder Mac. Sie wird erneut geladen, wenn ein Gerät sie benötigt."
+ "value" : "Firmware zum Wiederherstellen von Apple-Geräten wie iPhone, iPad oder Mac. Sie wird erneut geladen, wenn ein Gerät sie benötigt. Was Apple Configurator aufbewahrt, bleibt in dessen eigenem Container und wird unter „Systemeinstellungen“ > „Allgemein“ > „Speicher“ > „iOS-Dateien“ gelöscht."
}
},
"es" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Firmware para restaurar dispositivos Apple, como un iPhone, un iPad o un Mac. Se vuelve a descargar cuando un dispositivo lo necesita."
+ "value" : "Firmware para restaurar dispositivos Apple, como un iPhone, un iPad o un Mac. Se vuelve a descargar cuando un dispositivo lo necesita. Lo que guarda Apple Configurator se queda en su propio contenedor y se elimina en Ajustes del Sistema > General > Almacenamiento > Archivos de iOS."
}
},
"fr" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Programme interne servant à restaurer des appareils Apple, comme un iPhone, un iPad ou un Mac. Il est téléchargé à nouveau lorsqu’un appareil en a besoin."
+ "value" : "Programme interne servant à restaurer des appareils Apple, comme un iPhone, un iPad ou un Mac. Il est téléchargé à nouveau lorsqu’un appareil en a besoin. Ce que conserve Apple Configurator reste dans son propre conteneur et se supprime dans Réglages Système > Général > Stockage > Fichiers iOS."
}
},
"it" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Firmware per ripristinare i dispositivi Apple, come iPhone, iPad o Mac. Viene scaricato di nuovo quando un dispositivo ne ha bisogno."
+ "value" : "Firmware per ripristinare i dispositivi Apple, come iPhone, iPad o Mac. Viene scaricato di nuovo quando un dispositivo ne ha bisogno. Ciò che Apple Configurator conserva resta nel suo contenitore e si elimina in Impostazioni di Sistema > Generali > Spazio > File iOS."
}
},
"ja" : {
"stringUnit" : {
"state" : "translated",
- "value" : "iPhone、iPad、MacなどのAppleデバイスを復元するためのファームウェアです。デバイスが必要とするときに再びダウンロードされます。"
+ "value" : "iPhone、iPad、MacなどのAppleデバイスを復元するためのファームウェアです。デバイスが必要とするときに再びダウンロードされます。Apple Configuratorが保管しているものはApple Configurator自身のコンテナに残ります。削除は、“システム設定”>“一般”>“ストレージ”>“iOSファイル”で行います。"
}
},
"ko" : {
"stringUnit" : {
"state" : "translated",
- "value" : "iPhone, iPad 또는 Mac 같은 Apple 기기를 복원하기 위한 펌웨어입니다. 기기에 필요할 때 다시 다운로드됩니다."
+ "value" : "iPhone, iPad 또는 Mac 같은 Apple 기기를 복원하기 위한 펌웨어입니다. 기기에 필요할 때 다시 다운로드됩니다. Apple Configurator가 보관하는 항목은 자체 컨테이너에 남으며, 시스템 설정 > 일반 > 저장 공간 > iOS 파일에서 삭제합니다."
}
},
"nl" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Firmware om Apple-apparaten te herstellen, zoals een iPhone, iPad of Mac. Die wordt opnieuw gedownload wanneer een apparaat die nodig heeft."
+ "value" : "Firmware om Apple-apparaten te herstellen, zoals een iPhone, iPad of Mac. Die wordt opnieuw gedownload wanneer een apparaat die nodig heeft. Wat Apple Configurator bewaart, blijft in zijn eigen container en wordt verwijderd in Systeeminstellingen > Algemeen > Opslag > iOS-bestanden."
}
},
"pl" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Oprogramowanie sprzętowe do odtwarzania urządzeń Apple, takich jak iPhone, iPad czy Mac. Jest pobierane ponownie, gdy urządzenie go potrzebuje."
+ "value" : "Oprogramowanie sprzętowe do odtwarzania urządzeń Apple, takich jak iPhone, iPad czy Mac. Jest pobierane ponownie, gdy urządzenie go potrzebuje. To, co zachowuje Apple Configurator, pozostaje w jego własnym kontenerze i usuwa się to w Ustawieniach systemowych > Ogólne > Miejsce > Pliki iOS."
}
},
"pt" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Firmware para restaurar dispositivos Apple, como um iPhone, um iPad ou um Mac. Ele é baixado de novo quando um dispositivo precisa dele."
+ "value" : "Firmware para restaurar dispositivos Apple, como um iPhone, um iPad ou um Mac. Ele é baixado de novo quando um dispositivo precisa dele. O que o Apple Configurator guarda fica no contêiner dele e é apagado em Ajustes do Sistema > Geral > Armazenamento > Arquivos do iOS."
}
},
"ro" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Firmware pentru restaurarea dispozitivelor Apple, cum ar fi un iPhone, un iPad sau un Mac. Se descarcă din nou când un dispozitiv are nevoie de el."
+ "value" : "Firmware pentru restaurarea dispozitivelor Apple, cum ar fi un iPhone, un iPad sau un Mac. Se descarcă din nou când un dispozitiv are nevoie de el. Ce păstrează Apple Configurator rămâne în propriul său container și se șterge din Configurări sistem > General > Stocare > Fișiere iOS."
}
},
"ru" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Прошивки для восстановления устройств Apple, например iPhone, iPad или Mac. Прошивка загружается снова, когда она нужна устройству."
+ "value" : "Прошивки для восстановления устройств Apple, например iPhone, iPad или Mac. Прошивка загружается снова, когда она нужна устройству. То, что хранит Apple Configurator, остается в его собственном контейнере и удаляется в разделе «Системные настройки» > «Основные» > «Хранилище» > «Файлы iOS»."
}
},
"sv" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Fast programvara för att återställa Apple-enheter, till exempel en iPhone, en iPad eller en Mac. Den hämtas igen när en enhet behöver den."
+ "value" : "Fast programvara för att återställa Apple-enheter, till exempel en iPhone, en iPad eller en Mac. Den hämtas igen när en enhet behöver den. Det som Apple Configurator sparar stannar i appens egen behållare och raderas i Systeminställningar > Allmänt > Lagring > iOS-filer."
}
},
"tr" : {
"stringUnit" : {
"state" : "translated",
- "value" : "iPhone, iPad veya Mac gibi Apple aygıtlarını geri yüklemek için firmware. Bir aygıt ihtiyaç duyduğunda yeniden indirilir."
+ "value" : "iPhone, iPad veya Mac gibi Apple aygıtlarını geri yüklemek için firmware. Bir aygıt ihtiyaç duyduğunda yeniden indirilir. Apple Configurator’ın tuttukları kendi kapsayıcısında kalır ve Sistem Ayarları > Genel > Saklama Alanı > iOS Dosyaları bölümünde silinir."
}
},
"uk" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Прошивки для відновлення пристроїв Apple, як-от iPhone, iPad чи Mac. Їх буде викачано знову, коли пристрій цього потребуватиме."
+ "value" : "Прошивки для відновлення пристроїв Apple, як-от iPhone, iPad чи Mac. Їх буде викачано знову, коли пристрій цього потребуватиме. Те, що зберігає Apple Configurator, лишається в його власному контейнері, а видаляють це в розділі Системні параметри > Загальні > Сховище > Файли iOS."
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "用于恢复Apple设备(例如iPhone、iPad或Mac)的固件。设备需要时会重新下载。"
+ "value" : "用于恢复Apple设备(例如iPhone、iPad或Mac)的固件。设备需要时会重新下载。Apple Configurator保留的内容位于它自己的容器中,可在“系统设置”>“通用”>“储存空间”>“iOS文件”中删除。"
}
},
"zh-Hant" : {
"stringUnit" : {
"state" : "translated",
- "value" : "用於回復Apple裝置(例如iPhone、iPad或Mac)的韌體。裝置需要時會重新下載。"
+ "value" : "用於回復Apple裝置(例如iPhone、iPad或Mac)的韌體。裝置需要時會重新下載。Apple Configurator保留的項目會留在它自己的容器中,可在「系統設定」>「一般」>「儲存空間」>「iOS檔案」中刪除。"
}
}
}
diff --git a/Peel/Model/InstallerLibrary.swift b/Peel/Model/InstallerLibrary.swift
index 9f80d076..f58e4606 100644
--- a/Peel/Model/InstallerLibrary.swift
+++ b/Peel/Model/InstallerLibrary.swift
@@ -5,7 +5,15 @@ import PeelCore
@Observable
final class InstallerLibrary {
+ /// How long what a scan saw is shown before the page, appearing or with Peel coming forward, looks again: the
+ /// shortest time a reason beside a row speaks of.
+ static let scanAgainAfter: Duration = .seconds(60 * 60)
+
private(set) var scan: InstallerScan?
+ /// What the search in the list holds. A page's rows narrow with it, unless it names the page.
+ var searchText = ""
+ private let scanning: @Sendable ([InstalledApp], Exclusions) async -> InstallerScan
+ @ObservationIgnored private var scannedAt: ContinuousClock.Instant?
/// The scan this page runs, which a newer one or the Stop button ends.
let scanRun = ScanRun()
var isScanning: Bool { scanRun.isRunning }
@@ -13,6 +21,14 @@ final class InstallerLibrary {
var selection: InstallerItem.Kind?
var selectedURLs: Set<URL> = []
+ init(
+ scanning: @escaping @Sendable ([InstalledApp], Exclusions) async -> InstallerScan = {
+ await Installers.scan(installedApps: $0, exclusions: $1)
+ }
+ ) {
+ self.scanning = scanning
+ }
+
var sections: [InstallerItem.Kind] {
InstallerItem.Kind.allCases.filter { !items(in: $0).isEmpty }
}
@@ -21,6 +37,13 @@ final class InstallerLibrary {
scan?.items(in: kind) ?? []
}
+ /// The rows a kind's page shows while the list is searched.
+ func shownItems(in kind: InstallerItem.Kind) -> [InstallerItem] {
+ let items = items(in: kind)
+ guard !searchText.isEmpty, !SearchText.matches(String(localized: kind.title), searchText) else { return items }
+ return items.filter { $0.matches(searchText) }
+ }
+
var needsFullDiskAccess: Bool {
scan?.needsFullDiskAccess ?? false
}
@@ -38,12 +61,21 @@ final class InstallerLibrary {
selected.subtracting(items.filter { $0.isLocked(canUseHelper: canUseHelper) }.map(\.url))
}
+ /// Scans unless the last scan ended less than `age` ago, one or a removal runs, or the last scan was stopped: a
+ /// reason beside a row speaks of the last hour or of what runs now, so what a scan saw ages.
+ func refreshUnlessScanned(within age: Duration, installedApps: [InstalledApp]) async {
+ guard !scanRun.isWaitedFor, !isRemoving, !scanRun.wasStopped else { return }
+ if let scannedAt, ContinuousClock.now - scannedAt < age { return }
+ await refresh(installedApps: installedApps)
+ }
+
func refresh(installedApps: [InstalledApp]) async {
guard
- let result = await scanRun.run({
- await Installers.scan(installedApps: installedApps, exclusions: ExclusionsStore.shared.exclusions)
+ let result = await scanRun.run({ [scanning] in
+ await scanning(installedApps, ExclusionsStore.shared.exclusions)
})
else { return }
+ scannedAt = .now
scan = result
selectedURLs.formIntersection(Set(result.items.filter { $0.heldBack?.cannotBeMoved != true }.map(\.url)))
if let selection, result.items(in: selection).isEmpty {
@@ -120,8 +152,8 @@ nonisolated extension InstallerItem.Kind {
switch self {
case .appInstaller: "Disk images, packages, and archives holding an app or an installer, in Downloads, Desktop, Documents, Public, and Shared, and in the folders directly inside them, where installers are usually left, and packages in the folders apps keep in Application Support. A disk image can also be one you made to keep files in. What an installer installed stays where it is."
case .macOSInstaller: "A full copy of macOS, ready to install. Apple offers the newest release again to any Mac that can run it."
- case .firmware: "Firmware for restoring Apple devices, such as an iPhone, an iPad, or a Mac. It is downloaded again when a device needs it."
- case .deviceBackup: "Almost all of a device’s data and settings, backed up to this Mac. Peel shows what is here and leaves the rest to Finder."
+ case .firmware: "Firmware for restoring Apple devices, such as an iPhone, an iPad, or a Mac. It is downloaded again when a device needs it. What Apple Configurator keeps stays in its own container, and is deleted in System Settings > General > Storage > iOS Files."
+ case .deviceBackup: "Almost all of a device’s data and settings, backed up to this Mac. Peel shows what is here. A backup is deleted in System Settings > General > Storage > iOS Files, or in Finder."
case .incompleteDownload: "Downloads never finished, still under the name a file has until its download ends: .crdownload for Chrome and the browsers built on Chromium, .part for Firefox and programs such as torrent clients, and .download for Safari."
case .updateDownload: "Updates an app downloaded with Sparkle, Squirrel, or electron-updater and keeps in its caches until it installs them. If one is gone, the app downloads it again the next time it updates."
}
diff --git a/Peel/Views/Installers/InstallerDetailView.swift b/Peel/Views/Installers/InstallerDetailView.swift
index 53762618..02e74154 100644
--- a/Peel/Views/Installers/InstallerDetailView.swift
+++ b/Peel/Views/Installers/InstallerDetailView.swift
@@ -93,7 +93,7 @@ struct InstallerDetailView: View {
}
private var items: [InstallerItem] {
- installers.items(in: kind)
+ installers.shownItems(in: kind)
}
private func header(_ rows: [InstallerItem]) -> some View {
@@ -109,7 +109,7 @@ struct InstallerDetailView: View {
}
} trailing: {
TotalLabel(
- total: kind == .deviceBackup ? SizeTotal(rows.map(\.size)) : rows.movable(canUseHelper: helper.canAct),
+ total: rows.shownTotal(of: kind, canUseHelper: helper.canAct),
caption: Text(kind == .deviceBackup ? "on this Mac" : "to remove")
)
}
diff --git a/Peel/Views/Installers/InstallerList.swift b/Peel/Views/Installers/InstallerList.swift
index ade98968..98e82189 100644
--- a/Peel/Views/Installers/InstallerList.swift
+++ b/Peel/Views/Installers/InstallerList.swift
@@ -1,3 +1,4 @@
+import AppKit
import PeelCore
import SwiftUI
@@ -6,15 +7,10 @@ struct InstallerList: View {
@Environment(InstallerLibrary.self) private var installers
@Environment(HelperModel.self) private var helper
@State private var isRescanning = false
- @State private var searchText = ""
/// The kinds to list. During a search, a kind is kept when its title or any of its items matches.
private var listed: [InstallerItem.Kind] {
- guard !searchText.isEmpty else { return installers.sections }
- return installers.sections.filter { kind in
- SearchText.matches(String(localized: kind.title), searchText)
- || installers.items(in: kind).contains { $0.matches(searchText) }
- }
+ installers.sections.filter { !installers.shownItems(in: $0).isEmpty }
}
var body: some View {
@@ -26,13 +22,18 @@ struct InstallerList: View {
UnreadableFoldersNotice(folders: installers.unreadable, needsFullDiskAccess: true)
}
ForEach(filtered, id: \.self) { kind in
- let items = installers.items(in: kind)
- SectionRow(kind: kind, count: items.count, size: SizeTotal(items.map(\.size)))
+ let items = installers.shownItems(in: kind)
+ SectionRow(
+ kind: kind, count: items.count,
+ size: items.shownTotal(of: kind, canUseHelper: helper.canAct)
+ )
.tag(kind)
}
}
.accessibilityLabel(Text(Tool.installers.title))
- .columnSearch(text: $searchText, prompt: "Search Installers and Backups", when: !installers.sections.isEmpty)
+ .columnSearch(
+ text: $installers.searchText, prompt: "Search Installers and Backups", when: !installers.sections.isEmpty
+ )
.scanState(phase(filtered), isRescanning: isRescanning, scan: installers.scanRun) {
if installers.sections.isEmpty, installers.needsFullDiskAccess {
ContentUnavailableView {
@@ -52,7 +53,7 @@ struct InstallerList: View {
description: Text("Peel found no installers, device firmware, unfinished downloads, or downloaded updates of \(Installers.minimumSize.byteCount) or more, and no iPhone or iPad backups.")
)
} else if filtered.isEmpty {
- ContentUnavailableView.search(text: searchText)
+ ContentUnavailableView.search(text: installers.searchText)
}
}
.fadesInColumn(whenRowsChange: installers.scan?.items.map(\.id))
@@ -68,7 +69,7 @@ struct InstallerList: View {
ToolbarItem {
SelectOnEveryPage(
pages: SelectablePages(filtered.map { kind in
- (kind.page, installers.items(in: kind).selectableRows(canUseHelper: helper.canAct))
+ (kind.page, installers.shownItems(in: kind).selectableRows(canUseHelper: helper.canAct))
}),
selection: installers
) { page in
@@ -89,10 +90,16 @@ struct InstallerList: View {
}
}
.task(id: library.hasLoaded) {
- guard library.hasLoaded, installers.scan == nil, !installers.scanRun.isWaitedFor,
- !installers.scanRun.wasStopped
- else { return }
- await installers.refresh(installedApps: library.apps)
+ guard library.hasLoaded else { return }
+ await installers.refreshUnlessScanned(within: InstallerLibrary.scanAgainAfter, installedApps: library.apps)
+ }
+ .onReceive(NotificationCenter.default.publisher(for: NSApplication.didBecomeActiveNotification)) { _ in
+ guard library.hasLoaded else { return }
+ Task {
+ await installers.refreshUnlessScanned(
+ within: InstallerLibrary.scanAgainAfter, installedApps: library.apps
+ )
+ }
}
.rescanOnExclusionChange("InstallerList") { await installers.refresh(installedApps: library.apps) }
.rescanAfterPutBack(.installers) { await installers.refresh(installedApps: library.apps) }
diff --git a/PeelTests/InstallerSelectionTests.swift b/PeelTests/InstallerSelectionTests.swift
index 6ac409b2..bf848342 100644
--- a/PeelTests/InstallerSelectionTests.swift
+++ b/PeelTests/InstallerSelectionTests.swift
@@ -1,10 +1,63 @@
import Foundation
@testable import Peel
@testable import PeelCore
+import Synchronization
import Testing
@MainActor
struct InstallerSelectionTests {
+ private func item(_ name: String, kind: InstallerItem.Kind = .appInstaller, size: Int64 = 10) -> InstallerItem {
+ InstallerItem(
+ url: URL(filePath: "/Users/me/Downloads/\(name)"), kind: kind, name: name, size: size, date: nil,
+ installedApp: nil, isReadOnly: false, notes: []
+ )
+ }
+
+ @Test func scansAgainOnlyOnceItsLastScanIsOld() async {
+ let scans = Mutex(0)
+ let library = InstallerLibrary { _, _ in
+ scans.withLock { $0 += 1 }
+ return InstallerScan(items: [], unreadableLocations: [])
+ }
+
+ await library.refreshUnlessScanned(within: .seconds(3_600), installedApps: [])
+ await library.refreshUnlessScanned(within: .seconds(3_600), installedApps: [])
+ #expect(scans.withLock { $0 } == 1)
+ await library.refreshUnlessScanned(within: .zero, installedApps: [])
+ #expect(scans.withLock { $0 } == 2)
+ }
+
+ @Test func aSearchNarrowsThePageUnlessItNamesThePage() async {
+ let items = [item("Firefox.dmg"), item("Chrome.dmg"), item("Install macOS", kind: .macOSInstaller)]
+ let library = InstallerLibrary { _, _ in InstallerScan(items: items, unreadableLocations: []) }
+ await library.refresh(installedApps: [])
+
+ #expect(library.shownItems(in: .appInstaller).count == 2)
+ library.searchText = "firefox"
+ #expect(library.shownItems(in: .appInstaller).map(\.name) == ["Firefox.dmg"])
+ library.searchText = "app installers"
+ #expect(library.shownItems(in: .appInstaller).count == 2)
+ #expect(library.shownItems(in: .macOSInstaller).isEmpty)
+ }
+
+ @Test func anUpdateChosenByHandWaitsForItsAppToQuit() async {
+ var running = item("org.example.running", kind: .updateDownload)
+ running.updatesApp = InstallerItem.UpdatedApp(identifier: "com.apple.finder", name: "Finder")
+ var closed = item("org.example.closed", kind: .updateDownload)
+ closed.updatesApp = InstallerItem.UpdatedApp(identifier: "org.example.closed", name: "Closed")
+ let items = [running, closed]
+ let library = InstallerLibrary { _, _ in InstallerScan(items: items, unreadableLocations: []) }
+ await library.refresh(installedApps: [])
+ let page = InstallerItem.Kind.updateDownload.page
+
+ library.selectedURLs = [closed.url]
+ let free = library.carriedParts.first { $0.page == page }
+ #expect(free.flatMap(library.appToQuit(for:)) == nil)
+ library.selectedURLs = [closed.url, running.url]
+ let kept = library.carriedParts.first { $0.page == page }
+ #expect(kept.flatMap(library.appToQuit(for:)) == "Finder")
+ }
+
@Test func takesWhatWaitsForTheHelperOutOfTheSelection() {
let macOS = URL(filePath: "/Applications/Install macOS Tahoe.app", directoryHint: .isDirectory)
let image = URL(filePath: "/Users/me/Downloads/Tool.dmg")