Skip to content

Free, open-source macOS cleaner. CleanMyMac alternative with zero telemetry. Native SwiftUI, scheduled auto-cleaning, Xcode/Homebrew/system cache cleanup. MIT licensed.

Redesign Mac care and add storage and maintenance tools

momenbasel316778c049b6
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index e85a8ae..585ec8d 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -18,6 +18,15 @@ jobs:
- name: Generate Xcode project
run: xcodegen generate
+ - name: Test
+ run: |
+ xcodebuild -project PureMac.xcodeproj \
+ -scheme PureMac \
+ -configuration Debug \
+ -destination 'platform=macOS' \
+ -derivedDataPath build-tests \
+ CODE_SIGNING_ALLOWED=NO test
+
- name: Build (Universal Binary)
run: |
xcodebuild -project PureMac.xcodeproj \
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index ded51a9..bda227a 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -149,6 +149,16 @@ jobs:
# Verify identity loaded
security find-identity -v -p codesigning "${KEYCHAIN_PATH}" | grep "Developer ID Application: Moamen Basel"
+ - name: Run tests before signing
+ run: |
+ set -euo pipefail
+ xcodebuild -project "${PROJECT}" \
+ -scheme "${SCHEME}" \
+ -configuration Debug \
+ -destination 'platform=macOS' \
+ -derivedDataPath build-tests \
+ CODE_SIGNING_ALLOWED=NO test | xcbeautify
+
- name: Archive (universal arm64 + x86_64)
run: |
set -euo pipefail
@@ -321,7 +331,16 @@ jobs:
echo ""
echo "Universal binary (Intel + Apple Silicon). Signed with Developer ID + notarized + stapled by Apple."
echo ""
- if [[ "${VERSION}" == "2.9.8" ]]; then
+ if [[ "${VERSION}" == "3.0.0" ]]; then
+ echo "### What changed"
+ echo "- Redesigned dashboard and navigation, with clearer storage and cleanup review."
+ echo "- New Space Explorer, exact Duplicate Finder, and Similar Photos review."
+ echo "- Protection checks, startup and snapshot inspection, and Homebrew app updates."
+ echo "- Cleanup filters, persistent exclusions, stop-scan support, and safer removal confirmations."
+ echo ""
+ echo "Protection checks inspect macOS settings; they are not a malware scanner. App updates cover Homebrew casks. Similar Photos groups images for manual review."
+ echo ""
+ elif [[ "${VERSION}" == "2.9.8" ]]; then
echo "### What changed"
echo ""
echo "- Fixed switching Appearance from Dark back to System so the entire window updates immediately (#152)."
@@ -341,8 +360,7 @@ jobs:
echo "### Install"
echo ""
echo "\`\`\`"
- echo "brew tap momenbasel/tap"
- echo "brew install --cask puremac"
+ echo "brew install --cask momenbasel/tap/puremac"
echo "\`\`\`"
} > "${NOTES_FILE}"
}
diff --git a/PureMac.xcodeproj/project.pbxproj b/PureMac.xcodeproj/project.pbxproj
index fbde2a1..8387067 100644
--- a/PureMac.xcodeproj/project.pbxproj
+++ b/PureMac.xcodeproj/project.pbxproj
@@ -8,57 +8,80 @@
/* Begin PBXBuildFile section */
013EF7B96BF046D4DB38FBC5 /* Localizable.strings in Resources */ = {isa = PBXBuildFile; fileRef = 241E0895B09C71AB423B2F9E /* Localizable.strings */; };
+ 0BB6BC2EAFB02407FBC6CDA6 /* ApplicationUpdater.swift in Sources */ = {isa = PBXBuildFile; fileRef = 59873E44B520DE069F80CCD6 /* ApplicationUpdater.swift */; };
+ 0CC9A41781D1B1883279693E /* ProtectionView.swift in Sources */ = {isa = PBXBuildFile; fileRef = F270D47D1DD94D4577482B90 /* ProtectionView.swift */; };
+ 10959A68B277AEF7D2442C48 /* StorageExplorerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 78B8E84105970F69BBAB638F /* StorageExplorerTests.swift */; };
1B0D043102FDB245312A5147 /* AppFilesView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 798B80977D14647A5691B0A0 /* AppFilesView.swift */; };
2253F11BDF561B617439C96B /* FullDiskAccessManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = E866A1541D289C69144A5E62 /* FullDiskAccessManager.swift */; };
25E2304A3FF257F1740E304B /* FileProtection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7953B398E47A4C603DE287F1 /* FileProtection.swift */; };
27F449EDD1B082FE11FEC9DF /* SchedulerService.swift in Sources */ = {isa = PBXBuildFile; fileRef = 28181F034530331A550C6A3D /* SchedulerService.swift */; };
+ 2BCDC53C5E3AB58442C8E4B0 /* CleaningEngineTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 22B679C0120F1E3DDCB27FE2 /* CleaningEngineTests.swift */; };
340E424F759ACCDE7372F99F /* Theme.swift in Sources */ = {isa = PBXBuildFile; fileRef = C5ADDC35F31E40780FB5D017 /* Theme.swift */; };
39BEE5E2BEC526CCADFC9DDD /* ServicesMenu.strings in Resources */ = {isa = PBXBuildFile; fileRef = 57FBBF8C7EF27C8E09126ED5 /* ServicesMenu.strings */; };
41B27CACD7C6C7471EFD03F9 /* UpdateService.swift in Sources */ = {isa = PBXBuildFile; fileRef = 022D0EAEE2B6E54069FC2CBE /* UpdateService.swift */; };
47C5ECD49C4DD75F271DB6CE /* StringNormalization.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1D3AC5F17D7CA94FAB1E8D7A /* StringNormalization.swift */; };
48D1431A7C99C19EEBDB056B /* CleaningEngine.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2A8DE5D45BA19E2670B57DC5 /* CleaningEngine.swift */; };
+ 4D33329ABDA67E35B3FC5B85 /* SimilarPhotoFinder.swift in Sources */ = {isa = PBXBuildFile; fileRef = B97348789EA68B1ABADB1421 /* SimilarPhotoFinder.swift */; };
4F754D89F4CE5142BE384062 /* AppConstants.swift in Sources */ = {isa = PBXBuildFile; fileRef = F31F91226CDCFBB8E303B7DA /* AppConstants.swift */; };
+ 4FAAA6E9887181C4C0AA9F87 /* DuplicateFinderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = D379BB1C513985CF9AB783D5 /* DuplicateFinderTests.swift */; };
50304378D99F2E9E48B642AF /* Sparkle in Frameworks */ = {isa = PBXBuildFile; productRef = 9CC8F66E27BE52A6639E904B /* Sparkle */; };
52F11962555C639F0EECADD6 /* FDADemoView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 231FF7CBB5F621B66F2AB8A5 /* FDADemoView.swift */; };
535B23C0108C06475215B8E8 /* AppTheme.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1AB003A7751F05727DBFD1A5 /* AppTheme.swift */; };
+ 5882104828B9C5A5E06B2AFB /* PerformanceView.swift in Sources */ = {isa = PBXBuildFile; fileRef = D84FB753A60BE6BF54D5126A /* PerformanceView.swift */; };
59B3096E2AE8ED0397B16798 /* AppLanguagePreferencesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 491771F923C93FD61A263893 /* AppLanguagePreferencesTests.swift */; };
+ 5ED9C7AA76D850363CDC127C /* SimilarPhotosView.swift in Sources */ = {isa = PBXBuildFile; fileRef = F3C3342D6386FBB6DE3D18BC /* SimilarPhotosView.swift */; };
61D285E96DED76FDCD54570F /* PermissionSheet.swift in Sources */ = {isa = PBXBuildFile; fileRef = 069AAE87E3F9EDE5593AD8B3 /* PermissionSheet.swift */; };
6753946A301B2EB2FEF6998B /* SimulatorRuntimeSupport.swift in Sources */ = {isa = PBXBuildFile; fileRef = D74E66594478F53363BCB0F9 /* SimulatorRuntimeSupport.swift */; };
68F9CE5ED4908F674D673FB2 /* BinaryThinner.swift in Sources */ = {isa = PBXBuildFile; fileRef = 69B24B648B82186FC3B6EF2B /* BinaryThinner.swift */; };
+ 6BCC5E3773DF2E9189F75A6B /* CleanupReviewTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6116C5E9B68F439F6B2E42E5 /* CleanupReviewTests.swift */; };
+ 6D36632DFF74F26035204CE2 /* PerformanceInspectorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 043F28E28FB7B2D9E39E5F70 /* PerformanceInspectorTests.swift */; };
6D449325D54B9850FC6C119F /* UniversalBinaryScanner.swift in Sources */ = {isa = PBXBuildFile; fileRef = 95EC878D25C244BF94D0094C /* UniversalBinaryScanner.swift */; };
6E72022A661CBB41331A442C /* PermissionCoordinator.swift in Sources */ = {isa = PBXBuildFile; fileRef = F9DCBD97CC88D77AE8DB01A4 /* PermissionCoordinator.swift */; };
+ 74175B10C464D245E99BA6DB /* DuplicateFinderView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1343918E4CD9C8DA99EFA588 /* DuplicateFinderView.swift */; };
75B5F0401D37F2872B1AD85A /* AppListView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 60E6BC61614B27C065BB18C9 /* AppListView.swift */; };
76B132F9C499225D33E0D075 /* EmptyStateView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 424F7B28624C271620E13BBC /* EmptyStateView.swift */; };
+ 7796BCD9AB92D1A644C28AF3 /* StorageExplorer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8CF68B6BB9ED70387DF56728 /* StorageExplorer.swift */; };
826A750D2D7EC14C2AE306A3 /* Models.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3667D46D8E2004EB4D73835A /* Models.swift */; };
8947F0CE448791BD50EECF46 /* Conditions.swift in Sources */ = {isa = PBXBuildFile; fileRef = CB94E06E145558123BB5BFB3 /* Conditions.swift */; };
8B541441926847072DC5B75B /* DashboardCharts.swift in Sources */ = {isa = PBXBuildFile; fileRef = 08C60E04A0CA3F227816DB63 /* DashboardCharts.swift */; };
91751CF033E1541BFD39B12C /* MenuBarMonitorView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A27DB5A70FA829B6C3ED0AC3 /* MenuBarMonitorView.swift */; };
93743B036059418560D876E6 /* SettingsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3A8D39C3C250F26302EC45AB /* SettingsView.swift */; };
+ 94EA77AE33FBB24655EC19C5 /* ProtectionAuditTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 853B6D91596DB63ACE660F74 /* ProtectionAuditTests.swift */; };
95278ABDCF5F4D6AC60503B1 /* AppearancePill.swift in Sources */ = {isa = PBXBuildFile; fileRef = 92259B3E9F4468865F15DEEC /* AppearancePill.swift */; };
9AA80E035DF7B33F6EE118DF /* AppState.swift in Sources */ = {isa = PBXBuildFile; fileRef = CED1B71D5F9510582E869CFD /* AppState.swift */; };
9BB5AAA574AFED6C27A3F8E2 /* AppPathFinder.swift in Sources */ = {isa = PBXBuildFile; fileRef = AC0FEE7141871ED5F9E36121 /* AppPathFinder.swift */; };
+ 9D73A00AC536CD2D9BB5F882 /* CleanupReview.swift in Sources */ = {isa = PBXBuildFile; fileRef = D00EEBBBA38CC4B3F8077E7D /* CleanupReview.swift */; };
9E3639F9EFCB2A22F6747894 /* MenuBarController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 913E3064AA9BD7BE94A315CF /* MenuBarController.swift */; };
9E87638A3F12C12D93995DA7 /* LanguageFilesScanner.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0899FE169D270DF95334905 /* LanguageFilesScanner.swift */; };
A2AE68CC75CB72D6B10CBDF5 /* DashboardView.swift in Sources */ = {isa = PBXBuildFile; fileRef = F661A0F64CF93E482CB1728F /* DashboardView.swift */; };
A549D8A39A9E5E70D91B90A6 /* Haptics.swift in Sources */ = {isa = PBXBuildFile; fileRef = 40A3F22FCEF534DE4A2CAD0E /* Haptics.swift */; };
A9C3A1F643C26930F442E729 /* OrphanSafetyPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4AE790496C936424EF98320A /* OrphanSafetyPolicy.swift */; };
+ AA25686857BF1CB9250FC0E8 /* SimilarPhotoFinderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4144A1B8F1D52D44A6E8E726 /* SimilarPhotoFinderTests.swift */; };
ABDDD4F35102A39CC1A2C325 /* ConfettiView.swift in Sources */ = {isa = PBXBuildFile; fileRef = F0599AA604B0D6BA4F957537 /* ConfettiView.swift */; };
ABE3B80279483DB90B8EC1BC /* ThemeManagerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 55CE234DB2DB54ED53A4EFD6 /* ThemeManagerTests.swift */; };
B51E5A95BB49A6C0F5273E21 /* FileSize.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8CE522B406791BCE905BC55B /* FileSize.swift */; };
B52938BBD11842631314543D /* CategoryDetailView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 10B0AF194677EAC1D5568785 /* CategoryDetailView.swift */; };
+ B69BD60D8AB7EBB9F80C9965 /* CleanupExclusionsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C167DFBCD14DC84725EF15F /* CleanupExclusionsTests.swift */; };
B928E4369A3FC4369F014A29 /* SmartCareCoreArtwork.swift in Sources */ = {isa = PBXBuildFile; fileRef = DAA389C4F50505795FB31A51 /* SmartCareCoreArtwork.swift */; };
BB10A9AFDA394F918E068351 /* InfoPlist.strings in Resources */ = {isa = PBXBuildFile; fileRef = B55B1419D88851567DFB783A /* InfoPlist.strings */; };
BC6C800216343438413349A3 /* OnboardingView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3D4FD34378988D430A582ED0 /* OnboardingView.swift */; };
+ C85B54037A5989A85968F328 /* AppUpdatesView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5A0AF1B9C42A20B6C9FC2DD9 /* AppUpdatesView.swift */; };
CDCDFEBA39A3290101F86AC6 /* MainWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9F510F232341EE18F11DC934 /* MainWindow.swift */; };
CFA64F54CDBF8A4765E0068D /* LocalizationFilesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 155CE1B8CDCCCA6F9FD028C1 /* LocalizationFilesTests.swift */; };
+ D0E6B0AFF83228F121B4DDD3 /* DuplicateFinder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 089D484A0482787027665936 /* DuplicateFinder.swift */; };
+ D15B7A053D69D4348D9DCD88 /* ApplicationUpdaterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F77B9D7D5353CD42BD03ADBB /* ApplicationUpdaterTests.swift */; };
D50EB059E741011EB2523731 /* ScanError.swift in Sources */ = {isa = PBXBuildFile; fileRef = EEF15CB1B8EFCA78EF491824 /* ScanError.swift */; };
D9445C2641A8637B65DA5ACE /* ScanEngine.swift in Sources */ = {isa = PBXBuildFile; fileRef = A711CDF5285F68775D9B5513 /* ScanEngine.swift */; };
+ DAB58AB235C609464B5FF5B1 /* SpaceExplorerView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5EB777A06A7BFD324FFABB83 /* SpaceExplorerView.swift */; };
DBFD73E3D9BDA74EC1CA56AB /* SystemMonitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = DB798781B99987F55D77E2E3 /* SystemMonitor.swift */; };
DC32253D26D0E29762006DA0 /* AppBundleDragHandle.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2D3F9FEDC493A8E49E910F67 /* AppBundleDragHandle.swift */; };
DDD6BA35DBF32E7A6B5F6F8B /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = B2EA41E1096FA8E3B916AD13 /* Assets.xcassets */; };
DDDA5879006CB97D5D7BDD87 /* Logger.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5785762276FB5E3209C6DE4D /* Logger.swift */; };
E2403D82F00D749C9AD4A6D4 /* AppStateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 752603285F7DBBA12BB3AA91 /* AppStateTests.swift */; };
+ E4145581C55556DB43725FBB /* NodeCachePathTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5984F53676A523D97AF2A89 /* NodeCachePathTests.swift */; };
+ E4A14812146CC0A379644E74 /* CleanupExclusions.swift in Sources */ = {isa = PBXBuildFile; fileRef = EDBC9DA7C5043AD9A873BA03 /* CleanupExclusions.swift */; };
E60B0A2C5D0A6CAE35BF4DFB /* Locations.swift in Sources */ = {isa = PBXBuildFile; fileRef = 77D3D9A9BC52839E6D0A22BC /* Locations.swift */; };
+ E69ECB1F931950E9DE5BE251 /* PerformanceInspector.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5C8619CA3ECD70CBBC96475C /* PerformanceInspector.swift */; };
E726702EABBE56155861DBA9 /* AppLanguage.swift in Sources */ = {isa = PBXBuildFile; fileRef = 82BB0904726B38DEB141BECA /* AppLanguage.swift */; };
EDEF28CAD23E936FBED1783B /* PureMacApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = 63581B70F9B10231964E3602 /* PureMacApp.swift */; };
F1F506C146E17D6CEC4A12F3 /* AppInfoFetcher.swift in Sources */ = {isa = PBXBuildFile; fileRef = 23486A54A82EE3865B784D1C /* AppInfoFetcher.swift */; };
@@ -66,6 +89,7 @@
F4F02F966001A1504C2B4D33 /* SimulatorRuntimeSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C7D81BE7EA5DB17F4A0300AD /* SimulatorRuntimeSupportTests.swift */; };
FBEE9208E222616A8DF1FE75 /* ProviderPaths.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8AFB912A9A6CFDCB972E978F /* ProviderPaths.swift */; };
FDA30FE6349CA01C8D859F04 /* OrphanListView.swift in Sources */ = {isa = PBXBuildFile; fileRef = B71E8F62DB76D85F41F9A2E9 /* OrphanListView.swift */; };
+ FF6B92CAF96A58625A56A1C0 /* ProtectionAudit.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6F9B44A9C1B4065126789622 /* ProtectionAudit.swift */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
@@ -82,14 +106,18 @@
01B2C5F66B6D812572BD4F05 /* CLI.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CLI.swift; sourceTree = "<group>"; };
022D0EAEE2B6E54069FC2CBE /* UpdateService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UpdateService.swift; sourceTree = "<group>"; };
02E502E2B5C6AECC76E5CFEF /* zh-Hant */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = "zh-Hant"; path = "zh-Hant.lproj/Localizable.strings"; sourceTree = "<group>"; };
+ 043F28E28FB7B2D9E39E5F70 /* PerformanceInspectorTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PerformanceInspectorTests.swift; sourceTree = "<group>"; };
069AAE87E3F9EDE5593AD8B3 /* PermissionSheet.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PermissionSheet.swift; sourceTree = "<group>"; };
+ 089D484A0482787027665936 /* DuplicateFinder.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DuplicateFinder.swift; sourceTree = "<group>"; };
08C60E04A0CA3F227816DB63 /* DashboardCharts.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DashboardCharts.swift; sourceTree = "<group>"; };
0A544093C897FBCBA8E256F9 /* fr */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = fr; path = fr.lproj/InfoPlist.strings; sourceTree = "<group>"; };
10B0AF194677EAC1D5568785 /* CategoryDetailView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CategoryDetailView.swift; sourceTree = "<group>"; };
+ 1343918E4CD9C8DA99EFA588 /* DuplicateFinderView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DuplicateFinderView.swift; sourceTree = "<group>"; };
155CE1B8CDCCCA6F9FD028C1 /* LocalizationFilesTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LocalizationFilesTests.swift; sourceTree = "<group>"; };
1AB003A7751F05727DBFD1A5 /* AppTheme.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppTheme.swift; sourceTree = "<group>"; };
1C0D9A6F75D0B8ADDB32FC2A /* uk */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = uk; path = uk.lproj/Localizable.strings; sourceTree = "<group>"; };
1D3AC5F17D7CA94FAB1E8D7A /* StringNormalization.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StringNormalization.swift; sourceTree = "<group>"; };
+ 22B679C0120F1E3DDCB27FE2 /* CleaningEngineTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CleaningEngineTests.swift; sourceTree = "<group>"; };
231FF7CBB5F621B66F2AB8A5 /* FDADemoView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FDADemoView.swift; sourceTree = "<group>"; };
23486A54A82EE3865B784D1C /* AppInfoFetcher.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppInfoFetcher.swift; sourceTree = "<group>"; };
25D1CF5248C1D471BCBD212F /* fr */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = fr; path = fr.lproj/ServicesMenu.strings; sourceTree = "<group>"; };
@@ -105,27 +133,38 @@
3D4FD34378988D430A582ED0 /* OnboardingView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OnboardingView.swift; sourceTree = "<group>"; };
40A3F22FCEF534DE4A2CAD0E /* Haptics.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Haptics.swift; sourceTree = "<group>"; };
40CD4855FB5FA866CAA52C10 /* en */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = en; path = en.lproj/InfoPlist.strings; sourceTree = "<group>"; };
+ 4144A1B8F1D52D44A6E8E726 /* SimilarPhotoFinderTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SimilarPhotoFinderTests.swift; sourceTree = "<group>"; };
424F7B28624C271620E13BBC /* EmptyStateView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = EmptyStateView.swift; sourceTree = "<group>"; };
44392E486177839BA978685E /* en */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = en; path = en.lproj/ServicesMenu.strings; sourceTree = "<group>"; };
46660271CFF167AB0FE7371D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist; path = Info.plist; sourceTree = "<group>"; };
491771F923C93FD61A263893 /* AppLanguagePreferencesTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppLanguagePreferencesTests.swift; sourceTree = "<group>"; };
4AE790496C936424EF98320A /* OrphanSafetyPolicy.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OrphanSafetyPolicy.swift; sourceTree = "<group>"; };
+ 4C167DFBCD14DC84725EF15F /* CleanupExclusionsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CleanupExclusionsTests.swift; sourceTree = "<group>"; };
55CE234DB2DB54ED53A4EFD6 /* ThemeManagerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ThemeManagerTests.swift; sourceTree = "<group>"; };
5664D2BDAEAA9AE3A53DB364 /* PureMac.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = PureMac.entitlements; sourceTree = "<group>"; };
5785762276FB5E3209C6DE4D /* Logger.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Logger.swift; sourceTree = "<group>"; };
+ 59873E44B520DE069F80CCD6 /* ApplicationUpdater.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ApplicationUpdater.swift; sourceTree = "<group>"; };
+ 5A0AF1B9C42A20B6C9FC2DD9 /* AppUpdatesView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppUpdatesView.swift; sourceTree = "<group>"; };
5A5C80929EE4A430272674BC /* ja */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = ja; path = ja.lproj/Localizable.strings; sourceTree = "<group>"; };
+ 5C8619CA3ECD70CBBC96475C /* PerformanceInspector.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PerformanceInspector.swift; sourceTree = "<group>"; };
+ 5EB777A06A7BFD324FFABB83 /* SpaceExplorerView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SpaceExplorerView.swift; sourceTree = "<group>"; };
607B9A8C7B34D6A7DCF4FFE2 /* PureMacTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = PureMacTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
60E6BC61614B27C065BB18C9 /* AppListView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppListView.swift; sourceTree = "<group>"; };
+ 6116C5E9B68F439F6B2E42E5 /* CleanupReviewTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CleanupReviewTests.swift; sourceTree = "<group>"; };
63581B70F9B10231964E3602 /* PureMacApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PureMacApp.swift; sourceTree = "<group>"; };
69B24B648B82186FC3B6EF2B /* BinaryThinner.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BinaryThinner.swift; sourceTree = "<group>"; };
6ED5C9C10C69C3143B1F5CA6 /* ru */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = ru; path = ru.lproj/ServicesMenu.strings; sourceTree = "<group>"; };
+ 6F9B44A9C1B4065126789622 /* ProtectionAudit.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ProtectionAudit.swift; sourceTree = "<group>"; };
752603285F7DBBA12BB3AA91 /* AppStateTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppStateTests.swift; sourceTree = "<group>"; };
77D3D9A9BC52839E6D0A22BC /* Locations.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Locations.swift; sourceTree = "<group>"; };
+ 78B8E84105970F69BBAB638F /* StorageExplorerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StorageExplorerTests.swift; sourceTree = "<group>"; };
7953B398E47A4C603DE287F1 /* FileProtection.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FileProtection.swift; sourceTree = "<group>"; };
798B80977D14647A5691B0A0 /* AppFilesView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppFilesView.swift; sourceTree = "<group>"; };
82BB0904726B38DEB141BECA /* AppLanguage.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppLanguage.swift; sourceTree = "<group>"; };
+ 853B6D91596DB63ACE660F74 /* ProtectionAuditTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ProtectionAuditTests.swift; sourceTree = "<group>"; };
8AFB912A9A6CFDCB972E978F /* ProviderPaths.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ProviderPaths.swift; sourceTree = "<group>"; };
8CE522B406791BCE905BC55B /* FileSize.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FileSize.swift; sourceTree = "<group>"; };
+ 8CF68B6BB9ED70387DF56728 /* StorageExplorer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StorageExplorer.swift; sourceTree = "<group>"; };
8D5E63D733D1A3BDEDF4DCA5 /* pt-BR */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = "pt-BR"; path = "pt-BR.lproj/Localizable.strings"; sourceTree = "<group>"; };
8F97E4CB93302BFE911DB1FF /* fr */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = fr; path = fr.lproj/Localizable.strings; sourceTree = "<group>"; };
913E3064AA9BD7BE94A315CF /* MenuBarController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MenuBarController.swift; sourceTree = "<group>"; };
@@ -134,11 +173,13 @@
9F04B811BB0012F6D2F07F91 /* en */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = en; path = en.lproj/Localizable.strings; sourceTree = "<group>"; };
9F510F232341EE18F11DC934 /* MainWindow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MainWindow.swift; sourceTree = "<group>"; };
A27DB5A70FA829B6C3ED0AC3 /* MenuBarMonitorView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MenuBarMonitorView.swift; sourceTree = "<group>"; };
+ A5984F53676A523D97AF2A89 /* NodeCachePathTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NodeCachePathTests.swift; sourceTree = "<group>"; };
A711CDF5285F68775D9B5513 /* ScanEngine.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ScanEngine.swift; sourceTree = "<group>"; };
AC0FEE7141871ED5F9E36121 /* AppPathFinder.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppPathFinder.swift; sourceTree = "<group>"; };
B2CD0028599BE178B96F18A6 /* ar */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = ar; path = ar.lproj/Localizable.strings; sourceTree = "<group>"; };
B2EA41E1096FA8E3B916AD13 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
B71E8F62DB76D85F41F9A2E9 /* OrphanListView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OrphanListView.swift; sourceTree = "<group>"; };
+ B97348789EA68B1ABADB1421 /* SimilarPhotoFinder.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SimilarPhotoFinder.swift; sourceTree = "<group>"; };
C0899FE169D270DF95334905 /* LanguageFilesScanner.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LanguageFilesScanner.swift; sourceTree = "<group>"; };
C4332033E243C3571C49A5E9 /* ru */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = ru; path = ru.lproj/Localizable.strings; sourceTree = "<group>"; };
C5963EBBEE5BA6E147700821 /* pl */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = pl; path = pl.lproj/Localizable.strings; sourceTree = "<group>"; };
@@ -146,16 +187,23 @@
C7D81BE7EA5DB17F4A0300AD /* SimulatorRuntimeSupportTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SimulatorRuntimeSupportTests.swift; sourceTree = "<group>"; };
CB94E06E145558123BB5BFB3 /* Conditions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Conditions.swift; sourceTree = "<group>"; };
CED1B71D5F9510582E869CFD /* AppState.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppState.swift; sourceTree = "<group>"; };
+ D00EEBBBA38CC4B3F8077E7D /* CleanupReview.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CleanupReview.swift; sourceTree = "<group>"; };
+ D379BB1C513985CF9AB783D5 /* DuplicateFinderTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DuplicateFinderTests.swift; sourceTree = "<group>"; };
D74E66594478F53363BCB0F9 /* SimulatorRuntimeSupport.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SimulatorRuntimeSupport.swift; sourceTree = "<group>"; };
+ D84FB753A60BE6BF54D5126A /* PerformanceView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PerformanceView.swift; sourceTree = "<group>"; };
DAA389C4F50505795FB31A51 /* SmartCareCoreArtwork.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SmartCareCoreArtwork.swift; sourceTree = "<group>"; };
DB798781B99987F55D77E2E3 /* SystemMonitor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SystemMonitor.swift; sourceTree = "<group>"; };
DFC4A1FD7DB92C82725B4314 /* uk */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = uk; path = uk.lproj/InfoPlist.strings; sourceTree = "<group>"; };
E866A1541D289C69144A5E62 /* FullDiskAccessManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FullDiskAccessManager.swift; sourceTree = "<group>"; };
ED0C4D8912DA94F81B2AEF8F /* ru */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = ru; path = ru.lproj/InfoPlist.strings; sourceTree = "<group>"; };
+ EDBC9DA7C5043AD9A873BA03 /* CleanupExclusions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CleanupExclusions.swift; sourceTree = "<group>"; };
EEF15CB1B8EFCA78EF491824 /* ScanError.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ScanError.swift; sourceTree = "<group>"; };
F0599AA604B0D6BA4F957537 /* ConfettiView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ConfettiView.swift; sourceTree = "<group>"; };
+ F270D47D1DD94D4577482B90 /* ProtectionView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ProtectionView.swift; sourceTree = "<group>"; };
F31F91226CDCFBB8E303B7DA /* AppConstants.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppConstants.swift; sourceTree = "<group>"; };
+ F3C3342D6386FBB6DE3D18BC /* SimilarPhotosView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SimilarPhotosView.swift; sourceTree = "<group>"; };
F661A0F64CF93E482CB1728F /* DashboardView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DashboardView.swift; sourceTree = "<group>"; };
+ F77B9D7D5353CD42BD03ADBB /* ApplicationUpdaterTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ApplicationUpdaterTests.swift; sourceTree = "<group>"; };
F9DCBD97CC88D77AE8DB01A4 /* PermissionCoordinator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PermissionCoordinator.swift; sourceTree = "<group>"; };
/* End PBXFileReference section */
@@ -184,9 +232,19 @@
isa = PBXGroup;
children = (
491771F923C93FD61A263893 /* AppLanguagePreferencesTests.swift */,
+ F77B9D7D5353CD42BD03ADBB /* ApplicationUpdaterTests.swift */,
752603285F7DBBA12BB3AA91 /* AppStateTests.swift */,
+ 22B679C0120F1E3DDCB27FE2 /* CleaningEngineTests.swift */,
+ 4C167DFBCD14DC84725EF15F /* CleanupExclusionsTests.swift */,
+ 6116C5E9B68F439F6B2E42E5 /* CleanupReviewTests.swift */,
+ D379BB1C513985CF9AB783D5 /* DuplicateFinderTests.swift */,
155CE1B8CDCCCA6F9FD028C1 /* LocalizationFilesTests.swift */,
+ A5984F53676A523D97AF2A89 /* NodeCachePathTests.swift */,
+ 043F28E28FB7B2D9E39E5F70 /* PerformanceInspectorTests.swift */,
+ 853B6D91596DB63ACE660F74 /* ProtectionAuditTests.swift */,
+ 4144A1B8F1D52D44A6E8E726 /* SimilarPhotoFinderTests.swift */,
C7D81BE7EA5DB17F4A0300AD /* SimulatorRuntimeSupportTests.swift */,
+ 78B8E84105970F69BBAB638F /* StorageExplorerTests.swift */,
55CE234DB2DB54ED53A4EFD6 /* ThemeManagerTests.swift */,
);
path = PureMacTests;
@@ -196,12 +254,26 @@
isa = PBXGroup;
children = (
82BB0904726B38DEB141BECA /* AppLanguage.swift */,
+ D00EEBBBA38CC4B3F8077E7D /* CleanupReview.swift */,
3667D46D8E2004EB4D73835A /* Models.swift */,
EEF15CB1B8EFCA78EF491824 /* ScanError.swift */,
);
path = Models;
sourceTree = "<group>";
};
+ 3FF7D3D9EA9340F29D4811FC /* Tools */ = {
+ isa = PBXGroup;
+ children = (
+ 5A0AF1B9C42A20B6C9FC2DD9 /* AppUpdatesView.swift */,
+ 1343918E4CD9C8DA99EFA588 /* DuplicateFinderView.swift */,
+ D84FB753A60BE6BF54D5126A /* PerformanceView.swift */,
+ F270D47D1DD94D4577482B90 /* ProtectionView.swift */,
+ F3C3342D6386FBB6DE3D18BC /* SimilarPhotosView.swift */,
+ 5EB777A06A7BFD324FFABB83 /* SpaceExplorerView.swift */,
+ );
+ path = Tools;
+ sourceTree = "<group>";
+ };
4562CA9E5625FA4EEEFECB6D /* Products */ = {
isa = PBXGroup;
children = (
@@ -222,6 +294,7 @@
8AE26715B5748307483A1A5E /* Components */,
9D3C2DC382F5D4B77DFD218B /* Orphans */,
7BC68AB045DA6E5299FD3CB6 /* Settings */,
+ 3FF7D3D9EA9340F29D4811FC /* Tools */,
);
path = Views;
sourceTree = "<group>";
@@ -229,14 +302,21 @@
6184B2EC3D01E6E95633406E /* Services */ = {
isa = PBXGroup;
children = (
+ 59873E44B520DE069F80CCD6 /* ApplicationUpdater.swift */,
69B24B648B82186FC3B6EF2B /* BinaryThinner.swift */,
2A8DE5D45BA19E2670B57DC5 /* CleaningEngine.swift */,
+ EDBC9DA7C5043AD9A873BA03 /* CleanupExclusions.swift */,
+ 089D484A0482787027665936 /* DuplicateFinder.swift */,
E866A1541D289C69144A5E62 /* FullDiskAccessManager.swift */,
40A3F22FCEF534DE4A2CAD0E /* Haptics.swift */,
913E3064AA9BD7BE94A315CF /* MenuBarController.swift */,
+ 5C8619CA3ECD70CBBC96475C /* PerformanceInspector.swift */,
F9DCBD97CC88D77AE8DB01A4 /* PermissionCoordinator.swift */,
+ 6F9B44A9C1B4065126789622 /* ProtectionAudit.swift */,
A711CDF5285F68775D9B5513 /* ScanEngine.swift */,
28181F034530331A550C6A3D /* SchedulerService.swift */,
+ B97348789EA68B1ABADB1421 /* SimilarPhotoFinder.swift */,
+ 8CF68B6BB9ED70387DF56728 /* StorageExplorer.swift */,
DB798781B99987F55D77E2E3 /* SystemMonitor.swift */,
022D0EAEE2B6E54069FC2CBE /* UpdateService.swift */,
);
@@ -488,15 +568,21 @@
9BB5AAA574AFED6C27A3F8E2 /* AppPathFinder.swift in Sources */,
9AA80E035DF7B33F6EE118DF /* AppState.swift in Sources */,
535B23C0108C06475215B8E8 /* AppTheme.swift in Sources */,
+ C85B54037A5989A85968F328 /* AppUpdatesView.swift in Sources */,
95278ABDCF5F4D6AC60503B1 /* AppearancePill.swift in Sources */,
+ 0BB6BC2EAFB02407FBC6CDA6 /* ApplicationUpdater.swift in Sources */,
68F9CE5ED4908F674D673FB2 /* BinaryThinner.swift in Sources */,
F2FA881A4B2209CC2A6342FB /* CLI.swift in Sources */,
B52938BBD11842631314543D /* CategoryDetailView.swift in Sources */,
48D1431A7C99C19EEBDB056B /* CleaningEngine.swift in Sources */,
+ E4A14812146CC0A379644E74 /* CleanupExclusions.swift in Sources */,
+ 9D73A00AC536CD2D9BB5F882 /* CleanupReview.swift in Sources */,
8947F0CE448791BD50EECF46 /* Conditions.swift in Sources */,
ABDDD4F35102A39CC1A2C325 /* ConfettiView.swift in Sources */,
8B541441926847072DC5B75B /* DashboardCharts.swift in Sources */,
A2AE68CC75CB72D6B10CBDF5 /* DashboardView.swift in Sources */,
+ D0E6B0AFF83228F121B4DDD3 /* DuplicateFinder.swift in Sources */,
+ 74175B10C464D245E99BA6DB /* DuplicateFinderView.swift in Sources */,
76B132F9C499225D33E0D075 /* EmptyStateView.swift in Sources */,
52F11962555C639F0EECADD6 /* FDADemoView.swift in Sources */,
25E2304A3FF257F1740E304B /* FileProtection.swift in Sources */,
@@ -513,16 +599,24 @@
BC6C800216343438413349A3 /* OnboardingView.swift in Sources */,
FDA30FE6349CA01C8D859F04 /* OrphanListView.swift in Sources */,
A9C3A1F643C26930F442E729 /* OrphanSafetyPolicy.swift in Sources */,
+ E69ECB1F931950E9DE5BE251 /* PerformanceInspector.swift in Sources */,
+ 5882104828B9C5A5E06B2AFB /* PerformanceView.swift in Sources */,
6E72022A661CBB41331A442C /* PermissionCoordinator.swift in Sources */,
61D285E96DED76FDCD54570F /* PermissionSheet.swift in Sources */,
+ FF6B92CAF96A58625A56A1C0 /* ProtectionAudit.swift in Sources */,
+ 0CC9A41781D1B1883279693E /* ProtectionView.swift in Sources */,
FBEE9208E222616A8DF1FE75 /* ProviderPaths.swift in Sources */,
EDEF28CAD23E936FBED1783B /* PureMacApp.swift in Sources */,
D9445C2641A8637B65DA5ACE /* ScanEngine.swift in Sources */,
D50EB059E741011EB2523731 /* ScanError.swift in Sources */,
27F449EDD1B082FE11FEC9DF /* SchedulerService.swift in Sources */,
93743B036059418560D876E6 /* SettingsView.swift in Sources */,
+ 4D33329ABDA67E35B3FC5B85 /* SimilarPhotoFinder.swift in Sources */,
+ 5ED9C7AA76D850363CDC127C /* SimilarPhotosView.swift in Sources */,
6753946A301B2EB2FEF6998B /* SimulatorRuntimeSupport.swift in Sources */,
B928E4369A3FC4369F014A29 /* SmartCareCoreArtwork.swift in Sources */,
+ DAB58AB235C609464B5FF5B1 /* SpaceExplorerView.swift in Sources */,
+ 7796BCD9AB92D1A644C28AF3 /* StorageExplorer.swift in Sources */,
47C5ECD49C4DD75F271DB6CE /* StringNormalization.swift in Sources */,
DBFD73E3D9BDA74EC1CA56AB /* SystemMonitor.swift in Sources */,
340E424F759ACCDE7372F99F /* Theme.swift in Sources */,
@@ -537,8 +631,18 @@
files = (
59B3096E2AE8ED0397B16798 /* AppLanguagePreferencesTests.swift in Sources */,
E2403D82F00D749C9AD4A6D4 /* AppStateTests.swift in Sources */,
+ D15B7A053D69D4348D9DCD88 /* ApplicationUpdaterTests.swift in Sources */,
+ 2BCDC53C5E3AB58442C8E4B0 /* CleaningEngineTests.swift in Sources */,
+ B69BD60D8AB7EBB9F80C9965 /* CleanupExclusionsTests.swift in Sources */,
+ 6BCC5E3773DF2E9189F75A6B /* CleanupReviewTests.swift in Sources */,
+ 4FAAA6E9887181C4C0AA9F87 /* DuplicateFinderTests.swift in Sources */,
CFA64F54CDBF8A4765E0068D /* LocalizationFilesTests.swift in Sources */,
+ E4145581C55556DB43725FBB /* NodeCachePathTests.swift in Sources */,
+ 6D36632DFF74F26035204CE2 /* PerformanceInspectorTests.swift in Sources */,
+ 94EA77AE33FBB24655EC19C5 /* ProtectionAuditTests.swift in Sources */,
+ AA25686857BF1CB9250FC0E8 /* SimilarPhotoFinderTests.swift in Sources */,
F4F02F966001A1504C2B4D33 /* SimulatorRuntimeSupportTests.swift in Sources */,
+ 10959A68B277AEF7D2442C48 /* StorageExplorerTests.swift in Sources */,
ABE3B80279483DB90B8EC1BC /* ThemeManagerTests.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
@@ -637,7 +741,7 @@
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
COPY_PHASE_STRIP = NO;
- CURRENT_PROJECT_VERSION = 28;
+ CURRENT_PROJECT_VERSION = 29;
DEBUG_INFORMATION_FORMAT = dwarf;
DEVELOPMENT_TEAM = H3WXHVTP97;
ENABLE_STRICT_OBJC_MSGSEND = YES;
@@ -659,7 +763,7 @@
GENERATE_INFOPLIST_FILE = NO;
INFOPLIST_FILE = PureMac/Info.plist;
MACOSX_DEPLOYMENT_TARGET = 13.0;
- MARKETING_VERSION = 2.9.8;
+ MARKETING_VERSION = 3.0.0;
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
MTL_FAST_MATH = YES;
ONLY_ACTIVE_ARCH = NO;
@@ -761,7 +865,7 @@
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
COPY_PHASE_STRIP = NO;
- CURRENT_PROJECT_VERSION = 28;
+ CURRENT_PROJECT_VERSION = 29;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
DEVELOPMENT_TEAM = H3WXHVTP97;
ENABLE_NS_ASSERTIONS = NO;
@@ -777,7 +881,7 @@
GENERATE_INFOPLIST_FILE = NO;
INFOPLIST_FILE = PureMac/Info.plist;
MACOSX_DEPLOYMENT_TARGET = 13.0;
- MARKETING_VERSION = 2.9.8;
+ MARKETING_VERSION = 3.0.0;
MTL_ENABLE_DEBUG_INFO = NO;
MTL_FAST_MATH = YES;
ONLY_ACTIVE_ARCH = NO;
diff --git a/PureMac/Logic/Utilities/FileSize.swift b/PureMac/Logic/Utilities/FileSize.swift
index 1a258cf..6f56739 100644
--- a/PureMac/Logic/Utilities/FileSize.swift
+++ b/PureMac/Logic/Utilities/FileSize.swift
@@ -50,6 +50,7 @@ enum FileSizeCalculator {
var total: Int64 = 0
for case let fileURL as URL in enumerator {
+ if Task.isCancelled { break }
guard let values = try? fileURL.resourceValues(forKeys: [.totalFileAllocatedSizeKey, .fileAllocatedSizeKey, .isRegularFileKey, .isSymbolicLinkKey]) else { continue }
// Skip symlinks so we don't double-count or follow links that
// escape the directory. Only sum regular-file payload.
diff --git a/PureMac/Models/CleanupReview.swift b/PureMac/Models/CleanupReview.swift
new file mode 100644
index 0000000..d185206
--- /dev/null
+++ b/PureMac/Models/CleanupReview.swift
@@ -0,0 +1,77 @@
+import Foundation
+
+enum CleanupSizeFilter: String, CaseIterable, Identifiable {
+ case any = "Any size"
+ case megabytes100 = "Over 100 MB"
+ case gigabyte1 = "Over 1 GB"
+ case gigabytes10 = "Over 10 GB"
+
+ var id: String { rawValue }
+
+ var minimumBytes: Int64 {
+ switch self {
+ case .any: return 0
+ case .megabytes100: return 100_000_000
+ case .gigabyte1: return 1_000_000_000
+ case .gigabytes10: return 10_000_000_000
+ }
+ }
+}
+
+enum CleanupAgeFilter: String, CaseIterable, Identifiable {
+ case any = "Any age"
+ case month = "Older than 30 days"
+ case sixMonths = "Older than 6 months"
+ case year = "Older than a year"
+
+ var id: String { rawValue }
+
+ func cutoff(relativeTo now: Date) -> Date? {
+ switch self {
+ case .any: return nil
+ case .month: return Calendar.current.date(byAdding: .day, value: -30, to: now)
+ case .sixMonths: return Calendar.current.date(byAdding: .month, value: -6, to: now)
+ case .year: return Calendar.current.date(byAdding: .year, value: -1, to: now)
+ }
+ }
+}
+
+enum CleanupSortOrder: String, CaseIterable, Identifiable {
+ case largest = "Largest first"
+ case smallest = "Smallest first"
+ case oldest = "Oldest first"
+ case name = "Name"
+
+ var id: String { rawValue }
+}
+
+struct CleanupReviewFilter {
+ var query = ""
+ var size: CleanupSizeFilter = .any
+ var age: CleanupAgeFilter = .any
+ var order: CleanupSortOrder = .largest
+
+ func apply(to items: [CleanableItem], now: Date = Date()) -> [CleanableItem] {
+ let search = query.trimmingCharacters(in: .whitespacesAndNewlines)
+ let cutoff = age.cutoff(relativeTo: now)
+ return items.filter { item in
+ guard item.size >= size.minimumBytes else { return false }
+ if let cutoff {
+ guard let modified = item.lastModified, modified < cutoff else { return false }
+ }
+ return search.isEmpty || item.name.localizedCaseInsensitiveContains(search)
+ || item.path.localizedCaseInsensitiveContains(search)
+ }.sorted { left, right in
+ switch order {
+ case .largest where left.size != right.size: return left.size > right.size
+ case .smallest where left.size != right.size: return left.size < right.size
+ case .oldest where left.lastModified != right.lastModified:
+ return (left.lastModified ?? .distantFuture) < (right.lastModified ?? .distantFuture)
+ default:
+ let comparison = left.name.localizedStandardCompare(right.name)
+ if comparison != .orderedSame { return comparison == .orderedAscending }
+ return left.path < right.path
+ }
+ }
+ }
+}
diff --git a/PureMac/PureMacApp.swift b/PureMac/PureMacApp.swift
index 1b0e360..424374e 100644
--- a/PureMac/PureMacApp.swift
+++ b/PureMac/PureMacApp.swift
@@ -81,7 +81,7 @@ extension Notification.Name {
@main
struct PureMacApp: App {
@NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
- @StateObject private var appState = AppState()
+ @StateObject private var appState = AppState(performStartupTasks: NSClassFromString("XCTestCase") == nil)
@StateObject private var theme = ThemeManager.shared
@AppStorage("PureMac.OnboardingComplete") private var onboardingComplete = false
@@ -101,7 +101,7 @@ struct PureMacApp: App {
if onboardingComplete {
MainWindow()
.environmentObject(appState)
- .frame(minWidth: 900, minHeight: 600)
+ .frame(minWidth: 960, minHeight: 640)
} else {
OnboardingView(isComplete: $onboardingComplete)
}
@@ -115,7 +115,7 @@ struct PureMacApp: App {
.windowStyle(.automatic)
.windowToolbarStyle(.unified)
.windowResizability(.contentMinSize)
- .defaultSize(width: 1000, height: 680)
+ .defaultSize(width: 1120, height: 740)
.commands {
CommandGroup(replacing: .newItem) {}
CommandMenu("Updates") {
diff --git a/PureMac/Services/ApplicationUpdater.swift b/PureMac/Services/ApplicationUpdater.swift
new file mode 100644
index 0000000..8a31b81
--- /dev/null
+++ b/PureMac/Services/ApplicationUpdater.swift
@@ -0,0 +1,714 @@
+import AppKit
+import Darwin
+import Foundation
+
+struct ManagedAppUpdate: Identifiable, Hashable, Sendable {
+ let token: String
+ let installedVersions: [String]
+ let currentVersion: String
+ let isPinned: Bool
+
+ var id: String { token }
+
+ var installedVersion: String {
+ installedVersions.joined(separator: ", ")
+ }
+}
+
+struct InstalledCaskPresentation: @unchecked Sendable {
+ let displayName: String
+ let bundlePath: String?
+ let icon: NSImage?
+ let isBundleMissing: Bool
+}
+
+enum ApplicationUpdaterError: LocalizedError, Equatable {
+ case homebrewNotInstalled
+ case invalidResponse
+ case invalidCaskIdentifier(String)
+ case noSelection
+ case commandFailed(String)
+ case timedOut
+ case outputLimitExceeded
+
+ var errorDescription: String? {
+ switch self {
+ case .homebrewNotInstalled:
+ return "Homebrew was not found in a standard installation location."
+ case .invalidResponse:
+ return "Homebrew returned update information PureMac could not read."
+ case .invalidCaskIdentifier(let token):
+ return "Homebrew returned an invalid cask identifier: \(token)"
+ case .noSelection:
+ return "Select at least one app to update."
+ case .commandFailed(let message):
+ return message
+ case .timedOut:
+ return "Homebrew did not finish before the operation timed out."
+ case .outputLimitExceeded:
+ return "Homebrew produced more output than PureMac could safely retain."
+ }
+ }
+}
+
+@MainActor
+final class ApplicationUpdater: ObservableObject {
+ nonisolated static let trustedBrewPaths = ["/opt/homebrew/bin/brew", "/usr/local/bin/brew"]
+
+ @Published private(set) var updates: [ManagedAppUpdate] = []
+ @Published private(set) var isChecking = false
+ @Published private(set) var isUpgrading = false
+ @Published private(set) var hasChecked = false
+ @Published private(set) var errorMessage: String?
+ @Published private(set) var statusMessage: String?
+ @Published private(set) var lastCheckedAt: Date?
+ @Published private(set) var brewURL: URL?
+ @Published private(set) var caskPresentations: [String: InstalledCaskPresentation] = [:]
+ @Published var selectedTokens: Set<String> = []
+
+ init() {
+ brewURL = Self.findBrewExecutable()
+ }
+
+ var isHomebrewAvailable: Bool { brewURL != nil }
+ var isBusy: Bool { isChecking || isUpgrading }
+ var selectedCount: Int { selectedTokens.count }
+
+ func refreshAvailability() {
+ brewURL = Self.findBrewExecutable()
+ }
+
+ func setSelected(_ selected: Bool, token: String) {
+ guard updates.contains(where: { $0.token == token && !$0.isPinned }) else { return }
+ if selected {
+ selectedTokens.insert(token)
+ } else {
+ selectedTokens.remove(token)
+ }
+ }
+
+ func checkForUpdates() async {
+ guard !isBusy else { return }
+ refreshAvailability()
+ guard let brewURL else {
+ errorMessage = ApplicationUpdaterError.homebrewNotInstalled.localizedDescription
+ hasChecked = false
+ return
+ }
+
+ isChecking = true
+ errorMessage = nil
+ statusMessage = nil
+ defer { isChecking = false }
+
+ do {
+ updates = try await Self.fetchUpdates(using: brewURL)
+ caskPresentations = await Self.fetchCaskPresentations(for: updates, using: brewURL)
+ selectedTokens.formIntersection(Set(updates.filter { !$0.isPinned }.map(\.token)))
+ hasChecked = true
+ lastCheckedAt = Date()
+ } catch is CancellationError {
+ return
+ } catch {
+ errorMessage = Self.displayMessage(for: error)
+ }
+ }
+
+ func upgrade(_ selection: [ManagedAppUpdate]) async {
+ guard !isBusy else { return }
+ guard let brewURL else {
+ errorMessage = ApplicationUpdaterError.homebrewNotInstalled.localizedDescription
+ return
+ }
+
+ let availableTokens = Set(updates.filter { !$0.isPinned }.map(\.token))
+ let tokens = selection
+ .filter { availableTokens.contains($0.token) && !$0.isPinned }
+ .map(\.token)
+ .sorted()
+
+ isUpgrading = true
+ errorMessage = nil
+ statusMessage = nil
+ defer { isUpgrading = false }
+
+ do {
+ let arguments = try Self.upgradeArguments(caskTokens: tokens)
+ let output = try await BrewProcessRunner.run(
+ executableURL: brewURL,
+ arguments: arguments,
+ timeout: 1_800
+ )
+ guard output.status == 0 else {
+ throw ApplicationUpdaterError.commandFailed(Self.failureMessage(from: output))
+ }
+
+ do {
+ updates = try await Self.fetchUpdates(using: brewURL)
+ caskPresentations = await Self.fetchCaskPresentations(for: updates, using: brewURL)
+ hasChecked = true
+ lastCheckedAt = Date()
+ let remaining = Set(updates.map(\.token)).intersection(tokens)
+ selectedTokens.formIntersection(Set(updates.filter { !$0.isPinned }.map(\.token)))
+ if remaining.isEmpty {
+ statusMessage = tokens.count == 1
+ ? "Homebrew updated the selected app."
+ : "Homebrew updated the \(tokens.count) selected apps."
+ } else {
+ statusMessage = remaining.count == 1
+ ? "Homebrew finished, but 1 selected app still reports an update."
+ : "Homebrew finished, but \(remaining.count) selected apps still report updates."
+ }
+ } catch is CancellationError {
+ statusMessage = "Homebrew finished. Check again to verify installed versions."
+ } catch {
+ statusMessage = "Homebrew finished. Check again to verify installed versions."
+ errorMessage = Self.displayMessage(for: error)
+ }
+ } catch is CancellationError {
+ return
+ } catch {
+ errorMessage = Self.displayMessage(for: error)
+ }
+ }
+
+ func openAppStoreUpdates() {
+ guard let url = URL(string: "macappstore://showUpdatesPage") else { return }
+ NSWorkspace.shared.open(url)
+ }
+
+ nonisolated static func parseOutdatedCasks(_ data: Data) throws -> [ManagedAppUpdate] {
+ let payload: OutdatedPayload
+ do {
+ payload = try JSONDecoder().decode(OutdatedPayload.self, from: data)
+ } catch {
+ throw ApplicationUpdaterError.invalidResponse
+ }
+
+ var seenTokens = Set<String>()
+ return try payload.casks.map { cask in
+ guard isValidCaskIdentifier(cask.name),
+ !cask.installedVersions.isEmpty,
+ !cask.currentVersion.isEmpty
+ else {
+ if !isValidCaskIdentifier(cask.name) {
+ throw ApplicationUpdaterError.invalidCaskIdentifier(cask.name)
+ }
+ throw ApplicationUpdaterError.invalidResponse
+ }
+ guard seenTokens.insert(cask.name).inserted else {
+ throw ApplicationUpdaterError.invalidResponse
+ }
+ return ManagedAppUpdate(
+ token: cask.name,
+ installedVersions: cask.installedVersions,
+ currentVersion: cask.currentVersion,
+ isPinned: cask.pinned
+ )
+ }
+ .sorted { $0.token.localizedStandardCompare($1.token) == .orderedAscending }
+ }
+
+ nonisolated static func parseOutdatedCasks(_ json: String) throws -> [ManagedAppUpdate] {
+ guard let data = json.data(using: .utf8) else {
+ throw ApplicationUpdaterError.invalidResponse
+ }
+ return try parseOutdatedCasks(data)
+ }
+
+ nonisolated static func isValidCaskIdentifier(_ token: String) -> Bool {
+ guard !token.isEmpty, token.count <= 128,
+ let first = token.unicodeScalars.first,
+ isLowercaseLetterOrDigit(first)
+ else { return false }
+
+ return token.unicodeScalars.dropFirst().allSatisfy { scalar in
+ isLowercaseLetterOrDigit(scalar) || "+-.@_".unicodeScalars.contains(scalar)
+ }
+ }
+
+ nonisolated static func upgradeArguments(caskTokens: [String]) throws -> [String] {
+ guard !caskTokens.isEmpty else { throw ApplicationUpdaterError.noSelection }
+ for token in caskTokens where !isValidCaskIdentifier(token) {
+ throw ApplicationUpdaterError.invalidCaskIdentifier(token)
+ }
+ return ["upgrade", "--cask", "--"] + caskTokens
+ }
+
+ nonisolated static func parseCaskPresentationDescriptors(
+ _ data: Data,
+ requestedTokens: Set<String>
+ ) throws -> [String: (displayName: String, bundlePaths: [String])] {
+ guard let root = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
+ let casks = root["casks"] as? [[String: Any]]
+ else { throw ApplicationUpdaterError.invalidResponse }
+
+ var result: [String: (displayName: String, bundlePaths: [String])] = [:]
+ for cask in casks {
+ guard let token = cask["token"] as? String,
+ requestedTokens.contains(token),
+ isValidCaskIdentifier(token)
+ else { continue }
+
+ let names = cask["name"] as? [String]
+ let displayName = names?.first(where: { !$0.isEmpty })
+ ?? token
+ let artifacts = cask["artifacts"] as? [[String: Any]] ?? []
+ var bundlePaths: [String] = []
+
+ for artifact in artifacts {
+ guard let apps = artifact["app"] as? [Any] else { continue }
+ let explicitTarget = artifact["target"] as? String
+ for case let app as String in apps where app.hasSuffix(".app") {
+ let proposedPath = explicitTarget ?? "/Applications/\((app as NSString).lastPathComponent)"
+ if let path = trustedApplicationPath(proposedPath) {
+ bundlePaths.append(path)
+ }
+ }
+ }
+
+ result[token] = (displayName, Array(Set(bundlePaths)).sorted())
+ }
+ return result
+ }
+
+ nonisolated static func findBrewExecutable(
+ isExecutable: (String) -> Bool = FileManager.default.isExecutableFile(atPath:)
+ ) -> URL? {
+ trustedBrewPaths.first(where: isExecutable).map { URL(fileURLWithPath: $0) }
+ }
+
+ nonisolated private static func isLowercaseLetterOrDigit(_ scalar: Unicode.Scalar) -> Bool {
+ (scalar.value >= 97 && scalar.value <= 122) || (scalar.value >= 48 && scalar.value <= 57)
+ }
+
+ nonisolated private static func displayMessage(for error: Error) -> String {
+ if let updaterError = error as? ApplicationUpdaterError {
+ return updaterError.localizedDescription
+ }
+ return error.localizedDescription
+ }
+
+ nonisolated private static func failureMessage(from output: BrewProcessOutput) -> String {
+ let stderr = String(decoding: output.stderr, as: UTF8.self)
+ .trimmingCharacters(in: .whitespacesAndNewlines)
+ let stdout = String(decoding: output.stdout, as: UTF8.self)
+ .trimmingCharacters(in: .whitespacesAndNewlines)
+ let detail = stderr.isEmpty ? stdout : stderr
+ return detail.isEmpty ? "Homebrew exited with status \(output.status)." : detail
+ }
+
+ nonisolated private static func fetchUpdates(using brewURL: URL) async throws -> [ManagedAppUpdate] {
+ let output = try await BrewProcessRunner.run(
+ executableURL: brewURL,
+ arguments: ["outdated", "--cask", "--json=v2"],
+ timeout: 300
+ )
+ guard output.status == 0 else {
+ throw ApplicationUpdaterError.commandFailed(failureMessage(from: output))
+ }
+ return try parseOutdatedCasks(output.stdout)
+ }
+
+ nonisolated private static func fetchCaskPresentations(
+ for updates: [ManagedAppUpdate],
+ using brewURL: URL
+ ) async -> [String: InstalledCaskPresentation] {
+ let tokens = updates.map(\.token)
+ guard !tokens.isEmpty,
+ let output = try? await BrewProcessRunner.run(
+ executableURL: brewURL,
+ arguments: ["info", "--json=v2", "--cask", "--"] + tokens,
+ timeout: 60
+ ),
+ output.status == 0,
+ let descriptors = try? parseCaskPresentationDescriptors(
+ output.stdout,
+ requestedTokens: Set(tokens)
+ )
+ else { return [:] }
+
+ return await Task.detached(priority: .utility) {
+ var presentations: [String: InstalledCaskPresentation] = [:]
+ for (token, descriptor) in descriptors {
+ let existingPath = descriptor.bundlePaths.first {
+ FileManager.default.fileExists(atPath: $0)
+ }
+ let icon = existingPath.map { NSWorkspace.shared.icon(forFile: $0) }
+ presentations[token] = InstalledCaskPresentation(
+ displayName: descriptor.displayName,
+ bundlePath: existingPath ?? descriptor.bundlePaths.first,
+ icon: icon,
+ isBundleMissing: !descriptor.bundlePaths.isEmpty && existingPath == nil
+ )
+ }
+ return presentations
+ }.value
+ }
+
+ nonisolated private static func trustedApplicationPath(_ rawPath: String) -> String? {
+ let expanded = (rawPath as NSString).expandingTildeInPath
+ let standardized = (expanded as NSString).standardizingPath
+ guard (standardized as NSString).pathExtension.lowercased() == "app" else { return nil }
+ let roots = ["/Applications", "\(FileManager.default.homeDirectoryForCurrentUser.path)/Applications"]
+ guard roots.contains(where: { standardized.hasPrefix($0 + "/") }) else { return nil }
+ return standardized
+ }
+
+ private struct OutdatedPayload: Decodable {
+ let casks: [OutdatedCask]
+ }
+
+ private struct OutdatedCask: Decodable {
+ let name: String
+ let installedVersions: [String]
+ let currentVersion: String
+ let pinned: Bool
+
+ enum CodingKeys: String, CodingKey {
+ case name
+ case installedVersions = "installed_versions"
+ case currentVersion = "current_version"
+ case pinned
+ }
+ }
+}
+
+struct BrewProcessOutput: Sendable {
+ let stdout: Data
+ let stderr: Data
+ let status: Int32
+}
+
+enum BrewProcessRunner {
+ static let maxCapturedBytes = 4 * 1_024 * 1_024
+
+ static func run(
+ executableURL: URL,
+ arguments: [String],
+ timeout: TimeInterval,
+ environment: [String: String]? = nil
+ ) async throws -> BrewProcessOutput {
+ let handle = BrewProcessHandle()
+ return try await withTaskCancellationHandler {
+ try await withCheckedThrowingContinuation { continuation in
+ let execution = BrewProcessExecution(
+ executableURL: executableURL,
+ arguments: arguments,
+ timeout: timeout,
+ environment: environment,
+ continuation: continuation
+ )
+ handle.attach(execution)
+ execution.start()
+ }
+ } onCancel: {
+ handle.cancel()
+ }
+ }
+}
+
+private final class BrewProcessHandle: @unchecked Sendable {
+ private let lock = NSLock()
+ private var execution: BrewProcessExecution?
+ private var cancelled = false
+
+ func attach(_ execution: BrewProcessExecution) {
+ lock.lock()
+ self.execution = execution
+ let shouldCancel = cancelled
+ lock.unlock()
+ if shouldCancel { execution.cancel() }
+ }
+
+ func cancel() {
+ lock.lock()
+ cancelled = true
+ let execution = execution
+ lock.unlock()
+ execution?.cancel()
+ }
+}
+
+private final class BrewProcessExecution: @unchecked Sendable {
+ private let process = Process()
+ private let stdoutPipe = Pipe()
+ private let stderrPipe = Pipe()
+ private lazy var stdoutReader = BrewPipeReader(maxBytes: BrewProcessRunner.maxCapturedBytes) { [weak self] in
+ self?.failForOutputLimit()
+ }
+ private lazy var stderrReader = BrewPipeReader(maxBytes: BrewProcessRunner.maxCapturedBytes) { [weak self] in
+ self?.failForOutputLimit()
+ }
+ private let readers = DispatchGroup()
+ private let timeout: TimeInterval
+ private let continuation: CheckedContinuation<BrewProcessOutput, Error>
+ private let lock = NSLock()
+ private var startupError: Error?
+ private var timedOut = false
+ private var cancelled = false
+ private var outputLimitExceeded = false
+ private var completed = false
+ private var started = false
+ private var selfRetainer: BrewProcessExecution?
+
+ init(
+ executableURL: URL,
+ arguments: [String],
+ timeout: TimeInterval,
+ environment: [String: String]?,
+ continuation: CheckedContinuation<BrewProcessOutput, Error>
+ ) {
+ self.timeout = timeout
+ self.continuation = continuation
+ process.executableURL = executableURL
+ process.arguments = arguments
+ process.standardOutput = stdoutPipe
+ process.standardError = stderrPipe
+
+ var childEnvironment = environment ?? ProcessInfo.processInfo.environment
+ childEnvironment["HOMEBREW_NO_ANALYTICS"] = "1"
+ childEnvironment["HOMEBREW_NO_ENV_HINTS"] = "1"
+ childEnvironment["HOMEBREW_NO_ASK"] = "1"
+ childEnvironment["HOMEBREW_NO_COLOR"] = "1"
+ process.environment = childEnvironment
+ }
+
+ func start() {
+ lock.lock()
+ selfRetainer = self
+ let wasCancelled = cancelled
+ lock.unlock()
+
+ readers.enter()
+ stdoutReader.start(stdoutPipe.fileHandleForReading) { [readers] in readers.leave() }
+ readers.enter()
+ stderrReader.start(stderrPipe.fileHandleForReading) { [readers] in readers.leave() }
+
+ if wasCancelled {
+ lock.lock()
+ startupError = CancellationError()
+ lock.unlock()
+ closeWriters()
+ finishWhenDrained()
+ return
+ }
+
+ process.terminationHandler = { [weak self] _ in
+ self?.closeWriters()
+ self?.finishWhenDrained()
+ }
+
+ do {
+ try process.run()
+ } catch {
+ lock.lock()
+ startupError = error
+ lock.unlock()
+ closeWriters()
+ finishWhenDrained()
+ return
+ }
+
+ lock.lock()
+ started = true
+ let shouldCancel = cancelled
+ lock.unlock()
+ if shouldCancel {
+ terminateProcess()
+ }
+
+ DispatchQueue.global(qos: .utility).asyncAfter(deadline: .now() + timeout) { [weak self] in
+ self?.terminateForTimeout()
+ }
+ }
+
+ func cancel() {
+ lock.lock()
+ guard !completed else {
+ lock.unlock()
+ return
+ }
+ cancelled = true
+ let hasStarted = started
+ let running = process.isRunning
+ lock.unlock()
+
+ if !hasStarted {
+ return
+ } else if running {
+ terminateProcess()
+ } else {
+ forceFinish()
+ }
+ }
+
+ private func closeWriters() {
+ try? stdoutPipe.fileHandleForWriting.close()
+ try? stderrPipe.fileHandleForWriting.close()
+ }
+
+ private func finishWhenDrained() {
+ readers.notify(queue: .global(qos: .utility)) { [weak self] in
+ self?.finish()
+ }
+ }
+
+ private func terminateForTimeout() {
+ lock.lock()
+ guard !completed else {
+ lock.unlock()
+ return
+ }
+ timedOut = true
+ let running = process.isRunning
+ lock.unlock()
+
+ if running {
+ terminateProcess()
+ } else {
+ forceFinish()
+ }
+ }
+
+ private func failForOutputLimit() {
+ lock.lock()
+ guard !completed, !outputLimitExceeded else {
+ lock.unlock()
+ return
+ }
+ outputLimitExceeded = true
+ let running = process.isRunning
+ lock.unlock()
+
+ if running {
+ terminateProcess()
+ } else {
+ forceFinish()
+ }
+ }
+
+ private func terminateProcess() {
+ process.terminate()
+ DispatchQueue.global(qos: .utility).asyncAfter(deadline: .now() + 2) { [weak self] in
+ guard let self, self.process.isRunning else { return }
+ Darwin.kill(self.process.processIdentifier, SIGKILL)
+ }
+ DispatchQueue.global(qos: .utility).asyncAfter(deadline: .now() + 2.5) { [weak self] in
+ self?.forceFinish()
+ }
+ }
+
+ private func forceFinish() {
+ closeWriters()
+ stdoutReader.stop()
+ stderrReader.stop()
+ finishWhenDrained()
+ }
+
+ private func finish() {
+ lock.lock()
+ guard !completed else {
+ lock.unlock()
+ return
+ }
+ completed = true
+ let didTimeOut = timedOut
+ let wasCancelled = cancelled
+ let exceededOutputLimit = outputLimitExceeded
+ let launchError = startupError
+ selfRetainer = nil
+ lock.unlock()
+
+ if let launchError {
+ continuation.resume(throwing: launchError)
+ } else if didTimeOut {
+ continuation.resume(throwing: ApplicationUpdaterError.timedOut)
+ } else if wasCancelled {
+ continuation.resume(throwing: CancellationError())
+ } else if exceededOutputLimit {
+ continuation.resume(throwing: ApplicationUpdaterError.outputLimitExceeded)
+ } else {
+ continuation.resume(returning: BrewProcessOutput(
+ stdout: stdoutReader.data,
+ stderr: stderrReader.data,
+ status: process.terminationStatus
+ ))
+ }
+ }
+}
+
+private final class BrewPipeReader: @unchecked Sendable {
+ private let lock = NSLock()
+ private let maxBytes: Int
+ private let onLimitExceeded: @Sendable () -> Void
+ private var storage = Data()
+ private var finished = false
+ private var limitReported = false
+ private weak var handle: FileHandle?
+ private var completion: (@Sendable () -> Void)?
+
+ init(maxBytes: Int, onLimitExceeded: @escaping @Sendable () -> Void) {
+ self.maxBytes = maxBytes
+ self.onLimitExceeded = onLimitExceeded
+ }
+
+ var data: Data {
+ lock.lock()
+ defer { lock.unlock() }
+ return storage
+ }
+
+ func start(_ handle: FileHandle, completion: @escaping @Sendable () -> Void) {
+ lock.lock()
+ self.handle = handle
+ self.completion = completion
+ lock.unlock()
+
+ handle.readabilityHandler = { [weak self] readable in
+ let chunk = readable.availableData
+ guard let self else { return }
+
+ self.lock.lock()
+ guard !self.finished else {
+ self.lock.unlock()
+ return
+ }
+ if chunk.isEmpty {
+ self.lock.unlock()
+ self.stop()
+ } else {
+ let remaining = self.maxBytes - self.storage.count
+ if remaining > 0 {
+ self.storage.append(chunk.prefix(remaining))
+ }
+ let exceededLimit = chunk.count > remaining && !self.limitReported
+ if exceededLimit {
+ self.limitReported = true
+ }
+ self.lock.unlock()
+ if exceededLimit {
+ self.onLimitExceeded()
+ }
+ }
+ }
+ }
+
+ func stop() {
+ lock.lock()
+ guard !finished else {
+ lock.unlock()
+ return
+ }
+ finished = true
+ let handle = handle
+ let completion = completion
+ self.handle = nil
+ self.completion = nil
+ lock.unlock()
+
+ handle?.readabilityHandler = nil
+ try? handle?.close()
+ completion?()
+ }
+}
diff --git a/PureMac/Services/CleaningEngine.swift b/PureMac/Services/CleaningEngine.swift
index d240487..a27ac0a 100644
--- a/PureMac/Services/CleaningEngine.swift
+++ b/PureMac/Services/CleaningEngine.swift
@@ -26,10 +26,15 @@ actor CleaningEngine {
func cleanItems(_ items: [CleanableItem], progressHandler: @Sendable (Double) -> Void) async -> CleaningResult {
var result = CleaningResult()
let total = items.count
+ let exclusions = CleanupExclusions.paths()
for (index, item) in items.enumerated() {
let progress = Double(index + 1) / Double(total)
- progressHandler(progress)
+ defer { progressHandler(progress) }
+ if CleanupExclusions.excludes(item.path, paths: exclusions) {
+ result.errors.append("Excluded from cleanup: \(item.name)")
+ continue
+ }
if item.category == .purgeableSpace {
let purged = await purgePurgeableSpace()
@@ -109,12 +114,16 @@ actor CleaningEngine {
do {
let itemURL = URL(fileURLWithPath: item.path)
- guard fileManager.fileExists(atPath: item.path) else { continue }
-
- // Security: resolve symlinks, validate the real path, delete
- // through the resolved URL. Deleting through the unresolved
- // path lets an attacker-at-same-UID swap a component to a
- // symlink after the check and have us follow it.
+ guard !hasUnexpectedSymlink(in: item.path) else {
+ let msg = "Skipped symlink or unsafe path: \(item.path)"
+ Logger.shared.log(msg, level: .warning)
+ result.errors.append(msg)
+ continue
+ }
+ guard fileManager.fileExists(atPath: item.path) else {
+ result.cleanedPaths.insert(item.path)
+ continue
+ }
let resolvedURL = itemURL.resolvingSymlinksInPath()
let resolved = resolvedURL.path
@@ -139,15 +148,15 @@ actor CleaningEngine {
// Narrow the TOCTOU window: re-resolve right before the delete
// and require the resolved path to still match. Any concurrent
// swap between check and delete aborts the operation.
- let reResolved = URL(fileURLWithPath: item.path).resolvingSymlinksInPath().path
- guard reResolved == resolved else {
+ let reResolved = itemURL.resolvingSymlinksInPath().path
+ guard reResolved == resolved, !hasUnexpectedSymlink(in: item.path) else {
let msg = "Aborting delete: path resolution changed between check and unlink for \(item.path)"
Logger.shared.log(msg, level: .warning)
result.errors.append(msg)
continue
}
- try fileManager.removeItem(at: resolvedURL)
+ try fileManager.removeItem(at: itemURL)
result.freedSpace += item.size
result.itemsCleaned += 1
result.cleanedPaths.insert(item.path)
@@ -203,7 +212,13 @@ actor CleaningEngine {
// Re-validate. Don't trust the caller — anything not on the allow-list
// refuses to escalate.
+ let exclusions = CleanupExclusions.paths()
let validated: [(item: CleanableItem, resolved: String)] = items.compactMap { item in
+ guard !CleanupExclusions.excludes(item.path, paths: exclusions) else { return nil }
+ guard !hasUnexpectedSymlink(in: item.path) else {
+ Logger.shared.log("Refusing admin escalation for symlinked path: \(item.path)", level: .warning)
+ return nil
+ }
let resolved = URL(fileURLWithPath: item.path).resolvingSymlinksInPath().path
let accepted: Bool = {
if item.category == .largeFiles {
@@ -258,27 +273,25 @@ actor CleaningEngine {
do shell script "/usr/bin/xargs -0 /bin/rm -rf -- < \(quotedTempPath)" with administrator privileges
"""
- let runResult: (success: Bool, error: String?) = await withCheckedContinuation { continuation in
+ let runError: String? = await withCheckedContinuation { continuation in
DispatchQueue.global(qos: .userInitiated).async {
let appleScript = NSAppleScript(source: script)
var errorInfo: NSDictionary?
appleScript?.executeAndReturnError(&errorInfo)
if let errorInfo {
- continuation.resume(returning: (false, "\(errorInfo)"))
+ continuation.resume(returning: "\(errorInfo)")
} else {
- continuation.resume(returning: (true, nil))
+ continuation.resume(returning: nil)
}
}
}
- guard runResult.success else {
- // -128 is "user cancelled" — log quietly, no need for an error row.
- if let err = runResult.error, !err.contains("-128") {
- Logger.shared.log("Admin clean failed: \(err)", level: .error)
- result.errors.append("Administrator authorization failed")
- }
+ if let runError, runError.contains("-128") {
return result
}
+ if let runError {
+ Logger.shared.log("Admin clean incomplete: \(runError)", level: .error)
+ }
// Verify which items actually disappeared. xargs may have reported a
// partial failure even when the AppleScript exited cleanly, so we
@@ -513,9 +526,12 @@ actor CleaningEngine {
"\(home)/Library/Developer/XCTestDevices",
"\(home)/Library/Developer/Xcode/UserData/Previews",
"\(home)/Library/org.swift.swiftpm",
+ "\(home)/Library/pnpm/store",
"\(home)/.Trash",
"\(home)/.npm",
+ "\(home)/.pnpm-store",
"\(home)/.cache",
+ "\(home)/.local/share/pnpm/store",
"\(home)/Library/Containers/com.docker.docker",
// Docker/OrbStack cache + log roots surfaced by scanDockerCache.
// Without these the items scan fine but every delete is refused
@@ -527,8 +543,11 @@ actor CleaningEngine {
"\(home)/.orbstack/log",
"/Library/Caches",
"/Library/Logs",
+ "/opt/homebrew/Library/Caches",
+ "/usr/local/Homebrew/Library/Caches",
"/private/var/log",
"/private/var/tmp",
+ "/private/tmp",
// /var is a symlink to /private/var, and resolvingSymlinksInPath
// gives the /var form. Both spellings must be allow-listed or
// every system log/tmp deletion silently fails the safety check.
@@ -714,6 +733,21 @@ actor CleaningEngine {
return path.hasPrefix(rootWithSeparator)
}
+ private func hasUnexpectedSymlink(in path: String) -> Bool {
+ var url = URL(fileURLWithPath: path).standardizedFileURL
+ while url.path != "/" {
+ let current = url.path
+ let type = (try? fileManager.attributesOfItem(atPath: current)[.type]) as? FileAttributeType
+ if type == .typeSymbolicLink, current != "/tmp", current != "/var" {
+ return true
+ }
+ let parent = url.deletingLastPathComponent()
+ if parent.path == current { break }
+ url = parent
+ }
+ return false
+ }
+
private func shellSingleQuoted(_ value: String) -> String {
"'" + value.replacingOccurrences(of: "'", with: "'\\''") + "'"
}
diff --git a/PureMac/Services/CleanupExclusions.swift b/PureMac/Services/CleanupExclusions.swift
new file mode 100644
index 0000000..2d1e691
--- /dev/null
+++ b/PureMac/Services/CleanupExclusions.swift
@@ -0,0 +1,44 @@
+import Foundation
+
+enum CleanupExclusions {
+ static let defaultsKey = "settings.cleaning.excludedPaths"
+
+ static func paths(in defaults: UserDefaults = .standard) -> [String] {
+ defaults.stringArray(forKey: defaultsKey) ?? []
+ }
+
+ static func add(_ path: String, in defaults: UserDefaults = .standard) {
+ guard path.hasPrefix("/"), !path.contains("\0") else { return }
+ var values = Set(paths(in: defaults))
+ values.insert(URL(fileURLWithPath: path).standardizedFileURL.path)
+ defaults.set(values.sorted(), forKey: defaultsKey)
+ }
+
+ static func excludes(_ path: String, paths: [String]) -> Bool {
+ guard path.hasPrefix("/") else { return false }
+ let candidate = URL(fileURLWithPath: path).standardizedFileURL
+ let candidates = [candidate.path, resolvedPath(candidate)]
+ return paths.contains { excluded in
+ guard excluded.hasPrefix("/") else { return false }
+ let url = URL(fileURLWithPath: excluded).standardizedFileURL
+ return [url.path, resolvedPath(url)].contains { root in
+ candidates.contains { candidate in
+ root == "/" || candidate == root || candidate.hasPrefix(root + "/")
+ || root.hasPrefix(candidate + "/")
+ }
+ }
+ }
+ }
+
+ private static func resolvedPath(_ url: URL) -> String {
+ var ancestor = url
+ var suffix: [String] = []
+ while ancestor.path != "/", !FileManager.default.fileExists(atPath: ancestor.path) {
+ suffix.append(ancestor.lastPathComponent)
+ ancestor.deleteLastPathComponent()
+ }
+ return suffix.reversed().reduce(ancestor.resolvingSymlinksInPath()) {
+ $0.appendingPathComponent($1)
+ }.standardizedFileURL.path
+ }
+}
diff --git a/PureMac/Services/DuplicateFinder.swift b/PureMac/Services/DuplicateFinder.swift
new file mode 100644
index 0000000..5f3bebb
--- /dev/null
+++ b/PureMac/Services/DuplicateFinder.swift
@@ -0,0 +1,501 @@
+import CryptoKit
+import Darwin
+import Foundation
+
+struct DuplicateFileIdentity: Hashable, Sendable {
+ let device: UInt64
+ let inode: UInt64
+ let size: Int64
+ let modifiedSeconds: Int64
+ let modifiedNanoseconds: Int64
+ let flags: UInt32
+
+ var physicalID: DuplicatePhysicalFileID {
+ DuplicatePhysicalFileID(device: device, inode: inode)
+ }
+}
+
+struct DuplicatePhysicalFileID: Hashable, Sendable {
+ let device: UInt64
+ let inode: UInt64
+}
+
+struct DuplicateFile: Identifiable, Hashable, Sendable {
+ let url: URL
+ let size: Int64
+ let modifiedAt: Date?
+ let digest: String
+ let identity: DuplicateFileIdentity
+
+ var id: URL { url }
+}
+
+struct DuplicateGroup: Identifiable, Hashable, Sendable {
+ let digest: String
+ let files: [DuplicateFile]
+
+ var id: String { digest }
+ var keeper: DuplicateFile { files[0] }
+ var fileSize: Int64 { files[0].size }
+ var reclaimableSize: Int64 { fileSize * Int64(max(0, files.count - 1)) }
+
+ func contains(_ url: URL) -> Bool {
+ files.contains { $0.url == url }
+ }
+}
+
+enum DuplicateSkipReason: String, Hashable, Sendable {
+ case symbolicLink
+ case package
+ case cloudPlaceholder
+ case hardLink
+ case inaccessible
+ case changedDuringScan
+ case unreadable
+
+ var label: String {
+ switch self {
+ case .symbolicLink: return "Symbolic link"
+ case .package: return "Package contents"
+ case .cloudPlaceholder: return "Cloud-only file"
+ case .hardLink: return "Hard-linked copy"
+ case .inaccessible: return "Access denied"
+ case .changedDuringScan: return "Changed during scan"
+ case .unreadable: return "Could not read"
+ }
+ }
+}
+
+struct DuplicateSkippedFile: Identifiable, Hashable, Sendable {
+ let url: URL
+ let reason: DuplicateSkipReason
+ let detail: String?
+
+ var id: String { "\(reason.rawValue):\(url.path)" }
+}
+
+struct DuplicateScanResult: Hashable, Sendable {
+ let folder: URL
+ let groups: [DuplicateGroup]
+ let skippedFiles: [DuplicateSkippedFile]
+ let filesInspected: Int
+ let bytesHashed: Int64
+
+ var duplicateFileCount: Int { groups.reduce(0) { $0 + $1.files.count } }
+ var reclaimableSize: Int64 { groups.reduce(0) { $0 + $1.reclaimableSize } }
+}
+
+struct DuplicateScanProgress: Hashable, Sendable {
+ enum Phase: String, Hashable, Sendable {
+ case discovering
+ case hashing
+ }
+
+ let phase: Phase
+ let filesInspected: Int
+ let filesToHash: Int
+ let filesHashed: Int
+ let bytesHashed: Int64
+ let currentURL: URL?
+
+ var fractionCompleted: Double? {
+ guard phase == .hashing, filesToHash > 0 else { return nil }
+ return min(1, Double(filesHashed) / Double(filesToHash))
+ }
+}
+
+struct DuplicateTrashFailure: Identifiable, Hashable, Sendable {
+ let url: URL
+ let message: String
+
+ var id: URL { url }
+}
+
+struct DuplicateTrashReport: Hashable, Sendable {
+ let trashedFiles: [DuplicateFile]
+ let failures: [DuplicateTrashFailure]
+
+ var bytesMovedToTrash: Int64 { trashedFiles.reduce(0) { $0 + $1.size } }
+}
+
+enum DuplicateFinderError: LocalizedError, Equatable {
+ case invalidFolder(String)
+ case invalidSelection(String)
+ case keeperChanged(String)
+ case fileChanged(String)
+ case contentChanged(String)
+
+ var errorDescription: String? {
+ switch self {
+ case .invalidFolder(let path):
+ return "The selected folder cannot be scanned: \(path)"
+ case .invalidSelection(let path):
+ return "The protected copy cannot be moved to Trash: \(path)"
+ case .keeperChanged(let path):
+ return "The copy marked Keep is missing or changed: \(path)"
+ case .fileChanged(let path):
+ return "A selected file is missing or changed: \(path)"
+ case .contentChanged(let path):
+ return "A selected file no longer matches its kept copy: \(path)"
+ }
+ }
+}
+
+actor DuplicateFinder {
+ typealias ProgressHandler = @Sendable (DuplicateScanProgress) async -> Void
+ typealias TrashHandler = (URL) throws -> Void
+ typealias PreTrashHandler = (URL) throws -> Void
+
+ private struct Candidate: Sendable {
+ let url: URL
+ let identity: DuplicateFileIdentity
+ let modifiedAt: Date?
+ }
+
+ private struct DigestKey: Hashable {
+ let size: Int64
+ let digest: String
+ }
+
+ private let fileManager: FileManager
+ private let trashHandler: TrashHandler
+ private let preTrashHandler: PreTrashHandler?
+
+ init(
+ fileManager: FileManager = .default,
+ trashHandler: TrashHandler? = nil,
+ preTrashHandler: PreTrashHandler? = nil
+ ) {
+ self.fileManager = fileManager
+ self.preTrashHandler = preTrashHandler
+ self.trashHandler = trashHandler ?? { url in
+ var resultingURL: NSURL?
+ try FileManager.default.trashItem(at: url, resultingItemURL: &resultingURL)
+ }
+ }
+
+ func scan(
+ folder rawFolder: URL,
+ progress: @escaping ProgressHandler = { _ in }
+ ) async throws -> DuplicateScanResult {
+ let folder = rawFolder.standardizedFileURL
+ guard Self.identity(at: folder) != nil, Self.isDirectory(at: folder) else {
+ throw DuplicateFinderError.invalidFolder(folder.path)
+ }
+ guard !Self.isSymbolicLink(at: folder), !Self.isPackage(at: folder), !Self.isCloudPlaceholder(at: folder) else {
+ throw DuplicateFinderError.invalidFolder(folder.path)
+ }
+ var candidatesBySize: [Int64: [Candidate]] = [:]
+ var seenPhysicalFiles: [DuplicatePhysicalFileID: URL] = [:]
+ var skipped: [DuplicateSkippedFile] = []
+ var filesInspected = 0
+ let keys: [URLResourceKey] = [
+ .isDirectoryKey,
+ .isRegularFileKey,
+ .isSymbolicLinkKey,
+ .isPackageKey,
+ .isUbiquitousItemKey,
+ .ubiquitousItemDownloadingStatusKey,
+ .contentModificationDateKey
+ ]
+ guard let enumerator = fileManager.enumerator(
+ at: folder,
+ includingPropertiesForKeys: keys,
+ options: [.skipsPackageDescendants],
+ errorHandler: { url, error in
+ skipped.append(DuplicateSkippedFile(
+ url: url.standardizedFileURL,
+ reason: .inaccessible,
+ detail: error.localizedDescription
+ ))
+ return true
+ }
+ ) else {
+ throw DuplicateFinderError.invalidFolder(folder.path)
+ }
+
+ while let url = enumerator.nextObject() as? URL {
+ try Task.checkCancellation()
+ let normalizedURL = url.standardizedFileURL
+ if Self.isSymbolicLink(at: normalizedURL) {
+ enumerator.skipDescendants()
+ skipped.append(DuplicateSkippedFile(url: normalizedURL, reason: .symbolicLink, detail: nil))
+ continue
+ }
+ if Self.isPackage(at: normalizedURL) {
+ enumerator.skipDescendants()
+ skipped.append(DuplicateSkippedFile(url: normalizedURL, reason: .package, detail: nil))
+ continue
+ }
+ if Self.isCloudPlaceholder(at: normalizedURL) {
+ enumerator.skipDescendants()
+ skipped.append(DuplicateSkippedFile(url: normalizedURL, reason: .cloudPlaceholder, detail: nil))
+ continue
+ }
+ guard let identity = Self.identity(at: normalizedURL), Self.isRegularFile(at: normalizedURL) else {
+ continue
+ }
+
+ filesInspected += 1
+ if let firstURL = seenPhysicalFiles[identity.physicalID] {
+ skipped.append(DuplicateSkippedFile(
+ url: normalizedURL,
+ reason: .hardLink,
+ detail: "Shares storage with \(firstURL.lastPathComponent)"
+ ))
+ } else {
+ seenPhysicalFiles[identity.physicalID] = normalizedURL
+ let modifiedAt = try? normalizedURL.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate
+ candidatesBySize[identity.size, default: []].append(Candidate(
+ url: normalizedURL,
+ identity: identity,
+ modifiedAt: modifiedAt
+ ))
+ }
+
+ if filesInspected == 1 || filesInspected.isMultiple(of: 64) {
+ await progress(DuplicateScanProgress(
+ phase: .discovering,
+ filesInspected: filesInspected,
+ filesToHash: 0,
+ filesHashed: 0,
+ bytesHashed: 0,
+ currentURL: normalizedURL
+ ))
+ }
+ }
+
+ try Task.checkCancellation()
+ let candidates = candidatesBySize
+ .filter { $0.value.count > 1 }
+ .values
+ .flatMap { $0 }
+ .sorted { $0.url.path.localizedStandardCompare($1.url.path) == .orderedAscending }
+ var filesByDigest: [DigestKey: [DuplicateFile]] = [:]
+ var filesHashed = 0
+ var bytesHashed: Int64 = 0
+
+ await progress(DuplicateScanProgress(
+ phase: .hashing,
+ filesInspected: filesInspected,
+ filesToHash: candidates.count,
+ filesHashed: 0,
+ bytesHashed: 0,
+ currentURL: candidates.first?.url
+ ))
+
+ for candidate in candidates {
+ try Task.checkCancellation()
+ do {
+ let digest = try Self.hashFile(at: candidate.url)
+ if Self.identity(at: candidate.url) != candidate.identity {
+ skipped.append(DuplicateSkippedFile(url: candidate.url, reason: .changedDuringScan, detail: nil))
+ } else {
+ let file = DuplicateFile(
+ url: candidate.url,
+ size: candidate.identity.size,
+ modifiedAt: candidate.modifiedAt,
+ digest: digest,
+ identity: candidate.identity
+ )
+ filesByDigest[DigestKey(size: candidate.identity.size, digest: digest), default: []].append(file)
+ bytesHashed += candidate.identity.size
+ }
+ } catch is CancellationError {
+ throw CancellationError()
+ } catch {
+ skipped.append(DuplicateSkippedFile(
+ url: candidate.url,
+ reason: .unreadable,
+ detail: error.localizedDescription
+ ))
+ }
+ filesHashed += 1
+ await progress(DuplicateScanProgress(
+ phase: .hashing,
+ filesInspected: filesInspected,
+ filesToHash: candidates.count,
+ filesHashed: filesHashed,
+ bytesHashed: bytesHashed,
+ currentURL: candidate.url
+ ))
+ }
+
+ let groups = filesByDigest.values
+ .filter { $0.count > 1 }
+ .map { files -> DuplicateGroup in
+ let sortedFiles = files.sorted {
+ if $0.modifiedAt != $1.modifiedAt {
+ return ($0.modifiedAt ?? .distantPast) < ($1.modifiedAt ?? .distantPast)
+ }
+ return $0.url.path.localizedStandardCompare($1.url.path) == .orderedAscending
+ }
+ return DuplicateGroup(digest: sortedFiles[0].digest, files: sortedFiles)
+ }
+ .sorted {
+ if $0.reclaimableSize != $1.reclaimableSize {
+ return $0.reclaimableSize > $1.reclaimableSize
+ }
+ return $0.keeper.url.path.localizedStandardCompare($1.keeper.url.path) == .orderedAscending
+ }
+ let uniqueSkipped = Dictionary(grouping: skipped, by: \.id)
+ .compactMap { $0.value.first }
+ .sorted { $0.url.path.localizedStandardCompare($1.url.path) == .orderedAscending }
+
+ return DuplicateScanResult(
+ folder: folder,
+ groups: groups,
+ skippedFiles: uniqueSkipped,
+ filesInspected: filesInspected,
+ bytesHashed: bytesHashed
+ )
+ }
+
+ func moveToTrash(group: DuplicateGroup, selectedIDs: Set<URL>) throws -> DuplicateTrashReport {
+ guard !selectedIDs.contains(group.keeper.url) else {
+ throw DuplicateFinderError.invalidSelection(group.keeper.url.path)
+ }
+ let selectedFiles = group.files.filter { selectedIDs.contains($0.url) }
+ guard selectedFiles.count == selectedIDs.count else {
+ let unknownPath = selectedIDs.first { !group.contains($0) }?.path ?? "Unknown file"
+ throw DuplicateFinderError.invalidSelection(unknownPath)
+ }
+ guard !selectedFiles.isEmpty else {
+ return DuplicateTrashReport(trashedFiles: [], failures: [])
+ }
+
+ try Self.validateKeeper(group.keeper, expectedDigest: group.digest)
+ var selectedPhysicalIDs: Set<DuplicatePhysicalFileID> = [group.keeper.identity.physicalID]
+ for file in selectedFiles {
+ try Self.validateSelectedFile(file, expectedDigest: group.digest)
+ guard selectedPhysicalIDs.insert(file.identity.physicalID).inserted else {
+ throw DuplicateFinderError.fileChanged(file.url.path)
+ }
+ }
+
+ var trashed: [DuplicateFile] = []
+ var failures: [DuplicateTrashFailure] = []
+ for file in selectedFiles {
+ do {
+ try Self.validateKeeper(group.keeper, expectedDigest: group.digest)
+ try Self.validateSelectedFile(file, expectedDigest: group.digest)
+ try preTrashHandler?(file.url)
+ try Self.validateKeeper(group.keeper, expectedDigest: group.digest)
+ try Self.validateSelectedFile(file, expectedDigest: group.digest)
+ try trashHandler(file.url)
+ trashed.append(file)
+ } catch is CancellationError {
+ throw CancellationError()
+ } catch let error as DuplicateFinderError {
+ failures.append(DuplicateTrashFailure(url: file.url, message: error.localizedDescription))
+ } catch {
+ failures.append(DuplicateTrashFailure(url: file.url, message: error.localizedDescription))
+ }
+ }
+ try Self.validateKeeper(group.keeper, expectedDigest: group.digest)
+ return DuplicateTrashReport(trashedFiles: trashed, failures: failures)
+ }
+
+ private static func validateKeeper(_ file: DuplicateFile, expectedDigest: String) throws {
+ guard identity(at: file.url) == file.identity, !isCloudPlaceholder(at: file.url) else {
+ throw DuplicateFinderError.keeperChanged(file.url.path)
+ }
+ do {
+ guard try hashFile(at: file.url) == expectedDigest else {
+ throw DuplicateFinderError.keeperChanged(file.url.path)
+ }
+ guard identity(at: file.url) == file.identity, !isCloudPlaceholder(at: file.url) else {
+ throw DuplicateFinderError.keeperChanged(file.url.path)
+ }
+ } catch is CancellationError {
+ throw CancellationError()
+ } catch let error as DuplicateFinderError {
+ throw error
+ } catch {
+ throw DuplicateFinderError.keeperChanged(file.url.path)
+ }
+ }
+
+ private static func validateSelectedFile(_ file: DuplicateFile, expectedDigest: String) throws {
+ guard identity(at: file.url) == file.identity, !isCloudPlaceholder(at: file.url) else {
+ throw DuplicateFinderError.fileChanged(file.url.path)
+ }
+ do {
+ guard try hashFile(at: file.url) == expectedDigest else {
+ throw DuplicateFinderError.contentChanged(file.url.path)
+ }
+ guard identity(at: file.url) == file.identity, !isCloudPlaceholder(at: file.url) else {
+ throw DuplicateFinderError.fileChanged(file.url.path)
+ }
+ } catch is CancellationError {
+ throw CancellationError()
+ } catch let error as DuplicateFinderError {
+ throw error
+ } catch {
+ throw DuplicateFinderError.fileChanged(file.url.path)
+ }
+ }
+
+ private static func hashFile(at url: URL) throws -> String {
+ let handle = try FileHandle(forReadingFrom: url)
+ defer { try? handle.close() }
+ var hasher = SHA256()
+ while true {
+ try Task.checkCancellation()
+ guard let chunk = try handle.read(upToCount: 1_048_576), !chunk.isEmpty else { break }
+ hasher.update(data: chunk)
+ }
+ return hasher.finalize().map { String(format: "%02x", $0) }.joined()
+ }
+
+ private static func identity(at url: URL) -> DuplicateFileIdentity? {
+ var information = stat()
+ guard lstat(url.path, &information) == 0 else { return nil }
+ return DuplicateFileIdentity(
+ device: UInt64(information.st_dev),
+ inode: UInt64(information.st_ino),
+ size: Int64(information.st_size),
+ modifiedSeconds: Int64(information.st_mtimespec.tv_sec),
+ modifiedNanoseconds: Int64(information.st_mtimespec.tv_nsec),
+ flags: information.st_flags
+ )
+ }
+
+ private static func isRegularFile(at url: URL) -> Bool {
+ var information = stat()
+ guard lstat(url.path, &information) == 0 else { return false }
+ return information.st_mode & S_IFMT == S_IFREG
+ }
+
+ private static func isDirectory(at url: URL) -> Bool {
+ var information = stat()
+ guard lstat(url.path, &information) == 0 else { return false }
+ return information.st_mode & S_IFMT == S_IFDIR
+ }
+
+ private static func isSymbolicLink(at url: URL) -> Bool {
+ var information = stat()
+ guard lstat(url.path, &information) == 0 else { return false }
+ return information.st_mode & S_IFMT == S_IFLNK
+ }
+
+ private static func isPackage(at url: URL) -> Bool {
+ (try? url.resourceValues(forKeys: [.isPackageKey]).isPackage) == true
+ }
+
+ private static func isCloudPlaceholder(at url: URL) -> Bool {
+ if url.pathExtension.lowercased() == "icloud" { return true }
+ if let identity = identity(at: url), isDatalessFile(flags: identity.flags) { return true }
+ guard let values = try? url.resourceValues(forKeys: [
+ .isUbiquitousItemKey,
+ .ubiquitousItemDownloadingStatusKey
+ ]) else { return false }
+ guard values.isUbiquitousItem == true else { return false }
+ return values.ubiquitousItemDownloadingStatus != .current
+ && values.ubiquitousItemDownloadingStatus != .downloaded
+ }
+
+ static func isDatalessFile(flags: UInt32) -> Bool {
+ flags & UInt32(SF_DATALESS) != 0
+ }
+}
diff --git a/PureMac/Services/PerformanceInspector.swift b/PureMac/Services/PerformanceInspector.swift
new file mode 100644
index 0000000..8fb6ee4
--- /dev/null
+++ b/PureMac/Services/PerformanceInspector.swift
@@ -0,0 +1,460 @@
+import Darwin
+import Foundation
+
+enum PerformanceStartupDomain: String, CaseIterable, Hashable, Sendable {
+ case userAgent
+ case systemAgent
+ case systemDaemon
+
+ var title: String {
+ switch self {
+ case .userAgent: return "User agent"
+ case .systemAgent: return "System-wide agent"
+ case .systemDaemon: return "System daemon"
+ }
+ }
+}
+
+struct PerformanceStartupItem: Identifiable, Hashable, Sendable {
+ let label: String
+ let program: String?
+ let arguments: [String]
+ let sourceURL: URL
+ let domain: PerformanceStartupDomain
+ let isDisabled: Bool
+ let triggers: [String]
+
+ var id: String { sourceURL.path }
+}
+
+struct PerformanceSnapshot: Identifiable, Hashable, Sendable {
+ enum Kind: String, Hashable, Sendable {
+ case timeMachine
+ case systemUpdate
+ case local
+
+ var title: String {
+ switch self {
+ case .timeMachine: return "Time Machine"
+ case .systemUpdate: return "System update"
+ case .local: return "Local snapshot"
+ }
+ }
+ }
+
+ let identifier: String
+ let kind: Kind
+ let date: Date?
+
+ var id: String { identifier }
+}
+
+struct PerformanceInspectionIssue: Identifiable, Hashable, Sendable {
+ let title: String
+ let detail: String
+
+ var id: String { "\(title)\u{0}\(detail)" }
+}
+
+struct PerformanceInspection: Sendable {
+ let startupItems: [PerformanceStartupItem]
+ let snapshots: [PerformanceSnapshot]
+ let issues: [PerformanceInspectionIssue]
+}
+
+enum PerformanceInspectorError: LocalizedError, Equatable {
+ case invalidPropertyList
+ case invalidSnapshotIdentifier
+ case timedOut(String)
+ case commandFailed(String, Int32, String)
+
+ var errorDescription: String? {
+ switch self {
+ case .invalidPropertyList:
+ return "The launch item is not a property-list dictionary."
+ case .invalidSnapshotIdentifier:
+ return "This snapshot does not have a verified Time Machine timestamp."
+ case .timedOut(let command):
+ return "\(command) did not finish within the allowed time."
+ case .commandFailed(let command, let status, let detail):
+ let suffix = detail.isEmpty ? "" : ": \(detail)"
+ return "\(command) exited with status \(status)\(suffix)"
+ }
+ }
+}
+
+final class PerformanceInspector {
+ private struct StartupScanResult: Sendable {
+ let items: [PerformanceStartupItem]
+ let issues: [PerformanceInspectionIssue]
+ }
+
+ private struct CommandResult: Sendable {
+ let status: Int32
+ let standardOutput: String
+ let standardError: String
+ }
+
+ private static let startupDirectories: [(URL, PerformanceStartupDomain)] = [
+ (
+ FileManager.default.homeDirectoryForCurrentUser
+ .appendingPathComponent("Library/LaunchAgents", isDirectory: true),
+ .userAgent
+ ),
+ (URL(fileURLWithPath: "/Library/LaunchAgents", isDirectory: true), .systemAgent),
+ (URL(fileURLWithPath: "/Library/LaunchDaemons", isDirectory: true), .systemDaemon),
+ ]
+
+ func inspect() async throws -> PerformanceInspection {
+ async let startupScan = Self.scanStartupItems()
+ async let snapshotScan = Self.scanSnapshots()
+ let (startup, snapshotResult) = try await (startupScan, snapshotScan)
+ return PerformanceInspection(
+ startupItems: startup.items,
+ snapshots: snapshotResult.snapshots,
+ issues: startup.issues + snapshotResult.issues
+ )
+ }
+
+ func deleteSnapshot(_ snapshot: PerformanceSnapshot) async throws {
+ guard let timestamp = Self.deletionTimestamp(for: snapshot) else {
+ throw PerformanceInspectorError.invalidSnapshotIdentifier
+ }
+ let executable = URL(fileURLWithPath: "/usr/bin/tmutil")
+ guard FileManager.default.isExecutableFile(atPath: executable.path) else {
+ throw PerformanceInspectorError.commandFailed("tmutil deletelocalsnapshots", -1, "tmutil is unavailable")
+ }
+ let result = try await Self.runCommand(
+ executable: executable,
+ arguments: ["deletelocalsnapshots", timestamp],
+ timeout: 30
+ )
+ guard result.status == 0 else {
+ throw PerformanceInspectorError.commandFailed(
+ "tmutil deletelocalsnapshots",
+ result.status,
+ result.standardError.trimmingCharacters(in: .whitespacesAndNewlines)
+ )
+ }
+ }
+
+ static func parseLaunchItem(
+ data: Data,
+ sourceURL: URL,
+ domain: PerformanceStartupDomain
+ ) throws -> PerformanceStartupItem {
+ let value = try PropertyListSerialization.propertyList(from: data, options: [], format: nil)
+ guard let dictionary = value as? [String: Any] else {
+ throw PerformanceInspectorError.invalidPropertyList
+ }
+
+ let programArguments = stringArray(dictionary["ProgramArguments"])
+ let bundleArguments = stringArray(dictionary["BundleProgramArguments"])
+ let declaredProgram = nonEmptyString(dictionary["Program"])
+ ?? nonEmptyString(dictionary["BundleProgram"])
+ let inferredArguments = programArguments.isEmpty ? bundleArguments : programArguments
+ let program = declaredProgram ?? inferredArguments.first
+ let arguments = program == inferredArguments.first
+ ? Array(inferredArguments.dropFirst())
+ : inferredArguments
+ let fallbackLabel = sourceURL.deletingPathExtension().lastPathComponent
+ let label = nonEmptyString(dictionary["Label"]) ?? fallbackLabel
+
+ var triggers: [String] = []
+ if bool(dictionary["RunAtLoad"]) == true {
+ triggers.append("At login")
+ }
+ if let keepAlive = dictionary["KeepAlive"] {
+ if bool(keepAlive) == true {
+ triggers.append("Keep alive")
+ } else if let conditions = keepAlive as? [String: Any], !conditions.isEmpty {
+ triggers.append("Conditional keep alive")
+ }
+ }
+ if let interval = number(dictionary["StartInterval"]), interval.intValue > 0 {
+ triggers.append("Every \(interval.intValue) seconds")
+ }
+ if dictionary["StartCalendarInterval"] != nil {
+ triggers.append("Scheduled")
+ }
+ if !stringArray(dictionary["WatchPaths"]).isEmpty {
+ triggers.append("Watches paths")
+ }
+ if !stringArray(dictionary["QueueDirectories"]).isEmpty {
+ triggers.append("Watches folders")
+ }
+ if bool(dictionary["NetworkState"]) == true {
+ triggers.append("Network state")
+ }
+
+ return PerformanceStartupItem(
+ label: label,
+ program: program,
+ arguments: arguments,
+ sourceURL: sourceURL,
+ domain: domain,
+ isDisabled: bool(dictionary["Disabled"]) == true,
+ triggers: triggers
+ )
+ }
+
+ static func parseTimeMachineSnapshots(_ output: String) -> [PerformanceSnapshot] {
+ output
+ .split(whereSeparator: \Character.isNewline)
+ .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
+ .filter { !$0.isEmpty && !$0.hasPrefix("Snapshots for disk") }
+ .map { identifier in
+ let kind: PerformanceSnapshot.Kind
+ if identifier.hasPrefix("com.apple.TimeMachine.") {
+ kind = .timeMachine
+ } else if identifier.hasPrefix("com.apple.os.update-") {
+ kind = .systemUpdate
+ } else {
+ kind = .local
+ }
+ return PerformanceSnapshot(
+ identifier: identifier,
+ kind: kind,
+ date: snapshotDate(from: identifier)
+ )
+ }
+ .sorted { left, right in
+ switch (left.date, right.date) {
+ case let (leftDate?, rightDate?): return leftDate > rightDate
+ case (_?, nil): return true
+ case (nil, _?): return false
+ case (nil, nil): return left.identifier < right.identifier
+ }
+ }
+ }
+
+ static func deletionTimestamp(for snapshot: PerformanceSnapshot) -> String? {
+ guard snapshot.kind == .timeMachine else { return nil }
+ let prefix = "com.apple.TimeMachine."
+ let suffix = ".local"
+ guard snapshot.identifier.hasPrefix(prefix), snapshot.identifier.hasSuffix(suffix) else { return nil }
+ let start = snapshot.identifier.index(snapshot.identifier.startIndex, offsetBy: prefix.count)
+ let end = snapshot.identifier.index(snapshot.identifier.endIndex, offsetBy: -suffix.count)
+ let timestamp = String(snapshot.identifier[start..<end])
+ let separators = Set([4, 7, 10])
+ guard timestamp.utf8.count == 17,
+ timestamp.utf8.enumerated().allSatisfy({ index, byte in
+ separators.contains(index) ? byte == 45 : (48...57).contains(byte)
+ }),
+ parseSnapshotTimestamp(timestamp) != nil else { return nil }
+ return timestamp
+ }
+
+ private static func scanStartupItems() async throws -> StartupScanResult {
+ try await Task.detached(priority: .userInitiated) {
+ let fileManager = FileManager()
+ var items: [PerformanceStartupItem] = []
+ var issues: [PerformanceInspectionIssue] = []
+
+ for (directory, domain) in startupDirectories {
+ try Task.checkCancellation()
+ guard fileManager.fileExists(atPath: directory.path) else { continue }
+
+ let files: [URL]
+ do {
+ files = try fileManager.contentsOfDirectory(
+ at: directory,
+ includingPropertiesForKeys: [.isRegularFileKey, .isSymbolicLinkKey],
+ options: [.skipsHiddenFiles]
+ )
+ } catch {
+ issues.append(
+ PerformanceInspectionIssue(
+ title: "Could not read \(directory.path)",
+ detail: error.localizedDescription
+ )
+ )
+ continue
+ }
+
+ for file in files where file.pathExtension.lowercased() == "plist" {
+ try Task.checkCancellation()
+ do {
+ let values = try file.resourceValues(forKeys: [.isRegularFileKey, .isSymbolicLinkKey])
+ guard values.isRegularFile == true, values.isSymbolicLink != true else { continue }
+ let data = try Data(contentsOf: file, options: [.mappedIfSafe])
+ items.append(try parseLaunchItem(data: data, sourceURL: file, domain: domain))
+ } catch {
+ issues.append(
+ PerformanceInspectionIssue(
+ title: "Could not inspect \(file.lastPathComponent)",
+ detail: error.localizedDescription
+ )
+ )
+ }
+ }
+ }
+
+ return StartupScanResult(
+ items: items.sorted {
+ if $0.domain != $1.domain {
+ return domainOrder($0.domain) < domainOrder($1.domain)
+ }
+ return $0.label.localizedStandardCompare($1.label) == .orderedAscending
+ },
+ issues: issues
+ )
+ }.value
+ }
+
+ private static func scanSnapshots() async throws -> (
+ snapshots: [PerformanceSnapshot],
+ issues: [PerformanceInspectionIssue]
+ ) {
+ let executable = URL(fileURLWithPath: "/usr/bin/tmutil")
+ guard FileManager.default.isExecutableFile(atPath: executable.path) else {
+ return (
+ [],
+ [PerformanceInspectionIssue(
+ title: "Time Machine snapshots are unavailable",
+ detail: "tmutil is not available on this Mac."
+ )]
+ )
+ }
+
+ do {
+ let result = try await runCommand(
+ executable: executable,
+ arguments: ["listlocalsnapshots", "/"],
+ timeout: 10
+ )
+ guard result.status == 0 else {
+ throw PerformanceInspectorError.commandFailed(
+ "tmutil listlocalsnapshots",
+ result.status,
+ result.standardError.trimmingCharacters(in: .whitespacesAndNewlines)
+ )
+ }
+ return (parseTimeMachineSnapshots(result.standardOutput), [])
+ } catch is CancellationError {
+ throw CancellationError()
+ } catch {
+ return (
+ [],
+ [PerformanceInspectionIssue(
+ title: "Could not list Time Machine snapshots",
+ detail: error.localizedDescription
+ )]
+ )
+ }
+ }
+
+ private static func runCommand(
+ executable: URL,
+ arguments: [String],
+ timeout: TimeInterval
+ ) async throws -> CommandResult {
+ let process = Process()
+ let standardOutput = Pipe()
+ let standardError = Pipe()
+ process.executableURL = executable
+ process.arguments = arguments
+ process.standardOutput = standardOutput
+ process.standardError = standardError
+
+ try Task.checkCancellation()
+ try process.run()
+
+ return try await withTaskCancellationHandler {
+ try await withThrowingTaskGroup(of: CommandResult.self) { group in
+ group.addTask {
+ let outputReader = Task.detached {
+ standardOutput.fileHandleForReading.readDataToEndOfFile()
+ }
+ let errorReader = Task.detached {
+ standardError.fileHandleForReading.readDataToEndOfFile()
+ }
+ process.waitUntilExit()
+ let outputData = await outputReader.value
+ let errorData = await errorReader.value
+ return CommandResult(
+ status: process.terminationStatus,
+ standardOutput: String(decoding: outputData, as: UTF8.self),
+ standardError: String(decoding: errorData, as: UTF8.self)
+ )
+ }
+ group.addTask {
+ let nanoseconds = UInt64(max(0.1, timeout) * 1_000_000_000)
+ try await Task.sleep(nanoseconds: nanoseconds)
+ if process.isRunning {
+ process.terminate()
+ try? await Task.sleep(nanoseconds: 1_000_000_000)
+ }
+ if process.isRunning {
+ Darwin.kill(process.processIdentifier, SIGKILL)
+ }
+ throw PerformanceInspectorError.timedOut(executable.lastPathComponent)
+ }
+
+ guard let result = try await group.next() else {
+ throw CancellationError()
+ }
+ group.cancelAll()
+ try Task.checkCancellation()
+ return result
+ }
+ } onCancel: {
+ if process.isRunning {
+ process.terminate()
+ DispatchQueue.global(qos: .utility).asyncAfter(deadline: .now() + 1) {
+ if process.isRunning {
+ Darwin.kill(process.processIdentifier, SIGKILL)
+ }
+ }
+ }
+ }
+ }
+
+ private static func snapshotDate(from identifier: String) -> Date? {
+ let prefix = "com.apple.TimeMachine."
+ let suffix = ".local"
+ guard identifier.hasPrefix(prefix), identifier.hasSuffix(suffix) else { return nil }
+ let start = identifier.index(identifier.startIndex, offsetBy: prefix.count)
+ let end = identifier.index(identifier.endIndex, offsetBy: -suffix.count)
+ return parseSnapshotTimestamp(String(identifier[start..<end]))
+ }
+
+ private static func parseSnapshotTimestamp(_ timestamp: String) -> Date? {
+ let formatter = DateFormatter()
+ formatter.locale = Locale(identifier: "en_US_POSIX")
+ formatter.timeZone = .current
+ formatter.dateFormat = "yyyy-MM-dd-HHmmss"
+ formatter.isLenient = false
+ guard let date = formatter.date(from: timestamp), formatter.string(from: date) == timestamp else { return nil }
+ return date
+ }
+
+ private static func domainOrder(_ domain: PerformanceStartupDomain) -> Int {
+ switch domain {
+ case .userAgent: return 0
+ case .systemAgent: return 1
+ case .systemDaemon: return 2
+ }
+ }
+
+ private static func nonEmptyString(_ value: Any?) -> String? {
+ guard let string = value as? String else { return nil }
+ let trimmed = string.trimmingCharacters(in: .whitespacesAndNewlines)
+ return trimmed.isEmpty ? nil : trimmed
+ }
+
+ private static func stringArray(_ value: Any?) -> [String] {
+ guard let values = value as? [Any] else { return [] }
+ return values.compactMap(nonEmptyString)
+ }
+
+ private static func bool(_ value: Any?) -> Bool? {
+ if let bool = value as? Bool { return bool }
+ if let number = value as? NSNumber { return number.boolValue }
+ return nil
+ }
+
+ private static func number(_ value: Any?) -> NSNumber? {
+ value as? NSNumber
+ }
+}
diff --git a/PureMac/Services/ProtectionAudit.swift b/PureMac/Services/ProtectionAudit.swift
new file mode 100644
index 0000000..a0e8948
--- /dev/null
+++ b/PureMac/Services/ProtectionAudit.swift
@@ -0,0 +1,414 @@
+import Darwin
+import Foundation
+
+enum ProtectionCheck: String, CaseIterable, Identifiable, Sendable {
+ case gatekeeper
+ case fileVault
+ case firewall
+ case systemIntegrityProtection
+ case xProtect
+
+ var id: String { rawValue }
+}
+
+enum ProtectionStatus: Sendable, Equatable {
+ case enabled
+ case disabled
+ case unknown
+}
+
+struct ProtectionFinding: Identifiable, Sendable, Equatable {
+ let check: ProtectionCheck
+ let status: ProtectionStatus
+ let detail: String
+ let version: String?
+
+ var id: ProtectionCheck { check }
+}
+
+struct ProtectionSnapshot: Sendable, Equatable {
+ let findings: [ProtectionFinding]
+ let checkedAt: Date
+}
+
+enum ProtectionCommand: CaseIterable, Hashable, Sendable {
+ case gatekeeper
+ case fileVault
+ case firewall
+ case systemIntegrityProtection
+
+ var executableURL: URL {
+ switch self {
+ case .gatekeeper:
+ return URL(fileURLWithPath: "/usr/sbin/spctl")
+ case .fileVault:
+ return URL(fileURLWithPath: "/usr/bin/fdesetup")
+ case .firewall:
+ return URL(fileURLWithPath: "/usr/libexec/ApplicationFirewall/socketfilterfw")
+ case .systemIntegrityProtection:
+ return URL(fileURLWithPath: "/usr/bin/csrutil")
+ }
+ }
+
+ var arguments: [String] {
+ switch self {
+ case .gatekeeper:
+ return ["--status"]
+ case .fileVault:
+ return ["status"]
+ case .firewall:
+ return ["--getglobalstate"]
+ case .systemIntegrityProtection:
+ return ["status"]
+ }
+ }
+
+ var check: ProtectionCheck {
+ switch self {
+ case .gatekeeper:
+ return .gatekeeper
+ case .fileVault:
+ return .fileVault
+ case .firewall:
+ return .firewall
+ case .systemIntegrityProtection:
+ return .systemIntegrityProtection
+ }
+ }
+}
+
+struct ProtectionCommandResult: Sendable, Equatable {
+ let exitCode: Int32?
+ let stdout: String
+ let stderr: String
+ let timedOut: Bool
+ let cancelled: Bool
+ let launchError: String?
+
+ var succeeded: Bool {
+ exitCode == 0 && !timedOut && !cancelled && launchError == nil
+ }
+}
+
+struct ProtectionProcessRequest: Sendable {
+ let executableURL: URL
+ let arguments: [String]
+}
+
+private final class ProtectionOutputBuffer: @unchecked Sendable {
+ private let lock = NSLock()
+ private var data = Data()
+ private let limit = 65_536
+
+ func append(_ chunk: Data) {
+ lock.lock()
+ defer { lock.unlock() }
+ guard data.count < limit else { return }
+ data.append(chunk.prefix(limit - data.count))
+ }
+
+ func string() -> String {
+ lock.lock()
+ defer { lock.unlock() }
+ return String(decoding: data, as: UTF8.self)
+ .trimmingCharacters(in: .whitespacesAndNewlines)
+ }
+}
+
+private final class ProtectionProcessController: @unchecked Sendable {
+ private let lock = NSLock()
+ private var process: Process?
+ private var cancellationRequested = false
+
+ var isCancelled: Bool {
+ lock.lock()
+ defer { lock.unlock() }
+ return cancellationRequested
+ }
+
+ func install(_ process: Process) {
+ lock.lock()
+ self.process = process
+ let shouldStop = cancellationRequested
+ lock.unlock()
+ if shouldStop { stop(process) }
+ }
+
+ func cancel() {
+ lock.lock()
+ cancellationRequested = true
+ let process = process
+ lock.unlock()
+ if let process { stop(process) }
+ }
+
+ private func stop(_ process: Process) {
+ guard process.isRunning else { return }
+ process.terminate()
+ let processID = process.processIdentifier
+ DispatchQueue.global(qos: .utility).asyncAfter(deadline: .now() + 0.25) {
+ guard process.isRunning else { return }
+ Darwin.kill(processID, SIGKILL)
+ }
+ }
+}
+
+enum ProtectionCommandRunner {
+ static func run(_ command: ProtectionCommand, timeout: TimeInterval = 4) async -> ProtectionCommandResult {
+ await run(
+ ProtectionProcessRequest(
+ executableURL: command.executableURL,
+ arguments: command.arguments
+ ),
+ timeout: timeout
+ )
+ }
+
+ static func run(
+ _ request: ProtectionProcessRequest,
+ timeout: TimeInterval
+ ) async -> ProtectionCommandResult {
+ let controller = ProtectionProcessController()
+ return await withTaskCancellationHandler {
+ await withCheckedContinuation { continuation in
+ DispatchQueue.global(qos: .utility).async {
+ continuation.resume(
+ returning: runBlocking(request, timeout: max(timeout, 0), controller: controller)
+ )
+ }
+ }
+ } onCancel: {
+ controller.cancel()
+ }
+ }
+
+ private static func runBlocking(
+ _ request: ProtectionProcessRequest,
+ timeout: TimeInterval,
+ controller: ProtectionProcessController
+ ) -> ProtectionCommandResult {
+ let process = Process()
+ let outputPipe = Pipe()
+ let errorPipe = Pipe()
+ let exitSignal = DispatchSemaphore(value: 0)
+ let readers = DispatchGroup()
+ let output = ProtectionOutputBuffer()
+ let errors = ProtectionOutputBuffer()
+
+ process.executableURL = request.executableURL
+ process.arguments = request.arguments
+ process.standardOutput = outputPipe
+ process.standardError = errorPipe
+ process.standardInput = FileHandle.nullDevice
+ process.terminationHandler = { _ in exitSignal.signal() }
+ controller.install(process)
+
+ guard !controller.isCancelled else {
+ return ProtectionCommandResult(
+ exitCode: nil,
+ stdout: "",
+ stderr: "",
+ timedOut: false,
+ cancelled: true,
+ launchError: nil
+ )
+ }
+
+ do {
+ try process.run()
+ } catch {
+ return ProtectionCommandResult(
+ exitCode: nil,
+ stdout: "",
+ stderr: "",
+ timedOut: false,
+ cancelled: controller.isCancelled,
+ launchError: error.localizedDescription
+ )
+ }
+
+ if controller.isCancelled {
+ controller.cancel()
+ }
+
+ drain(outputPipe.fileHandleForReading, into: output, group: readers)
+ drain(errorPipe.fileHandleForReading, into: errors, group: readers)
+
+ let deadline = DispatchTime.now() + timeout
+ var exited = exitSignal.wait(timeout: deadline) == .success
+ let timedOut = !exited
+
+ if !exited {
+ process.terminate()
+ exited = exitSignal.wait(timeout: .now() + 0.25) == .success
+ }
+
+ if !exited {
+ Darwin.kill(process.processIdentifier, SIGKILL)
+ exited = exitSignal.wait(timeout: .now() + 0.75) == .success
+ }
+
+ if readers.wait(timeout: .now() + 0.25) == .timedOut {
+ try? outputPipe.fileHandleForReading.close()
+ try? errorPipe.fileHandleForReading.close()
+ _ = readers.wait(timeout: .now() + 0.25)
+ }
+
+ return ProtectionCommandResult(
+ exitCode: exited ? process.terminationStatus : nil,
+ stdout: output.string(),
+ stderr: errors.string(),
+ timedOut: timedOut,
+ cancelled: controller.isCancelled,
+ launchError: nil
+ )
+ }
+
+ private static func drain(
+ _ handle: FileHandle,
+ into buffer: ProtectionOutputBuffer,
+ group: DispatchGroup
+ ) {
+ group.enter()
+ DispatchQueue.global(qos: .utility).async {
+ defer { group.leave() }
+ while true {
+ do {
+ guard let chunk = try handle.read(upToCount: 4_096), !chunk.isEmpty else { return }
+ buffer.append(chunk)
+ } catch {
+ return
+ }
+ }
+ }
+ }
+}
+
+struct ProtectionAudit: Sendable {
+ typealias CommandExecutor = @Sendable (ProtectionCommand) async -> ProtectionCommandResult
+ typealias XProtectInspector = @Sendable () -> ProtectionFinding
+
+ private let commandExecutor: CommandExecutor
+ private let xProtectInspector: XProtectInspector
+
+ init(
+ commandExecutor: @escaping CommandExecutor = { await ProtectionCommandRunner.run($0) },
+ xProtectInspector: @escaping XProtectInspector = { ProtectionAudit.inspectXProtect() }
+ ) {
+ self.commandExecutor = commandExecutor
+ self.xProtectInspector = xProtectInspector
+ }
+
+ func run() async -> ProtectionSnapshot {
+ async let gatekeeper = run(.gatekeeper)
+ async let fileVault = run(.fileVault)
+ async let firewall = run(.firewall)
+ async let systemIntegrityProtection = run(.systemIntegrityProtection)
+ async let xProtect = xProtectInspector()
+
+ let findings = await [
+ gatekeeper,
+ fileVault,
+ firewall,
+ systemIntegrityProtection,
+ xProtect
+ ]
+ return ProtectionSnapshot(findings: findings, checkedAt: Date())
+ }
+
+ private func run(_ command: ProtectionCommand) async -> ProtectionFinding {
+ Self.parse(command.check, result: await commandExecutor(command))
+ }
+
+ static func parse(_ check: ProtectionCheck, result: ProtectionCommandResult) -> ProtectionFinding {
+ guard result.succeeded else {
+ return ProtectionFinding(
+ check: check,
+ status: .unknown,
+ detail: result.timedOut ? "The check timed out." : "PureMac could not read this setting.",
+ version: nil
+ )
+ }
+
+ let output = "\(result.stdout)\n\(result.stderr)".lowercased()
+ switch check {
+ case .gatekeeper:
+ if output.contains("assessments enabled") {
+ return finding(check, .enabled, "App downloads are checked before opening.")
+ }
+ if output.contains("assessments disabled") {
+ return finding(check, .disabled, "Downloaded apps are not being assessed by Gatekeeper.")
+ }
+ case .fileVault:
+ if output.contains("filevault is on") {
+ return finding(check, .enabled, "The startup disk is encrypted with FileVault.")
+ }
+ if output.contains("filevault is off") {
+ return finding(check, .disabled, "The startup disk is not encrypted with FileVault.")
+ }
+ case .firewall:
+ if output.contains("firewall is enabled") || output.contains("state = 1") {
+ return finding(check, .enabled, "Incoming network connections are filtered.")
+ }
+ if output.contains("firewall is disabled") || output.contains("state = 0") {
+ return finding(check, .disabled, "The macOS application firewall is turned off.")
+ }
+ case .systemIntegrityProtection:
+ if output.contains("system integrity protection status: enabled") {
+ return finding(check, .enabled, "Protected system locations and processes are restricted.")
+ }
+ if output.contains("system integrity protection status: disabled") {
+ return finding(check, .disabled, "System Integrity Protection is turned off.")
+ }
+ case .xProtect:
+ break
+ }
+
+ return ProtectionFinding(
+ check: check,
+ status: .unknown,
+ detail: "The system returned an unrecognized status.",
+ version: nil
+ )
+ }
+
+ static func inspectXProtect() -> ProtectionFinding {
+ let engine = bundleVersion(at: "/Library/Apple/System/Library/CoreServices/XProtect.app")
+ let definitions = bundleVersion(at: "/Library/Apple/System/Library/CoreServices/XProtect.bundle")
+
+ guard engine != nil || definitions != nil else {
+ return ProtectionFinding(
+ check: .xProtect,
+ status: .unknown,
+ detail: "PureMac could not confirm the local XProtect installation.",
+ version: nil
+ )
+ }
+
+ let parts = [
+ engine.map { "engine \($0)" },
+ definitions.map { "definitions \($0)" }
+ ].compactMap { $0 }
+ let version = parts.joined(separator: ", ")
+ return ProtectionFinding(
+ check: .xProtect,
+ status: .enabled,
+ detail: "Apple's built-in malware protection is installed. Update recency is managed by macOS.",
+ version: version
+ )
+ }
+
+ private static func bundleVersion(at path: String) -> String? {
+ guard let bundle = Bundle(path: path) else { return nil }
+ return bundle.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String
+ ?? bundle.object(forInfoDictionaryKey: "CFBundleVersion") as? String
+ }
+
+ private static func finding(
+ _ check: ProtectionCheck,
+ _ status: ProtectionStatus,
+ _ detail: String
+ ) -> ProtectionFinding {
+ ProtectionFinding(check: check, status: status, detail: detail, version: nil)
+ }
+}
diff --git a/PureMac/Services/ScanEngine.swift b/PureMac/Services/ScanEngine.swift
index 9d4d815..0c708f1 100644
--- a/PureMac/Services/ScanEngine.swift
+++ b/PureMac/Services/ScanEngine.swift
@@ -34,6 +34,12 @@ actor ScanEngine {
}
}
+ enum NodeCacheManager: String, CaseIterable {
+ case npm
+ case yarn
+ case pnpm
+ }
+
// MARK: - Public API
func scanCategory(
@@ -62,11 +68,11 @@ actor ScanEngine {
case .xcodeJunk:
return scanXcodeJunk()
case .brewCache:
- return scanBrewCache()
+ return await scanBrewCache()
case .nodeCache:
- return scanNodeCache()
+ return await scanNodeCache()
case .dockerCache:
- return scanDockerCache()
+ return await scanDockerCache()
case .universalBinaries:
return scanUniversalBinaries()
case .languageFiles:
@@ -139,6 +145,9 @@ actor ScanEngine {
"\(home)/Library/Caches/Homebrew",
"\(home)/Library/Caches/com.electron.ollama",
"\(home)/Library/Caches/ollama",
+ "\(home)/Library/Caches/npm",
+ "\(home)/Library/Caches/Yarn",
+ "\(home)/Library/Caches/dev.kdrag0n.MacVirt",
] + ProviderPaths.deniedRoots).map(normalizePath))
// Dynamically enumerate ~/Library/Caches/ so every subdirectory is visible
@@ -154,10 +163,7 @@ actor ScanEngine {
// Also scan for npm/pip/yarn caches
let devCaches = [
- "\(home)/.npm/_cacache",
"\(home)/.cache/pip",
- "\(home)/.cache/yarn",
- "\(home)/.cache/pnpm",
"\(home)/Library/Caches/pip",
]
@@ -518,7 +524,7 @@ actor ScanEngine {
return runtimes
}
- private func scanBrewCache() -> CategoryResult {
+ private func scanBrewCache() async -> CategoryResult {
var items: [CleanableItem] = []
// Default Homebrew download cache
@@ -543,22 +549,19 @@ actor ScanEngine {
var detectedCustomCache = false
for brewBin in brewBinPaths {
guard fileManager.fileExists(atPath: brewBin) else { continue }
- let task = Process()
- task.executableURL = URL(fileURLWithPath: brewBin)
- task.arguments = ["--cache"]
var sanitizedEnv = ProcessInfo.processInfo.environment
for key in Array(sanitizedEnv.keys) where key.hasPrefix("HOMEBREW_") {
sanitizedEnv.removeValue(forKey: key)
}
- task.environment = sanitizedEnv
- let pipe = Pipe()
- task.standardOutput = pipe
- task.standardError = Pipe()
do {
- try task.run()
- task.waitUntilExit()
- let data = pipe.fileHandleForReading.readDataToEndOfFile()
- if let output = String(data: data, encoding: .utf8)?.trimmingCharacters(in: .whitespacesAndNewlines),
+ let result = try await BrewProcessRunner.run(
+ executableURL: URL(fileURLWithPath: brewBin),
+ arguments: ["--cache"],
+ timeout: 10,
+ environment: sanitizedEnv
+ )
+ if result.status == 0,
+ let output = String(data: result.stdout, encoding: .utf8)?.trimmingCharacters(in: .whitespacesAndNewlines),
!output.isEmpty {
let normalized = normalizePath(output)
let isKnown = knownBrewRoots.contains { root in
@@ -573,6 +576,8 @@ actor ScanEngine {
}
detectedCustomCache = true
}
+ } catch is CancellationError {
+ return CategoryResult(category: .brewCache, items: items, totalSize: 0)
} catch {
Logger.shared.log("Failed to run \(brewBin) --cache: \(error.localizedDescription)", level: .warning)
}
@@ -603,25 +608,22 @@ actor ScanEngine {
return CategoryResult(category: .brewCache, items: items, totalSize: totalSize)
}
- private func scanNodeCache() -> CategoryResult {
- // Each entry is `(displayName, defaultPath, optional CLI for cache-dir
- // detection)`. The CLI invocation overrides `defaultPath` if the user
- // has set a custom location (e.g. via `npm config set cache`).
+ private func scanNodeCache() async -> CategoryResult {
struct ManagerCache {
let name: String
- let defaultPath: String
+ let manager: NodeCacheManager
let detectionCommand: (cli: String, args: [String])?
}
let managers: [ManagerCache] = [
ManagerCache(
name: String(localized: "npm cache"),
- defaultPath: "\(home)/.npm",
+ manager: .npm,
detectionCommand: (cli: "npm", args: ["config", "get", "cache"])
),
ManagerCache(
name: String(localized: "yarn classic cache"),
- defaultPath: "\(home)/Library/Caches/Yarn",
+ manager: .yarn,
detectionCommand: (cli: "yarn", args: ["cache", "dir"])
),
// Yarn Berry / v2+ uses a per-project .yarn/cache. We don't try to
@@ -630,7 +632,7 @@ actor ScanEngine {
// global, safe-to-clean location.
ManagerCache(
name: String(localized: "pnpm content-addressable store"),
- defaultPath: "\(home)/Library/pnpm/store",
+ manager: .pnpm,
detectionCommand: (cli: "pnpm", args: ["store", "path"])
),
]
@@ -647,19 +649,34 @@ actor ScanEngine {
]
for manager in managers {
- var paths: [String] = []
- paths.append(manager.defaultPath)
+ if Task.isCancelled { break }
+ var paths = Self.approvedNodeCacheRoots(for: manager.manager, home: home)
+ .compactMap {
+ Self.validatedNodeCachePath($0, manager: manager.manager, home: home)
+ }
if let cmd = manager.detectionCommand,
let cliPath = locateExecutable(named: cmd.cli, searchPaths: cliSearchPaths),
- let detected = runCommandReadingStdout(executable: cliPath, args: cmd.args) {
- let normalized = detected.trimmingCharacters(in: .whitespacesAndNewlines)
- if !normalized.isEmpty,
- !paths.map(normalizePath).contains(normalizePath(normalized)) {
- paths.append(normalized)
+ let detected = await runCommandReadingStdout(executable: cliPath, args: cmd.args) {
+ if let validated = Self.validatedNodeCachePath(
+ detected,
+ manager: manager.manager,
+ home: home
+ ) {
+ if !paths.contains(validated) {
+ paths.append(validated)
+ }
+ } else {
+ Logger.shared.log(
+ "Refusing untrusted \(manager.manager.rawValue) cache path",
+ level: .warning
+ )
}
}
+ if Task.isCancelled { break }
+ paths = Self.prunedNodeCachePaths(paths)
+
for path in paths {
guard fileManager.fileExists(atPath: path) else { continue }
let size = directorySize(path: path)
@@ -679,6 +696,71 @@ actor ScanEngine {
return CategoryResult(category: .nodeCache, items: items, totalSize: totalSize)
}
+ nonisolated static func approvedNodeCacheRoots(
+ for manager: NodeCacheManager,
+ home: String
+ ) -> [String] {
+ let normalizedHome = (home as NSString).standardizingPath
+ switch manager {
+ case .npm:
+ return [
+ "\(normalizedHome)/.npm",
+ "\(normalizedHome)/Library/Caches/npm",
+ ]
+ case .yarn:
+ return [
+ "\(normalizedHome)/Library/Caches/Yarn",
+ "\(normalizedHome)/.cache/yarn",
+ ]
+ case .pnpm:
+ return [
+ "\(normalizedHome)/Library/pnpm/store",
+ "\(normalizedHome)/.local/share/pnpm/store",
+ "\(normalizedHome)/.pnpm-store",
+ "\(normalizedHome)/.cache/pnpm",
+ ]
+ }
+ }
+
+ nonisolated static func validatedNodeCachePath(
+ _ candidate: String,
+ manager: NodeCacheManager,
+ home: String
+ ) -> String? {
+ let trimmed = candidate.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !trimmed.isEmpty,
+ trimmed.hasPrefix("/"),
+ !trimmed.unicodeScalars.contains(where: CharacterSet.controlCharacters.contains)
+ else { return nil }
+
+ let standardized = (trimmed as NSString).standardizingPath
+ let resolved = URL(fileURLWithPath: standardized, isDirectory: true)
+ .resolvingSymlinksInPath()
+ .standardizedFileURL.path
+ let approvedRoots = approvedNodeCacheRoots(for: manager, home: home)
+ .map { ($0 as NSString).standardizingPath }
+
+ guard approvedRoots.contains(where: { root in
+ resolved == root || resolved.hasPrefix(root + "/")
+ }) else { return nil }
+
+ return resolved
+ }
+
+ nonisolated static func prunedNodeCachePaths(_ paths: [String]) -> [String] {
+ var kept: [String] = []
+ for path in paths.sorted(by: {
+ if $0.count != $1.count { return $0.count < $1.count }
+ return $0.localizedStandardCompare($1) == .orderedAscending
+ }) {
+ if kept.contains(where: { path == $0 || path.hasPrefix($0 + "/") }) {
+ continue
+ }
+ kept.append(path)
+ }
+ return kept
+ }
+
// -- Process helpers (used by scanNodeCache) --
private func locateExecutable(named name: String, searchPaths: [String]) -> String? {
@@ -701,26 +783,24 @@ actor ScanEngine {
return nil
}
- private func runCommandReadingStdout(executable: String, args: [String]) -> String? {
- let task = Process()
- task.executableURL = URL(fileURLWithPath: executable)
- task.arguments = args
- let pipe = Pipe()
- task.standardOutput = pipe
- task.standardError = Pipe()
+ private func runCommandReadingStdout(executable: String, args: [String]) async -> String? {
do {
- try task.run()
- task.waitUntilExit()
+ let result = try await BrewProcessRunner.run(
+ executableURL: URL(fileURLWithPath: executable),
+ arguments: args,
+ timeout: 10
+ )
+ guard result.status == 0 else { return nil }
+ return String(data: result.stdout, encoding: .utf8)
+ } catch is CancellationError {
+ return nil
} catch {
Logger.shared.log("\(executable) \(args.joined(separator: " ")) failed: \(error.localizedDescription)", level: .warning)
return nil
}
- guard task.terminationStatus == 0 else { return nil }
- let data = pipe.fileHandleForReading.readDataToEndOfFile()
- return String(data: data, encoding: .utf8)
}
- private func scanDockerCache() -> CategoryResult {
+ private func scanDockerCache() async -> CategoryResult {
var items: [CleanableItem] = []
// Docker Desktop on macOS keeps its VM disk + caches under
@@ -776,7 +856,8 @@ actor ScanEngine {
// at these locations).
let dockerBinPaths = ["/usr/local/bin/docker", "/opt/homebrew/bin/docker"]
for dockerBin in dockerBinPaths where fileManager.fileExists(atPath: dockerBin) {
- if let reclaimable = reclaimableDockerSpace(dockerBin: dockerBin), reclaimable > 0 {
+ if Task.isCancelled { break }
+ if let reclaimable = await reclaimableDockerSpace(dockerBin: dockerBin), reclaimable > 0 {
items.append(CleanableItem(
name: String(localized: "Docker prune (stopped containers, dangling images, build cache)"),
path: "",
@@ -846,23 +927,23 @@ actor ScanEngine {
/// Sum the reclaimable bytes reported by `docker system df --format json`.
/// Returns nil when Docker isn't running or the command fails — callers
/// should treat that as "no reclaimable info available", not as an error.
- private func reclaimableDockerSpace(dockerBin: String) -> Int64? {
- let task = Process()
- task.executableURL = URL(fileURLWithPath: dockerBin)
- task.arguments = ["system", "df", "--format", "{{.Reclaimable}}"]
- let stdoutPipe = Pipe()
- task.standardOutput = stdoutPipe
- task.standardError = Pipe()
+ private func reclaimableDockerSpace(dockerBin: String) async -> Int64? {
+ let result: BrewProcessOutput
do {
- try task.run()
- task.waitUntilExit()
+ result = try await BrewProcessRunner.run(
+ executableURL: URL(fileURLWithPath: dockerBin),
+ arguments: ["system", "df", "--format", "{{.Reclaimable}}"],
+ timeout: 10
+ )
+ } catch is CancellationError {
+ return nil
} catch {
Logger.shared.log("docker system df failed: \(error.localizedDescription)", level: .warning)
return nil
}
- guard task.terminationStatus == 0 else { return nil }
- let data = stdoutPipe.fileHandleForReading.readDataToEndOfFile()
- guard let output = String(data: data, encoding: .utf8) else { return nil }
+ guard result.status == 0,
+ let output = String(data: result.stdout, encoding: .utf8)
+ else { return nil }
// Each line looks like e.g. "1.234GB (45%)" — parse the leading number.
var total: Int64 = 0
for line in output.split(separator: "\n") {
diff --git a/PureMac/Services/SimilarPhotoFinder.swift b/PureMac/Services/SimilarPhotoFinder.swift
new file mode 100644
index 0000000..1a869b2
--- /dev/null
+++ b/PureMac/Services/SimilarPhotoFinder.swift
@@ -0,0 +1,492 @@
+import CoreGraphics
+import Darwin
+import Foundation
+import ImageIO
+import UniformTypeIdentifiers
+
+struct SimilarPhotoScanLimits: Hashable, Sendable {
+ let maxPhotos: Int
+ let maxEntries: Int
+
+ static let standard = SimilarPhotoScanLimits(maxPhotos: 500, maxEntries: 10_000)
+}
+
+struct SimilarPhoto: Identifiable, Sendable {
+ let url: URL
+ let size: Int64
+ let modifiedAt: Date?
+ let pixelWidth: Int
+ let pixelHeight: Int
+ let thumbnailData: Data
+
+ var id: URL { url }
+}
+
+struct SimilarPhotoGroup: Identifiable, Sendable {
+ let photos: [SimilarPhoto]
+ let similarity: Double
+
+ var id: URL { photos[0].url }
+ var totalSize: Int64 { photos.reduce(0) { $0 + $1.size } }
+}
+
+struct SimilarPhotoScanResult: Sendable {
+ let folder: URL
+ let groups: [SimilarPhotoGroup]
+ let entriesVisited: Int
+ let candidatesFound: Int
+ let photosAnalyzed: Int
+ let skippedItems: Int
+ let photoLimitReached: Bool
+ let entryLimitReached: Bool
+
+ var matchedPhotoCount: Int { groups.reduce(0) { $0 + $1.photos.count } }
+ var matchedPhotoSize: Int64 { groups.reduce(0) { $0 + $1.totalSize } }
+ var isPartial: Bool { photoLimitReached || entryLimitReached }
+}
+
+struct SimilarPhotoScanProgress: Hashable, Sendable {
+ enum Phase: Hashable, Sendable {
+ case discovering
+ case analyzing
+ case comparing
+ }
+
+ let phase: Phase
+ let entriesVisited: Int
+ let candidatesFound: Int
+ let photosAnalyzed: Int
+ let currentURL: URL?
+}
+
+enum SimilarPhotoFinderError: LocalizedError, Equatable {
+ case invalidFolder(String)
+
+ var errorDescription: String? {
+ switch self {
+ case .invalidFolder(let path):
+ return "The selected folder cannot be scanned: \(path)"
+ }
+ }
+}
+
+actor SimilarPhotoFinder {
+ typealias ProgressHandler = @Sendable (SimilarPhotoScanProgress) async -> Void
+
+ private struct FileIdentity: Equatable, Sendable {
+ let device: UInt64
+ let inode: UInt64
+ let size: Int64
+ let modifiedSeconds: Int64
+ let modifiedNanoseconds: Int64
+ }
+
+ private struct Candidate: Sendable {
+ let url: URL
+ let identity: FileIdentity
+ let modifiedAt: Date?
+ }
+
+ private struct Signature: Sendable {
+ let differenceHash: UInt64
+ let averageHash: UInt64
+ let red: Double
+ let green: Double
+ let blue: Double
+ let aspectRatio: Double
+ }
+
+ private struct AnalyzedPhoto: Sendable {
+ let photo: SimilarPhoto
+ let signature: Signature
+ }
+
+ private static let supportedExtensions: Set<String> = [
+ "avif", "bmp", "gif", "heic", "heif", "jpeg", "jpg", "png", "tif", "tiff", "webp"
+ ]
+
+ private let fileManager: FileManager
+ private let limits: SimilarPhotoScanLimits
+
+ init(fileManager: FileManager = .default, limits: SimilarPhotoScanLimits = .standard) {
+ self.fileManager = fileManager
+ self.limits = limits
+ }
+
+ func scan(
+ folder rawFolder: URL,
+ progress: @escaping ProgressHandler = { _ in }
+ ) async throws -> SimilarPhotoScanResult {
+ let folder = rawFolder.standardizedFileURL
+ guard Self.isDirectory(at: folder),
+ !Self.isSymbolicLink(at: folder),
+ !Self.isPackage(at: folder),
+ !Self.isCloudPlaceholder(at: folder) else {
+ throw SimilarPhotoFinderError.invalidFolder(folder.path)
+ }
+
+ var candidates: [Candidate] = []
+ var entriesVisited = 0
+ var skippedItems = 0
+ var photoLimitReached = false
+ var entryLimitReached = false
+ let keys: [URLResourceKey] = [
+ .contentModificationDateKey,
+ .isPackageKey,
+ .isUbiquitousItemKey,
+ .ubiquitousItemDownloadingStatusKey
+ ]
+ guard let enumerator = fileManager.enumerator(
+ at: folder,
+ includingPropertiesForKeys: keys,
+ options: [.skipsHiddenFiles, .skipsPackageDescendants],
+ errorHandler: { _, _ in
+ skippedItems += 1
+ return true
+ }
+ ) else {
+ throw SimilarPhotoFinderError.invalidFolder(folder.path)
+ }
+
+ while let rawURL = enumerator.nextObject() as? URL {
+ try Task.checkCancellation()
+ if entriesVisited >= limits.maxEntries {
+ entryLimitReached = true
+ break
+ }
+ entriesVisited += 1
+ let url = rawURL.standardizedFileURL
+
+ if Self.isSymbolicLink(at: url) {
+ enumerator.skipDescendants()
+ skippedItems += 1
+ continue
+ }
+ if Self.isPackage(at: url) {
+ enumerator.skipDescendants()
+ skippedItems += 1
+ continue
+ }
+ if Self.isCloudPlaceholder(at: url) {
+ enumerator.skipDescendants()
+ skippedItems += 1
+ continue
+ }
+ guard Self.isRegularFile(at: url),
+ Self.supportedExtensions.contains(url.pathExtension.lowercased()),
+ let identity = Self.identity(at: url) else {
+ continue
+ }
+ if candidates.count >= limits.maxPhotos {
+ photoLimitReached = true
+ break
+ }
+
+ let modifiedAt = try? url.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate
+ candidates.append(Candidate(url: url, identity: identity, modifiedAt: modifiedAt))
+
+ if candidates.count == 1 || candidates.count.isMultiple(of: 20) {
+ await progress(SimilarPhotoScanProgress(
+ phase: .discovering,
+ entriesVisited: entriesVisited,
+ candidatesFound: candidates.count,
+ photosAnalyzed: 0,
+ currentURL: url
+ ))
+ }
+ }
+
+ let orderedCandidates = candidates.sorted {
+ $0.url.path.localizedStandardCompare($1.url.path) == .orderedAscending
+ }
+ var analyzed: [AnalyzedPhoto] = []
+ analyzed.reserveCapacity(orderedCandidates.count)
+
+ for candidate in orderedCandidates {
+ try Task.checkCancellation()
+ if let photo = Self.analyze(candidate), Self.identity(at: candidate.url) == candidate.identity {
+ analyzed.append(photo)
+ } else {
+ skippedItems += 1
+ }
+ if analyzed.count == 1 || analyzed.count.isMultiple(of: 10) || candidate.url == orderedCandidates.last?.url {
+ await progress(SimilarPhotoScanProgress(
+ phase: .analyzing,
+ entriesVisited: entriesVisited,
+ candidatesFound: orderedCandidates.count,
+ photosAnalyzed: analyzed.count,
+ currentURL: candidate.url
+ ))
+ }
+ }
+
+ try Task.checkCancellation()
+ await progress(SimilarPhotoScanProgress(
+ phase: .comparing,
+ entriesVisited: entriesVisited,
+ candidatesFound: orderedCandidates.count,
+ photosAnalyzed: analyzed.count,
+ currentURL: nil
+ ))
+ let groups = try Self.makeGroups(from: analyzed)
+
+ return SimilarPhotoScanResult(
+ folder: folder,
+ groups: groups,
+ entriesVisited: entriesVisited,
+ candidatesFound: candidates.count,
+ photosAnalyzed: analyzed.count,
+ skippedItems: skippedItems,
+ photoLimitReached: photoLimitReached,
+ entryLimitReached: entryLimitReached
+ )
+ }
+
+ private static func analyze(_ candidate: Candidate) -> AnalyzedPhoto? {
+ guard let source = CGImageSourceCreateWithURL(candidate.url as CFURL, nil),
+ let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any],
+ let width = number(properties[kCGImagePropertyPixelWidth]),
+ let height = number(properties[kCGImagePropertyPixelHeight]),
+ width > 0,
+ height > 0 else {
+ return nil
+ }
+ let options: [CFString: Any] = [
+ kCGImageSourceCreateThumbnailFromImageAlways: true,
+ kCGImageSourceCreateThumbnailWithTransform: true,
+ kCGImageSourceThumbnailMaxPixelSize: 256,
+ kCGImageSourceShouldCacheImmediately: true
+ ]
+ guard let thumbnail = CGImageSourceCreateThumbnailAtIndex(source, 0, options as CFDictionary),
+ let signature = signature(for: thumbnail, aspectRatio: Double(width) / Double(height)),
+ let thumbnailData = encodeThumbnail(thumbnail) else {
+ return nil
+ }
+ let photo = SimilarPhoto(
+ url: candidate.url,
+ size: candidate.identity.size,
+ modifiedAt: candidate.modifiedAt,
+ pixelWidth: width,
+ pixelHeight: height,
+ thumbnailData: thumbnailData
+ )
+ return AnalyzedPhoto(photo: photo, signature: signature)
+ }
+
+ private static func number(_ value: Any?) -> Int? {
+ if let number = value as? NSNumber { return number.intValue }
+ if let number = value as? Int { return number }
+ return nil
+ }
+
+ private static func signature(for image: CGImage, aspectRatio: Double) -> Signature? {
+ guard let gray = grayscalePixels(image, width: 9, height: 8),
+ let averageGray = grayscalePixels(image, width: 8, height: 8),
+ let colors = colorPixels(image, width: 8, height: 8) else {
+ return nil
+ }
+
+ var differenceHash: UInt64 = 0
+ var differenceBit = 0
+ for row in 0..<8 {
+ for column in 0..<8 {
+ if gray[row * 9 + column] > gray[row * 9 + column + 1] {
+ differenceHash |= UInt64(1) << UInt64(differenceBit)
+ }
+ differenceBit += 1
+ }
+ }
+
+ let average = averageGray.reduce(0) { $0 + Int($1) } / 64
+ var averageHash: UInt64 = 0
+ for index in 0..<64 where Int(averageGray[index]) >= average {
+ averageHash |= UInt64(1) << UInt64(index)
+ }
+
+ var red = 0.0
+ var green = 0.0
+ var blue = 0.0
+ for index in 0..<64 {
+ red += Double(colors[index * 4])
+ green += Double(colors[index * 4 + 1])
+ blue += Double(colors[index * 4 + 2])
+ }
+
+ return Signature(
+ differenceHash: differenceHash,
+ averageHash: averageHash,
+ red: red / (64 * 255),
+ green: green / (64 * 255),
+ blue: blue / (64 * 255),
+ aspectRatio: aspectRatio
+ )
+ }
+
+ private static func grayscalePixels(_ image: CGImage, width: Int, height: Int) -> [UInt8]? {
+ var pixels = [UInt8](repeating: 0, count: width * height)
+ guard let context = CGContext(
+ data: &pixels,
+ width: width,
+ height: height,
+ bitsPerComponent: 8,
+ bytesPerRow: width,
+ space: CGColorSpaceCreateDeviceGray(),
+ bitmapInfo: CGImageAlphaInfo.none.rawValue
+ ) else {
+ return nil
+ }
+ context.interpolationQuality = .high
+ context.draw(image, in: CGRect(x: 0, y: 0, width: width, height: height))
+ return pixels
+ }
+
+ private static func colorPixels(_ image: CGImage, width: Int, height: Int) -> [UInt8]? {
+ var pixels = [UInt8](repeating: 0, count: width * height * 4)
+ guard let context = CGContext(
+ data: &pixels,
+ width: width,
+ height: height,
+ bitsPerComponent: 8,
+ bytesPerRow: width * 4,
+ space: CGColorSpaceCreateDeviceRGB(),
+ bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue
+ ) else {
+ return nil
+ }
+ context.setFillColor(CGColor(gray: 1, alpha: 1))
+ context.fill(CGRect(x: 0, y: 0, width: width, height: height))
+ context.interpolationQuality = .high
+ context.draw(image, in: CGRect(x: 0, y: 0, width: width, height: height))
+ return pixels
+ }
+
+ private static func encodeThumbnail(_ image: CGImage) -> Data? {
+ let data = NSMutableData()
+ guard let destination = CGImageDestinationCreateWithData(
+ data,
+ UTType.jpeg.identifier as CFString,
+ 1,
+ nil
+ ) else {
+ return nil
+ }
+ CGImageDestinationAddImage(
+ destination,
+ image,
+ [kCGImageDestinationLossyCompressionQuality: 0.82] as CFDictionary
+ )
+ guard CGImageDestinationFinalize(destination) else { return nil }
+ return data as Data
+ }
+
+ private static func makeGroups(from photos: [AnalyzedPhoto]) throws -> [SimilarPhotoGroup] {
+ var remaining = Set(photos.indices)
+ var groups: [SimilarPhotoGroup] = []
+
+ for seedIndex in photos.indices where remaining.contains(seedIndex) {
+ try Task.checkCancellation()
+ remaining.remove(seedIndex)
+ var matches: [(index: Int, score: Double)] = []
+
+ for candidateIndex in remaining.sorted() {
+ try Task.checkCancellation()
+ if let score = similarity(photos[seedIndex].signature, photos[candidateIndex].signature) {
+ matches.append((candidateIndex, score))
+ }
+ }
+ guard !matches.isEmpty else { continue }
+
+ let matchedIndices = matches.map(\.index)
+ remaining.subtract(matchedIndices)
+ let members = ([seedIndex] + matchedIndices)
+ .map { photos[$0].photo }
+ .sorted {
+ if $0.modifiedAt != $1.modifiedAt {
+ return ($0.modifiedAt ?? .distantPast) < ($1.modifiedAt ?? .distantPast)
+ }
+ return $0.url.path.localizedStandardCompare($1.url.path) == .orderedAscending
+ }
+ groups.append(SimilarPhotoGroup(
+ photos: members,
+ similarity: matches.map(\.score).min() ?? 1
+ ))
+ }
+
+ return groups.sorted {
+ if $0.totalSize != $1.totalSize { return $0.totalSize > $1.totalSize }
+ return $0.id.path.localizedStandardCompare($1.id.path) == .orderedAscending
+ }
+ }
+
+ private static func similarity(_ lhs: Signature, _ rhs: Signature) -> Double? {
+ let aspectDifference = abs(lhs.aspectRatio - rhs.aspectRatio) / max(lhs.aspectRatio, rhs.aspectRatio)
+ guard aspectDifference <= 0.12 else { return nil }
+
+ let differenceDistance = (lhs.differenceHash ^ rhs.differenceHash).nonzeroBitCount
+ let averageDistance = (lhs.averageHash ^ rhs.averageHash).nonzeroBitCount
+ let colorDistance = sqrt(
+ pow(lhs.red - rhs.red, 2) +
+ pow(lhs.green - rhs.green, 2) +
+ pow(lhs.blue - rhs.blue, 2)
+ ) / sqrt(3)
+ guard differenceDistance <= 10, averageDistance <= 10, colorDistance <= 0.28 else { return nil }
+
+ let score = 1 - (
+ 0.45 * Double(differenceDistance) / 64 +
+ 0.35 * Double(averageDistance) / 64 +
+ 0.20 * colorDistance
+ )
+ return score >= 0.84 ? score : nil
+ }
+
+ private static func identity(at url: URL) -> FileIdentity? {
+ var information = stat()
+ guard lstat(url.path, &information) == 0 else { return nil }
+ return FileIdentity(
+ device: UInt64(information.st_dev),
+ inode: UInt64(information.st_ino),
+ size: Int64(information.st_size),
+ modifiedSeconds: Int64(information.st_mtimespec.tv_sec),
+ modifiedNanoseconds: Int64(information.st_mtimespec.tv_nsec)
+ )
+ }
+
+ private static func isRegularFile(at url: URL) -> Bool {
+ var information = stat()
+ guard lstat(url.path, &information) == 0 else { return false }
+ return information.st_mode & S_IFMT == S_IFREG
+ }
+
+ private static func isDirectory(at url: URL) -> Bool {
+ var information = stat()
+ guard lstat(url.path, &information) == 0 else { return false }
+ return information.st_mode & S_IFMT == S_IFDIR
+ }
+
+ private static func isSymbolicLink(at url: URL) -> Bool {
+ var information = stat()
+ guard lstat(url.path, &information) == 0 else { return false }
+ return information.st_mode & S_IFMT == S_IFLNK
+ }
+
+ private static func isPackage(at url: URL) -> Bool {
+ (try? url.resourceValues(forKeys: [.isPackageKey]).isPackage) == true
+ }
+
+ private static func isCloudPlaceholder(at url: URL) -> Bool {
+ if url.pathExtension.lowercased() == "icloud" { return true }
+ var information = stat()
+ if lstat(url.path, &information) == 0 && information.st_flags & UInt32(SF_DATALESS) != 0 {
+ return true
+ }
+ guard let values = try? url.resourceValues(forKeys: [
+ .isUbiquitousItemKey,
+ .ubiquitousItemDownloadingStatusKey
+ ]) else {
+ return false
+ }
+ return values.isUbiquitousItem == true &&
+ values.ubiquitousItemDownloadingStatus != .current &&
+ values.ubiquitousItemDownloadingStatus != .downloaded
+ }
+}
diff --git a/PureMac/Services/StorageExplorer.swift b/PureMac/Services/StorageExplorer.swift
new file mode 100644
index 0000000..74ff32e
--- /dev/null
+++ b/PureMac/Services/StorageExplorer.swift
@@ -0,0 +1,328 @@
+import Darwin
+import Foundation
+
+struct StorageEntry: Identifiable, Hashable, Sendable {
+ enum Kind: Hashable, Sendable {
+ case file
+ case directory
+ case package
+ }
+
+ let url: URL
+ let kind: Kind
+ let allocatedSize: Int64
+ let fileCount: Int
+ let directoryCount: Int
+ let inaccessibleCount: Int
+ let skippedCount: Int
+
+ var id: URL { url }
+ var name: String { url.lastPathComponent }
+ var isDirectory: Bool { kind == .directory }
+ var isPackage: Bool { kind == .package }
+ var isPartial: Bool { inaccessibleCount > 0 || skippedCount > 0 }
+ var itemCount: Int { fileCount + directoryCount }
+}
+
+struct StorageScanProgress: Sendable {
+ let rootURL: URL
+ let currentURL: URL
+ let allocatedSize: Int64
+ let scannedItemCount: Int
+ let inaccessibleCount: Int
+ let skippedCount: Int
+}
+
+struct StorageScanResult: Sendable {
+ let rootURL: URL
+ let entries: [StorageEntry]
+ let totalAllocatedSize: Int64
+ let fileCount: Int
+ let directoryCount: Int
+ let inaccessibleCount: Int
+ let skippedCount: Int
+
+ var scannedItemCount: Int { fileCount + directoryCount }
+ var isPartial: Bool { inaccessibleCount > 0 || skippedCount > 0 }
+}
+
+enum StorageExplorerError: LocalizedError, Equatable {
+ case notDirectory(String)
+ case symbolicLink(String)
+ case package(String)
+ case cloudOnly(String)
+ case unavailable(String)
+
+ var errorDescription: String? {
+ switch self {
+ case .notDirectory(let path):
+ return "The selected item is not a folder: \(path)"
+ case .symbolicLink(let path):
+ return "Symbolic links cannot be scanned: \(path)"
+ case .package(let path):
+ return "App and document packages are excluded: \(path)"
+ case .cloudOnly(let path):
+ return "The selected folder is stored in the cloud and has not been downloaded: \(path)"
+ case .unavailable(let path):
+ return "The selected folder could not be read: \(path)"
+ }
+ }
+}
+
+actor StorageExplorer {
+ typealias ProgressHandler = @Sendable (StorageScanProgress) -> Void
+
+ private struct FileIdentity: Hashable {
+ let device: UInt64
+ let inode: UInt64
+ }
+
+ private struct FileMetadata {
+ let identity: FileIdentity
+ let allocatedSize: Int64
+ let isDataless: Bool
+ }
+
+ private struct ScanContext {
+ var allocatedSize: Int64 = 0
+ var fileCount = 0
+ var directoryCount = 0
+ var inaccessibleCount = 0
+ var skippedCount = 0
+ var seenFiles: Set<FileIdentity> = []
+ }
+
+ private struct EntryMeasure {
+ var allocatedSize: Int64 = 0
+ var fileCount = 0
+ var directoryCount = 0
+ var inaccessibleCount = 0
+ var skippedCount = 0
+ }
+
+ private static let resourceKeys: Set<URLResourceKey> = [
+ .isDirectoryKey,
+ .isRegularFileKey,
+ .isSymbolicLinkKey,
+ .isPackageKey,
+ .isUbiquitousItemKey,
+ .ubiquitousItemDownloadingStatusKey
+ ]
+
+ func scan(
+ at selectedURL: URL,
+ progress: ProgressHandler? = nil
+ ) async throws -> StorageScanResult {
+ try Task.checkCancellation()
+
+ let rootURL = selectedURL.standardizedFileURL
+ let rootValues: URLResourceValues
+ do {
+ rootValues = try rootURL.resourceValues(forKeys: Self.resourceKeys)
+ } catch {
+ throw StorageExplorerError.unavailable(rootURL.path)
+ }
+
+ guard rootValues.isSymbolicLink != true else {
+ throw StorageExplorerError.symbolicLink(rootURL.path)
+ }
+ guard rootValues.isPackage != true else {
+ throw StorageExplorerError.package(rootURL.path)
+ }
+ guard rootValues.isDirectory == true else {
+ throw StorageExplorerError.notDirectory(rootURL.path)
+ }
+ guard !Self.isUnavailableCloudItem(rootValues) else {
+ throw StorageExplorerError.cloudOnly(rootURL.path)
+ }
+ guard let rootMetadata = Self.metadata(for: rootURL) else {
+ throw StorageExplorerError.unavailable(rootURL.path)
+ }
+ guard !rootMetadata.isDataless else {
+ throw StorageExplorerError.cloudOnly(rootURL.path)
+ }
+
+ let children: [URL]
+ do {
+ children = try FileManager.default.contentsOfDirectory(
+ at: rootURL,
+ includingPropertiesForKeys: Array(Self.resourceKeys),
+ options: []
+ )
+ } catch {
+ throw StorageExplorerError.unavailable(rootURL.path)
+ }
+
+ var context = ScanContext()
+ var entries: [StorageEntry] = []
+ let orderedChildren = children.sorted {
+ $0.lastPathComponent.localizedStandardCompare($1.lastPathComponent) == .orderedAscending
+ }
+
+ for child in orderedChildren {
+ try Task.checkCancellation()
+ if let entry = try measure(
+ child,
+ rootURL: rootURL,
+ context: &context,
+ progress: progress
+ ) {
+ entries.append(entry)
+ }
+ }
+
+ entries.sort {
+ if $0.allocatedSize == $1.allocatedSize {
+ return $0.name.localizedStandardCompare($1.name) == .orderedAscending
+ }
+ return $0.allocatedSize > $1.allocatedSize
+ }
+
+ progress?(
+ StorageScanProgress(
+ rootURL: rootURL,
+ currentURL: rootURL,
+ allocatedSize: context.allocatedSize,
+ scannedItemCount: context.fileCount + context.directoryCount,
+ inaccessibleCount: context.inaccessibleCount,
+ skippedCount: context.skippedCount
+ )
+ )
+
+ return StorageScanResult(
+ rootURL: rootURL,
+ entries: entries,
+ totalAllocatedSize: context.allocatedSize,
+ fileCount: context.fileCount,
+ directoryCount: context.directoryCount,
+ inaccessibleCount: context.inaccessibleCount,
+ skippedCount: context.skippedCount
+ )
+ }
+
+ private func measure(
+ _ topURL: URL,
+ rootURL: URL,
+ context: inout ScanContext,
+ progress: ProgressHandler?
+ ) throws -> StorageEntry? {
+ var stack = [topURL]
+ var entryMeasure = EntryMeasure()
+ var topKind: StorageEntry.Kind?
+
+ while let url = stack.popLast() {
+ try Task.checkCancellation()
+
+ let values: URLResourceValues
+ do {
+ values = try url.resourceValues(forKeys: Self.resourceKeys)
+ } catch {
+ context.inaccessibleCount += 1
+ entryMeasure.inaccessibleCount += 1
+ continue
+ }
+
+ if values.isSymbolicLink == true || Self.isUnavailableCloudItem(values) {
+ context.skippedCount += 1
+ entryMeasure.skippedCount += 1
+ continue
+ }
+
+ guard let metadata = Self.metadata(for: url) else {
+ context.inaccessibleCount += 1
+ entryMeasure.inaccessibleCount += 1
+ continue
+ }
+ if metadata.isDataless {
+ context.skippedCount += 1
+ entryMeasure.skippedCount += 1
+ continue
+ }
+
+ if values.isDirectory == true {
+ if url == topURL {
+ topKind = values.isPackage == true ? .package : .directory
+ }
+ context.allocatedSize += metadata.allocatedSize
+ context.directoryCount += 1
+ entryMeasure.allocatedSize += metadata.allocatedSize
+ entryMeasure.directoryCount += 1
+
+ do {
+ let children = try FileManager.default.contentsOfDirectory(
+ at: url,
+ includingPropertiesForKeys: Array(Self.resourceKeys),
+ options: []
+ )
+ stack.append(contentsOf: children)
+ } catch {
+ context.inaccessibleCount += 1
+ entryMeasure.inaccessibleCount += 1
+ }
+ } else if values.isRegularFile == true {
+ if url == topURL {
+ topKind = .file
+ }
+ if context.seenFiles.insert(metadata.identity).inserted {
+ context.allocatedSize += metadata.allocatedSize
+ context.fileCount += 1
+ entryMeasure.allocatedSize += metadata.allocatedSize
+ entryMeasure.fileCount += 1
+ } else {
+ context.skippedCount += 1
+ entryMeasure.skippedCount += 1
+ }
+ } else {
+ context.skippedCount += 1
+ entryMeasure.skippedCount += 1
+ }
+
+ let scannedCount = context.fileCount + context.directoryCount
+ if scannedCount > 0 && scannedCount.isMultiple(of: 64) {
+ progress?(
+ StorageScanProgress(
+ rootURL: rootURL,
+ currentURL: url,
+ allocatedSize: context.allocatedSize,
+ scannedItemCount: scannedCount,
+ inaccessibleCount: context.inaccessibleCount,
+ skippedCount: context.skippedCount
+ )
+ )
+ }
+ }
+
+ guard let topKind, entryMeasure.fileCount + entryMeasure.directoryCount > 0 else { return nil }
+ return StorageEntry(
+ url: topURL,
+ kind: topKind,
+ allocatedSize: entryMeasure.allocatedSize,
+ fileCount: entryMeasure.fileCount,
+ directoryCount: entryMeasure.directoryCount,
+ inaccessibleCount: entryMeasure.inaccessibleCount,
+ skippedCount: entryMeasure.skippedCount
+ )
+ }
+
+ private static func isUnavailableCloudItem(_ values: URLResourceValues) -> Bool {
+ guard values.isUbiquitousItem == true else { return false }
+ let status = values.ubiquitousItemDownloadingStatus
+ return status != .current && status != .downloaded
+ }
+
+ private static func metadata(for url: URL) -> FileMetadata? {
+ var fileStat = stat()
+ let status: Int32 = url.withUnsafeFileSystemRepresentation { path in
+ guard let path else { return Int32(-1) }
+ return lstat(path, &fileStat)
+ }
+ guard status == 0 else { return nil }
+
+ let blocks = max(Int64(0), Int64(fileStat.st_blocks))
+ return FileMetadata(
+ identity: FileIdentity(device: UInt64(fileStat.st_dev), inode: UInt64(fileStat.st_ino)),
+ allocatedSize: blocks * 512,
+ isDataless: fileStat.st_flags & UInt32(SF_DATALESS) != 0
+ )
+ }
+}
diff --git a/PureMac/ViewModels/AppState.swift b/PureMac/ViewModels/AppState.swift
index 435e741..908e895 100644
--- a/PureMac/ViewModels/AppState.swift
+++ b/PureMac/ViewModels/AppState.swift
@@ -8,6 +8,12 @@ import AppKit
enum AppSection: Hashable {
case apps
case orphans
+ case spaceExplorer
+ case duplicates
+ case similarPhotos
+ case protection
+ case performance
+ case appUpdates
case cleaning(CleaningCategory)
}
@@ -46,6 +52,10 @@ final class AppState: ObservableObject {
_ locations: Locations,
_ completion: @escaping (Set<URL>) -> Void
) -> Void
+ typealias AppFileTrasher = @MainActor (
+ _ urls: [URL],
+ _ completion: @escaping ([URL], Bool, [URL], [URL]) -> Void
+ ) -> Void
// MARK: - Scan / Clean State
@@ -56,6 +66,11 @@ final class AppState: ObservableObject {
@Published var totalJunkSize: Int64 = 0
@Published var totalFreedSpace: Int64 = 0
@Published var scanProgress: Double = 0
+ @Published var scanWasCancelled = false
+ @Published var lastScanDate: Date?
+ private var scanTask: Task<Void, Never>?
+ private var scanGeneration = UUID()
+ private var cleanupGeneration = UUID()
@Published var cleanProgress: Double = 0
@Published var currentScanCategory: String = ""
/// Live filesystem path the scan engine is touching, feeding the dashboard's
@@ -70,6 +85,7 @@ final class AppState: ObservableObject {
@Published var hasFullDiskAccess: Bool = true
@Published var fdaBannerDismissed: Bool = false
@Published var cleanError: String?
+ @Published private(set) var lastCleanupHadFailures = false
/// True when the most recent clean error is rooted in a TCC/FDA refusal
/// (i.e. items survived even the admin pass). MainWindow uses this to
/// route the user into the PermissionSheet instead of the generic alert.
@@ -89,6 +105,7 @@ final class AppState: ObservableObject {
@Published var isSearchingOrphans: Bool = false
@Published var isLoadingApps: Bool = false
@Published var isScanningAppFiles: Bool = false
+ @Published var isRemovingAppFiles = false
@Published var removalError: String?
@Published var removalNeedsFullDiskAccess = false
/// Snapshot of the URLs that failed the most recent uninstall due to a
@@ -104,6 +121,7 @@ final class AppState: ObservableObject {
@Published var pendingExternalApp: InstalledApp?
private var externalUninstallObserver: AnyCancellable?
+ private var appFileScanGeneration = UUID()
// MARK: - Services
@@ -112,6 +130,7 @@ final class AppState: ObservableObject {
private let cleaningEngine = CleaningEngine()
private let locationsProvider: () -> Locations
private let appFileScanner: AppFileScanner
+ private let appFileTrasher: AppFileTrasher
// MARK: - Computed
@@ -143,10 +162,12 @@ final class AppState: ObservableObject {
init(
performStartupTasks: Bool = true,
locationsProvider: @escaping () -> Locations = Locations.init,
- appFileScanner: @escaping AppFileScanner = AppState.defaultAppFileScanner
+ appFileScanner: @escaping AppFileScanner = AppState.defaultAppFileScanner,
+ appFileTrasher: @escaping AppFileTrasher = AppState.defaultAppFileTrasher
) {
self.locationsProvider = locationsProvider
self.appFileScanner = appFileScanner
+ self.appFileTrasher = appFileTrasher
// Listen for right-click "Uninstall with PureMac" hand-offs from the
// Finder Services handler in AppDelegate.
@@ -234,8 +255,10 @@ final class AppState: ObservableObject {
isScanningAppFiles = true
let locations = locationsProvider()
appFileScanLocationCount = locations.appSearch.paths.count
+ let generation = UUID()
+ appFileScanGeneration = generation
appFileScanner(app, locations) { [weak self] urls in
- guard let self else { return }
+ guard let self, self.appFileScanGeneration == generation else { return }
let sorted = urls.sorted { $0.path < $1.path }
self.discoveredFiles = sorted
self.selectedFiles = urls
@@ -244,7 +267,7 @@ final class AppState: ObservableObject {
}
}
- func removeSelectedFiles() {
+ func removeSelectedFiles(confirmedURLs: Set<URL>? = nil) {
// Re-entrance guard: if a previous removal is still resolving and
// the FDA sheet/retry hasn't finished, a second call would race-
// overwrite `lastFailedRemovalURLs` before the first batch's retry
@@ -254,7 +277,7 @@ final class AppState: ObservableObject {
// would pass the guard while the coordinator is still polling.
// PermissionCoordinator.isRequesting covers the full sheet-open +
// retry-pending span.
- guard !removalNeedsFullDiskAccess,
+ guard !isRemovingAppFiles, !removalNeedsFullDiskAccess,
!PermissionCoordinator.shared.isRequesting else {
Logger.shared.log("Refused duplicate removeSelectedFiles while FDA flow is active", level: .info)
return
@@ -263,7 +286,7 @@ final class AppState: ObservableObject {
// Conditions.swift) to be trashed no matter how it ended up in the
// selection. Catches selection-time additions that slipped past the
// scanner-side filters.
- let allURLs = Array(selectedFiles)
+ let allURLs = Array(confirmedURLs ?? selectedFiles)
let (urls, blocked): ([URL], [URL]) = allURLs.reduce(into: ([], [])) { acc, url in
let resolved = url.resolvingSymlinksInPath().path
let isBlocked = highRiskHomeDotPaths.contains { root in
@@ -288,7 +311,8 @@ final class AppState: ObservableObject {
}
return
}
- trashDirectly(urls: urls) { [weak self] removed, needsFullDiskAccess, needsAdmin, failed in
+ isRemovingAppFiles = true
+ appFileTrasher(urls) { [weak self] removed, needsFullDiskAccess, needsAdmin, failed in
Task { @MainActor in
guard let self else { return }
@@ -331,7 +355,7 @@ final class AppState: ObservableObject {
/// Full Disk Access list. The previous AppleScript-via-Finder bridge
/// caused the syscall to originate from Finder, which is why granting
/// FDA to PureMac made no difference (issue #75).
- private func trashDirectly(urls: [URL], completion: @escaping ([URL], Bool, [URL], [URL]) -> Void) {
+ private static func defaultAppFileTrasher(urls: [URL], completion: @escaping ([URL], Bool, [URL], [URL]) -> Void) {
DispatchQueue.global(qos: .userInitiated).async {
let hasFullDiskAccess = FullDiskAccessManager.shared.hasFullDiskAccess
var removed: [URL] = []
@@ -391,6 +415,7 @@ final class AppState: ObservableObject {
) {
// Freeze the failed batch before the FDA sheet opens so the retry
// path can't be poisoned by later selection edits or app switches.
+ isRemovingAppFiles = false
lastFailedRemovalURLs = needsFullDiskAccess ? failed : []
removalNeedsFullDiskAccess = needsFullDiskAccess
if let message = removalFailureMessage(
@@ -588,6 +613,38 @@ final class AppState: ObservableObject {
objectWillChange.send()
}
+ var excludedCleanupPaths: [String] {
+ CleanupExclusions.paths()
+ }
+
+ func excludeFromCleanup(_ item: CleanableItem) {
+ guard !item.isActionItem, !scanState.isActive else { return }
+ CleanupExclusions.add(item.path)
+ for (category, result) in categoryResults {
+ categoryResults[category] = applyingCleanupExclusions(to: result)
+ }
+ totalJunkSize = categoryResults.values.reduce(0) { $0 + $1.totalSize }
+ }
+
+ func removeCleanupExclusion(_ path: String) {
+ UserDefaults.standard.set(excludedCleanupPaths.filter { $0 != path }, forKey: CleanupExclusions.defaultsKey)
+ objectWillChange.send()
+ }
+
+ private func applyingCleanupExclusions(to result: CategoryResult) -> CategoryResult {
+ let excluded = excludedCleanupPaths
+ guard !excluded.isEmpty else { return result }
+ let items = result.items.filter { !CleanupExclusions.excludes($0.path, paths: excluded) }
+ return CategoryResult(category: result.category, items: items, totalSize: items.reduce(0) { $0 + $1.size })
+ }
+
+ func setSelection(_ selected: Bool, for items: [CleanableItem]) {
+ guard !scanState.isActive else { return }
+ for item in items where isItemSelected(item) != selected {
+ toggleItem(item)
+ }
+ }
+
// MARK: - Selection
func isItemSelected(_ item: CleanableItem) -> Bool {
@@ -725,23 +782,35 @@ final class AppState: ObservableObject {
) { [weak self] in
Task { @MainActor [weak self] in
guard let self else { return }
- self.pendingPermissionRetryItems = []
- self.cleanError = nil
- self.cleanErrorIsFDAFixable = false
- guard !capturedItems.isEmpty else { return }
- await self.retryCleanItems(capturedItems)
+ await self.retryAfterFullDiskAccess(items: capturedItems, context: context)
}
}
}
+ func retryAfterFullDiskAccess(items: [CleanableItem], context: PermissionCoordinator.PromptContext) async {
+ pendingPermissionRetryItems = []
+ cleanError = nil
+ cleanErrorIsFDAFixable = false
+ guard !items.isEmpty else { return }
+ if case .uninstall = context {
+ removeSelectedFiles(confirmedURLs: Set(items.map { URL(fileURLWithPath: $0.path) }))
+ } else {
+ await retryCleanItems(items)
+ }
+ }
+
private func retryCleanItems(_ items: [CleanableItem]) async {
+ guard !scanState.isActive else { return }
+ let generation = UUID()
+ cleanupGeneration = generation
scanState = .cleaning(progress: 0)
cleanProgress = 0
var result = await cleaningEngine.cleanItems(items) { [weak self] progress in
Task { @MainActor [weak self] in
- self?.cleanProgress = progress
- self?.scanState = .cleaning(progress: progress)
+ guard let self, self.cleanupGeneration == generation, case .cleaning = self.scanState else { return }
+ self.cleanProgress = progress
+ self.scanState = .cleaning(progress: progress)
}
}
if !result.requiresAdmin.isEmpty {
@@ -754,7 +823,7 @@ final class AppState: ObservableObject {
}
totalFreedSpace = result.freedSpace
- lastCleanedDate = Date()
+ if result.itemsCleaned > 0 { lastCleanedDate = Date() }
for (cat, catResult) in categoryResults {
let remaining = catResult.items.filter { !result.cleanedPaths.contains($0.path) }
@@ -781,11 +850,8 @@ final class AppState: ObservableObject {
let survivors = survivingItems(from: items, result: result)
handleCleanOutcome(errors: result.errors, survivors: survivors)
- scanState = .cleaned
+ scanState = result.itemsCleaned > 0 ? .cleaned : .completed
loadDiskInfo()
- try? await Task.sleep(nanoseconds: 3_000_000_000)
- scanState = .idle
- totalFreedSpace = 0
}
// MARK: - Disk Info
@@ -801,73 +867,72 @@ final class AppState: ObservableObject {
func startSmartScan() {
guard !scanState.isActive else { return }
+ beginScan(categories: CleaningCategory.scannable, replacingResults: true)
+ }
- scanState = .scanning(progress: 0, currentCategory: "Preparing...")
- categoryResults = [:]
- totalJunkSize = 0
- scanProgress = 0
- clearSelectionState()
+ func scanSingleCategory(_ category: CleaningCategory) {
+ guard !scanState.isActive, CleaningCategory.scannable.contains(category) else { return }
+ beginScan(categories: [category], replacingResults: false)
+ }
- Task {
- let categories = CleaningCategory.scannable
- let total = categories.count
+ func cancelScan() {
+ guard case .scanning = scanState else { return }
+ scanTask?.cancel()
+ scanTask = nil
+ scanGeneration = UUID()
+ scanWasCancelled = true
+ scanTicker.path = ""
+ scanState = categoryResults.isEmpty ? .idle : .completed
+ }
+ private func beginScan(categories: [CleaningCategory], replacingResults: Bool) {
+ let generation = UUID()
+ scanGeneration = generation
+ scanWasCancelled = false
+ totalFreedSpace = 0
+ scanProgress = 0
+ scanState = .scanning(progress: 0, currentCategory: "Preparing...")
+ if replacingResults {
+ categoryResults = [:]
+ totalJunkSize = 0
+ clearSelectionState()
+ }
+ scanTask = Task {
for (index, category) in categories.enumerated() {
- let progress = Double(index) / Double(total)
+ guard !Task.isCancelled, scanGeneration == generation else { return }
+ let progress = Double(index) / Double(categories.count)
scanProgress = progress
currentScanCategory = category.rawValue
scanState = .scanning(progress: progress, currentCategory: category.rawValue)
-
+ clearSelectionState(for: category)
let result = await scanEngine.scanCategory(category) { [weak self] path in
Task { @MainActor [weak self] in
- self?.scanTicker.path = path
+ guard let self, self.scanGeneration == generation else { return }
+ self.scanTicker.path = path
}
}
- categoryResults[category] = result
- totalJunkSize += result.totalSize
+ guard !Task.isCancelled, scanGeneration == generation else { return }
+ categoryResults[category] = applyingCleanupExclusions(to: result)
+ totalJunkSize = categoryResults.values.reduce(0) { $0 + $1.totalSize }
}
-
- scanProgress = 1.0
+ scanProgress = 1
scanTicker.path = ""
- scanState = .scanning(progress: 1.0, currentCategory: "Finishing scan")
- try? await Task.sleep(nanoseconds: 800_000_000)
+ lastScanDate = Date()
scanState = .completed
+ scanTask = nil
loadDiskInfo()
}
}
- func scanSingleCategory(_ category: CleaningCategory) {
- guard !scanState.isActive else { return }
-
- scanState = .scanning(progress: 0, currentCategory: category.rawValue)
- scanProgress = 0
-
- Task {
- scanProgress = 0.5
- clearSelectionState(for: category)
- let result = await scanEngine.scanCategory(category) { [weak self] path in
- Task { @MainActor [weak self] in
- self?.scanTicker.path = path
- }
- }
- categoryResults[category] = result
-
- totalJunkSize = categoryResults.values.reduce(0) { $0 + $1.totalSize }
- scanProgress = 1.0
- scanTicker.path = ""
- scanState = .scanning(progress: 1.0, currentCategory: "Finishing scan")
- try? await Task.sleep(nanoseconds: 800_000_000)
- scanState = .completed
- }
- }
-
// MARK: - Cleaning
- func cleanAll() {
+ func cleanAll(itemIDs: Set<UUID>? = nil) {
guard !scanState.isActive else { return }
- let itemsToClean = allResults.flatMap { $0.items }.filter { isItemSelected($0) }
+ let itemsToClean = allResults.flatMap { $0.items }.filter { isItemSelected($0) && (itemIDs?.contains($0.id) ?? true) }
guard !itemsToClean.isEmpty else { return }
+ let generation = UUID()
+ cleanupGeneration = generation
scanState = .cleaning(progress: 0)
cleanProgress = 0
@@ -875,8 +940,9 @@ final class AppState: ObservableObject {
Task {
var result = await cleaningEngine.cleanItems(itemsToClean) { [weak self] progress in
Task { @MainActor [weak self] in
- self?.cleanProgress = progress
- self?.scanState = .cleaning(progress: progress)
+ guard let self, self.cleanupGeneration == generation, case .cleaning = self.scanState else { return }
+ self.cleanProgress = progress
+ self.scanState = .cleaning(progress: progress)
}
}
@@ -892,7 +958,7 @@ final class AppState: ObservableObject {
}
totalFreedSpace = result.freedSpace
- lastCleanedDate = Date()
+ if result.itemsCleaned > 0 { lastCleanedDate = Date() }
if result.itemsCleaned > 0 { Haptics.successWithSound() }
let survivors = survivingItems(from: itemsToClean, result: result)
@@ -918,20 +984,18 @@ final class AppState: ObservableObject {
handleCleanOutcome(errors: result.errors, survivors: survivors)
- scanState = .cleaned
+ scanState = result.itemsCleaned > 0 ? .cleaned : .completed
loadDiskInfo()
-
- try? await Task.sleep(nanoseconds: 3_000_000_000)
- scanState = .idle
- totalFreedSpace = 0
}
}
- func cleanCategory(_ category: CleaningCategory) {
+ func cleanCategory(_ category: CleaningCategory, itemIDs: Set<UUID>? = nil) {
guard let result = categoryResults[category], !scanState.isActive else { return }
- let selectedItems = result.items.filter { isItemSelected($0) }
+ let selectedItems = result.items.filter { isItemSelected($0) && (itemIDs?.contains($0.id) ?? true) }
guard !selectedItems.isEmpty else { return }
+ let generation = UUID()
+ cleanupGeneration = generation
scanState = .cleaning(progress: 0)
cleanProgress = 0
@@ -939,8 +1003,9 @@ final class AppState: ObservableObject {
Task {
var cleanResult = await cleaningEngine.cleanItems(selectedItems) { [weak self] progress in
Task { @MainActor [weak self] in
- self?.cleanProgress = progress
- self?.scanState = .cleaning(progress: progress)
+ guard let self, self.cleanupGeneration == generation, case .cleaning = self.scanState else { return }
+ self.cleanProgress = progress
+ self.scanState = .cleaning(progress: progress)
}
}
@@ -954,7 +1019,7 @@ final class AppState: ObservableObject {
}
totalFreedSpace = cleanResult.freedSpace
- lastCleanedDate = Date()
+ if cleanResult.itemsCleaned > 0 { lastCleanedDate = Date() }
if let existing = categoryResults[category] {
let remaining = existing.items.filter { !cleanResult.cleanedPaths.contains($0.path) }
@@ -978,12 +1043,8 @@ final class AppState: ObservableObject {
let survivors = survivingItems(from: selectedItems, result: cleanResult)
handleCleanOutcome(errors: cleanResult.errors, survivors: survivors)
- scanState = .cleaned
+ scanState = cleanResult.itemsCleaned > 0 ? .cleaned : .completed
loadDiskInfo()
-
- try? await Task.sleep(nanoseconds: 3_000_000_000)
- scanState = .idle
- totalFreedSpace = 0
}
}
@@ -1007,6 +1068,7 @@ final class AppState: ObservableObject {
/// PermissionSheet (FDA is the most likely cause) or surface a richer
/// error alert that lists actual paths instead of "Check the log".
private func handleCleanOutcome(errors: [String], survivors: [CleanableItem]) {
+ lastCleanupHadFailures = !errors.isEmpty || !survivors.isEmpty
guard !errors.isEmpty || !survivors.isEmpty else {
cleanError = nil
cleanErrorIsFDAFixable = false
@@ -1044,53 +1106,46 @@ final class AppState: ObservableObject {
// MARK: - Purgeable
func purgePurgeable() {
- guard !scanState.isActive else { return }
-
- scanState = .cleaning(progress: 0)
-
- Task {
- scanState = .cleaning(progress: 0.5)
- let freed = await cleaningEngine.purgePurgeableSpace()
- totalFreedSpace = freed
- scanState = .cleaned
- loadDiskInfo()
-
- try? await Task.sleep(nanoseconds: 3_000_000_000)
- scanState = .idle
- totalFreedSpace = 0
- }
+ loadDiskInfo()
}
// MARK: - Scheduled Scan
- private func runScheduledScan() async {
- // App-modifying categories (see CleaningCategory.appModifying) never
- // run unattended — a scheduled autoClean must not re-sign or strip
- // installed apps behind the user's back.
- let categories = scheduler.config.categoriesToScan
- .filter { !CleaningCategory.appModifying.contains($0) }
- var totalFound: Int64 = 0
+ func canRunScheduledScan(isAppActive: Bool) -> Bool {
+ !scanState.isActive && !(scanState == .completed && isAppActive)
+ && !showCleanConfirmation && !isScanningAppFiles && !isRemovingAppFiles
+ && !isSearchingOrphans && !PermissionCoordinator.shared.isRequesting
+ }
+
+ func runScheduledScan() async {
+ guard canRunScheduledScan(isAppActive: NSApp.isActive) else { return }
+ let categories = scheduler.config.categoriesToScan.filter { CleaningCategory.scannable.contains($0) }
+ guard !categories.isEmpty else { return }
+ let generation = UUID()
+ scanGeneration = generation
+ scanWasCancelled = false
clearSelectionState()
categoryResults = [:]
-
- for category in categories {
- let result = await scanEngine.scanCategory(category)
+ totalJunkSize = 0
+ for (index, category) in categories.enumerated() {
+ let progress = Double(index) / Double(categories.count)
+ scanState = .scanning(progress: progress, currentCategory: category.rawValue)
+ scanProgress = progress
+ currentScanCategory = category.rawValue
+ let result = applyingCleanupExclusions(to: await scanEngine.scanCategory(category))
+ guard scanGeneration == generation, !Task.isCancelled else { return }
categoryResults[category] = result
- totalFound += result.totalSize
+ totalJunkSize += result.totalSize
}
-
- totalJunkSize = totalFound
-
- if scheduler.config.autoClean && totalFound >= scheduler.config.minimumCleanSize {
+ scanProgress = 1
+ lastScanDate = Date()
+ scanState = .completed
+ let found = totalJunkSize
+ if scheduler.config.autoClean && totalSelectedSize >= scheduler.config.minimumCleanSize {
cleanAll()
}
-
- // Purgeable space is intentionally NOT auto-purged: macOS reserves and
- // reclaims it on its own and PureMac does not claim to free it. See
- // CleaningCategory.scannable.
-
if scheduler.config.notifyOnCompletion {
- sendNotification(freed: totalFound)
+ sendNotification(freed: found)
}
}
diff --git a/PureMac/Views/Apps/AppFilesView.swift b/PureMac/Views/Apps/AppFilesView.swift
index 5f00902..2f1dc93 100644
--- a/PureMac/Views/Apps/AppFilesView.swift
+++ b/PureMac/Views/Apps/AppFilesView.swift
@@ -60,6 +60,8 @@ struct AppFilesView: View {
@State private var collapsedGroups: Set<LeftoverGroup> = []
@State private var iconHovering = false
+ @State private var showBulkConfirmation = false
+ @State private var pendingRemoval: Set<URL> = []
/// One-pass size cache so group headers and the selected-size counter
/// don't re-stat the disk on every render.
@State private var sizeCache: [URL: Int64] = [:]
@@ -106,8 +108,30 @@ struct AppFilesView: View {
actionBar
}
}
- .onAppear { rebuildSizeCache() }
- .onChange(of: appState.discoveredFiles) { _ in rebuildSizeCache() }
+ .task(id: appState.discoveredFiles) {
+ let urls = appState.discoveredFiles
+ let task = Task.detached(priority: .utility) {
+ var sizes: [URL: Int64] = [:]
+ for url in urls {
+ guard !Task.isCancelled else { break }
+ sizes[url] = FileSizeCalculator.size(of: url) ?? 0
+ }
+ return sizes
+ }
+ let sizes = await withTaskCancellationHandler(operation: { await task.value }, onCancel: { task.cancel() })
+ guard !Task.isCancelled else { return }
+ sizeCache = sizes
+ }
+ .disabled(appState.isRemovingAppFiles)
+ .confirmationDialog("Remove selected app files?", isPresented: $showBulkConfirmation, titleVisibility: .visible) {
+ Button("Remove \(pendingRemoval.count) files", role: .destructive) {
+ appState.removeSelectedFiles(confirmedURLs: pendingRemoval)
+ pendingRemoval = []
+ }
+ Button("Cancel", role: .cancel) { pendingRemoval = [] }
+ } message: {
+ Text("PureMac will move the selected app and related files to the Trash. Items requiring administrator authorization may be permanently deleted. Review the selection before continuing.")
+ }
.onChange(of: appState.removalNeedsFullDiskAccess) { needs in
// FDA-fixable removals jump straight into the rich sheet, the
// same flow cleanup uses. The user grants permission once and we
@@ -317,7 +341,8 @@ struct AppFilesView: View {
if !appState.selectedFiles.isEmpty {
Button(role: .destructive) {
- appState.removeSelectedFiles()
+ pendingRemoval = appState.selectedFiles
+ showBulkConfirmation = true
} label: {
Text(removeFilesLabel)
}
@@ -371,20 +396,7 @@ struct AppFilesView: View {
}
private func cachedSize(_ url: URL) -> Int64? {
- if let cached = sizeCache[url] { return cached }
- return fileSize(url)
- }
-
- private func rebuildSizeCache() {
- var cache: [URL: Int64] = [:]
- for url in appState.discoveredFiles {
- cache[url] = fileSize(url) ?? 0
- }
- sizeCache = cache
- }
-
- private func fileSize(_ url: URL) -> Int64? {
- FileSizeCalculator.size(of: url)
+ sizeCache[url]
}
private func removeSingleFile(_ url: URL) {
diff --git a/PureMac/Views/CategoryDetailView.swift b/PureMac/Views/CategoryDetailView.swift
index 2b5d9c3..b1b9466 100644
--- a/PureMac/Views/CategoryDetailView.swift
+++ b/PureMac/Views/CategoryDetailView.swift
@@ -2,353 +2,264 @@ import SwiftUI
struct CategoryDetailView: View {
@EnvironmentObject var appState: AppState
+ @Environment(\.accessibilityReduceMotion) private var reduceMotion
let category: CleaningCategory
- @State private var sortDescending: Bool = true
- @State private var searchText = ""
+ @State private var filter = CleanupReviewFilter()
@State private var showConfirmation = false
- @Environment(\.accessibilityReduceMotion) private var reduceMotion
+ @State private var pendingItems: [CleanableItem] = []
- private var result: CategoryResult? {
- appState.categoryResults[category]
- }
+ private var result: CategoryResult? { appState.categoryResults[category] }
+ private var visibleItems: [CleanableItem] { filter.apply(to: result?.items ?? []) }
+ private var selectedItems: [CleanableItem] { (result?.items ?? []).filter(appState.isItemSelected) }
+ private var selectedSize: Int64 { selectedItems.reduce(0) { $0 + $1.size } }
var body: some View {
VStack(spacing: 0) {
- heroCard
- .padding(.horizontal, 20)
- .padding(.top, 16)
- .padding(.bottom, 12)
-
- Group {
- if let result = result {
- if result.items.isEmpty {
- EmptyStateView("All Clean", systemImage: "checkmark.circle", description: "No junk files found in this category.", tint: Tint.green)
- } else {
- VStack(spacing: 0) {
- selectionStrip(result)
- .padding(.horizontal, 20)
- .padding(.bottom, 10)
- fileList(result)
- }
- }
- } else {
- EmptyStateView("Not Scanned", systemImage: category.icon, description: "Run a scan to analyze this category.", action: { appState.scanSingleCategory(category) }, actionLabel: "Scan Now", tint: category.color)
- }
- }
- }
- .searchable(text: $searchText, prompt: "Filter files")
- .navigationTitle(Text(LocalizedStringKey(category.rawValue)))
- .toolbar {
- ToolbarItem(placement: .automatic) {
- Button {
- appState.scanSingleCategory(category)
- } label: {
- Label("Scan", systemImage: "arrow.clockwise")
+ header
+ if case .scanning = appState.scanState {
+ HStack(spacing: 12) {
+ ProgressView().controlSize(.small)
+ Text("Scanning \(appState.currentScanCategory)…")
+ .font(.callout)
+ .foregroundStyle(.secondary)
+ Spacer()
+ Button("Stop scan") { appState.cancelScan() }
}
- .disabled(appState.scanState.isActive)
+ .padding(.horizontal, 28)
+ .padding(.bottom, 16)
}
-
- ToolbarItem(placement: .automatic) {
- if let result = result, !result.items.isEmpty {
- Button(action: { sortDescending.toggle() }) {
- Label {
- Text(LocalizedStringKey(sortDescending ? "Largest First" : "Smallest First"))
- } icon: {
- Image(systemName: "arrow.up.arrow.down")
- }
+ if let result, !result.items.isEmpty {
+ filters
+ Divider()
+ if visibleItems.isEmpty {
+ EmptyStateView("No matching files", systemImage: "line.3.horizontal.decrease.circle", description: "Try another name, size, or date range.", action: { filter = CleanupReviewFilter() }, actionLabel: "Clear filters", tint: Tint.teal)
+ } else {
+ List(visibleItems) { item in
+ CleanupFileRow(item: item)
+ .listRowSeparator(.visible)
}
- .help(LocalizedStringKey(sortDescending ? "Sorted: Largest First" : "Sorted: Smallest First"))
+ .listStyle(.inset)
+ .disabled(appState.scanState.isActive)
}
+ selectionBar
+ } else if result != nil {
+ EmptyStateView("No files found", systemImage: "checkmark.circle", description: appState.hasFullDiskAccess ? "There are no cleanup items in this category." : "Some protected locations are unavailable. Full Disk Access allows a more complete scan.", tint: Tint.teal)
+ } else if !appState.scanState.isActive {
+ EmptyStateView("See what is taking up space", systemImage: category.icon, description: "Scan first, then review the exact files before removing anything.", action: { appState.scanSingleCategory(category) }, actionLabel: "Scan this category", tint: Tint.teal)
+ } else {
+ Spacer()
}
}
- .confirmationDialog(cleanConfirmationTitle, isPresented: $showConfirmation, titleVisibility: .visible) {
- Button("Clean", role: .destructive) {
- appState.cleanCategory(category)
+ .navigationTitle(Text(LocalizedStringKey(category.rawValue)))
+ .confirmationDialog("Remove selected files?", isPresented: $showConfirmation, titleVisibility: .visible) {
+ Button("Permanently remove \(pendingItems.count) items", role: .destructive) {
+ appState.cleanCategory(category, itemIDs: Set(pendingItems.map(\.id)))
+ pendingItems = []
}
- Button("Cancel", role: .cancel) {}
+ Button("Cancel", role: .cancel) { pendingItems = [] }
} message: {
- Text("This will permanently delete the selected files. This cannot be undone.")
+ Text(confirmationMessage)
+ }
+ .onChange(of: category) { _ in
+ filter = CleanupReviewFilter()
+ pendingItems = []
+ showConfirmation = false
}
}
- private func cleanItemsLabel(count: Int) -> String {
- String(format: String(localized: "Clean %lld items"), Int64(count))
- }
-
- private var cleanConfirmationTitle: String {
- String(
- format: String(localized: "Clean %@?"),
- ByteCountFormatter.string(fromByteCount: appState.selectedSizeInCategory(category), countStyle: .file)
- )
- }
-
- // MARK: - Hero
-
- private var heroCard: some View {
- let totalSize = result?.totalSize ?? 0
- let itemCount = result?.itemCount ?? 0
- let isScanning = appState.scanState.isActive
-
- return CardSurface(padding: 20, tint: category.color) {
- HStack(alignment: .center, spacing: 16) {
- IconTile(systemName: category.icon, tint: category.color, size: 60, corner: 16, vivid: true)
-
- VStack(alignment: .leading, spacing: 4) {
- Text(LocalizedStringKey(category.rawValue))
- .font(.system(size: 22, weight: .bold))
- Text(LocalizedStringKey(category.description))
- .font(.system(size: 12.5))
+ private var header: some View {
+ HStack(alignment: .top, spacing: 16) {
+ IconTile(systemName: category.icon, tint: Tint.teal, size: 48, corner: 12)
+ VStack(alignment: .leading, spacing: 7) {
+ Text(LocalizedStringKey(category.rawValue))
+ .font(.system(size: 26, weight: .semibold))
+ Text(LocalizedStringKey(category.description))
+ .font(.system(size: 13))
+ .foregroundStyle(.secondary)
+ if let result {
+ Text("\(result.itemCount) items · \(result.formattedSize) found")
+ .font(.system(size: 12, weight: .medium))
.foregroundStyle(.secondary)
- if itemCount > 0 {
- Text(itemsAndSizeText(itemCount: itemCount, totalSize: totalSize))
- .font(.system(size: 11.5, weight: .semibold))
- .monospacedDigit()
- .contentTransition(reduceMotion ? .identity : .numericText())
- .foregroundStyle(category.color)
- .padding(.horizontal, 8)
- .padding(.vertical, 3)
- .background(Capsule().fill(category.color.opacity(0.12)))
- .padding(.top, 4)
- .animation(reduceMotion ? nil : MotionTokens.gentle, value: totalSize)
- }
- }
-
- Spacer()
-
- Button {
- appState.scanSingleCategory(category)
- } label: {
- Label {
- Text(scanButtonLabel(isScanning: isScanning, hasResult: result != nil))
- } icon: {
- Image(systemName: "arrow.clockwise")
- }
- .font(.system(size: 12.5, weight: .semibold))
+ .monospacedDigit()
}
- .buttonStyle(.bordered)
- .tint(category.color)
- .controlSize(.large)
- .disabled(isScanning)
}
+ Spacer(minLength: 16)
+ Button {
+ appState.scanSingleCategory(category)
+ } label: {
+ Label(result == nil ? "Scan" : "Rescan", systemImage: "arrow.clockwise")
+ }
+ .buttonStyle(.bordered)
+ .controlSize(.large)
+ .disabled(appState.scanState.isActive)
}
+ .padding(28)
}
- /// Persistent action strip above the file list: tri-state select-all,
- /// live selection count, selected size, and the Clean CTA. Previously
- /// these lived only in the toolbar, one extra glance away from the rows
- /// they act on.
- private func selectionStrip(_ result: CategoryResult) -> some View {
- let selectedCount = appState.selectedCountInCategory(category)
- let totalCount = result.itemCount
- let selectedSize = appState.selectedSizeInCategory(category)
-
- return CardSurface(padding: 10, elevation: .flat) {
+ private var filters: some View {
+ VStack(spacing: 12) {
+ HStack(spacing: 10) {
+ Image(systemName: "magnifyingglass").foregroundStyle(.secondary)
+ TextField("Find a file or path", text: $filter.query)
+ .textFieldStyle(.plain)
+ .accessibilityLabel("Filter cleanup files")
+ if !filter.query.isEmpty {
+ Button { filter.query = "" } label: { Image(systemName: "xmark.circle.fill") }
+ .buttonStyle(.plain)
+ .foregroundStyle(.secondary)
+ .help("Clear search")
+ .accessibilityLabel("Clear search")
+ }
+ }
+ .padding(10)
+ .background(Color.primary.opacity(0.045), in: RoundedRectangle(cornerRadius: 8))
HStack(spacing: 12) {
- Toggle(isOn: Binding(
- get: { selectedCount == totalCount && totalCount > 0 },
- set: { newValue in
- if newValue {
- appState.selectAllInCategory(category)
- } else {
- appState.deselectAllInCategory(category)
- }
- }
- )) {
- Text(
- String(
- format: String(localized: "%lld of %lld selected"),
- Int64(selectedCount),
- Int64(totalCount)
- )
- )
- .font(.system(size: 12, weight: .medium))
- .monospacedDigit()
- .contentTransition(reduceMotion ? .identity : .numericText())
+ Picker("Size", selection: $filter.size) {
+ ForEach(CleanupSizeFilter.allCases) { Text($0.rawValue).tag($0) }
}
- .toggleStyle(AnimatedCheckboxStyle(tint: category.color))
- .animation(reduceMotion ? nil : MotionTokens.gentle, value: selectedCount)
-
- Spacer()
-
- Text(ByteCountFormatter.string(fromByteCount: selectedSize, countStyle: .file))
- .font(.system(size: 13, weight: .semibold))
- .monospacedDigit()
+ .frame(maxWidth: 180)
+ Picker("Modified", selection: $filter.age) {
+ ForEach(CleanupAgeFilter.allCases) { Text($0.rawValue).tag($0) }
+ }
+ .frame(maxWidth: 210)
+ Spacer(minLength: 0)
+ Picker("Sort", selection: $filter.order) {
+ ForEach(CleanupSortOrder.allCases) { Text($0.rawValue).tag($0) }
+ }
+ .frame(maxWidth: 185)
+ }
+ .controlSize(.small)
+ HStack {
+ Text("\(visibleItems.count) of \(result?.itemCount ?? 0) items shown")
+ .font(.caption)
.foregroundStyle(.secondary)
-
- if selectedSize > 0 {
- Button {
- showConfirmation = true
- } label: {
- Label {
- Text(cleanItemsLabel(count: selectedCount))
- } icon: {
- Image(systemName: "trash")
- }
- }
- .buttonStyle(GlowProminentButtonStyle(tint: Tint.red, gradient: TintGradient.destructive))
- .transition(reduceMotion ? .opacity : .opacity.combined(with: .scale(scale: 0.92)))
+ Spacer()
+ Button(visibleItems.allSatisfy(appState.isItemSelected) ? "Deselect visible" : "Select visible") {
+ appState.setSelection(!visibleItems.allSatisfy(appState.isItemSelected), for: visibleItems)
}
+ .disabled(visibleItems.isEmpty || appState.scanState.isActive)
+ .buttonStyle(.borderless)
}
- .animation(reduceMotion ? nil : MotionTokens.snappy, value: selectedSize > 0)
}
+ .padding(.horizontal, 28)
+ .padding(.bottom, 14)
}
- private func itemsAndSizeText(itemCount: Int, totalSize: Int64) -> String {
- String(
- format: String(localized: "%lld items · %@"),
- Int64(itemCount),
- ByteCountFormatter.string(fromByteCount: totalSize, countStyle: .file)
- )
- }
-
- private func scanButtonLabel(isScanning: Bool, hasResult: Bool) -> LocalizedStringKey {
- if isScanning { return "Scanning…" }
- if hasResult { return "Rescan" }
- return "Scan"
- }
-
- // MARK: - File List
-
- private func fileList(_ result: CategoryResult) -> some View {
- let items = sortedItems(result.items).filter { item in
- searchText.isEmpty || item.name.localizedCaseInsensitiveContains(searchText) || item.path.localizedCaseInsensitiveContains(searchText)
- }
- return List {
- // No .staggered() here: List is lazy, so a delayed-reveal
- // modifier would blank each row for ~0.45s as it scrolls into
- // view on large scans. The row hover/selection polish carries
- // the motion; the list-level sort/filter animation handles
- // reorders.
- ForEach(Array(items.enumerated()), id: \.element.id) { _, item in
- FileRowView(item: item)
+ private var selectionBar: some View {
+ let visibleIDs = Set(visibleItems.map(\.id))
+ let hiddenCount = selectedItems.filter { !visibleIDs.contains($0.id) }.count
+ return HStack(spacing: 16) {
+ VStack(alignment: .leading, spacing: 4) {
+ Text("\(selectedItems.count) selected · \(ByteCountFormatter.string(fromByteCount: selectedSize, countStyle: .file))")
+ .font(.system(size: 13, weight: .semibold))
+ .monospacedDigit()
+ Text(hiddenCount > 0 ? "Includes \(hiddenCount) selected items hidden by filters." : "Selected cleanup items are permanently removed.")
+ .font(.caption)
+ .foregroundStyle(.secondary)
}
+ Spacer(minLength: 8)
+ if !selectedItems.isEmpty {
+ Button("Clear selection") { appState.deselectAllInCategory(category) }
+ .buttonStyle(.borderless)
+ .disabled(appState.scanState.isActive)
+ }
+ Button {
+ pendingItems = selectedItems
+ showConfirmation = true
+ } label: {
+ Label("Review removal", systemImage: "trash")
+ .font(.system(size: 13, weight: .semibold))
+ }
+ .buttonStyle(.borderedProminent)
+ .tint(Tint.teal)
+ .controlSize(.large)
+ .disabled(selectedItems.isEmpty || appState.scanState.isActive)
}
- // CleanableItem ids are stable, so SwiftUI move-animates re-sorts and
- // fades filtered rows instead of snapping.
- .animation(reduceMotion ? nil : .spring(response: 0.4, dampingFraction: 0.85), value: sortDescending)
- .animation(reduceMotion ? nil : .easeOut(duration: 0.2), value: searchText)
+ .padding(.horizontal, 28)
+ .padding(.vertical, 18)
+ .background(.bar)
+ .overlay(alignment: .top) { Divider() }
}
- private func sortedItems(_ items: [CleanableItem]) -> [CleanableItem] {
- items.sorted { sortDescending ? $0.size > $1.size : $0.size < $1.size }
+ private var confirmationMessage: String {
+ let size = ByteCountFormatter.string(fromByteCount: pendingItems.reduce(0) { $0 + $1.size }, countStyle: .file)
+ let names = pendingItems.prefix(5).map(\.name).joined(separator: "\n")
+ let more = pendingItems.count > 5 ? "\nAnd \(pendingItems.count - 5) more." : ""
+ return "\(size) selected. This permanently removes the selected files or runs the listed cleanup actions. It cannot be undone.\n\n\(names)\(more)"
}
}
-// MARK: - File Row View
-
-private struct FileRowView: View {
+private struct CleanupFileRow: View {
@EnvironmentObject var appState: AppState
let item: CleanableItem
- @State private var hovering = false
- @Environment(\.accessibilityReduceMotion) private var reduceMotion
-
- private var isSelected: Bool {
- appState.isItemSelected(item)
- }
-
var body: some View {
- Toggle(isOn: Binding(
- get: { isSelected },
- set: { _ in appState.toggleItem(item) }
- )) {
- HStack {
- Image(systemName: fileIcon)
- .foregroundStyle(item.category.color.opacity(0.85))
- .frame(width: 20)
-
- VStack(alignment: .leading, spacing: 2) {
- Text(item.name)
- .lineLimit(1)
- .truncationMode(.middle)
-
- if !item.isActionItem {
- Text(item.path)
- .font(.caption)
- .foregroundStyle(.tertiary)
- .lineLimit(1)
- .truncationMode(.middle)
- } else if item.simctlRuntimeIdentifier != nil {
- Text(String(localized: "Simulator runtime"))
- .font(.caption)
- .foregroundStyle(.tertiary)
- .lineLimit(1)
- }
- }
-
- Spacer()
-
- // Hover-revealed Finder shortcut; stays in the layout so the
- // trailing size never shifts sideways.
- if !item.isActionItem {
- Button {
- NSWorkspace.shared.selectFile(item.path, inFileViewerRootedAtPath: "")
- } label: {
- Image(systemName: "folder")
- .font(.caption)
- .foregroundStyle(.secondary)
- }
- .buttonStyle(.plain)
+ HStack(spacing: 12) {
+ Toggle("Select \(item.name)", isOn: appState.itemBinding(for: item))
+ .labelsHidden()
+ .toggleStyle(.checkbox)
+ .tint(Tint.teal)
+ .accessibilityLabel("Select \(item.name)")
+ Image(systemName: item.isActionItem ? "gearshape.2" : "doc")
+ .font(.system(size: 18))
+ .foregroundStyle(.secondary)
+ .frame(width: 25)
+ VStack(alignment: .leading, spacing: 4) {
+ Text(item.name)
+ .font(.system(size: 13, weight: .medium))
+ .lineLimit(1)
+ .truncationMode(.middle)
+ Text(item.isActionItem ? "Managed cleanup action" : (item.path as NSString).abbreviatingWithTildeInPath)
+ .font(.system(size: 11))
+ .foregroundStyle(.secondary)
+ .lineLimit(1)
+ .truncationMode(.middle)
+ .help(item.path)
+ }
+ Spacer(minLength: 12)
+ if !item.isSelected {
+ Text("Review")
+ .font(.system(size: 10, weight: .medium))
+ .foregroundStyle(.secondary)
+ .padding(.horizontal, 6)
+ .padding(.vertical, 3)
+ .background(Color.primary.opacity(0.05), in: Capsule())
+ .help("Personal data or an optional cleanup action. Left unselected by default.")
+ }
+ if let date = item.lastModified {
+ Text(date, style: .date)
+ .font(.system(size: 11))
+ .foregroundStyle(.secondary)
+ .frame(width: 78, alignment: .trailing)
+ }
+ Text(item.formattedSize)
+ .font(.system(size: 13, weight: .medium, design: .monospaced))
+ .frame(width: 85, alignment: .trailing)
+ if !item.isActionItem {
+ Button { reveal() } label: { Image(systemName: "arrow.up.forward.square") }
+ .buttonStyle(.borderless)
+ .foregroundStyle(.secondary)
.help("Reveal in Finder")
- .opacity(hovering ? 1 : 0)
- .scaleEffect(reduceMotion ? 1 : (hovering ? 1 : 0.8))
- .allowsHitTesting(hovering)
- }
-
- if let date = item.lastModified {
- Text(date, style: .date)
- .font(.caption)
- .foregroundStyle(.secondary)
- }
-
- Text(item.formattedSize)
- .font(.callout)
- .fontWeight(.medium)
- .monospacedDigit()
- .frame(width: 80, alignment: .trailing)
+ .accessibilityLabel("Reveal \(item.name) in Finder")
}
}
- .toggleStyle(AnimatedCheckboxStyle(tint: item.category.color))
- .padding(.vertical, 2)
- .padding(.horizontal, 4)
- .background(
- RoundedRectangle(cornerRadius: 6, style: .continuous)
- .fill(
- hovering
- ? Color.primary.opacity(0.06)
- : (isSelected ? item.category.color.opacity(0.04) : .clear)
- )
- )
- .animation(reduceMotion ? nil : MotionTokens.snappy, value: hovering)
- .animation(reduceMotion ? nil : .easeOut(duration: 0.15), value: isSelected)
- .onHover { hovering = $0 }
+ .padding(.vertical, 9)
.contextMenu {
if !item.isActionItem {
- Button("Reveal in Finder") {
- NSWorkspace.shared.selectFile(item.path, inFileViewerRootedAtPath: "")
+ Button("Reveal in Finder") { reveal() }
+ Button("Copy path") {
+ NSPasteboard.general.clearContents()
+ NSPasteboard.general.setString(item.path, forType: .string)
}
+ Divider()
+ Button("Always exclude from cleanup") { appState.excludeFromCleanup(item) }
+ .disabled(appState.scanState.isActive)
}
}
}
- private var fileIcon: String {
- if item.simctlRuntimeIdentifier != nil {
- return "iphone"
- }
- let ext = (item.name as NSString).pathExtension.lowercased()
- switch ext {
- case "log", "txt": return "doc.text"
- case "zip", "gz", "tar": return "doc.zipper"
- case "dmg", "iso": return "opticaldisc"
- case "app": return "app"
- case "pkg": return "shippingbox"
- default:
- var isDir: ObjCBool = false
- if FileManager.default.fileExists(atPath: item.path, isDirectory: &isDir), isDir.boolValue {
- return "folder"
- }
- return "doc"
- }
+ private func reveal() {
+ NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: item.path)])
}
}
diff --git a/PureMac/Views/Components/AppTheme.swift b/PureMac/Views/Components/AppTheme.swift
index aab09ff..e2752c2 100644
--- a/PureMac/Views/Components/AppTheme.swift
+++ b/PureMac/Views/Components/AppTheme.swift
@@ -1,10 +1,9 @@
import AppKit
import SwiftUI
-/// User-overridable appearance setting that lives independently of the system
-/// preference, mirroring the prototype's titlebar light/dark toggle.
enum AppearanceMode: String, CaseIterable, Identifiable {
case system, light, dark
+
var id: String { rawValue }
var label: String {
@@ -36,166 +35,113 @@ enum AppearanceMode: String, CaseIterable, Identifiable {
final class ThemeManager: ObservableObject {
static let shared = ThemeManager()
- @AppStorage("PureMac.Appearance") private var rawValue: String = AppearanceMode.system.rawValue
+ @AppStorage("PureMac.Appearance") private var rawValue = AppearanceMode.system.rawValue
- private init() { applyToApp() }
+ private init() {
+ applyToApp()
+ }
var appearance: AppearanceMode {
get { AppearanceMode(rawValue: rawValue) ?? .system }
- set { rawValue = newValue.rawValue; objectWillChange.send(); applyToApp() }
+ set {
+ rawValue = newValue.rawValue
+ objectWillChange.send()
+ applyToApp()
+ }
}
- /// The theme is driven through NSApp.appearance, not SwiftUI's
- /// .preferredColorScheme: resetting preferredColorScheme back to nil
- /// (System) inside a WindowGroup hosting a NavigationSplitView only
- /// re-appearances the titlebar — the content's colorScheme environment
- /// isn't re-evaluated until the window resigns key, so the body stays
- /// stuck in the previous scheme while focused. The AppKit route applies
- /// immediately and also themes windows outside the main scene
- /// (Settings, menus, popovers).
func applyToApp() {
NSApplication.shared.appearance = appearance.nsAppearance
}
}
-/// Centralized accent palette. One blue, one green for success, one orange
-/// for warning, one red for destructive. Other tints exist for categorical
-/// differentiation but the surface chrome only uses these four.
enum Tint {
- static let blue = Color(red: 0.04, green: 0.52, blue: 1.00)
- static let green = Color(red: 0.18, green: 0.78, blue: 0.47)
- static let orange = Color(red: 1.00, green: 0.58, blue: 0.04)
- static let purple = Color(red: 0.55, green: 0.32, blue: 0.87)
- static let pink = Color(red: 1.00, green: 0.30, blue: 0.50)
- static let cyan = Color(red: 0.30, green: 0.78, blue: 0.95)
- static let red = Color(red: 1.00, green: 0.27, blue: 0.23)
- static let yellow = Color(red: 1.00, green: 0.78, blue: 0.04)
+ static let accent = Color(red: 0.08, green: 0.58, blue: 0.54)
+ static let teal = accent
+ static let blue = Color(red: 0.18, green: 0.48, blue: 0.88)
+ static let green = Color(red: 0.18, green: 0.65, blue: 0.43)
+ static let orange = Color(red: 0.92, green: 0.52, blue: 0.16)
+ static let purple = Color(red: 0.49, green: 0.38, blue: 0.72)
+ static let pink = Color(red: 0.82, green: 0.34, blue: 0.49)
+ static let cyan = Color(red: 0.19, green: 0.63, blue: 0.72)
+ static let red = Color(red: 0.85, green: 0.25, blue: 0.24)
+ static let yellow = Color(red: 0.87, green: 0.68, blue: 0.16)
}
-/// Shared animation vocabulary so every surface moves with the same feel.
-/// Hover/selection feedback uses `snappy`, entrances and state swaps use
-/// `gentle`, press acknowledgment uses `press`.
enum MotionTokens {
- static let snappy = Animation.spring(response: 0.3, dampingFraction: 0.7)
- static let gentle = Animation.spring(response: 0.5, dampingFraction: 0.85)
- static let press = Animation.easeOut(duration: 0.12)
+ static let snappy = Animation.spring(response: 0.28, dampingFraction: 0.82)
+ static let gentle = Animation.spring(response: 0.46, dampingFraction: 0.88)
+ static let press = Animation.easeOut(duration: 0.1)
}
-/// Gradient pairs built from the flat `Tint` palette. Reserved for primary
-/// CTAs and focal chrome — secondary surfaces stay flat.
enum TintGradient {
static let accent = LinearGradient(
- colors: [Tint.blue, Tint.purple],
- startPoint: .topLeading, endPoint: .bottomTrailing
+ colors: [Tint.accent, Tint.accent.opacity(0.86)],
+ startPoint: .top,
+ endPoint: .bottom
)
- /// Immersive Smart Care backdrop. Kept separate from `accent` so primary
- /// controls stay bright while the dashboard can use a deeper scenic plane.
static let smartCare = LinearGradient(
colors: [
- Color(red: 0.025, green: 0.031, blue: 0.047),
- Color(red: 0.035, green: 0.051, blue: 0.086),
- Color(red: 0.018, green: 0.071, blue: 0.108)
+ Color(red: 0.075, green: 0.085, blue: 0.09),
+ Color(red: 0.045, green: 0.052, blue: 0.055)
],
- startPoint: .topLeading,
- endPoint: .bottomTrailing
+ startPoint: .top,
+ endPoint: .bottom
)
static let destructive = LinearGradient(
- colors: [Tint.red, Tint.red.opacity(0.8)],
- startPoint: .top, endPoint: .bottom
+ colors: [Tint.red, Tint.red.opacity(0.86)],
+ startPoint: .top,
+ endPoint: .bottom
)
+
static func of(_ color: Color) -> LinearGradient {
- LinearGradient(colors: [color, color.opacity(0.65)], startPoint: .top, endPoint: .bottom)
+ LinearGradient(colors: [color, color.opacity(0.82)], startPoint: .top, endPoint: .bottom)
}
}
-/// Tinted square icon container used in the sidebar and on dashboard cards.
-/// Two-stop tinted fill with a hairline inner stroke. When `glow` is set
-/// (selected sidebar row, emphasized card) the tile picks up a stronger
-/// gradient and a soft tinted halo. When `vivid` is set the tile becomes a
-/// full-saturation gradient bubble with a white glyph — reserved for focal
-/// spots (category heroes, result rows) so the chrome stays matte elsewhere.
struct IconTile: View {
let systemName: String
- var tint: Color = Tint.blue
+ var tint: Color = Tint.accent
var size: CGFloat = 26
var corner: CGFloat = 7
- var glow: Bool = false
- var vivid: Bool = false
-
- @Environment(\.accessibilityReduceMotion) private var reduceMotion
+ var glow = false
+ var vivid = false
var body: some View {
ZStack {
RoundedRectangle(cornerRadius: corner, style: .continuous)
- .fill(
- LinearGradient(
- colors: vivid
- ? [tint, tint.opacity(0.72)]
- : [tint.opacity(glow ? 0.32 : 0.16), tint.opacity(glow ? 0.16 : 0.07)],
- startPoint: .topLeading, endPoint: .bottomTrailing
- )
- )
- .overlay(
+ .fill(vivid ? tint : tint.opacity(glow ? 0.20 : 0.12))
+ .overlay {
RoundedRectangle(cornerRadius: corner, style: .continuous)
- .strokeBorder(vivid ? Color.white.opacity(0.22) : tint.opacity(glow ? 0.38 : 0.20),
- lineWidth: 0.5)
- )
- .shadow(color: tint.opacity(vivid ? 0.42 : (glow ? 0.45 : 0)),
- radius: vivid ? 6 : (glow ? 5 : 0))
+ .strokeBorder(tint.opacity(vivid ? 0.22 : 0.16), lineWidth: 0.5)
+ }
Image(systemName: systemName)
- .font(.system(size: size * 0.52, weight: .semibold))
+ .font(.system(size: size * 0.48, weight: .semibold))
.foregroundStyle(vivid ? Color.white : tint)
- .shadow(color: vivid ? Color.black.opacity(0.18) : tint.opacity(glow ? 0.5 : 0),
- radius: vivid ? 2 : (glow ? 3 : 0))
}
.frame(width: size, height: size)
- .animation(reduceMotion ? nil : MotionTokens.snappy, value: glow)
}
}
-/// Shared ambient backdrop for the app's detail surfaces: layered radial
-/// washes in jewel tones, concentrated at the top where hero content lives
-/// and fading to nothing at the bottom. Static layers — no Reduce Motion
-/// concerns. Opacities halve in light mode so surfaces stay clean.
struct AmbientBackdrop: View {
@Environment(\.colorScheme) private var colorScheme
- private var strength: Double { colorScheme == .dark ? 1 : 0.55 }
-
var body: some View {
- ZStack {
+ ZStack(alignment: .top) {
Color(nsColor: .windowBackgroundColor)
- RadialGradient(
- colors: [Tint.blue.opacity(0.10 * strength), .clear],
- center: .topLeading, startRadius: 0, endRadius: 700
- )
- RadialGradient(
- colors: [Tint.purple.opacity(0.08 * strength), .clear],
- center: .topTrailing, startRadius: 0, endRadius: 620
- )
- RadialGradient(
- colors: [Tint.pink.opacity(0.05 * strength), .clear],
- center: UnitPoint(x: 0.5, y: -0.15), startRadius: 0, endRadius: 480
- )
+ Rectangle()
+ .fill(colorScheme == .dark ? Color.white.opacity(0.018) : Color.black.opacity(0.014))
+ .frame(height: 96)
}
.ignoresSafeArea()
}
}
-/// Card surface. Flat fill, hairline border, soft shadow. No accent stripe —
-/// content hierarchy carries the meaning, not chrome. Pass `material` for a
-/// vibrancy/glass panel (used on focal hero states where a tinted backdrop
-/// sits behind the card). Pass `tint` for a barely-there vertical color wash
-/// that gives the card an identity without adding chrome.
struct CardSurface<Content: View>: View {
var padding: CGFloat = 16
- /// Retained for callsite compatibility; the accent line is intentionally
- /// not rendered in the restrained design.
var accent: Color? = nil
var elevation: CardElevation = .standard
var material: Material? = nil
- /// Optional identity wash. Kept under ~7% opacity so text contrast and
- /// light-mode cleanliness are unaffected.
var tint: Color? = nil
@ViewBuilder var content: Content
@@ -204,7 +150,7 @@ struct CardSurface<Content: View>: View {
var body: some View {
content
.padding(padding)
- .background(
+ .background {
ZStack {
if let material {
RoundedRectangle(cornerRadius: cornerRadius, style: .continuous)
@@ -215,23 +161,27 @@ struct CardSurface<Content: View>: View {
}
if let tint {
RoundedRectangle(cornerRadius: cornerRadius, style: .continuous)
- .fill(
- LinearGradient(
- colors: [tint.opacity(0.07), tint.opacity(0.015)],
- startPoint: .top, endPoint: .bottom
- )
- )
+ .fill(tint.opacity(0.035))
}
}
- )
- .overlay(
+ }
+ .overlay {
RoundedRectangle(cornerRadius: cornerRadius, style: .continuous)
- .strokeBorder(
- material != nil ? Color.white.opacity(0.14) : Color.primary.opacity(0.07),
- lineWidth: material != nil ? 1 : 0.5
- )
+ .strokeBorder(Color.primary.opacity(0.075), lineWidth: 0.5)
+ }
+ .overlay(alignment: .top) {
+ if let accent {
+ Capsule()
+ .fill(accent.opacity(0.72))
+ .frame(width: 36, height: 2)
+ .padding(.top, 1)
+ }
+ }
+ .shadow(
+ color: .black.opacity(elevation.ambient),
+ radius: elevation.ambientRadius,
+ y: elevation.ambientY
)
- .shadow(color: .black.opacity(elevation.ambient), radius: elevation.ambientRadius, y: elevation.ambientY)
}
}
@@ -240,17 +190,17 @@ enum CardElevation {
var ambient: Double {
switch self {
- case .flat: return 0.0
- case .standard: return 0.05
- case .raised: return 0.10
+ case .flat: return 0
+ case .standard: return 0.035
+ case .raised: return 0.07
}
}
var ambientRadius: CGFloat {
switch self {
case .flat: return 0
- case .standard: return 7
- case .raised: return 20
+ case .standard: return 6
+ case .raised: return 16
}
}
@@ -258,40 +208,40 @@ enum CardElevation {
switch self {
case .flat: return 0
case .standard: return 2
- case .raised: return 8
+ case .raised: return 7
}
}
}
-/// Small status pill. Solid tint background at low opacity, no gradient.
struct StatusChip: View {
let label: String
var systemImage: String? = nil
- var tint: Color = Tint.blue
+ var tint: Color = Tint.accent
var body: some View {
- HStack(spacing: 4) {
+ HStack(spacing: 5) {
if let systemImage {
Image(systemName: systemImage)
- .font(.system(size: 9, weight: .bold))
+ .font(.system(size: 9, weight: .semibold))
}
Text(label)
- .font(.system(size: 11, weight: .semibold))
+ .font(.system(size: 10.5, weight: .semibold))
.monospacedDigit()
}
.padding(.horizontal, 8)
- .padding(.vertical, 3)
- .background(Capsule().fill(tint.opacity(0.14)))
+ .padding(.vertical, 4)
.foregroundStyle(tint)
+ .background(Capsule().fill(tint.opacity(0.11)))
+ .overlay(Capsule().strokeBorder(tint.opacity(0.15), lineWidth: 0.5))
}
}
-/// Consistent section title used on dashboard-style surfaces. Single source
-/// of truth for the "quiet bold headline" look so every section matches.
struct SectionHeader: View {
let title: LocalizedStringKey
- init(_ title: LocalizedStringKey) { self.title = title }
+ init(_ title: LocalizedStringKey) {
+ self.title = title
+ }
var body: some View {
Text(title)
@@ -299,24 +249,17 @@ struct SectionHeader: View {
}
}
-/// Hover/press feedback for tappable cards. Plain mode is a subtle scale;
-/// `lift` mode adds the CleanMyMac-style float (rise + soft shadow). Under
-/// Reduce Motion the scale/offset are dropped and only the shadow remains.
struct PressableScale: ViewModifier {
@State private var hovering = false
@State private var pressing = false
var hoverScale: CGFloat = 1.006
- var lift: Bool = false
-
+ var lift = false
@Environment(\.accessibilityReduceMotion) private var reduceMotion
func body(content: Content) -> some View {
content
- .scaleEffect(reduceMotion ? 1.0 : (pressing ? 0.97 : (hovering ? (lift ? 1.02 : hoverScale) : 1.0)))
- .offset(y: lift && hovering && !reduceMotion ? -2 : 0)
- .shadow(color: .black.opacity(lift && hovering ? 0.12 : 0),
- radius: lift && hovering ? 14 : 0,
- y: lift && hovering ? 6 : 0)
+ .scaleEffect(reduceMotion ? 1 : pressing ? 0.985 : hovering ? hoverScale : 1)
+ .shadow(color: .black.opacity(lift && hovering ? 0.06 : 0), radius: 10, y: 4)
.animation(reduceMotion ? nil : MotionTokens.snappy, value: hovering)
.animation(reduceMotion ? nil : MotionTokens.press, value: pressing)
.onHover { hovering = $0 }
@@ -334,99 +277,47 @@ extension View {
}
}
-/// Gradient capsule CTA with a soft tinted glow — the primary-action style.
-/// Hover lifts the glow and scale; press squeezes. `breathes` adds a gentle
-/// idle glow pulse (radius only, no scale) for the single hero CTA on an
-/// otherwise calm screen. `large` bumps the type and padding for the one
-/// dominant call-to-action on a surface. All motion is suppressed under
-/// Reduce Motion.
struct GlowProminentButtonStyle: ButtonStyle {
- var tint: Color = Tint.blue
+ var tint: Color = Tint.accent
var gradient: LinearGradient = TintGradient.accent
- var breathes: Bool = false
- var large: Bool = false
+ var breathes = false
+ var large = false
func makeBody(configuration: Configuration) -> some View {
- GlowBody(configuration: configuration, tint: tint, gradient: gradient,
- breathes: breathes, large: large)
- }
-
- private struct GlowBody: View {
- let configuration: ButtonStyleConfiguration
- let tint: Color
- let gradient: LinearGradient
- let breathes: Bool
- let large: Bool
-
- @State private var hovering = false
- @State private var breathe = false
- @Environment(\.accessibilityReduceMotion) private var reduceMotion
-
- var body: some View {
- configuration.label
- .font(.system(size: large ? 14 : 13, weight: .semibold))
- .foregroundStyle(.white)
- .padding(.horizontal, large ? 22 : 18)
- .padding(.vertical, large ? 11 : 9)
- .background(Capsule().fill(gradient))
- .overlay(Capsule().strokeBorder(.white.opacity(0.18), lineWidth: 0.5))
- .shadow(color: tint.opacity(hovering ? 0.45 : (breathe ? 0.40 : 0.22)),
- radius: hovering ? 14 : (breathe ? 12 : 7), y: 3)
- .scaleEffect(reduceMotion ? 1 : (configuration.isPressed ? 0.97 : (hovering ? 1.03 : 1)))
- .animation(reduceMotion ? nil : MotionTokens.snappy, value: hovering)
- .animation(reduceMotion ? nil : MotionTokens.press, value: configuration.isPressed)
- .onHover { hovering = $0 }
- .onAppear {
- guard breathes, !reduceMotion else { return }
- withAnimation(.easeInOut(duration: 1.2).repeatForever(autoreverses: true)) {
- breathe = true
- }
- }
- }
+ configuration.label
+ .font(.system(size: large ? 14 : 13, weight: .semibold))
+ .foregroundStyle(.white)
+ .padding(.horizontal, large ? 20 : 16)
+ .padding(.vertical, large ? 10 : 8)
+ .background(Capsule().fill(gradient))
+ .overlay(Capsule().strokeBorder(Color.white.opacity(0.14), lineWidth: 0.5))
+ .opacity(configuration.isPressed ? 0.84 : 1)
}
}
-/// Checkbox replacement with a springy check pop. Visually matches the size
-/// of the native control so adopting it doesn't shift row layout. Keeps the
-/// native checkbox's accessibility semantics (role, checked value, Space-key
-/// toggling, VoiceOver) via accessibilityRepresentation so swapping it in
-/// doesn't regress keyboard/screen-reader users.
struct AnimatedCheckboxStyle: ToggleStyle {
- var tint: Color = Tint.blue
+ var tint: Color = Tint.accent
func makeBody(configuration: Configuration) -> some View {
- CheckBody(configuration: configuration, tint: tint)
- .accessibilityRepresentation {
- Toggle(isOn: configuration.$isOn) { configuration.label }
- .toggleStyle(.checkbox)
- }
- }
-
- private struct CheckBody: View {
- let configuration: ToggleStyleConfiguration
- let tint: Color
- @Environment(\.accessibilityReduceMotion) private var reduceMotion
-
- var body: some View {
- HStack(spacing: 8) {
- ZStack {
- RoundedRectangle(cornerRadius: 4.5, style: .continuous)
- .fill(configuration.isOn ? tint : Color.primary.opacity(0.05))
- RoundedRectangle(cornerRadius: 4.5, style: .continuous)
- .strokeBorder(configuration.isOn ? tint : Color.primary.opacity(0.25), lineWidth: 1)
- Image(systemName: "checkmark")
- .font(.system(size: 9, weight: .bold))
- .foregroundStyle(.white)
- .scaleEffect(configuration.isOn ? 1 : 0.3)
- .opacity(configuration.isOn ? 1 : 0)
- }
- .frame(width: 15, height: 15)
- .animation(reduceMotion ? nil : .spring(response: 0.25, dampingFraction: 0.6), value: configuration.isOn)
-
- configuration.label
+ HStack(spacing: 8) {
+ ZStack {
+ RoundedRectangle(cornerRadius: 4, style: .continuous)
+ .fill(configuration.isOn ? tint : Color.primary.opacity(0.04))
+ RoundedRectangle(cornerRadius: 4, style: .continuous)
+ .strokeBorder(configuration.isOn ? tint : Color.primary.opacity(0.24), lineWidth: 1)
+ Image(systemName: "checkmark")
+ .font(.system(size: 9, weight: .bold))
+ .foregroundStyle(.white)
+ .opacity(configuration.isOn ? 1 : 0)
}
- .contentShape(Rectangle())
- .onTapGesture { configuration.isOn.toggle() }
+ .frame(width: 15, height: 15)
+ configuration.label
+ }
+ .contentShape(Rectangle())
+ .onTapGesture { configuration.isOn.toggle() }
+ .accessibilityRepresentation {
+ Toggle(isOn: configuration.$isOn) { configuration.label }
+ .toggleStyle(.checkbox)
}
}
}
diff --git a/PureMac/Views/Components/DashboardCharts.swift b/PureMac/Views/Components/DashboardCharts.swift
index 8abc1cb..de4490a 100644
--- a/PureMac/Views/Components/DashboardCharts.swift
+++ b/PureMac/Views/Components/DashboardCharts.swift
@@ -1,157 +1,67 @@
-import SwiftUI
import Charts
-
-// MARK: - Health Ring
-//
-// Premium animated radial gauge that replaces the flat StorageGauge. An
-// angular-gradient sweep with a soft tinted glow, a rounded cap, and a
-// spring-driven fill. The center number rolls via numericText. Honors
-// Reduce Motion (no spring, no idle shimmer).
+import SwiftUI
struct HealthRing: View {
- /// Primary fill, 0...1 (e.g. fraction of disk used).
let percent: Double
- var tint: Color = Tint.blue
+ var size: CGFloat = 190
+ var lineWidth: CGFloat = 13
+ var tint: Color = Tint.accent
var warnTint: Color = Tint.orange
- var stressThreshold: Double = 0.85
- var lineWidth: CGFloat = 14
+ var stressThreshold: Double = 0.9
var subtitle: LocalizedStringKey = "USED"
- @State private var sweep: Double = 0
- @State private var displayPercent: Int = 0
+ @State private var reveal: Double = 0
@Environment(\.accessibilityReduceMotion) private var reduceMotion
- private var clamped: Double { max(0, min(1, percent)) }
- private var stress: Bool { clamped >= stressThreshold }
- private var arcColor: Color { stress ? warnTint : tint }
- private var trailColor: Color { stress ? Tint.red : Tint.purple }
+ private var clamped: Double {
+ max(0, min(1, percent))
+ }
+
+ private var ringTint: Color {
+ clamped >= stressThreshold ? warnTint : tint
+ }
var body: some View {
ZStack {
- // Orb body — a deep jewel fill that turns the flat ring into a
- // glowing sphere. Inset so it never bleeds across the track.
Circle()
- .fill(
- RadialGradient(
- colors: [arcColor.opacity(0.14), arcColor.opacity(0.05), .clear],
- center: .center,
- startRadius: 2,
- endRadius: 160
- )
- )
- .padding(lineWidth + 10)
-
- // Slow conic sheen sweeping the orb interior — the "alive" cue.
- // Removed entirely under Reduce Motion.
- if !reduceMotion {
- TimelineView(.animation) { timeline in
- let t = timeline.date.timeIntervalSinceReferenceDate
- let angle = (t.truncatingRemainder(dividingBy: 6.0) / 6.0) * 360.0
- Circle()
- .fill(
- AngularGradient(
- colors: [.clear, .clear, arcColor.opacity(0.10), .clear],
- center: .center
- )
- )
- .rotationEffect(.degrees(angle))
- }
- .padding(lineWidth + 10)
- .clipShape(Circle())
- }
-
+ .stroke(Color.primary.opacity(0.075), lineWidth: lineWidth)
Circle()
- .stroke(Color.primary.opacity(0.06), lineWidth: lineWidth)
-
- // Bloom: a wide soft halo under a tighter, brighter one. The
- // glow comes from these blurred duplicates of the crisp arc.
- Circle()
- .trim(from: 0, to: sweep)
- .stroke(arcColor.opacity(0.35),
- style: StrokeStyle(lineWidth: lineWidth, lineCap: .round))
- .rotationEffect(.degrees(-90))
- .blur(radius: 16)
-
- Circle()
- .trim(from: 0, to: sweep)
- .stroke(arcColor.opacity(0.55),
- style: StrokeStyle(lineWidth: lineWidth * 0.7, lineCap: .round))
+ .trim(from: 0, to: reveal)
+ .stroke(ringTint, style: StrokeStyle(lineWidth: lineWidth, lineCap: .round))
.rotationEffect(.degrees(-90))
- .blur(radius: 7)
-
- Circle()
- .trim(from: 0, to: sweep)
- .stroke(
- AngularGradient(
- gradient: Gradient(colors: [arcColor.opacity(0.85), trailColor, arcColor]),
- center: .center,
- startAngle: .degrees(-90),
- endAngle: .degrees(-90 + 360 * max(sweep, 0.0001))
- ),
- style: StrokeStyle(lineWidth: lineWidth, lineCap: .round)
- )
- .rotationEffect(.degrees(-90))
-
- // Endpoint highlight dot for a polished finish. The dot sits at the
- // top of the ring and the whole layer rotates about the ring
- // center so it orbits to the arc's end. Radius is derived from the
- // real frame so it tracks the stroke at any size.
- if sweep > 0.02 {
- GeometryReader { geo in
- let radius = (min(geo.size.width, geo.size.height) - lineWidth) / 2
- Circle()
- .fill(.white)
- .frame(width: lineWidth * 0.42, height: lineWidth * 0.42)
- .position(x: geo.size.width / 2, y: geo.size.height / 2 - radius)
- .shadow(color: arcColor.opacity(0.7), radius: 4)
- }
- .rotationEffect(.degrees(360 * sweep))
- }
-
- VStack(spacing: 1) {
- Text("\(displayPercent)%")
- .font(.system(size: 44, weight: .semibold))
+ VStack(spacing: 2) {
+ Text("\(Int((clamped * 100).rounded()))%")
+ .font(.system(size: 38, weight: .semibold, design: .rounded))
.monospacedDigit()
- .contentTransition(.numericText())
- .foregroundStyle(stress ? warnTint : Color.primary)
Text(subtitle)
- .font(.system(size: 10, weight: .semibold))
- .tracking(0.8)
+ .font(.system(size: 9.5, weight: .semibold))
+ .tracking(1)
.foregroundStyle(.secondary)
}
}
- .onAppear { animate(to: clamped) }
- .onChange(of: clamped) { animate(to: $0) }
+ .frame(width: size, height: size)
+ .onAppear { animate() }
+ .onChange(of: clamped) { _ in animate() }
+ .accessibilityElement(children: .ignore)
+ .accessibilityLabel(Text(subtitle))
+ .accessibilityValue("\(Int((clamped * 100).rounded())) percent")
}
- private func animate(to value: Double) {
+ private func animate() {
if reduceMotion {
- sweep = value
- displayPercent = Int(round(value * 100))
- return
- }
- withAnimation(.spring(response: 1.0, dampingFraction: 0.82)) {
- sweep = value
- }
- withAnimation(.easeOut(duration: 0.9)) {
- displayPercent = Int(round(value * 100))
+ reveal = clamped
+ } else {
+ withAnimation(.easeOut(duration: 0.65)) {
+ reveal = clamped
+ }
}
}
}
-// MARK: - Storage Donut
-//
-// Custom multi-segment donut (Used / Junk / Purgeable / Free) drawn from
-// trimmed arcs so it works on macOS 13 (SectorMark is 14+). Segments grow in
-// with a spring on appear and animate when values change.
-
struct StorageDonut: View {
struct Segment: Identifiable {
- /// Stable id (e.g. "used"/"junk") so legend rows keep identity across
- /// the many @Published refreshes that rebuild this array — otherwise a
- /// fresh UUID per render replays the staggered entrance animation.
let id: String
- let value: Double // raw byte fraction; normalized internally
+ let value: Double
let color: Color
let label: LocalizedStringKey
let display: String
@@ -159,57 +69,60 @@ struct StorageDonut: View {
let segments: [Segment]
var lineWidth: CGFloat = 16
- var gap: Double = 0.006 // angular gap between segments (fraction of circle)
- /// When set (legend hover), every other segment dims for cross-highlight.
+ var gap: Double = 0.008
var highlightedID: String? = nil
- @State private var reveal: CGFloat = 0
+ @State private var reveal: Double = 0
@Environment(\.accessibilityReduceMotion) private var reduceMotion
- private var total: Double { max(segments.reduce(0) { $0 + $1.value }, 0.0001) }
+ private var total: Double {
+ max(segments.reduce(0) { $0 + $1.value }, 0.0001)
+ }
var body: some View {
- // A single segment is a full ring — no inter-segment hairline, so the
- // gap would otherwise carve a false missing slice.
let effectiveGap = segments.count <= 1 ? 0 : gap
let fractions = segments.map { $0.value / total }
var cursor = 0.0
var ranges: [(start: Double, end: Double)] = []
- for frac in fractions {
+
+ for fraction in fractions {
let start = cursor
- cursor += frac
- // Trim back the trailing edge by `gap` for a hairline between
- // segments, clamped so a tiny slice never inverts.
+ cursor += fraction
ranges.append((start, max(start, cursor - effectiveGap)))
}
return ZStack {
- Circle().stroke(Color.primary.opacity(0.05), lineWidth: lineWidth)
- ForEach(Array(segments.enumerated()), id: \.element.id) { idx, seg in
+ Circle()
+ .stroke(Color.primary.opacity(0.065), lineWidth: lineWidth)
+ ForEach(Array(segments.enumerated()), id: \.element.id) { index, segment in
Circle()
- .trim(from: ranges[idx].start * reveal, to: ranges[idx].end * reveal)
- .stroke(seg.color, style: StrokeStyle(lineWidth: lineWidth, lineCap: .butt))
+ .trim(
+ from: ranges[index].start * reveal,
+ to: ranges[index].end * reveal
+ )
+ .stroke(
+ segment.color,
+ style: StrokeStyle(lineWidth: lineWidth, lineCap: .butt)
+ )
.rotationEffect(.degrees(-90))
- .opacity(highlightedID == nil || highlightedID == seg.id ? 1 : 0.25)
+ .opacity(highlightedID == nil || highlightedID == segment.id ? 1 : 0.22)
}
}
- .animation(reduceMotion ? nil : .easeOut(duration: 0.2), value: highlightedID)
+ .animation(reduceMotion ? nil : .easeOut(duration: 0.16), value: highlightedID)
.onAppear {
- if reduceMotion { reveal = 1; return }
- withAnimation(.spring(response: 1.0, dampingFraction: 0.85)) { reveal = 1 }
+ if reduceMotion {
+ reveal = 1
+ } else {
+ withAnimation(.easeOut(duration: 0.7)) {
+ reveal = 1
+ }
+ }
}
}
}
-// MARK: - Category Bar Chart
-//
-// Horizontal Swift Charts bar chart of junk size per category. BarMark is
-// available on macOS 13. Used in the completed-scan state to give an
-// at-a-glance "where the space is" graphic above the toggle list.
-
struct CategoryBarChart: View {
struct Bar: Identifiable {
- // Category is unique per bar, so derive a stable id from it.
var id: String { category.rawValue }
let category: CleaningCategory
let size: Int64
@@ -217,36 +130,28 @@ struct CategoryBarChart: View {
}
let bars: [Bar]
-
- @State private var reveal: Double = 0
+ @State private var reveal = 0.0
@Environment(\.accessibilityReduceMotion) private var reduceMotion
var body: some View {
- // Reserve ~28% trailing headroom so the byte-size annotation on the
- // longest bar renders fully instead of clipping at the chart edge
- // (the macOS 14+ annotation overflowResolution isn't available here).
let maxSize = bars.map(\.size).max() ?? 0
- let upper = max(Int64(1), Int64(Double(maxSize) * 1.28))
+ let upper = max(Int64(1), Int64(Double(maxSize) * 1.25))
- return Chart(bars) { bar in
+ Chart(bars) { bar in
BarMark(
x: .value("Size", Double(bar.size) * reveal),
y: .value(String(localized: "Category"), bar.name)
)
- .foregroundStyle(bar.category.color.gradient)
- .cornerRadius(5)
+ .foregroundStyle(bar.category.color)
+ .cornerRadius(4)
.annotation(position: .trailing, alignment: .leading) {
Text(ByteCountFormatter.string(fromByteCount: bar.size, countStyle: .file))
- .font(.system(size: 10, weight: .semibold))
+ .font(.system(size: 10, weight: .medium))
.monospacedDigit()
.foregroundStyle(.secondary)
.opacity(reveal)
}
}
- .onAppear {
- if reduceMotion { reveal = 1; return }
- withAnimation(.spring(response: 0.8, dampingFraction: 0.85)) { reveal = 1 }
- }
.chartXScale(domain: 0...upper)
.chartXAxis(.hidden)
.chartYAxis {
@@ -255,25 +160,31 @@ struct CategoryBarChart: View {
}
}
.chartLegend(.hidden)
- .frame(height: max(120, CGFloat(bars.count) * 34))
+ .frame(height: max(120, CGFloat(bars.count) * 32))
+ .onAppear {
+ if reduceMotion {
+ reveal = 1
+ } else {
+ withAnimation(.easeOut(duration: 0.6)) {
+ reveal = 1
+ }
+ }
+ }
}
}
-// MARK: - Legend chip
-
struct LegendChip: View {
let color: Color
let label: LocalizedStringKey
let value: String
- /// Optional share readout ("72%") rendered after the value.
var percent: String? = nil
var body: some View {
HStack(spacing: 7) {
- RoundedRectangle(cornerRadius: 3.5, style: .continuous)
+ Circle()
.fill(color)
- .frame(width: 10, height: 10)
- VStack(alignment: .leading, spacing: 0) {
+ .frame(width: 8, height: 8)
+ VStack(alignment: .leading, spacing: 1) {
Text(label)
.font(.system(size: 10.5))
.foregroundStyle(.secondary)
@@ -283,8 +194,7 @@ struct LegendChip: View {
.monospacedDigit()
if let percent {
Text(percent)
- .font(.system(size: 10, weight: .medium))
- .monospacedDigit()
+ .font(.system(size: 9.5, weight: .medium))
.foregroundStyle(.tertiary)
}
}
@@ -293,136 +203,114 @@ struct LegendChip: View {
}
}
-// MARK: - Stacked meter
-//
-// Full-width segmented storage bar (Used / Junk / Purgeable / Free). Segments
-// sit flush inside one track with thin separators, grow in with a spring on
-// appear, and cross-dim when a legend chip reports a hover. Honors Reduce
-// Motion (instant reveal, instant cross-dim).
-
struct StackedMeter: View {
struct Segment: Identifiable {
- /// Stable id so legend hover can cross-highlight the matching segment.
let id: String
let value: Double
let color: Color
}
let segments: [Segment]
- var height: CGFloat = 14
- /// When set (legend hover), every other segment dims for cross-highlight.
+ var height: CGFloat = 12
var highlightedID: String? = nil
@State private var reveal: CGFloat = 0
@Environment(\.accessibilityReduceMotion) private var reduceMotion
- private var total: Double { max(segments.reduce(0) { $0 + $1.value }, 0.0001) }
+ private var total: Double {
+ max(segments.reduce(0) { $0 + $1.value }, 0.0001)
+ }
var body: some View {
- GeometryReader { geo in
- let separator: CGFloat = 2
- let available = geo.size.width - separator * CGFloat(max(0, segments.count - 1))
- HStack(spacing: separator) {
- ForEach(segments) { seg in
- let frac = CGFloat(seg.value / total)
- RoundedRectangle(cornerRadius: height * 0.3, style: .continuous)
- .fill(seg.color)
- .frame(width: max(frac > 0 ? 4 : 0, available * frac * reveal))
- .opacity(highlightedID == nil || highlightedID == seg.id ? 1 : 0.28)
+ GeometryReader { geometry in
+ let spacing: CGFloat = 2
+ let available = geometry.size.width - spacing * CGFloat(max(0, segments.count - 1))
+ HStack(spacing: spacing) {
+ ForEach(segments) { segment in
+ let fraction = CGFloat(segment.value / total)
+ RoundedRectangle(cornerRadius: height * 0.28, style: .continuous)
+ .fill(segment.color)
+ .frame(width: max(fraction > 0 ? 3 : 0, available * fraction * reveal))
+ .opacity(highlightedID == nil || highlightedID == segment.id ? 1 : 0.24)
}
}
}
.frame(height: height)
- .animation(reduceMotion ? nil : .easeOut(duration: 0.2), value: highlightedID)
+ .animation(reduceMotion ? nil : .easeOut(duration: 0.16), value: highlightedID)
.onAppear {
- if reduceMotion { reveal = 1; return }
- withAnimation(.spring(response: 0.9, dampingFraction: 0.85)) { reveal = 1 }
+ if reduceMotion {
+ reveal = 1
+ } else {
+ withAnimation(.easeOut(duration: 0.65)) {
+ reveal = 1
+ }
+ }
}
}
}
-// MARK: - Success medal
-//
-// Center checkmark with two concentric rings that expand and fade once on
-// appear — a calm, premium "done" beat to pair with the freed-space number.
-
struct SuccessMedal: View {
var tint: Color = Tint.green
var size: CGFloat = 120
-
- @State private var pop = false
- @State private var ripple = false
+ @State private var visible = false
@Environment(\.accessibilityReduceMotion) private var reduceMotion
var body: some View {
ZStack {
- ForEach(0..<2) { i in
- Circle()
- .stroke(tint.opacity(ripple ? 0 : 0.45), lineWidth: 2)
- .scaleEffect(ripple ? 1.5 + CGFloat(i) * 0.25 : 0.7)
- }
Circle()
- .fill(tint.opacity(0.14))
- .scaleEffect(pop ? 1 : 0.6)
-
+ .fill(tint.opacity(0.11))
+ Circle()
+ .strokeBorder(tint.opacity(0.18), lineWidth: 1)
Image(systemName: "checkmark")
- .font(.system(size: size * 0.42, weight: .bold))
+ .font(.system(size: size * 0.34, weight: .semibold))
.foregroundStyle(tint)
- .scaleEffect(pop ? 1 : 0.3)
- .opacity(pop ? 1 : 0)
}
.frame(width: size, height: size)
+ .scaleEffect(visible ? 1 : 0.92)
+ .opacity(visible ? 1 : 0)
.onAppear {
- if reduceMotion { pop = true; return }
- withAnimation(.spring(response: 0.5, dampingFraction: 0.6)) { pop = true }
- withAnimation(.easeOut(duration: 1.1)) { ripple = true }
+ if reduceMotion {
+ visible = true
+ } else {
+ withAnimation(MotionTokens.gentle) {
+ visible = true
+ }
+ }
}
}
}
-// MARK: - Staggered reveal
-//
-// Drop-in entrance animation: fades + lifts content with a per-index delay so
-// grids and lists cascade in. Honors Reduce Motion.
-
struct StaggeredReveal: ViewModifier {
let index: Int
- var baseDelay: Double = 0.04
+ var baseDelay = 0.035
@State private var shown = false
@Environment(\.accessibilityReduceMotion) private var reduceMotion
func body(content: Content) -> some View {
content
.opacity(shown ? 1 : 0)
- .offset(y: shown ? 0 : 10)
+ .offset(y: shown || reduceMotion ? 0 : 6)
.onAppear {
- if reduceMotion { shown = true; return }
- withAnimation(.spring(response: 0.5, dampingFraction: 0.85)
- .delay(Double(index) * baseDelay)) {
+ if reduceMotion {
shown = true
+ } else {
+ withAnimation(.easeOut(duration: 0.28).delay(Double(index) * baseDelay)) {
+ shown = true
+ }
}
}
}
}
extension View {
- func staggered(_ index: Int, baseDelay: Double = 0.04) -> some View {
+ func staggered(_ index: Int, baseDelay: Double = 0.035) -> some View {
modifier(StaggeredReveal(index: index, baseDelay: baseDelay))
}
}
-// MARK: - Count-up bytes
-//
-// Animatable byte counter. `.contentTransition(.numericText())` only rolls
-// when the change happens inside an animation transaction — values assigned
-// during a plain data refresh snap instead. Driving the formatter through
-// `animatableData` makes the roll-up play every time the target changes.
-// Styling (font/color) flows in from the environment of the call site.
-
struct CountUpBytes: View {
let bytes: Int64
-
- @State private var shown: Double = 0
+ @State private var shown = 0.0
@Environment(\.accessibilityReduceMotion) private var reduceMotion
var body: some View {
@@ -436,10 +324,10 @@ struct CountUpBytes: View {
private func animate(to target: Int64) {
if reduceMotion {
shown = Double(target)
- return
- }
- withAnimation(.easeOut(duration: 0.8)) {
- shown = Double(target)
+ } else {
+ withAnimation(.easeOut(duration: 0.55)) {
+ shown = Double(target)
+ }
}
}
}
@@ -458,87 +346,44 @@ private struct ByteRollEffect: AnimatableModifier {
}
}
-// MARK: - Scanning gauge
-//
-// Active-scan focal element: a rotating trimmed arc over a radar wedge sweep
-// with two expanding halo rings. Reduce Motion freezes every loop and falls
-// back to the static arc + rolling percent.
-
struct ScanningGauge: View {
let progress: Double
- var tint: Color = Tint.blue
+ var tint: Color = Tint.accent
var label: LocalizedStringKey = "SCANNING"
- @State private var rotate = false
- @State private var pulse = false
+ @State private var rotation = 0.0
@Environment(\.accessibilityReduceMotion) private var reduceMotion
+ private var clamped: Double {
+ max(0, min(1, progress))
+ }
+
var body: some View {
ZStack {
- // Expanding halo rings, SuccessMedal-style but repeating.
- if !reduceMotion {
- ForEach(0..<2, id: \.self) { i in
- Circle()
- .stroke(tint.opacity(0.35), lineWidth: 1.5)
- .scaleEffect(pulse ? 1.22 : 0.9)
- .opacity(pulse ? 0 : 0.6)
- .animation(
- .easeOut(duration: 1.6)
- .repeatForever(autoreverses: false)
- .delay(Double(i) * 0.8),
- value: pulse
- )
- }
- }
-
- // Radar wedge sweeping the ring interior. TimelineView keeps the
- // angle deterministic; the branch above removes it entirely under
- // Reduce Motion.
- if !reduceMotion {
- TimelineView(.animation) { timeline in
- let t = timeline.date.timeIntervalSinceReferenceDate
- let angle = (t.truncatingRemainder(dividingBy: 3.0) / 3.0) * 360.0
- Circle()
- .fill(
- AngularGradient(
- colors: [tint.opacity(0), tint.opacity(0), tint.opacity(0.22)],
- center: .center
- )
- )
- .rotationEffect(.degrees(angle))
- }
- .padding(14)
- .clipShape(Circle())
- }
-
Circle()
.stroke(Color.primary.opacity(0.07), lineWidth: 10)
-
Circle()
- .trim(from: 0, to: CGFloat(max(0.05, min(0.95, progress))))
+ .trim(from: 0, to: max(0.035, clamped))
.stroke(tint, style: StrokeStyle(lineWidth: 10, lineCap: .round))
- .rotationEffect(.degrees(rotate ? 360 : 0))
- .animation(
- reduceMotion ? nil : .linear(duration: 4).repeatForever(autoreverses: false),
- value: rotate
- )
-
+ .rotationEffect(.degrees(-90 + rotation))
VStack(spacing: 2) {
- Text("\(Int(progress * 100))%")
- .font(.system(size: 36, weight: .semibold))
+ Text("\(Int((clamped * 100).rounded()))%")
+ .font(.system(size: 34, weight: .semibold, design: .rounded))
.monospacedDigit()
- .contentTransition(reduceMotion ? .identity : .numericText())
- .animation(reduceMotion ? nil : .easeOut(duration: 0.3), value: Int(progress * 100))
Text(label)
- .font(.system(size: 10, weight: .medium))
- .tracking(0.6)
+ .font(.system(size: 9.5, weight: .semibold))
+ .tracking(0.9)
.foregroundStyle(.secondary)
}
}
.onAppear {
guard !reduceMotion else { return }
- rotate = true
- pulse = true
+ withAnimation(.linear(duration: 5).repeatForever(autoreverses: false)) {
+ rotation = 360
+ }
}
+ .accessibilityElement(children: .ignore)
+ .accessibilityLabel(Text(label))
+ .accessibilityValue("\(Int((clamped * 100).rounded())) percent")
}
}
diff --git a/PureMac/Views/DashboardView.swift b/PureMac/Views/DashboardView.swift
index bb98e08..06758cb 100644
--- a/PureMac/Views/DashboardView.swift
+++ b/PureMac/Views/DashboardView.swift
@@ -1,1624 +1,749 @@
import SwiftUI
-/// Landing screen modeled after the new prototype:
-/// hero gauge + stats + quick actions + suggestion cards.
-/// Replaces the old SmartScanView idle/completed states with a richer
-/// at-a-glance view, and delegates active-scan progress to inline state UI.
struct DashboardView: View {
@EnvironmentObject var appState: AppState
var onNavigate: (AppSection) -> Void = { _ in }
@State private var showConfirmation = false
- @State private var fireCleanConfetti = false
- @State private var lastCleanedScanState: Bool = false
@State private var hoveredSegment: String?
- /// Confetti burst origin as a fraction of the dashboard, derived from the
- /// SuccessMedal's real frame so the burst tracks it across window sizes
- /// and RTL layout instead of a hand-aimed constant.
- @State private var burstOrigin: UnitPoint = UnitPoint(x: 0.25, y: 0.28)
- @State private var dashboardSize: CGSize = .zero
+ @State private var pendingCleanItems: [CleanableItem] = []
@Environment(\.accessibilityReduceMotion) private var reduceMotion
- private let dashboardSpace = "dashboard"
-
- /// Hero cards rise in with a slight settle and dissolve out; under
- /// Reduce Motion both directions collapse to a plain cross-fade.
- private var heroTransition: AnyTransition {
- reduceMotion
- ? .opacity
- : .asymmetric(
- insertion: .opacity
- .combined(with: .offset(y: 12))
- .combined(with: .scale(scale: 0.98, anchor: .top)),
- removal: .opacity
- )
- }
-
var body: some View {
- ZStack {
- ScrollView {
- VStack(alignment: .leading, spacing: 14) {
- pageHeader
-
- switch appState.scanState {
- case .idle:
- hero
- .transition(heroTransition)
- sectionHeader("Care areas")
- careOverview
- case .scanning:
- scanningHero
- .transition(heroTransition)
- if !appState.allResults.isEmpty {
- sectionHeader("Found so far")
- liveResults
- }
- case .completed:
- completedHero
- .transition(heroTransition)
- if appState.totalJunkSize > 0 {
- sectionHeader("Review what was found")
- findingsGrid
- }
- case .cleaning:
- cleaningHero
- .transition(heroTransition)
- case .cleaned:
- cleanedHero
- .transition(heroTransition)
- }
- }
- .padding(.horizontal, 24)
- .padding(.vertical, 18)
- .frame(maxWidth: 1220, alignment: .leading)
- .frame(maxWidth: .infinity, alignment: .top)
- .animation(reduceMotion ? nil : MotionTokens.gentle, value: appState.scanState)
- }
-
- // Celebratory burst when a clean cycle finishes with something
- // freed. Origin tracks the SuccessMedal's real frame (see
- // burstOrigin) so it explodes from the celebration on any window
- // size / layout direction.
- // allowsHitTesting=false keeps Done clickable through particles.
- ConfettiView(trigger: fireCleanConfetti, mode: .burst(origin: burstOrigin))
- .allowsHitTesting(false)
- }
- .coordinateSpace(name: dashboardSpace)
- .background(
- GeometryReader { geo in
- Color.clear.onAppear { dashboardSize = geo.size }
- .onChange(of: geo.size) { dashboardSize = $0 }
- }
- )
- .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top)
- .onChange(of: appState.scanState) { newState in
- // Fire only on the rising edge of .cleaned with freed > 0 so
- // the burst doesn't replay when the user navigates back to the
- // dashboard while .cleaned is still on screen.
- let isCleaned: Bool = {
- if case .cleaned = newState { return true }
- return false
- }()
- if isCleaned && !lastCleanedScanState && appState.totalFreedSpace > 0 {
- if reduceMotion {
- // Confetti renders nothing under Reduce Motion; no need
- // to wait for an entrance spring that isn't playing.
- fireCleanConfetti.toggle()
- } else {
- // Let the hero settle and the counter roll before the
- // burst so the celebration lands as one beat.
- DispatchQueue.main.asyncAfter(deadline: .now() + 0.55) {
- fireCleanConfetti.toggle()
- }
- }
+ ScrollView {
+ VStack(alignment: .leading, spacing: 20) {
+ pageHeader
+ stateContent
}
- lastCleanedScanState = isCleaned
+ .padding(.horizontal, 28)
+ .padding(.vertical, 24)
+ .frame(maxWidth: 1180, alignment: .leading)
+ .frame(maxWidth: .infinity, alignment: .top)
}
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
.confirmationDialog(
cleanConfirmationTitle,
isPresented: $showConfirmation,
titleVisibility: .visible
) {
- Button("Clean", role: .destructive) { appState.cleanAll() }
- Button("Cancel", role: .cancel) {}
+ Button("Clean selected items", role: .destructive) {
+ appState.cleanAll(itemIDs: Set(pendingCleanItems.map(\.id)))
+ pendingCleanItems = []
+ }
+ Button("Cancel", role: .cancel) {
+ pendingCleanItems = []
+ }
} message: {
- Text("This will permanently delete the selected files. This cannot be undone.")
+ Text(cleanConfirmationMessage)
}
}
- // MARK: - Page chrome
-
private var pageHeader: some View {
- let status = headerStatus
-
- return HStack(alignment: .top, spacing: 18) {
- VStack(alignment: .leading, spacing: 4) {
+ HStack(alignment: .top, spacing: 16) {
+ VStack(alignment: .leading, spacing: 5) {
Text("Smart Care")
- .font(.system(size: 24, weight: .bold))
+ .font(.system(size: 28, weight: .semibold))
.tracking(-0.45)
.accessibilityAddTraits(.isHeader)
Text(headerSubtitle)
- .font(.system(size: 12.5))
+ .font(.system(size: 13))
.foregroundStyle(.secondary)
- .lineLimit(1)
}
Spacer(minLength: 20)
- HStack(spacing: 12) {
- StatusChip(
- label: status.label,
- systemImage: status.systemImage,
- tint: status.tint
- )
+ VStack(alignment: .trailing, spacing: 7) {
+ let status = headerStatus
+ StatusChip(label: status.label, systemImage: status.icon, tint: status.tint)
TimelineView(.periodic(from: .now, by: 60)) { timeline in
Text(lastCareText(relativeTo: timeline.date))
- .font(.system(size: 11))
+ .font(.system(size: 10.5))
.foregroundStyle(.tertiary)
}
}
}
}
+ @ViewBuilder
+ private var stateContent: some View {
+ switch appState.scanState {
+ case .idle:
+ idleContent
+ .transition(stateTransition)
+ case .scanning:
+ scanningContent
+ .transition(stateTransition)
+ case .completed:
+ resultsContent
+ .transition(stateTransition)
+ case .cleaning:
+ cleaningContent
+ .transition(stateTransition)
+ case .cleaned:
+ cleanedContent
+ .transition(stateTransition)
+ }
+ }
+
+ private var stateTransition: AnyTransition {
+ reduceMotion ? .opacity : .opacity.combined(with: .offset(y: 5))
+ }
+
private var headerSubtitle: String {
switch appState.scanState {
case .idle:
- return String(localized: "One scan checks every cleanup tool and prepares a plan for your review.")
+ return String(localized: "A clear view of reclaimable storage and the tools that manage it.")
case .scanning:
- return String(localized: "PureMac is checking your Mac without removing anything.")
+ return String(localized: "Checking your Mac. Nothing is removed during a scan.")
case .completed:
- return String(localized: "Choose what to keep, then clean everything in one controlled pass.")
+ return appState.scanWasCancelled
+ ? String(localized: "The scan stopped. Available results are ready to review.")
+ : String(localized: "Review the results and choose exactly what to remove.")
case .cleaning:
- return String(localized: "Selected items are being removed safely.")
+ return String(localized: "Removing the items you selected.")
case .cleaned:
- return String(localized: "Cleanup complete. Your storage summary is refreshing.")
+ return String(localized: "Cleanup finished and disk information is refreshing.")
}
}
- private var headerStatus: (label: String, systemImage: String, tint: Color) {
+ private var headerStatus: (label: String, icon: String, tint: Color) {
switch appState.scanState {
case .idle:
return appState.hasFullDiskAccess
? (String(localized: "Ready"), "checkmark.circle.fill", Tint.green)
: (String(localized: "Limited access"), "lock.fill", Tint.orange)
case .scanning:
- return (String(localized: "Scanning"), "sparkles", Tint.blue)
+ return (String(localized: "Scanning"), "magnifyingglass", Tint.accent)
case .completed:
- return appState.totalJunkSize > 0
- ? (String(localized: "Review ready"), "list.bullet.clipboard.fill", Tint.orange)
- : (String(localized: "All clear"), "checkmark.seal.fill", Tint.green)
+ if appState.scanWasCancelled {
+ return (String(localized: "Stopped"), "stop.circle.fill", Tint.orange)
+ }
+ return (String(localized: "Review ready"), "checklist", Tint.accent)
case .cleaning:
- return (String(localized: "Cleaning"), "wand.and.stars", Tint.orange)
+ return (String(localized: "Cleaning"), "trash.fill", Tint.orange)
case .cleaned:
- return (String(localized: "Complete"), "checkmark.seal.fill", Tint.green)
+ return appState.lastCleanupHadFailures
+ ? (String(localized: "Needs attention"), "exclamationmark.circle.fill", Tint.orange)
+ : (String(localized: "Complete"), "checkmark.circle.fill", Tint.green)
}
}
private func lastCareText(relativeTo now: Date) -> String {
- guard let date = appState.lastCleanedDate else {
- return String(localized: "No cleanup run yet")
+ let date = appState.lastCleanedDate ?? appState.lastScanDate
+ guard let date else {
+ return String(localized: "No scan run yet")
}
let formatter = RelativeDateTimeFormatter()
formatter.unitsStyle = .full
let relative = formatter.localizedString(for: date, relativeTo: now)
- return String(format: String(localized: "Last clean: %@"), relative)
- }
-
- private var cleanConfirmationTitle: String {
- String(
- format: String(localized: "Clean %@?"),
- ByteCountFormatter.string(fromByteCount: appState.totalSelectedSize, countStyle: .file)
- )
- }
-
- // MARK: - Hero (idle)
-
- private var hero: some View {
- let total = appState.diskInfo.totalSpace
- let free = appState.diskInfo.freeSpace
- // Use one source of truth for every percentage shown in this hero.
- // APFS can report `usedSpace` and `freeSpace` on slightly different
- // schedules, which previously produced a visible 71%/72% mismatch.
- let used = max(0, total - free)
- let percentUsed = total > 0
- ? max(0, min(1, Double(used) / Double(total)))
- : 0
- let stress = percentUsed >= 0.85
- let compact = dashboardSize.width > 0 && dashboardSize.width < 760
- let coreSize: CGFloat = compact ? 250 : 304
-
- return SmartCareStageSurface(
- tint: stress ? Tint.orange : Tint.blue,
- padding: compact ? 22 : 28
- ) {
- HStack(spacing: compact ? 14 : 28) {
- VStack(alignment: .leading, spacing: 12) {
- HStack(spacing: 8) {
- Image(systemName: "square.3.layers.3d")
- Text("\(CleaningCategory.scannable.count)-POINT LOCAL SCAN")
- .tracking(0.7)
- if stress {
- Text("LOW SPACE")
- .padding(.horizontal, 8)
- .padding(.vertical, 4)
- .background(Capsule().fill(Tint.orange.opacity(0.22)))
- }
- }
- .font(.system(size: 10.5, weight: .bold))
- .foregroundStyle(.white.opacity(0.70))
-
- Text(stress ? "Make room.\nKeep control." : "Scan first.\nDecide what goes.")
- .font(.system(size: compact ? 30 : 36, weight: .bold))
- .tracking(-1.0)
- .foregroundStyle(.white)
- .lineSpacing(-1)
-
- Text("PureMac builds a reviewable cleanup plan on your Mac. Nothing is removed until you approve it.")
- .font(.system(size: 13.5))
- .foregroundStyle(.white.opacity(0.68))
- .fixedSize(horizontal: false, vertical: true)
- .frame(maxWidth: 430, alignment: .leading)
-
- Button {
- appState.startSmartScan()
- } label: {
- Label("Scan My Mac", systemImage: "sparkles")
- }
- .buttonStyle(.borderedProminent)
- .controlSize(.large)
- .tint(Tint.blue)
- .foregroundStyle(.white)
- .accessibilityHint("Checks every cleanup category without deleting files")
- .padding(.vertical, 2)
-
- HStack(spacing: 14) {
- trustLabel("Local", icon: "lock.shield.fill")
- trustLabel("Private", icon: "eye.slash.fill")
- trustLabel("Reviewable", icon: "checklist")
- }
-
- storagePlaque(
- free: free,
- total: total,
- used: used,
- percentUsed: percentUsed
- )
- .padding(.top, 4)
+ return String(format: String(localized: "Last activity: %@"), relative)
+ }
+
+ private var idleContent: some View {
+ VStack(alignment: .leading, spacing: 20) {
+ GeometryReader { geometry in
+ let diskWidth = min(390, max(286, geometry.size.width * 0.38))
+ HStack(alignment: .top, spacing: 14) {
+ scanIntroduction
+ .frame(width: geometry.size.width - diskWidth - 14, height: 246)
+ diskOverview
+ .frame(width: diskWidth, height: 246)
}
- .frame(maxWidth: .infinity, alignment: .leading)
-
- storageVolumeScene(size: coreSize)
- .frame(width: compact ? 270 : 340)
}
- .frame(height: compact ? 296 : 326)
- }
- }
-
- private func trustLabel(_ title: LocalizedStringKey, icon: String) -> some View {
- Label(title, systemImage: icon)
- .font(.system(size: 10.5, weight: .semibold))
- .foregroundStyle(.white.opacity(0.58))
- }
-
- private func storagePlaque(
- free: Int64,
- total: Int64,
- used: Int64,
- percentUsed: Double
- ) -> some View {
- HStack(spacing: 12) {
- Image(systemName: "internaldrive.fill")
- .font(.system(size: 15, weight: .semibold))
- .foregroundStyle(Tint.cyan)
-
- VStack(alignment: .leading, spacing: 2) {
- Text("\(formatted(free)) free")
- .font(.system(size: 12.5, weight: .bold))
- .monospacedDigit()
- .foregroundStyle(.white)
- Text(freeOfText(total: total))
- .font(.system(size: 9.5))
- .foregroundStyle(.white.opacity(0.48))
- }
-
- StackedMeter(
- segments: [
- .init(id: "used", value: Double(used), color: Tint.blue),
- .init(id: "free", value: Double(max(0, free)), color: .white.opacity(0.10))
- ]
- )
- .frame(maxWidth: 150)
-
- Text(percentUsedText(percentUsed))
- .font(.system(size: 10.5, weight: .semibold))
- .monospacedDigit()
- .foregroundStyle(.white.opacity(0.58))
- }
- .padding(.horizontal, 13)
- .padding(.vertical, 10)
- .background(
- RoundedRectangle(cornerRadius: 13, style: .continuous)
- .fill(.white.opacity(0.065))
- )
- .overlay(
- RoundedRectangle(cornerRadius: 13, style: .continuous)
- .strokeBorder(.white.opacity(0.12), lineWidth: 0.7)
- )
- .frame(maxWidth: 470)
- }
-
- private func storageVolumeScene(size: CGFloat) -> some View {
- SmartCareCoreArtwork(phase: .idle, size: size)
- .accessibilityLabel("Twelve-layer storage inspection model")
- }
-
- private func freeOfText(total: Int64) -> String {
- String(
- format: String(localized: "free of %@"),
- ByteCountFormatter.string(fromByteCount: total, countStyle: .file)
- )
- }
-
- /// Full-width segmented meter (Used / Junk / Purgeable / Free) with a
- /// hoverable legend. The same segment math as the composition donut, so
- /// both surfaces always agree.
- private func storageMeter(used: Int64, total: Int64) -> some View {
- let purge = max(0, appState.diskInfo.purgeableSpace)
- let junk = max(0, min(appState.totalJunkSize, used))
- let usedCore = max(0, used - junk - purge)
- let free = max(0, appState.diskInfo.freeSpace)
-
- var segments: [StackedMeter.Segment] = [
- .init(id: "used", value: Double(usedCore), color: Tint.blue)
- ]
- if junk > 0 {
- segments.append(.init(id: "junk", value: Double(junk), color: Tint.orange))
- }
- if purge > 0 {
- segments.append(.init(id: "purgeable", value: Double(purge), color: Tint.green))
- }
- segments.append(.init(id: "free", value: Double(free), color: Color.primary.opacity(0.10)))
-
- let usedPct = total > 0 ? Double(used) / Double(total) : 0
+ .frame(height: 246)
- return VStack(alignment: .leading, spacing: 10) {
- StackedMeter(segments: segments, highlightedID: hoveredSegment)
+ dashboardSection("Tools", detail: "Focused utilities for storage, apps, and system maintenance")
- HStack(spacing: 18) {
- HoverableLegendChip(color: Tint.blue, label: "Used",
- value: formatted(usedCore),
- percent: shareString(usedCore, of: total)) { hovering in
- hoveredSegment = hovering ? "used" : nil
+ LazyVGrid(
+ columns: [GridItem(.adaptive(minimum: 210, maximum: 280), spacing: 14)],
+ spacing: 14
+ ) {
+ DashboardToolCard(
+ title: "Space Explorer",
+ detail: "Find what uses the most disk space",
+ icon: "square.3.layers.3d.down.right",
+ tint: Tint.accent
+ ) {
+ onNavigate(.spaceExplorer)
}
- if junk > 0 {
- HoverableLegendChip(color: Tint.orange, label: "Junk",
- value: formatted(junk),
- percent: shareString(junk, of: total)) { hovering in
- hoveredSegment = hovering ? "junk" : nil
- }
+ DashboardToolCard(
+ title: "Duplicate Finder",
+ detail: "Review matching files side by side",
+ icon: "doc.on.doc",
+ tint: Tint.purple
+ ) {
+ onNavigate(.duplicates)
}
- if purge > 0 {
- HoverableLegendChip(color: Tint.green, label: "Purgeable",
- value: formatted(purge),
- percent: shareString(purge, of: total)) { hovering in
- hoveredSegment = hovering ? "purgeable" : nil
- }
+ DashboardToolCard(
+ title: "Similar Photos",
+ detail: "Compare visually similar photos",
+ icon: "photo.stack",
+ tint: Tint.pink
+ ) {
+ onNavigate(.similarPhotos)
+ }
+ DashboardToolCard(
+ title: "Uninstaller",
+ detail: "Remove apps and their related files",
+ icon: "app.dashed",
+ tint: Tint.blue
+ ) {
+ onNavigate(.apps)
+ }
+ DashboardToolCard(
+ title: "App Updates",
+ detail: "Check installed apps for new versions",
+ icon: "arrow.triangle.2.circlepath",
+ tint: Tint.accent
+ ) {
+ onNavigate(.appUpdates)
+ }
+ DashboardToolCard(
+ title: "Protection",
+ detail: "Review built-in privacy and safety checks",
+ icon: "shield.checkered",
+ tint: Tint.green
+ ) {
+ onNavigate(.protection)
+ }
+ DashboardToolCard(
+ title: "Performance",
+ detail: "Inspect memory and background activity",
+ icon: "gauge.with.dots.needle.67percent",
+ tint: Tint.cyan
+ ) {
+ onNavigate(.performance)
}
- Spacer()
- Text(percentUsedText(usedPct))
- .font(.system(size: 11.5, weight: .semibold))
- .foregroundStyle(.secondary)
- .monospacedDigit()
}
}
}
- private func formatted(_ bytes: Int64) -> String {
- ByteCountFormatter.string(fromByteCount: bytes, countStyle: .file)
- }
-
- private func shareString(_ part: Int64, of total: Int64) -> String? {
- guard total > 0, part > 0 else { return nil }
- let share = Int((Double(part) / Double(total) * 100).rounded())
- // A rounded 0% is noise — hide it for slivers like APFS purgeable.
- guard share > 0 else { return nil }
- return "\(share)%"
- }
-
- private func percentUsedText(_ usedPct: Double) -> String {
- let clamped = max(0, min(1, usedPct))
- return String(
- format: String(localized: "%lld%% used"),
- Int64((clamped * 100).rounded())
- )
- }
-
- // MARK: - Care overview
-
- // Both lists are filtered against `scannable`, so a category withdrawn
- // there (see CleaningCategory.appModifying) drops out of the Care areas
- // counts instead of contributing a permanent zero.
- private var everydayCleanupCategories: [CleaningCategory] {
- [.systemJunk, .userCache, .mailAttachments, .trashBins, .largeFiles]
- .filter(CleaningCategory.scannable.contains)
- }
-
- private var developerCleanupCategories: [CleaningCategory] {
- [.aiApps, .xcodeJunk, .brewCache, .nodeCache, .dockerCache]
- .filter(CleaningCategory.scannable.contains)
- }
-
- private var careOverview: some View {
- let cleanupSize = summarySize(for: everydayCleanupCategories)
- let developerSize = summarySize(for: developerCleanupCategories)
- let compact = dashboardSize.width > 0 && dashboardSize.width < 900
- let supportingWidth: CGFloat = compact ? 136 : 178
+ private var scanIntroduction: some View {
+ CardSurface(padding: 24, elevation: .standard, tint: Tint.accent) {
+ VStack(alignment: .leading, spacing: 18) {
+ HStack {
+ IconTile(systemName: "sparkles", tint: Tint.accent, size: 38, corner: 10, vivid: true)
+ Spacer()
+ Text("\(CleaningCategory.scannable.count) areas")
+ .font(.system(size: 11, weight: .medium))
+ .foregroundStyle(.secondary)
+ }
- return HStack(spacing: 12) {
- CareModuleCard(
- icon: "sparkles.rectangle.stack.fill",
- tint: Tint.blue,
- title: "Cleanup",
- value: summaryValue(size: cleanupSize, categories: everydayCleanupCategories),
- detail: cleanupSize > 0
- ? String(localized: "Ready for review")
- : String(localized: "Caches, mail, trash, and large files"),
- prominent: true,
- showsDetail: !compact
- ) {
- onNavigate(.cleaning(largestCategory(in: everydayCleanupCategories) ?? .systemJunk))
- }
- .staggered(0)
- .frame(maxWidth: .infinity)
+ VStack(alignment: .leading, spacing: 8) {
+ Text("Find space to reclaim.")
+ .font(.system(size: 25, weight: .semibold))
+ .tracking(-0.35)
+ Text("PureMac checks caches, logs, developer data, downloads, and Trash. You review the result before anything is removed.")
+ .font(.system(size: 13))
+ .foregroundStyle(.secondary)
+ .fixedSize(horizontal: false, vertical: true)
+ }
- CareModuleCard(
- icon: "hammer.circle.fill",
- tint: Tint.orange,
- title: "Developer",
- value: summaryValue(size: developerSize, categories: developerCleanupCategories),
- detail: developerSize > 0
- ? String(localized: "Ready for review")
- : String(localized: "Xcode and package tools"),
- showsDetail: !compact
- ) {
- onNavigate(.cleaning(largestCategory(in: developerCleanupCategories) ?? .xcodeJunk))
- }
- .staggered(1)
- .frame(width: supportingWidth)
+ Spacer()
- CareModuleCard(
- icon: "square.grid.2x2.fill",
- tint: Tint.purple,
- title: "Applications",
- value: "\(appState.installedApps.count)",
- detail: String(localized: "Installed apps"),
- showsDetail: !compact
- ) {
- onNavigate(.apps)
- }
- .staggered(2)
- .frame(width: supportingWidth)
+ HStack(spacing: 12) {
+ Button {
+ appState.startSmartScan()
+ } label: {
+ Label("Scan this Mac", systemImage: "magnifyingglass")
+ }
+ .buttonStyle(.borderedProminent)
+ .controlSize(.large)
+ .tint(Tint.accent)
- CareModuleCard(
- icon: "doc.questionmark.fill",
- tint: Tint.pink,
- title: "Orphaned Files",
- value: "\(appState.orphanedFiles.count)",
- detail: appState.orphanedFiles.isEmpty
- ? String(localized: "No known leftovers")
- : String(localized: "App leftovers to inspect"),
- showsDetail: !compact
- ) {
- onNavigate(.orphans)
+ Label("Local and private", systemImage: "lock")
+ .font(.system(size: 11.5, weight: .medium))
+ .foregroundStyle(.secondary)
+ }
}
- .staggered(3)
- .frame(width: supportingWidth)
- }
- .frame(height: compact ? 128 : 134)
- }
-
- private func summarySize(for categories: [CleaningCategory]) -> Int64 {
- categories.reduce(0) { partial, category in
- partial + (appState.categoryResults[category]?.totalSize ?? 0)
- }
- }
-
- private func summaryValue(size: Int64, categories: [CleaningCategory]) -> String {
- if size > 0 {
- return formatted(size)
+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading)
}
-
- let scannedCount = categories.reduce(0) { count, category in
- count + (appState.categoryResults[category] == nil ? 0 : 1)
- }
- if scannedCount == 0 {
- return String(
- format: String(localized: "%lld checks"),
- Int64(categories.count)
- )
- }
- if scannedCount < categories.count {
- return String(
- format: String(localized: "%lld/%lld checked"),
- Int64(scannedCount),
- Int64(categories.count)
- )
- }
- return String(localized: "Clear")
- }
-
- private func largestCategory(in categories: [CleaningCategory]) -> CleaningCategory? {
- categories
- .compactMap { appState.categoryResults[$0] }
- .max { $0.totalSize < $1.totalSize }?
- .category
- }
-
- private func junkFoundDelta(count: Int) -> String {
- String(format: String(localized: "across %lld categories"), Int64(count))
}
- // MARK: - Storage composition
-
- private var storageComposition: some View {
- let total = appState.diskInfo.totalSpace
- let free = appState.diskInfo.freeSpace
- let purge = max(0, appState.diskInfo.purgeableSpace)
- let junk = max(0, min(appState.totalJunkSize, appState.diskInfo.usedSpace))
- // "Used" excludes the junk + purgeable slices so the four segments sum
- // to the whole disk without double-counting.
- let usedCore = max(0, appState.diskInfo.usedSpace - junk - purge)
-
- var segments: [StorageDonut.Segment] = []
- func add(_ id: String, _ value: Int64, _ color: Color, _ label: LocalizedStringKey) {
- guard value > 0 else { return }
- segments.append(.init(
- id: id,
- value: Double(value),
- color: color,
- label: label,
- display: ByteCountFormatter.string(fromByteCount: value, countStyle: .file)
- ))
- }
- add("used", usedCore, Tint.blue, "Used")
- add("junk", junk, Tint.orange, "Junk")
- add("purgeable", purge, Tint.green, "Purgeable")
- add("free", free, Color.primary.opacity(0.14), "Free")
-
- return CardSurface(padding: 20, elevation: .standard) {
- HStack(alignment: .center, spacing: 28) {
- ZStack {
- StorageDonut(segments: segments, highlightedID: hoveredSegment)
- .frame(width: 148, height: 148)
- VStack(spacing: 1) {
- Text(ByteCountFormatter.string(fromByteCount: total, countStyle: .file))
- .font(.system(size: 18, weight: .bold))
- .monospacedDigit()
- Text("total")
- .font(.system(size: 10))
+ private var diskOverview: some View {
+ CardSurface(padding: 22, elevation: .standard) {
+ VStack(alignment: .leading, spacing: 16) {
+ HStack {
+ VStack(alignment: .leading, spacing: 3) {
+ Text("Mac storage")
+ .font(.system(size: 15, weight: .semibold))
+ Text("\(appState.diskInfo.formattedFree) available")
+ .font(.system(size: 11.5))
.foregroundStyle(.secondary)
}
+ Spacer()
+ Button {
+ appState.loadDiskInfo()
+ } label: {
+ Image(systemName: "arrow.clockwise")
+ }
+ .buttonStyle(.borderless)
+ .help("Refresh disk information")
}
- VStack(alignment: .leading, spacing: 12) {
- ForEach(Array(segments.enumerated()), id: \.element.id) { idx, seg in
- HoverableLegendChip(
- color: seg.color, label: seg.label, value: seg.display,
- percent: shareString(Int64(seg.value), of: total)
- ) { hovering in
- hoveredSegment = hovering ? seg.id : nil
+ HStack(spacing: 16) {
+ ZStack {
+ StorageDonut(
+ segments: diskSegments,
+ lineWidth: 13,
+ highlightedID: hoveredSegment
+ )
+ VStack(spacing: 0) {
+ Text("\(usedPercent)%")
+ .font(.system(size: 24, weight: .semibold, design: .rounded))
+ .monospacedDigit()
+ Text("USED")
+ .font(.system(size: 8.5, weight: .semibold))
+ .tracking(0.8)
+ .foregroundStyle(.tertiary)
+ }
+ }
+ .frame(width: 108, height: 108)
+
+ VStack(alignment: .leading, spacing: 12) {
+ diskLegendRow(
+ id: "used",
+ color: Color.primary.opacity(0.56),
+ label: "Used",
+ value: appState.diskInfo.formattedUsed
+ )
+ if appState.diskInfo.purgeableSpace > 0 {
+ diskLegendRow(
+ id: "purgeable",
+ color: Tint.cyan,
+ label: "Purgeable",
+ value: appState.diskInfo.formattedPurgeable
+ )
}
- .staggered(idx)
+ diskLegendRow(
+ id: "free",
+ color: Tint.accent,
+ label: "Available",
+ value: appState.diskInfo.formattedFree
+ )
}
}
- Spacer(minLength: 0)
+
}
+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
}
}
- // MARK: - Suggestions
-
- private var suggestions: some View {
- VStack(spacing: 10) {
- ForEach(Array(suggestionRows.enumerated()), id: \.offset) { idx, row in
- SuggestionRow(suggestion: row)
- .staggered(idx)
+ private func diskLegendRow(id: String, color: Color, label: String, value: String) -> some View {
+ HStack(spacing: 8) {
+ Circle()
+ .fill(color)
+ .frame(width: 7, height: 7)
+ Text(label)
+ .font(.system(size: 11))
+ .foregroundStyle(.secondary)
+ .lineLimit(1)
+ .fixedSize(horizontal: true, vertical: false)
+ Spacer()
+ Text(value)
+ .font(.system(size: 11, weight: .semibold))
+ .monospacedDigit()
+ .lineLimit(1)
+ .fixedSize(horizontal: true, vertical: false)
+ }
+ .opacity(hoveredSegment == nil || hoveredSegment == id ? 1 : 0.38)
+ .contentShape(Rectangle())
+ .onHover { hovering in
+ withAnimation(reduceMotion ? nil : .easeOut(duration: 0.15)) {
+ hoveredSegment = hovering ? id : nil
}
}
}
- private var suggestionRows: [Suggestion] {
- var out: [Suggestion] = []
- // Surface the largest pending category as a contextual nudge.
- if let biggest = appState.allResults.max(by: { $0.totalSize < $1.totalSize }), biggest.totalSize > 0 {
- let title = String(
- format: String(localized: "%@ is using %@"),
- String(localized: String.LocalizationValue(biggest.category.rawValue)),
- biggest.formattedSize
+ private var diskSegments: [StorageDonut.Segment] {
+ let info = appState.diskInfo
+ let used = max(0, info.usedSpace - info.purgeableSpace)
+ var segments = [
+ StorageDonut.Segment(
+ id: "used",
+ value: Double(used),
+ color: Color.primary.opacity(0.56),
+ label: "Used",
+ display: ByteCountFormatter.string(fromByteCount: used, countStyle: .file)
+ )
+ ]
+ if info.purgeableSpace > 0 {
+ segments.append(
+ StorageDonut.Segment(
+ id: "purgeable",
+ value: Double(info.purgeableSpace),
+ color: Tint.cyan,
+ label: "Purgeable",
+ display: info.formattedPurgeable
+ )
)
- out.append(Suggestion(
- icon: biggest.category.icon,
- tint: biggest.category.color,
- title: title,
- subtitle: String(localized: String.LocalizationValue(biggest.category.description)),
- pill: biggest.formattedSize
- ))
- }
- if !appState.hasFullDiskAccess {
- out.append(Suggestion(
- icon: "lock.shield.fill",
- tint: Tint.orange,
- title: String(localized: "Grant Full Disk Access for full results"),
- subtitle: String(localized: "Without it, most caches and uninstall flows fail."),
- pill: String(localized: "Action")
- ))
}
- return out
+ segments.append(
+ StorageDonut.Segment(
+ id: "free",
+ value: Double(max(0, info.freeSpace)),
+ color: Tint.accent,
+ label: "Available",
+ display: info.formattedFree
+ )
+ )
+ return segments
}
- // MARK: - Scanning state
+ private var usedPercent: Int {
+ guard appState.diskInfo.totalSpace > 0 else { return 0 }
+ let used = appState.diskInfo.totalSpace - appState.diskInfo.freeSpace
+ return Int((Double(max(0, used)) / Double(appState.diskInfo.totalSpace) * 100).rounded())
+ }
- private var scanningHero: some View {
- let compact = dashboardSize.width > 0 && dashboardSize.width < 700
- let coreSize: CGFloat = compact ? 248 : 292
+ private var scanningContent: some View {
+ VStack(alignment: .leading, spacing: 20) {
+ CardSurface(padding: 28, elevation: .standard, tint: Tint.accent) {
+ HStack(spacing: 34) {
+ ScanningGauge(progress: appState.scanProgress, tint: Tint.accent)
+ .frame(width: 164, height: 164)
- return SmartCareStageSurface(tint: Tint.blue) {
- HStack(spacing: compact ? 16 : 30) {
- VStack(alignment: .leading, spacing: 12) {
- HStack(spacing: 8) {
- Image(systemName: "sparkles")
+ VStack(alignment: .leading, spacing: 12) {
Text("Scanning your Mac")
- .font(.system(size: compact ? 26 : 31, weight: .bold))
- .tracking(-0.5)
+ .font(.system(size: 25, weight: .semibold))
+ .tracking(-0.35)
+ Text(appState.currentScanCategory)
+ .font(.system(size: 13, weight: .medium))
+ .foregroundStyle(Tint.accent)
+ ScanPathTicker(ticker: appState.scanTicker)
+ .frame(maxWidth: 520, alignment: .leading)
+ ProgressView(value: appState.scanProgress)
+ .progressViewStyle(.linear)
+ .tint(Tint.accent)
+ .frame(maxWidth: 480)
+ HStack(spacing: 10) {
+ Button("Stop scan", role: .cancel) {
+ appState.cancelScan()
+ }
+ .buttonStyle(.bordered)
+ Text("Stopping keeps the results found so far.")
+ .font(.system(size: 10.5))
+ .foregroundStyle(.tertiary)
+ }
}
- .foregroundStyle(.white)
-
- // Category line slides up as the scan advances.
- Text(currentlyInText)
- .font(.system(size: 13))
- .foregroundStyle(.white.opacity(0.68))
- .id(appState.currentScanCategory)
- .transition(
- reduceMotion
- ? .opacity
- : .asymmetric(
- insertion: .move(edge: .bottom).combined(with: .opacity),
- removal: .move(edge: .top).combined(with: .opacity)
- )
- )
-
- ShimmerProgressBar(progress: appState.scanProgress)
- .frame(maxWidth: 320)
- .padding(.top, 2)
-
- // Live file-path ticker — the "it's really working"
- // signal. Observes the standalone ScanProgressTicker so the
- // ~10Hz path churn re-renders only this label, not the whole
- // dashboard (issues #119, #120).
- ScanPathTicker(ticker: appState.scanTicker)
+ Spacer()
}
- .frame(maxWidth: .infinity, alignment: .leading)
- .animation(reduceMotion ? nil : .easeOut(duration: 0.18), value: appState.currentScanCategory)
+ }
- workingCore(
- phase: .scanning(appState.scanProgress),
- progress: appState.scanProgress,
- label: "SCANNING",
- size: coreSize
- )
+ if !appState.allResults.isEmpty {
+ dashboardSection("Found so far", detail: "\(appState.totalItemCount) items")
+ resultRows(results: Array(appState.allResults.sorted { $0.totalSize > $1.totalSize }.prefix(6)))
}
- .frame(height: compact ? 250 : 286)
}
}
- private var currentlyInText: String {
- String(
- format: String(localized: "Currently in: %@"),
- String(localized: String.LocalizationValue(appState.currentScanCategory))
- )
- }
+ private var resultsContent: some View {
+ VStack(alignment: .leading, spacing: 20) {
+ CardSurface(padding: 24, elevation: .standard, tint: appState.scanWasCancelled ? Tint.orange : Tint.accent) {
+ HStack(alignment: .center, spacing: 24) {
+ IconTile(
+ systemName: appState.scanWasCancelled ? "stop.circle" : "checklist",
+ tint: appState.scanWasCancelled ? Tint.orange : Tint.accent,
+ size: 52,
+ corner: 14
+ )
- private var liveResults: some View {
- CardSurface(padding: 0) {
- VStack(spacing: 0) {
- ForEach(appState.allResults.prefix(8)) { result in
- HStack(spacing: 12) {
- IconTile(systemName: result.category.icon, tint: result.category.color, size: 26)
- Text(LocalizedStringKey(result.category.rawValue))
- .font(.system(size: 13))
- Spacer()
- Text(result.formattedSize)
- .font(.system(size: 13, weight: .semibold))
- .monospacedDigit()
+ VStack(alignment: .leading, spacing: 5) {
+ Text(appState.scanWasCancelled ? "Scan stopped" : "Scan complete")
+ .font(.system(size: 23, weight: .semibold))
+ .tracking(-0.3)
+ Text(resultSummary)
+ .font(.system(size: 12.5))
.foregroundStyle(.secondary)
}
- .padding(.horizontal, 16)
- .padding(.vertical, 12)
- .transition(
- reduceMotion
- ? .opacity
- : .move(edge: .bottom).combined(with: .opacity)
- )
- if result.id != appState.allResults.prefix(8).last?.id {
- Divider().padding(.leading, 54)
- }
- }
- }
- .animation(reduceMotion ? nil : .spring(response: 0.4, dampingFraction: 0.85),
- value: appState.allResults.count)
- }
- }
- // MARK: - Completed state
+ Spacer()
- private var completedHero: some View {
- let isClean = appState.totalJunkSize <= 0
- let compact = dashboardSize.width > 0 && dashboardSize.width < 700
- let coreSize: CGFloat = compact ? 248 : 292
-
- return SmartCareStageSurface(tint: isClean ? Tint.green : Tint.orange) {
- HStack(spacing: compact ? 16 : 30) {
- VStack(alignment: .leading, spacing: 10) {
- Label(
- isClean ? "ALL CLEAR" : "SCAN COMPLETE",
- systemImage: isClean ? "checkmark.seal.fill" : "sparkles.rectangle.stack.fill"
- )
- .font(.system(size: 11, weight: .bold))
- .tracking(1)
- .foregroundStyle(.white.opacity(0.72))
-
- if isClean {
- Text("Your Mac is in good shape.")
- .font(.system(size: 30, weight: .bold))
- .tracking(-0.6)
- .foregroundStyle(.white)
- Text("No removable junk was found in the areas PureMac checked.")
- .font(.system(size: 14))
- .foregroundStyle(.white.opacity(0.68))
- } else {
- Text("Ready to reclaim")
- .font(.system(size: 15, weight: .medium))
- .foregroundStyle(.white.opacity(0.68))
- CountUpBytes(bytes: appState.totalJunkSize)
- .font(.system(size: 42, weight: .bold))
- .foregroundStyle(.white)
- Text(junkFoundDelta(count: appState.allResults.count))
- .font(.system(size: 13))
- .foregroundStyle(.white.opacity(0.66))
+ VStack(alignment: .trailing, spacing: 2) {
+ Text("Selected")
+ .font(.system(size: 10.5))
+ .foregroundStyle(.secondary)
+ CountUpBytes(bytes: appState.totalSelectedSize)
+ .font(.system(size: 26, weight: .semibold, design: .rounded))
}
- HStack(spacing: 10) {
- if !isClean && appState.totalSelectedSize > 0 {
+ VStack(spacing: 8) {
+ if appState.totalSelectedSize > 0 {
Button {
- showConfirmation = true
+ prepareCleanupConfirmation()
} label: {
- Label(cleanSelectedLabel, systemImage: "sparkles")
+ Label(cleanSelectedLabel, systemImage: "trash")
}
.buttonStyle(.borderedProminent)
.controlSize(.large)
- .tint(Tint.blue)
- .foregroundStyle(.white)
+ .tint(Tint.accent)
}
-
- Button("Scan Again") { appState.startSmartScan() }
- .buttonStyle(.bordered)
- .controlSize(.large)
- .tint(.white)
+ Button("Scan again") {
+ appState.startSmartScan()
+ }
+ .buttonStyle(.borderless)
}
- .padding(.top, 4)
}
- .frame(maxWidth: .infinity, alignment: .leading)
-
- resultCore(isClean: isClean, size: coreSize)
}
- .frame(height: compact ? 250 : 286)
- }
- }
- private var cleanSelectedLabel: String {
- String(
- format: String(localized: "Clean %@"),
- ByteCountFormatter.string(fromByteCount: appState.totalSelectedSize, countStyle: .file)
- )
- }
-
- private var findingsGrid: some View {
- let columnCount = dashboardSize.width > 0 && dashboardSize.width < 900 ? 2 : 3
- let results = appState.allResults.sorted { $0.totalSize > $1.totalSize }
-
- return LazyVGrid(
- columns: Array(repeating: GridItem(.flexible(), spacing: 14), count: columnCount),
- spacing: 14
- ) {
- ForEach(Array(results.enumerated()), id: \.element.id) { index, result in
- FindingTile(result: result) {
- onNavigate(.cleaning(result.category))
- }
- .staggered(index)
+ if appState.allResults.isEmpty {
+ emptyResults
+ } else {
+ dashboardSection(
+ appState.scanWasCancelled ? "Partial results" : "Cleanup plan",
+ detail: "Open a category to review individual items"
+ )
+ resultRows(results: appState.allResults.sorted { $0.totalSize > $1.totalSize })
}
}
}
- @ViewBuilder
- private var cleanSealIcon: some View {
- let base = Image(systemName: "checkmark.seal.fill")
- .font(.system(size: 26, weight: .bold))
- .foregroundStyle(Tint.green)
- if #available(macOS 14.0, *) {
- base.symbolEffect(.bounce, value: appState.totalJunkSize)
- } else {
- base
+ private var resultSummary: String {
+ if appState.allResults.isEmpty {
+ return appState.scanWasCancelled
+ ? String(localized: "No reclaimable items were found before the scan stopped.")
+ : String(localized: "No reclaimable items were found in the areas checked.")
}
- }
-
- @ViewBuilder
- private var sparklesIcon: some View {
- let base = Image(systemName: "sparkles")
- .font(.system(size: 18, weight: .semibold))
- .foregroundStyle(
- LinearGradient(colors: [Tint.blue, Tint.purple],
- startPoint: .topLeading, endPoint: .bottomTrailing)
- )
- if #available(macOS 14.0, *) {
- base.symbolEffect(.variableColor.iterative, options: .repeating)
- } else {
- base
+ let size = ByteCountFormatter.string(fromByteCount: appState.totalJunkSize, countStyle: .file)
+ if appState.scanWasCancelled {
+ return String(format: String(localized: "%@ found before the scan stopped. Results may be incomplete."), size)
}
+ return String(format: String(localized: "%@ found across %lld categories."), size, Int64(appState.allResults.count))
}
- private var cleaningHero: some View {
- let compact = dashboardSize.width > 0 && dashboardSize.width < 700
- let coreSize: CGFloat = compact ? 248 : 292
-
- return SmartCareStageSurface(tint: Tint.orange) {
- HStack(spacing: compact ? 16 : 30) {
- VStack(alignment: .leading, spacing: 10) {
- Text("Cleaning safely…")
- .font(.system(size: compact ? 26 : 31, weight: .bold))
- .tracking(-0.5)
- .foregroundStyle(.white)
- Text(percentCompleteText)
- .font(.system(size: 13))
- .foregroundStyle(.white.opacity(0.68))
- ShimmerProgressBar(progress: appState.cleanProgress, tint: Tint.orange)
- .frame(maxWidth: 320)
- .padding(.top, 2)
+ private var emptyResults: some View {
+ CardSurface(padding: 28, elevation: .flat) {
+ HStack(spacing: 18) {
+ SuccessMedal(tint: Tint.green, size: 72)
+ VStack(alignment: .leading, spacing: 5) {
+ Text(appState.scanWasCancelled ? "No results yet" : "Nothing to clean")
+ .font(.system(size: 18, weight: .semibold))
+ Text(
+ appState.scanWasCancelled
+ ? "Run the scan again when you are ready to check every area."
+ : "PureMac did not find removable items in the selected scan areas."
+ )
+ .font(.system(size: 12.5))
+ .foregroundStyle(.secondary)
}
- .frame(maxWidth: .infinity, alignment: .leading)
-
- workingCore(
- phase: .cleaning(appState.cleanProgress),
- progress: appState.cleanProgress,
- label: "CLEANING",
- size: coreSize
- )
+ Spacer()
}
- .frame(height: compact ? 250 : 286)
}
}
- private var percentCompleteText: String {
- String(format: String(localized: "%lld%% complete"), Int64(appState.cleanProgress * 100))
- }
-
- /// Convert the medal's frame (in dashboard coordinates) into a UnitPoint
- /// for the confetti emitter. Falls back to the existing value until the
- /// dashboard size is known.
- private func updateBurstOrigin(medalFrame: CGRect) {
- guard dashboardSize.width > 0, dashboardSize.height > 0 else { return }
- burstOrigin = UnitPoint(
- x: max(0, min(1, medalFrame.midX / dashboardSize.width)),
- y: max(0, min(1, medalFrame.midY / dashboardSize.height))
- )
- }
-
- private var cleanedHero: some View {
- let compact = dashboardSize.width > 0 && dashboardSize.width < 700
- let coreSize: CGFloat = compact ? 248 : 292
-
- return SmartCareStageSurface(tint: Tint.green) {
- HStack(spacing: compact ? 16 : 30) {
- VStack(alignment: .leading, spacing: 6) {
- Text("Cleanup complete")
- .font(.system(size: 15, weight: .semibold))
- .foregroundStyle(.white.opacity(0.70))
- CountUpBytes(bytes: appState.totalFreedSpace)
- .font(.system(size: 42, weight: .bold))
- .foregroundStyle(.white)
- Text("freed")
- .font(.system(size: 14))
- .foregroundStyle(.white.opacity(0.68))
- Button("Done") { appState.scanState = .idle }
- .buttonStyle(.borderedProminent)
- .controlSize(.large)
- .tint(Tint.blue)
- .foregroundStyle(.white)
- .padding(.top, 4)
+ private func resultRows(results: [CategoryResult]) -> some View {
+ CardSurface(padding: 0, elevation: .flat) {
+ VStack(spacing: 0) {
+ ForEach(Array(results.enumerated()), id: \.element.id) { index, result in
+ CategoryResultRow(
+ result: result,
+ selectedCount: appState.selectedCountInCategory(result.category),
+ selection: appState.categoryBinding(for: result.category)
+ ) {
+ onNavigate(.cleaning(result.category))
+ }
+ if index < results.count - 1 {
+ Divider()
+ .padding(.leading, 58)
+ }
}
- .frame(maxWidth: .infinity, alignment: .leading)
-
- resultCore(isClean: true, size: coreSize)
- .background(
- GeometryReader { geo in
- Color.clear.onAppear {
- updateBurstOrigin(medalFrame: geo.frame(in: .named(dashboardSpace)))
- }
- }
- )
}
- .frame(height: compact ? 250 : 286)
}
}
- private func workingCore(
- phase: SmartCareCoreArtwork.Phase,
- progress: Double,
- label: LocalizedStringKey,
- size: CGFloat
- ) -> some View {
- let clamped = max(0, min(1, progress))
- let percentage = Int((clamped * 100).rounded())
-
- return SmartCareCoreArtwork(phase: phase, size: size)
- .frame(width: size, height: size)
- .fixedSize()
- .accessibilityElement(children: .ignore)
- .accessibilityLabel(Text(label))
- .accessibilityValue("\(percentage) percent")
- }
-
- private func resultCore(isClean: Bool, size: CGFloat) -> some View {
- SmartCareCoreArtwork(phase: isClean ? .success : .review, size: size)
- .frame(width: size, height: size)
- .frame(width: size, height: size)
- .fixedSize()
- .accessibilityElement(children: .ignore)
- .accessibilityLabel(isClean ? "All clear" : "Review scan results")
- }
-
- // MARK: - Helpers
-
- private func sectionHeader(_ text: LocalizedStringKey) -> some View {
- Text(text)
- .font(.system(size: 15, weight: .semibold))
- .foregroundStyle(.primary)
- .padding(.top, 4)
- .accessibilityAddTraits(.isHeader)
- }
-}
-
-// MARK: - Components
-
-/// Deep, stateful dashboard plane inspired by premium Mac utilities while
-/// preserving native SwiftUI content, focus, and accessibility behavior.
-private struct SmartCareStageSurface<Content: View>: View {
- let tint: Color
- var padding: CGFloat = 28
- @ViewBuilder var content: Content
-
- private let cornerRadius: CGFloat = 28
-
- var body: some View {
- content
- .padding(padding)
- .frame(maxWidth: .infinity, alignment: .leading)
- .background(
- ZStack {
- RoundedRectangle(cornerRadius: cornerRadius, style: .continuous)
- .fill(TintGradient.smartCare)
- RadialGradient(
- colors: [tint.opacity(0.18), .clear],
- center: .topTrailing,
- startRadius: 0,
- endRadius: 460
- )
- RadialGradient(
- colors: [Tint.cyan.opacity(0.06), .clear],
- center: .bottomLeading,
- startRadius: 0,
- endRadius: 420
- )
- LinearGradient(
- colors: [.white.opacity(0.03), .clear, .black.opacity(0.14)],
- startPoint: .top,
- endPoint: .bottom
- )
+ private var cleaningContent: some View {
+ CardSurface(padding: 34, elevation: .standard, tint: Tint.accent) {
+ VStack(spacing: 22) {
+ ScanningGauge(progress: appState.cleanProgress, tint: Tint.accent, label: "CLEANING")
+ .frame(width: 170, height: 170)
+ VStack(spacing: 6) {
+ Text("Cleaning selected items")
+ .font(.system(size: 24, weight: .semibold))
+ Text("Keep PureMac open until this pass finishes.")
+ .font(.system(size: 12.5))
+ .foregroundStyle(.secondary)
}
- )
- .clipShape(RoundedRectangle(cornerRadius: cornerRadius, style: .continuous))
- .overlay(
- RoundedRectangle(cornerRadius: cornerRadius, style: .continuous)
- .strokeBorder(
- LinearGradient(
- colors: [.white.opacity(0.17), tint.opacity(0.10), .white.opacity(0.05)],
- startPoint: .topLeading,
- endPoint: .bottomTrailing
- ),
- lineWidth: 0.8
- )
- )
- .shadow(color: tint.opacity(0.08), radius: 28, y: 12)
- .shadow(color: .black.opacity(0.28), radius: 22, y: 10)
- // The scenic surface is always dark, even when the surrounding app
- // is light, so semantic primary/secondary styles remain legible.
- .environment(\.colorScheme, .dark)
+ ProgressView(value: appState.cleanProgress)
+ .tint(Tint.accent)
+ .frame(maxWidth: 460)
+ }
+ .frame(maxWidth: .infinity, minHeight: 380)
+ }
}
-}
-
-private struct CareModuleCard: View {
- let icon: String
- let tint: Color
- let title: LocalizedStringKey
- let value: String
- let detail: String
- var prominent: Bool = false
- var showsDetail: Bool = true
- let action: () -> Void
- @State private var hovering = false
- @Environment(\.accessibilityReduceMotion) private var reduceMotion
- @Environment(\.colorScheme) private var colorScheme
-
- var body: some View {
- Button(action: action) {
- VStack(alignment: .leading, spacing: prominent ? 11 : 8) {
- if prominent {
- HStack(spacing: 9) {
- IconTile(
- systemName: icon,
- tint: tint,
- size: 32,
- corner: 9,
- glow: hovering,
- vivid: true
- )
- Text(title)
- .font(.system(size: 14, weight: .semibold))
- Spacer(minLength: 5)
- Image(systemName: "arrow.up.right")
- .font(.system(size: 9.5, weight: .bold))
- .foregroundStyle(hovering ? tint : Color.secondary.opacity(0.7))
- }
- } else {
- HStack {
- IconTile(
- systemName: icon,
- tint: tint,
- size: 25,
- corner: 7,
- glow: hovering
- )
- Spacer(minLength: 4)
- Image(systemName: "arrow.up.right")
- .font(.system(size: 8.5, weight: .bold))
- .foregroundStyle(hovering ? tint : Color.secondary.opacity(0.65))
+ private var cleanedContent: some View {
+ CardSurface(
+ padding: 38,
+ elevation: .standard,
+ tint: appState.lastCleanupHadFailures ? Tint.orange : Tint.green
+ ) {
+ HStack(spacing: 34) {
+ SuccessMedal(tint: appState.lastCleanupHadFailures ? Tint.orange : Tint.green, size: 126)
+ VStack(alignment: .leading, spacing: 9) {
+ Text(appState.lastCleanupHadFailures ? "Some items need attention" : "Cleanup complete")
+ .font(.system(size: 25, weight: .semibold))
+ if appState.totalFreedSpace > 0 {
+ CountUpBytes(bytes: appState.totalFreedSpace)
+ .font(.system(size: 38, weight: .semibold, design: .rounded))
+ Text("reclaimed")
+ .font(.system(size: 12.5))
+ .foregroundStyle(.secondary)
}
- Text(title)
- .font(.system(size: 11.5, weight: .semibold))
- .lineLimit(1)
- .minimumScaleFactor(0.70)
- }
-
- HStack(alignment: .firstTextBaseline, spacing: 8) {
- Text(value)
- .font(.system(size: prominent ? 27 : 22, weight: .bold))
- .monospacedDigit()
- .contentTransition(.numericText())
- .lineLimit(1)
- .minimumScaleFactor(0.64)
- if prominent && showsDetail {
- Text(detail)
- .font(.system(size: 11.5))
+ if let cleanError = appState.cleanError {
+ Text(cleanError)
+ .font(.system(size: 12))
.foregroundStyle(.secondary)
- .lineLimit(1)
+ .lineLimit(3)
}
+ Button("Done") {
+ appState.scanState = .idle
+ }
+ .buttonStyle(.borderedProminent)
+ .controlSize(.large)
+ .tint(Tint.accent)
+ .padding(.top, 5)
}
-
- if !prominent && showsDetail {
- Text(detail)
- .font(.system(size: 10.5))
- .foregroundStyle(.secondary)
- .lineLimit(1)
- }
- }
- .padding(.horizontal, prominent ? 18 : 15)
- .padding(.vertical, prominent ? 15 : 14)
- .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
- .background(cardBackground)
- .overlay(cardBorder)
- .overlay(alignment: .topLeading) {
- Capsule()
- .fill(
- LinearGradient(
- colors: [tint.opacity(0.85), tint.opacity(0.18)],
- startPoint: .leading,
- endPoint: .trailing
- )
- )
- .frame(width: prominent ? 68 : 38, height: 2)
- .padding(.leading, prominent ? 18 : 15)
+ Spacer()
}
- .shadow(
- color: hovering ? tint.opacity(0.13) : .black.opacity(colorScheme == .dark ? 0.11 : 0.06),
- radius: hovering ? 16 : 9,
- y: hovering ? 7 : 4
- )
+ .frame(maxWidth: .infinity, minHeight: 320, alignment: .leading)
}
- .buttonStyle(.plain)
- .contentShape(RoundedRectangle(cornerRadius: 18, style: .continuous))
- .scaleEffect(hovering && !reduceMotion ? 1.012 : 1)
- .offset(y: hovering && !reduceMotion ? -3 : 0)
- .animation(reduceMotion ? nil : MotionTokens.snappy, value: hovering)
- .onHover { hovering = $0 }
- }
-
- private var cardBackground: some View {
- RoundedRectangle(cornerRadius: 18, style: .continuous)
- .fill(.ultraThinMaterial)
- .overlay(
- RoundedRectangle(cornerRadius: 18, style: .continuous)
- .fill(
- LinearGradient(
- colors: [
- tint.opacity(prominent ? 0.105 : 0.045),
- Color.white.opacity(colorScheme == .dark ? 0.025 : 0.24),
- .clear
- ],
- startPoint: .topLeading,
- endPoint: .bottomTrailing
- )
- )
- )
}
- private var cardBorder: some View {
- RoundedRectangle(cornerRadius: 18, style: .continuous)
- .strokeBorder(
- LinearGradient(
- colors: [
- Color.white.opacity(colorScheme == .dark ? 0.15 : 0.65),
- tint.opacity(hovering ? 0.30 : 0.10),
- Color.primary.opacity(0.04)
- ],
- startPoint: .topLeading,
- endPoint: .bottomTrailing
- ),
- lineWidth: 0.8
- )
- }
-}
-
-private struct FindingTile: View {
- @EnvironmentObject var appState: AppState
- let result: CategoryResult
- let onReview: () -> Void
-
- @State private var hovering = false
- @Environment(\.accessibilityReduceMotion) private var reduceMotion
-
- private var isFullySelected: Bool {
- appState.selectedCountInCategory(result.category) == result.itemCount
- }
-
- private var selection: Binding<Bool> {
- Binding(
- get: { isFullySelected },
- set: { selected in
- if selected {
- appState.selectAllInCategory(result.category)
- } else {
- appState.deselectAllInCategory(result.category)
- }
- }
+ private var cleanConfirmationTitle: String {
+ let size = pendingCleanItems.reduce(Int64(0)) { $0 + $1.size }
+ return String(
+ format: String(localized: "Permanently delete %@?"),
+ ByteCountFormatter.string(fromByteCount: size, countStyle: .file)
)
}
- var body: some View {
- VStack(alignment: .leading, spacing: 11) {
- HStack(spacing: 10) {
- Toggle(isOn: selection) {
- Text(LocalizedStringKey(result.category.rawValue))
- .font(.system(size: 13.5, weight: .semibold))
- }
- .toggleStyle(.checkbox)
-
- Spacer(minLength: 8)
- IconTile(
- systemName: result.category.icon,
- tint: result.category.color,
- size: 34,
- glow: hovering,
- vivid: true
- )
- }
-
- Text(result.formattedSize)
- .font(.system(size: 27, weight: .bold))
- .monospacedDigit()
- .contentTransition(.numericText())
-
- Text(itemsCountText)
- .font(.system(size: 11.5))
- .foregroundStyle(.secondary)
-
- HStack {
- Text(selectedCountText)
- .font(.system(size: 11, weight: .medium))
- .foregroundStyle(result.category.color)
- Spacer()
- Button("Review", action: onReview)
- .buttonStyle(.bordered)
- .controlSize(.small)
- .tint(result.category.color)
- }
- }
- .padding(17)
- .frame(maxWidth: .infinity, minHeight: 158, alignment: .topLeading)
- .background(
- ZStack {
- RoundedRectangle(cornerRadius: 17, style: .continuous)
- .fill(Color(nsColor: .controlBackgroundColor))
- RoundedRectangle(cornerRadius: 17, style: .continuous)
- .fill(
- LinearGradient(
- colors: [result.category.color.opacity(0.16), .clear],
- startPoint: .topTrailing,
- endPoint: .bottomLeading
- )
- )
- }
- )
- .overlay(
- RoundedRectangle(cornerRadius: 17, style: .continuous)
- .strokeBorder(result.category.color.opacity(hovering ? 0.34 : 0.16), lineWidth: 0.8)
+ private var cleanConfirmationMessage: String {
+ String(
+ format: String(localized: "%lld selected items will be permanently deleted. Review the list before continuing."),
+ Int64(pendingCleanItems.count)
)
- .shadow(color: .black.opacity(hovering ? 0.12 : 0.06),
- radius: hovering ? 14 : 8, y: hovering ? 6 : 3)
- .scaleEffect(hovering && !reduceMotion ? 1.012 : 1)
- .offset(y: hovering && !reduceMotion ? -2 : 0)
- .animation(reduceMotion ? nil : MotionTokens.snappy, value: hovering)
- .onHover { hovering = $0 }
}
- private var itemsCountText: String {
- String(format: String(localized: "%lld items found"), Int64(result.itemCount))
+ private func prepareCleanupConfirmation() {
+ pendingCleanItems = appState.allResults
+ .flatMap(\.items)
+ .filter(appState.isItemSelected)
+ showConfirmation = !pendingCleanItems.isEmpty
}
- private var selectedCountText: String {
+ private var cleanSelectedLabel: String {
String(
- format: String(localized: "%lld selected"),
- Int64(appState.selectedCountInCategory(result.category))
+ format: String(localized: "Clean %@"),
+ ByteCountFormatter.string(fromByteCount: appState.totalSelectedSize, countStyle: .file)
)
}
-}
-
-private struct StatCard: View {
- let icon: String
- let tint: Color
- let label: LocalizedStringKey
- let value: String
- let delta: String?
- /// When set, the headline renders as a rolling byte counter instead of
- /// the static `value` string.
- var byteValue: Int64? = nil
- var body: some View {
- CardSurface(padding: 16, tint: tint) {
- VStack(alignment: .leading, spacing: 8) {
- HStack(spacing: 8) {
- IconTile(systemName: icon, tint: tint, size: 28, glow: true)
- Text(label)
- .font(.system(size: 11, weight: .semibold))
- .foregroundStyle(.secondary)
- .textCase(.uppercase)
- .tracking(0.5)
- Spacer(minLength: 0)
- }
- Group {
- if let byteValue {
- CountUpBytes(bytes: byteValue)
- } else {
- Text(value)
- .monospacedDigit()
- .contentTransition(.numericText())
- }
- }
- .font(.system(size: 23, weight: .bold))
- .lineLimit(1)
- .minimumScaleFactor(0.6)
- if let delta {
- Text(delta)
- .font(.system(size: 11))
- .foregroundStyle(.tertiary)
- .lineLimit(1)
- }
+ private func dashboardSection(_ title: LocalizedStringKey, detail: String? = nil) -> some View {
+ HStack(alignment: .firstTextBaseline) {
+ Text(title)
+ .font(.system(size: 16, weight: .semibold))
+ .accessibilityAddTraits(.isHeader)
+ Spacer()
+ if let detail {
+ Text(detail)
+ .font(.system(size: 10.5))
+ .foregroundStyle(.tertiary)
}
}
- .pressable(hoverScale: 1.02, lift: true)
}
}
-private struct Suggestion: Identifiable {
- let id = UUID()
+private struct DashboardToolCard: View {
+ let title: LocalizedStringKey
+ let detail: LocalizedStringKey
let icon: String
let tint: Color
- let title: String
- let subtitle: String
- let pill: String?
-}
-
-private struct SuggestionRow: View {
- let suggestion: Suggestion
- var body: some View {
- CardSurface(padding: 14, tint: suggestion.tint) {
- HStack(spacing: 14) {
- IconTile(systemName: suggestion.icon, tint: suggestion.tint,
- size: 38, corner: 10, glow: true)
- VStack(alignment: .leading, spacing: 2) {
- Text(suggestion.title)
- .font(.system(size: 14, weight: .semibold))
- Text(suggestion.subtitle)
- .font(.system(size: 12))
- .foregroundStyle(.secondary)
- }
- Spacer()
- if let pill = suggestion.pill {
- StatusChip(label: pill, tint: suggestion.tint)
- }
- Image(systemName: "chevron.right")
- .font(.system(size: 11, weight: .semibold))
- .foregroundStyle(.tertiary)
- }
- }
- .pressable(hoverScale: 1.01, lift: true)
- }
-}
-
-/// Live file-path ticker. Observes the standalone `ScanProgressTicker` directly
-/// so the scan engine's ~10Hz path updates re-render only this one label rather
-/// than the whole AppState-observing view tree (issues #119, #120).
-private struct ScanPathTicker: View {
- @ObservedObject var ticker: ScanProgressTicker
-
- private var display: String {
- guard !ticker.path.isEmpty else { return "" }
- return (ticker.path as NSString).abbreviatingWithTildeInPath
- }
-
- var body: some View {
- Text(display)
- .font(.system(size: 11, design: .monospaced))
- .foregroundStyle(.tertiary)
- .lineLimit(1)
- .truncationMode(.middle)
- .frame(maxWidth: 360, alignment: .leading)
- .frame(height: 14)
- .opacity(display.isEmpty ? 0 : 1)
- }
-}
-
-// MARK: - Gauges
-
-// ScanningGauge now lives in Components/DashboardCharts.swift (radar sweep +
-// halo rings + Reduce Motion compliance).
-
-/// Legend chip wrapper that reports hover for donut/meter cross-highlighting
-/// and scales slightly while hovered.
-private struct HoverableLegendChip: View {
- let color: Color
- let label: LocalizedStringKey
- let value: String
- var percent: String? = nil
- let onHoverChange: (Bool) -> Void
+ let action: () -> Void
@State private var hovering = false
- @Environment(\.accessibilityReduceMotion) private var reduceMotion
-
- var body: some View {
- LegendChip(color: color, label: label, value: value, percent: percent)
- .scaleEffect(hovering && !reduceMotion ? 1.05 : 1, anchor: .leading)
- .animation(reduceMotion ? nil : MotionTokens.snappy, value: hovering)
- .onHover { h in
- hovering = h
- onHoverChange(h)
- }
- }
-}
-
-/// Barely-there radial wash that drifts behind the idle hero ring. Static at
-/// rest size under Reduce Motion.
-private struct HeroDrift: View {
- let tint: Color
-
- @State private var drift = false
- @Environment(\.accessibilityReduceMotion) private var reduceMotion
-
- var body: some View {
- RadialGradient(
- colors: [tint.opacity(0.16), .clear],
- center: .center, startRadius: 10, endRadius: 130
- )
- .blur(radius: 24)
- .scaleEffect(drift ? 1.12 : 0.96)
- .offset(x: drift ? 8 : -8)
- .onAppear {
- guard !reduceMotion else { return }
- withAnimation(.easeInOut(duration: 3.0).repeatForever(autoreverses: true)) {
- drift = true
- }
- }
- }
-}
-
-/// Two small glass bubbles hovering just outside the hero ring. They bob on
-/// offset rhythms so the composition feels alive without competing with the
-/// gauge itself. Positions are static under Reduce Motion.
-private struct OrbSatellites: View {
- let tint: Color
- let ringSize: CGFloat
-
- @State private var bob = false
- @Environment(\.accessibilityReduceMotion) private var reduceMotion
var body: some View {
- let orbit = ringSize / 2 + 14
- ZStack {
- Circle()
- .fill(tint.opacity(0.22))
- .frame(width: 13, height: 13)
- .blur(radius: 0.5)
- .offset(x: -orbit - 6, y: -orbit * 0.55 + (bob ? -7 : 7))
- .opacity(bob ? 0.9 : 0.55)
- Circle()
- .stroke(tint.opacity(0.30), lineWidth: 1)
- .frame(width: 17, height: 17)
- .offset(x: orbit + 4, y: orbit * 0.5 + (bob ? 6 : -6))
- Circle()
- .fill(Tint.purple.opacity(0.18))
- .frame(width: 8, height: 8)
- .offset(x: orbit * 0.35, y: -orbit - 8 + (bob ? -5 : 5))
- }
- .allowsHitTesting(false)
- .onAppear {
- guard !reduceMotion else { return }
- withAnimation(.easeInOut(duration: 2.8).repeatForever(autoreverses: true)) {
- bob = true
- }
- }
- }
-}
-
-/// Gradient progress capsule with a traveling shimmer band, replacing the
-/// stock linear ProgressView during scans/cleans. Shimmer is masked to the
-/// filled portion and removed entirely under Reduce Motion.
-private struct ShimmerProgressBar: View {
- let progress: Double
- var tint: Color = Tint.blue
-
- @Environment(\.accessibilityReduceMotion) private var reduceMotion
-
- private var clamped: Double { max(0, min(1, progress)) }
-
- var body: some View {
- ZStack(alignment: .leading) {
- Capsule()
- .fill(Color.primary.opacity(0.08))
-
- if reduceMotion {
- ShimmerProgressFill(progress: CGFloat(clamped), cycle: nil, tint: tint)
- } else {
- TimelineView(.animation) { timeline in
- let t = timeline.date.timeIntervalSinceReferenceDate
- let cycle = CGFloat((t.truncatingRemainder(dividingBy: 1.8)) / 1.8)
- ShimmerProgressFill(progress: CGFloat(clamped), cycle: cycle, tint: tint)
- .animation(.easeOut(duration: 0.35), value: clamped)
- }
- }
- }
- .clipShape(Capsule())
- .frame(height: 9)
- }
-}
-
-/// Keeps the fill, its clipping boundary, and the shimmer path on the same
-/// interpolated progress value while `TimelineView` independently drives the
-/// shimmer phase.
-private struct ShimmerProgressFill: View, Animatable {
- var progress: CGFloat
- let cycle: CGFloat?
- let tint: Color
-
- var animatableData: CGFloat {
- get { progress }
- set { progress = newValue }
- }
-
- var body: some View {
- GeometryReader { geo in
- let fillWidth = geo.size.width * max(0, min(1, progress))
- let visibleFillWidth = min(geo.size.width, max(8, fillWidth))
-
- ZStack(alignment: .leading) {
- LinearGradient(colors: [tint, tint.opacity(0.7)],
- startPoint: .leading, endPoint: .trailing)
-
- if let cycle {
- let bandWidth = min(56, max(3, visibleFillWidth * 0.6))
- LinearGradient(
- colors: [.clear, .white.opacity(0.35), .clear],
- startPoint: .leading, endPoint: .trailing
- )
- .frame(width: bandWidth)
- .offset(x: cycle * (visibleFillWidth + bandWidth) - bandWidth)
- .frame(maxWidth: .infinity, alignment: .leading)
+ Button(action: action) {
+ CardSurface(padding: 16, elevation: .flat, tint: hovering ? tint : nil) {
+ HStack(spacing: 12) {
+ IconTile(systemName: icon, tint: tint, size: 36, corner: 10)
+ VStack(alignment: .leading, spacing: 3) {
+ Text(title)
+ .font(.system(size: 13.5, weight: .semibold))
+ .foregroundStyle(.primary)
+ Text(detail)
+ .font(.system(size: 10.5))
+ .foregroundStyle(.secondary)
+ .lineLimit(2)
+ }
+ Spacer(minLength: 5)
+ Image(systemName: "chevron.right")
+ .font(.system(size: 9, weight: .semibold))
+ .foregroundStyle(.tertiary)
}
+ .frame(maxWidth: .infinity, minHeight: 46, alignment: .leading)
}
- .frame(width: visibleFillWidth)
- .clipShape(Capsule())
}
+ .buttonStyle(.plain)
+ .contentShape(RoundedRectangle(cornerRadius: 14, style: .continuous))
+ .onHover { hovering = $0 }
}
}
-// MARK: - Toggle row
-
-private struct CategoryToggleRow: View {
- @EnvironmentObject var appState: AppState
+private struct CategoryResultRow: View {
let result: CategoryResult
-
- private var isFullySelected: Bool {
- appState.selectedCountInCategory(result.category) == result.itemCount
- }
+ let selectedCount: Int
+ @Binding var selection: Bool
+ let open: () -> Void
var body: some View {
- Toggle(isOn: Binding(
- get: { isFullySelected },
- set: { newValue in
- if newValue {
- appState.selectAllInCategory(result.category)
- } else {
- appState.deselectAllInCategory(result.category)
- }
- }
- )) {
- HStack(spacing: 12) {
- IconTile(systemName: result.category.icon, tint: result.category.color, size: 28, vivid: true)
- VStack(alignment: .leading, spacing: 1) {
- Text(LocalizedStringKey(result.category.rawValue))
- .font(.system(size: 13.5, weight: .semibold))
- Text(itemsCountText)
- .font(.system(size: 11.5))
- .foregroundStyle(.secondary)
+ HStack(spacing: 12) {
+ Toggle("", isOn: $selection)
+ .labelsHidden()
+ .toggleStyle(AnimatedCheckboxStyle(tint: Tint.accent))
+ IconTile(systemName: result.category.icon, tint: result.category.color, size: 30, corner: 8)
+ Button(action: open) {
+ HStack {
+ VStack(alignment: .leading, spacing: 2) {
+ Text(LocalizedStringKey(result.category.rawValue))
+ .font(.system(size: 13, weight: .semibold))
+ .foregroundStyle(.primary)
+ Text("\(selectedCount) of \(result.itemCount) selected")
+ .font(.system(size: 10.5))
+ .foregroundStyle(.secondary)
+ }
+ Spacer()
+ Text(result.formattedSize)
+ .font(.system(size: 12.5, weight: .semibold))
+ .monospacedDigit()
+ .foregroundStyle(.primary)
+ Image(systemName: "chevron.right")
+ .font(.system(size: 9, weight: .semibold))
+ .foregroundStyle(.tertiary)
}
- Spacer()
- Text(result.formattedSize)
- .font(.system(size: 13, weight: .semibold))
- .monospacedDigit()
- .foregroundStyle(.secondary)
+ .contentShape(Rectangle())
}
+ .buttonStyle(.plain)
}
- .toggleStyle(.checkbox)
.padding(.horizontal, 16)
- .padding(.vertical, 10)
- }
-
- private var itemsCountText: String {
- String(format: String(localized: "%lld items"), Int64(result.itemCount))
+ .padding(.vertical, 11)
}
}
-/// Lays its content out horizontally at full width and vertically when the
-/// container is too narrow for the row to fit, so wide hero rows reflow into a
-/// stacked layout instead of overflowing.
-struct AdaptiveStack<Content: View>: View {
- let compact: Bool
- var spacing: CGFloat = 28
- @ViewBuilder var content: Content
+private struct ScanPathTicker: View {
+ @ObservedObject var ticker: ScanProgressTicker
var body: some View {
- if compact {
- VStack(alignment: .leading, spacing: spacing) { content }
- } else {
- HStack(alignment: .center, spacing: spacing) { content }
+ HStack(spacing: 6) {
+ Image(systemName: "folder")
+ .font(.system(size: 10))
+ Text(ticker.path.isEmpty ? String(localized: "Preparing the next area…") : ticker.path)
+ .lineLimit(1)
+ .truncationMode(.middle)
}
+ .font(.system(size: 10.5, design: .monospaced))
+ .foregroundStyle(.secondary)
+ .accessibilityLabel("Current scan path")
+ .accessibilityValue(ticker.path)
}
}
diff --git a/PureMac/Views/MainWindow.swift b/PureMac/Views/MainWindow.swift
index 2988ac0..db20b8e 100644
--- a/PureMac/Views/MainWindow.swift
+++ b/PureMac/Views/MainWindow.swift
@@ -6,6 +6,7 @@ struct MainWindow: View {
@ObservedObject private var permission = PermissionCoordinator.shared
@State private var selectedSection: AppSection? = .cleaning(.smartScan)
@State private var columnVisibility: NavigationSplitViewVisibility = .all
+ @State private var cleanupExpanded = false
@State private var advancedToolsExpanded = false
@FocusState private var focusedSection: AppSection?
@Environment(\.accessibilityReduceMotion) private var reduceMotion
@@ -16,42 +17,36 @@ struct MainWindow: View {
.userCache,
.mailAttachments,
.trashBins,
- .largeFiles,
+ .largeFiles
]
- // Filtered against `scannable` so a category withdrawn there (see
- // CleaningCategory.appModifying) cannot linger here as a dead sidebar row.
private static let advancedCategories: [CleaningCategory] = [
.aiApps,
.xcodeJunk,
.brewCache,
.nodeCache,
- .dockerCache,
+ .dockerCache
].filter(CleaningCategory.scannable.contains)
var body: some View {
NavigationSplitView(columnVisibility: $columnVisibility) {
sidebar
- .navigationSplitViewColumnWidth(min: 232, ideal: 244, max: 300)
+ .navigationSplitViewColumnWidth(min: 232, ideal: 248, max: 288)
} detail: {
detailContainer
}
- .frame(minWidth: 980, minHeight: 600)
+ .frame(minWidth: 960, minHeight: 640)
+ .tint(Tint.accent)
.onReceive(NotificationCenter.default.publisher(for: NSApplication.didBecomeActiveNotification)) { _ in
appState.checkFullDiskAccess()
permission.refreshStatus()
}
.onChange(of: appState.pendingExternalApp) { app in
- // A right-clicked app arrived via Finder Services — surface the
- // Installed Apps view so its related-files scan is visible.
guard app != nil else { return }
selectSection(.apps)
appState.pendingExternalApp = nil
}
.onAppear {
- // Covers a request that landed before MainWindow mounted (cold
- // launch, or while onboarding was still showing) — onChange alone
- // fires only on subsequent changes and would miss it.
if appState.pendingExternalApp != nil {
selectSection(.apps)
appState.pendingExternalApp = nil
@@ -60,9 +55,6 @@ struct MainWindow: View {
}
}
.onChange(of: appState.cleanErrorIsFDAFixable) { isFDAFixable in
- // Auto-route FDA-fixable clean errors straight into the rich
- // sheet — skip the generic alert entirely so the user gets
- // 1-tap remediation instead of "Check the log for details".
guard isFDAFixable else { return }
let pending = appState.pendingPermissionRetryItems
appState.cleanError = nil
@@ -88,85 +80,150 @@ struct MainWindow: View {
}
}
- // MARK: - Sidebar
-
private var sidebar: some View {
List {
Section {
- navRow(section: .cleaning(.smartScan), label: "Smart Care",
- icon: "sparkles",
- tint: SidebarPalette.smartCarePrimary,
- secondaryTint: SidebarPalette.smartCareSecondary,
- badge: dashboardBadge,
- isFeatured: true)
- } header: { sectionLabel("Overview") }
-
- Section {
- ForEach(Self.cleanupCategories) { category in
- navRow(section: .cleaning(category),
- label: LocalizedStringKey(category.rawValue),
- icon: category.icon,
- tint: category.color,
- secondaryTint: category.color,
- badge: sizeBadge(for: category))
- }
- } header: { sectionLabel("Cleanup") }
+ navRow(
+ section: .cleaning(.smartScan),
+ label: "Smart Care",
+ icon: "sparkles",
+ tint: Tint.accent,
+ badge: dashboardBadge,
+ emphasized: true
+ )
+ navRow(
+ section: .protection,
+ label: "Protection",
+ icon: "shield.checkered",
+ tint: Tint.green,
+ badge: nil
+ )
+ navRow(
+ section: .performance,
+ label: "Performance",
+ icon: "gauge.with.dots.needle.67percent",
+ tint: Tint.cyan,
+ badge: nil
+ )
+ } header: {
+ sectionLabel("Care")
+ }
Section {
- navRow(section: .apps, label: "Installed Apps",
- icon: "square.grid.2x2.fill",
- tint: SidebarPalette.applicationsPrimary,
- secondaryTint: SidebarPalette.applicationsSecondary,
- badge: appState.installedApps.isEmpty ? nil : "\(appState.installedApps.count)")
- navRow(section: .orphans, label: "Orphaned Files",
- icon: "doc.questionmark.fill",
- tint: Tint.orange,
- secondaryTint: Tint.orange,
- badge: appState.orphanedFiles.isEmpty ? nil : "\(appState.orphanedFiles.count)")
- } header: { sectionLabel("Applications") }
+ navRow(
+ section: .apps,
+ label: "Uninstaller",
+ icon: "app.dashed",
+ tint: Tint.blue,
+ badge: appState.installedApps.isEmpty ? nil : "\(appState.installedApps.count)"
+ )
+ navRow(
+ section: .appUpdates,
+ label: "App Updates",
+ icon: "arrow.triangle.2.circlepath",
+ tint: Tint.accent,
+ badge: nil
+ )
+ navRow(
+ section: .orphans,
+ label: "Leftovers",
+ icon: "doc.questionmark",
+ tint: Tint.orange,
+ badge: appState.orphanedFiles.isEmpty ? nil : "\(appState.orphanedFiles.count)"
+ )
+ } header: {
+ sectionLabel("Applications")
+ }
Section {
+ navRow(
+ section: .spaceExplorer,
+ label: "Space Explorer",
+ icon: "square.3.layers.3d.down.right",
+ tint: Tint.accent,
+ badge: nil
+ )
+ navRow(
+ section: .duplicates,
+ label: "Duplicate Finder",
+ icon: "doc.on.doc",
+ tint: Tint.purple,
+ badge: nil
+ )
+ navRow(
+ section: .similarPhotos,
+ label: "Similar Photos",
+ icon: "photo.stack",
+ tint: Tint.pink,
+ badge: nil
+ )
+ DisclosureGroup(isExpanded: $cleanupExpanded) {
+ ForEach(Self.cleanupCategories) { category in
+ navRow(
+ section: .cleaning(category),
+ label: LocalizedStringKey(category.rawValue),
+ icon: category.icon,
+ tint: category.color,
+ badge: sizeBadge(for: category)
+ )
+ }
+ } label: {
+ HStack(spacing: 10) {
+ IconTile(systemName: "trash.slash", tint: Tint.accent, size: 24)
+ Text("Cleanup")
+ .font(.system(size: 12.5, weight: .medium))
+ .foregroundStyle(sidebarLabelColor)
+ }
+ .frame(minHeight: 34)
+ .contentShape(Rectangle())
+ }
+ .tint(.secondary)
+ .listRowInsets(rowInsets)
+ .listRowSeparator(.hidden)
+ .listRowBackground(Color.clear)
DisclosureGroup(isExpanded: $advancedToolsExpanded) {
ForEach(Self.advancedCategories) { category in
- navRow(section: .cleaning(category),
- label: LocalizedStringKey(category.rawValue),
- icon: category.icon,
- tint: category.color,
- secondaryTint: category.color,
- badge: sizeBadge(for: category))
+ navRow(
+ section: .cleaning(category),
+ label: LocalizedStringKey(category.rawValue),
+ icon: category.icon,
+ tint: category.color,
+ badge: sizeBadge(for: category)
+ )
}
} label: {
- HStack(spacing: 9) {
- IconTile(
- systemName: "wrench.and.screwdriver.fill",
- tint: SidebarPalette.advanced,
- size: 24,
- corner: 7
- )
- Text("Advanced Tools")
+ HStack(spacing: 10) {
+ IconTile(systemName: "wrench.and.screwdriver", tint: .secondary, size: 24)
+ Text("Developer Cleanup")
.font(.system(size: 12.5, weight: .medium))
.foregroundStyle(sidebarLabelColor)
}
- .frame(minHeight: 36)
+ .frame(minHeight: 34)
.contentShape(Rectangle())
}
.tint(.secondary)
- .listRowInsets(EdgeInsets(top: 1, leading: 12, bottom: 1, trailing: 12))
+ .listRowInsets(rowInsets)
.listRowSeparator(.hidden)
.listRowBackground(Color.clear)
+ } header: {
+ sectionLabel("Tools")
}
}
.listStyle(.sidebar)
- .environment(\.defaultMinListRowHeight, 36)
+ .environment(\.defaultMinListRowHeight, 35)
.scrollContentBackground(.hidden)
- .background(sidebarBackdrop)
+ .background(sidebarBackground)
.navigationTitle("PureMac")
.onMoveCommand(perform: moveSelection)
.onChange(of: selectedSection) { section in
- guard case let .cleaning(category)? = section,
- Self.advancedCategories.contains(category) else { return }
+ guard case let .cleaning(category)? = section else { return }
withAnimation(reduceMotion ? nil : MotionTokens.gentle) {
- advancedToolsExpanded = true
+ if Self.cleanupCategories.contains(category) {
+ cleanupExpanded = true
+ }
+ if Self.advancedCategories.contains(category) {
+ advancedToolsExpanded = true
+ }
}
}
.safeAreaInset(edge: .bottom) {
@@ -174,17 +231,26 @@ struct MainWindow: View {
}
}
+ private var rowInsets: EdgeInsets {
+ EdgeInsets(top: 1, leading: 12, bottom: 1, trailing: 12)
+ }
+
private func sectionLabel(_ text: LocalizedStringKey) -> some View {
Text(text)
- .font(.system(size: 10.5, weight: .semibold))
- .tracking(0.5)
+ .font(.system(size: 10, weight: .semibold))
+ .tracking(0.7)
.foregroundStyle(.tertiary)
.textCase(.uppercase)
}
- private func navRow(section: AppSection, label: LocalizedStringKey, icon: String,
- tint: Color, secondaryTint: Color, badge: String?,
- isFeatured: Bool = false) -> some View {
+ private func navRow(
+ section: AppSection,
+ label: LocalizedStringKey,
+ icon: String,
+ tint: Color,
+ badge: String?,
+ emphasized: Bool = false
+ ) -> some View {
Button {
selectSection(section)
} label: {
@@ -192,24 +258,36 @@ struct MainWindow: View {
label: label,
icon: icon,
tint: tint,
- secondaryTint: secondaryTint,
badge: badge,
isSelected: selectedSection == section,
- isFeatured: isFeatured
+ emphasized: emphasized
)
}
.buttonStyle(.plain)
.focused($focusedSection, equals: section)
+ .accessibilityLabel(Text(label))
+ .accessibilityIdentifier(accessibilityIdentifier(for: section))
.accessibilityAddTraits(selectedSection == section ? .isSelected : [])
- .listRowInsets(EdgeInsets(top: 1, leading: 12, bottom: 1, trailing: 12))
+ .listRowInsets(rowInsets)
.listRowSeparator(.hidden)
.listRowBackground(Color.clear)
}
private var visibleSections: [AppSection] {
- var sections: [AppSection] = [.cleaning(.smartScan)]
- sections.append(contentsOf: Self.cleanupCategories.map(AppSection.cleaning))
- sections.append(contentsOf: [.apps, .orphans])
+ var sections: [AppSection] = [
+ .cleaning(.smartScan),
+ .protection,
+ .performance,
+ .apps,
+ .appUpdates,
+ .orphans,
+ .spaceExplorer,
+ .duplicates,
+ .similarPhotos
+ ]
+ if cleanupExpanded {
+ sections.append(contentsOf: Self.cleanupCategories.map(AppSection.cleaning))
+ }
if advancedToolsExpanded {
sections.append(contentsOf: Self.advancedCategories.map(AppSection.cleaning))
}
@@ -221,10 +299,23 @@ struct MainWindow: View {
focusedSection = section
}
+ private func accessibilityIdentifier(for section: AppSection) -> String {
+ switch section {
+ case .apps: return "sidebar.uninstaller"
+ case .orphans: return "sidebar.leftovers"
+ case .spaceExplorer: return "sidebar.spaceExplorer"
+ case .duplicates: return "sidebar.duplicates"
+ case .similarPhotos: return "sidebar.similarPhotos"
+ case .protection: return "sidebar.protection"
+ case .performance: return "sidebar.performance"
+ case .appUpdates: return "sidebar.appUpdates"
+ case .cleaning(let category): return "sidebar.cleaning.\(category.id)"
+ }
+ }
+
private func moveSelection(_ direction: MoveCommandDirection) {
let sections = visibleSections
guard !sections.isEmpty else { return }
-
let current = focusedSection ?? selectedSection
let currentIndex = current.flatMap(sections.firstIndex(of:))
let targetIndex: Int
@@ -242,9 +333,8 @@ struct MainWindow: View {
}
private var dashboardBadge: String? {
- appState.totalJunkSize > 0
- ? ByteCountFormatter.string(fromByteCount: appState.totalJunkSize, countStyle: .file)
- : nil
+ guard appState.totalJunkSize > 0 else { return nil }
+ return ByteCountFormatter.string(fromByteCount: appState.totalJunkSize, countStyle: .file)
}
private func sizeBadge(for category: CleaningCategory) -> String? {
@@ -252,96 +342,68 @@ struct MainWindow: View {
return ByteCountFormatter.string(fromByteCount: size, countStyle: .file)
}
- private var sidebarBackdrop: some View {
- ZStack {
- Rectangle()
- .fill(.ultraThinMaterial)
-
- RadialGradient(
- colors: [
- SidebarPalette.smartCarePrimary.opacity(colorScheme == .dark ? 0.16 : 0.08),
- SidebarPalette.smartCareSecondary.opacity(colorScheme == .dark ? 0.06 : 0.025),
- .clear,
- ],
- center: .topLeading,
- startRadius: 0,
- endRadius: 360
- )
-
- LinearGradient(
- colors: [
- Color.white.opacity(colorScheme == .dark ? 0.018 : 0.20),
- Color.clear,
- Color.black.opacity(colorScheme == .dark ? 0.08 : 0.018),
- ],
- startPoint: .top,
- endPoint: .bottom
- )
- }
- .ignoresSafeArea()
+ private var sidebarBackground: some View {
+ Color(nsColor: colorScheme == .dark ? .underPageBackgroundColor : .windowBackgroundColor)
+ .overlay(alignment: .trailing) {
+ Rectangle()
+ .fill(Color.primary.opacity(0.07))
+ .frame(width: 0.5)
+ }
+ .ignoresSafeArea()
}
private var sidebarFooter: some View {
- VStack(spacing: 7) {
- healthFooter
+ VStack(spacing: 8) {
+ permissionStatus
appearanceMenu
}
.padding(.horizontal, 12)
- .padding(.top, 8)
+ .padding(.top, 9)
.padding(.bottom, 10)
- .background(.ultraThinMaterial)
+ .background(.regularMaterial)
.overlay(alignment: .top) {
- Rectangle()
- .fill(Color.white.opacity(colorScheme == .dark ? 0.08 : 0.42))
- .frame(height: 0.5)
+ Divider()
}
}
- private var healthFooter: some View {
- let ok = appState.hasFullDiskAccess
- let tint = ok ? Tint.green : Tint.orange
- return HStack(spacing: 8) {
- PulsingDot(tint: tint, isPulsing: !ok)
- .scaleEffect(0.78)
- .frame(width: 14, height: 14)
+ private var permissionStatus: some View {
+ let granted = appState.hasFullDiskAccess
+ let tint = granted ? Tint.green : Tint.orange
+
+ return HStack(spacing: 9) {
+ Circle()
+ .fill(tint)
+ .frame(width: 7, height: 7)
VStack(alignment: .leading, spacing: 1) {
- Text(LocalizedStringKey(ok ? "Ready to clean" : "Limited access"))
- .font(.system(size: 11, weight: .semibold))
- // Explicit solid color — same vibrancy-collapse guard as the
- // sidebar rows (#117); this title also inherited the default.
+ Text(granted ? "Full access" : "Limited access")
+ .font(.system(size: 11.5, weight: .semibold))
.foregroundStyle(sidebarLabelColor)
- Text(LocalizedStringKey(ok ? "Full Disk Access granted" : "Grant FDA in Settings"))
+ Text(granted ? "Ready for protected locations" : "Some locations are unavailable")
.font(.system(size: 9.5))
.foregroundStyle(.secondary)
.lineLimit(1)
}
- Spacer()
- if !ok {
- Button("Fix") {
+
+ Spacer(minLength: 4)
+
+ if !granted {
+ Button("Set up") {
permission.requestAccess(context: .general) {
appState.checkFullDiskAccess()
}
}
.buttonStyle(.bordered)
- .tint(Tint.orange)
.controlSize(.small)
- .help("Fix permission")
+ .tint(Tint.orange)
}
}
.padding(.horizontal, 10)
- .padding(.vertical, 7)
- .background(
- RoundedRectangle(cornerRadius: 11, style: .continuous)
- .fill(Color.white.opacity(colorScheme == .dark ? 0.055 : 0.44))
- )
- .overlay(
- RoundedRectangle(cornerRadius: 11, style: .continuous)
- .strokeBorder(
- Color.white.opacity(colorScheme == .dark ? 0.10 : 0.62),
- lineWidth: 0.5
- )
- )
+ .padding(.vertical, 8)
+ .background {
+ RoundedRectangle(cornerRadius: 10, style: .continuous)
+ .fill(Color.primary.opacity(0.035))
+ }
}
private var appearanceMenu: some View {
@@ -356,72 +418,49 @@ struct MainWindow: View {
} label: {
HStack(spacing: 8) {
Image(systemName: theme.appearance.icon)
- .font(.system(size: 11.5, weight: .semibold))
- .foregroundStyle(.secondary)
+ .font(.system(size: 11, weight: .medium))
.frame(width: 16)
-
Text("Appearance")
.font(.system(size: 11.5, weight: .medium))
.foregroundStyle(sidebarLabelColor)
-
- Spacer(minLength: 6)
-
+ Spacer()
Text(LocalizedStringKey(theme.appearance.label))
- .font(.system(size: 10.5, weight: .medium))
+ .font(.system(size: 10.5))
.foregroundStyle(.secondary)
-
Image(systemName: "chevron.up.chevron.down")
- .font(.system(size: 8.5, weight: .semibold))
+ .font(.system(size: 8, weight: .semibold))
.foregroundStyle(.tertiary)
}
.frame(minHeight: 26)
.padding(.horizontal, 9)
- .contentShape(RoundedRectangle(cornerRadius: 9, style: .continuous))
+ .contentShape(Rectangle())
}
.buttonStyle(.plain)
.menuStyle(.borderlessButton)
- .help("Change appearance")
.accessibilityLabel("Appearance")
.accessibilityValue(Text(LocalizedStringKey(theme.appearance.label)))
}
private var sidebarLabelColor: Color {
- colorScheme == .dark
- ? Color.white.opacity(0.92)
- : Color.black.opacity(0.85)
+ colorScheme == .dark ? Color.white.opacity(0.90) : Color.black.opacity(0.84)
}
- // MARK: - Detail
-
@ViewBuilder
private var detailContainer: some View {
VStack(spacing: 0) {
if !appState.hasFullDiskAccess && !appState.fdaBannerDismissed {
- fdaToast
- .padding(.horizontal, 16)
- .padding(.top, 12)
- .transition(
- reduceMotion
- ? .opacity
- : .move(edge: .top).combined(with: .opacity)
- )
+ accessBanner
+ .padding(.horizontal, 20)
+ .padding(.top, 14)
+ .transition(reduceMotion ? .opacity : .move(edge: .top).combined(with: .opacity))
}
detailView
.id(selectedSection)
- .transition(
- reduceMotion
- ? .opacity
- : .asymmetric(
- insertion: .opacity.combined(with: .offset(y: 10)),
- removal: .opacity
- )
- )
+ .transition(reduceMotion ? .opacity : .opacity.combined(with: .offset(y: 6)))
}
- .animation(reduceMotion ? nil : .easeOut(duration: 0.22), value: selectedSection)
- .animation(reduceMotion ? nil : .spring(response: 0.4, dampingFraction: 0.8),
- value: appState.fdaBannerDismissed)
- .animation(reduceMotion ? nil : .spring(response: 0.4, dampingFraction: 0.8),
- value: appState.hasFullDiskAccess)
+ .animation(reduceMotion ? nil : .easeOut(duration: 0.18), value: selectedSection)
+ .animation(reduceMotion ? nil : MotionTokens.gentle, value: appState.fdaBannerDismissed)
+ .animation(reduceMotion ? nil : MotionTokens.gentle, value: appState.hasFullDiskAccess)
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(AmbientBackdrop())
}
@@ -433,6 +472,18 @@ struct MainWindow: View {
AppListView()
case .orphans:
OrphanListView()
+ case .spaceExplorer:
+ SpaceExplorerView()
+ case .duplicates:
+ DuplicateFinderView()
+ case .similarPhotos:
+ SimilarPhotosView()
+ case .protection:
+ ProtectionView()
+ case .performance:
+ PerformanceView()
+ case .appUpdates:
+ AppUpdatesView()
case .cleaning(let category):
if category == .smartScan {
DashboardView { selectSection($0) }
@@ -440,31 +491,25 @@ struct MainWindow: View {
CategoryDetailView(category: category)
}
case nil:
- EmptyStateView("PureMac", systemImage: "sparkles",
- description: "Select a category from the sidebar to get started.")
+ EmptyStateView(
+ "PureMac",
+ systemImage: "sparkles",
+ description: "Select a tool from the sidebar."
+ )
}
}
- @ViewBuilder
- private var pulsingLockIcon: some View {
- pulsingLockIconView()
- }
-
- // Quiet FDA bar — single tinted surface, no gradient or glow.
- private var fdaToast: some View {
+ private var accessBanner: some View {
HStack(spacing: 12) {
- IconTile(systemName: "lock.shield.fill", tint: Tint.orange, size: 32, corner: 8)
-
- VStack(alignment: .leading, spacing: 1) {
- Text("Full Disk Access required")
+ IconTile(systemName: "lock.shield", tint: Tint.orange, size: 32, corner: 8)
+ VStack(alignment: .leading, spacing: 2) {
+ Text("Full Disk Access is off")
.font(.system(size: 13, weight: .semibold))
- Text("1-tap setup. We'll auto-retry what failed.")
+ Text("Protected caches and app containers will be skipped.")
.font(.system(size: 11.5))
.foregroundStyle(.secondary)
}
-
Spacer()
-
Button("Set up") {
permission.requestAccess(context: .general) {
appState.checkFullDiskAccess()
@@ -472,7 +517,7 @@ struct MainWindow: View {
}
.buttonStyle(.borderedProminent)
.controlSize(.regular)
-
+ .tint(Tint.accent)
Button {
appState.fdaBannerDismissed = true
} label: {
@@ -480,207 +525,91 @@ struct MainWindow: View {
.font(.system(size: 10, weight: .semibold))
.foregroundStyle(.secondary)
.padding(6)
- .contentShape(Rectangle())
}
.buttonStyle(.plain)
.help("Dismiss")
}
.padding(.horizontal, 14)
.padding(.vertical, 10)
- .background(
+ .background {
RoundedRectangle(cornerRadius: 12, style: .continuous)
- .fill(Tint.orange.opacity(0.08))
- )
- .overlay(
+ .fill(Tint.orange.opacity(0.075))
+ }
+ .overlay {
RoundedRectangle(cornerRadius: 12, style: .continuous)
- .strokeBorder(Tint.orange.opacity(0.22), lineWidth: 0.5)
- )
- }
-}
-
-@ViewBuilder
-private func pulsingLockIconView() -> some View {
- let base = Image(systemName: "lock.shield.fill")
- .font(.system(size: 18, weight: .semibold))
- .foregroundStyle(.white)
- if #available(macOS 14.0, *) {
- base.symbolEffect(.pulse.byLayer, options: .repeating)
- } else {
- base
+ .strokeBorder(Tint.orange.opacity(0.18), lineWidth: 0.5)
+ }
}
}
-/// Premium navigation row with explicit selection, independent of List's
-/// system-blue selection rendering.
private struct SidebarNavRow: View {
let label: LocalizedStringKey
let icon: String
let tint: Color
- let secondaryTint: Color
let badge: String?
let isSelected: Bool
- let isFeatured: Bool
+ let emphasized: Bool
@State private var hovering = false
@Environment(\.accessibilityReduceMotion) private var reduceMotion
@Environment(\.colorScheme) private var colorScheme
var body: some View {
- HStack(spacing: 9) {
+ HStack(spacing: 10) {
IconTile(
systemName: icon,
tint: tint,
size: 24,
corner: 7,
- glow: isFeatured && isSelected,
- vivid: isFeatured
+ glow: isSelected,
+ vivid: emphasized && isSelected
)
- .shadow(
- color: isFeatured ? tint.opacity(isSelected ? 0.52 : 0.28) : .clear,
- radius: isFeatured ? (isSelected ? 9 : 5) : 0
- )
Text(label)
.font(.system(size: 12.5, weight: isSelected ? .semibold : .medium))
- .lineLimit(1)
- // Force an explicit, solid foreground instead of inheriting the
- // sidebar list's default. On some configs (custom accent /
- // reduced transparency, seen on M1 Max — issue #117) the
- // inherited emphasized/vibrant label style resolves transparent
- // and the row text disappears while explicitly-colored text
- // (headers, badges) stays visible. A colorScheme-driven solid
- // color sidesteps that vibrancy path entirely.
.foregroundStyle(labelColor)
- Spacer()
+ .lineLimit(1)
+ Spacer(minLength: 5)
if let badge {
Text(badge)
- .font(.system(size: 9.75, weight: .semibold))
+ .font(.system(size: 9.5, weight: .semibold))
.monospacedDigit()
- .foregroundStyle(isFeatured && isSelected ? tint : .secondary)
+ .foregroundStyle(isSelected ? tint : .secondary)
.padding(.horizontal, 6)
.padding(.vertical, 2)
- .background(
- Capsule()
- .fill(Color.primary.opacity(isSelected ? 0.075 : 0.045))
- )
- .contentTransition(.numericText())
- .fixedSize(horizontal: true, vertical: false)
+ .background(Capsule().fill(Color.primary.opacity(0.05)))
}
}
- .frame(maxWidth: .infinity, minHeight: 36, alignment: .leading)
+ .frame(maxWidth: .infinity, minHeight: 34, alignment: .leading)
.padding(.horizontal, 8)
- .background(rowBackground)
+ .background {
+ RoundedRectangle(cornerRadius: 9, style: .continuous)
+ .fill(rowFill)
+ }
.overlay(alignment: .leading) {
if isSelected {
Capsule()
- .fill(
- LinearGradient(
- colors: [tint, secondaryTint],
- startPoint: .top,
- endPoint: .bottom
- )
- )
- .frame(width: 2.5, height: 20)
- .padding(.leading, 3)
- .shadow(
- color: isFeatured ? tint.opacity(0.55) : .clear,
- radius: isFeatured ? 5 : 0
- )
+ .fill(tint)
+ .frame(width: 2.5, height: 18)
+ .padding(.leading, 2)
}
}
+ .contentShape(RoundedRectangle(cornerRadius: 9, style: .continuous))
.animation(reduceMotion ? nil : MotionTokens.snappy, value: hovering)
.animation(reduceMotion ? nil : MotionTokens.snappy, value: isSelected)
- .contentShape(RoundedRectangle(cornerRadius: 11, style: .continuous))
.onHover { hovering = $0 }
}
- @ViewBuilder
- private var rowBackground: some View {
- let shape = RoundedRectangle(cornerRadius: 11, style: .continuous)
-
+ private var rowFill: Color {
if isSelected {
- shape
- .fill(.thinMaterial)
- .overlay {
- shape.fill(Color.white.opacity(colorScheme == .dark ? 0.045 : 0.24))
- }
- .overlay {
- shape.strokeBorder(
- Color.white.opacity(colorScheme == .dark ? 0.13 : 0.72),
- lineWidth: 0.55
- )
- }
- .shadow(
- color: Color.black.opacity(colorScheme == .dark ? 0.18 : 0.08),
- radius: 5,
- y: 2
- )
- } else {
- shape.fill(
- hovering
- ? Color.primary.opacity(colorScheme == .dark ? 0.045 : 0.032)
- : Color.clear
- )
+ return tint.opacity(colorScheme == .dark ? 0.13 : 0.10)
}
- }
-
- /// Solid, opaque label color that adapts to light/dark without routing
- /// through the sidebar's vibrant primary style (see #117).
- private var labelColor: Color {
- colorScheme == .dark
- ? Color.white.opacity(0.92)
- : Color.black.opacity(0.85)
- }
-}
-
-private enum SidebarPalette {
- static let smartCarePrimary = Tint.purple
- static let smartCareSecondary = Tint.blue
- static let cleanupPrimary = Tint.blue
- static let cleanupSecondary = Tint.cyan
- static let applicationsPrimary = Tint.purple
- static let applicationsSecondary = Tint.pink
- static let advanced = Tint.orange
-}
-
-/// Small reusable status dot with optional pulse. Used in the sidebar health
-/// footer and other "system status" surfaces.
-private struct PulsingDot: View {
- let tint: Color
- var isPulsing: Bool = false
- @State private var pulse = false
- @Environment(\.accessibilityReduceMotion) private var reduceMotion
-
- var body: some View {
- ZStack {
- if isPulsing && !reduceMotion {
- Circle()
- .stroke(tint.opacity(pulse ? 0.0 : 0.6), lineWidth: 2)
- .frame(width: 18, height: 18)
- .scaleEffect(pulse ? 1.6 : 0.8)
- } else {
- Circle()
- .fill(tint.opacity(0.20))
- .frame(width: 16, height: 16)
- }
- Circle()
- .fill(tint)
- .frame(width: 8, height: 8)
- .shadow(color: tint.opacity(0.6), radius: 3)
+ if hovering {
+ return Color.primary.opacity(0.035)
}
- .frame(width: 18, height: 18)
- .onAppear { syncPulse() }
- // The FDA status can flip while the window stays open — onAppear
- // alone latches the first value and never starts/stops the loop.
- .onChange(of: isPulsing) { _ in syncPulse() }
+ return .clear
}
- private func syncPulse() {
- guard isPulsing, !reduceMotion else {
- pulse = false
- return
- }
- withAnimation(.easeOut(duration: 1.4).repeatForever(autoreverses: false)) {
- pulse = true
- }
+ private var labelColor: Color {
+ colorScheme == .dark ? Color.white.opacity(0.91) : Color.black.opacity(0.84)
}
}
diff --git a/PureMac/Views/Orphans/OrphanListView.swift b/PureMac/Views/Orphans/OrphanListView.swift
index 9d33309..82e8292 100644
--- a/PureMac/Views/Orphans/OrphanListView.swift
+++ b/PureMac/Views/Orphans/OrphanListView.swift
@@ -4,6 +4,8 @@ struct OrphanListView: View {
@EnvironmentObject var appState: AppState
@State private var selectedOrphans: Set<URL> = []
@State private var isRemoving = false
+ @State private var showRemovalConfirmation = false
+ @State private var pendingRemoval: Set<URL> = []
@State private var removalErrorMessage: String?
/// Orphan sizes computed off the main thread. Orphans are exactly the large
/// leftovers (multi-GB Caches/Containers/Application Support), and their
@@ -40,7 +42,10 @@ struct OrphanListView: View {
NSPasteboard.general.setString(fileURL.path, forType: .string)
},
onIgnore: { ignoreOrphans([fileURL]) },
- onTrash: { Task { await removeSingleOrphan(fileURL) } }
+ onTrash: {
+ pendingRemoval = [fileURL]
+ showRemovalConfirmation = true
+ }
)
.transition(
reduceMotion
@@ -93,9 +98,8 @@ struct OrphanListView: View {
.disabled(isRemoving)
Button(removeSelectedLabel, role: .destructive) {
- Task {
- await removeSelectedOrphans()
- }
+ pendingRemoval = selectedOrphans
+ showRemovalConfirmation = true
}
.buttonStyle(.borderedProminent)
.tint(.red)
@@ -103,6 +107,16 @@ struct OrphanListView: View {
}
}
}
+ .confirmationDialog("Remove selected leftovers?", isPresented: $showRemovalConfirmation, titleVisibility: .visible) {
+ Button("Remove \(pendingRemoval.count) items", role: .destructive) {
+ let batch = pendingRemoval
+ pendingRemoval = []
+ Task { await removeSelectedOrphans(batch) }
+ }
+ Button("Cancel", role: .cancel) { pendingRemoval = [] }
+ } message: {
+ Text("Files will be moved to the Trash. Items requiring administrator authorization may be permanently deleted. App matching is a best-effort estimate; review files you recognize before removing them.")
+ }
.alert("Some files could not be removed", isPresented: Binding(
get: { removalErrorMessage != nil },
set: { if !$0 { removalErrorMessage = nil } }
@@ -145,11 +159,12 @@ struct OrphanListView: View {
)
}
- private func removeSelectedOrphans() async {
+ private func removeSelectedOrphans(_ batch: Set<URL>) async {
+ guard !isRemoving else { return }
isRemoving = true
defer { isRemoving = false }
- let urlsToRemove = selectedOrphans
+ let urlsToRemove = batch
var failedPaths: [String] = []
var removedURLs: Set<URL> = []
var needsAdminURLs: [URL] = []
@@ -160,7 +175,8 @@ struct OrphanListView: View {
continue
}
- switch removeOrphan(url) {
+ let outcome = await Task.detached(priority: .userInitiated) { Self.removeOrphan(url) }.value
+ switch outcome {
case .removed:
removedURLs.insert(url)
case .needsAdmin:
@@ -171,7 +187,9 @@ struct OrphanListView: View {
}
if !needsAdminURLs.isEmpty {
- if removeWithAdminPrivileges(needsAdminURLs) {
+ let adminURLs = needsAdminURLs
+ let adminSucceeded = await Task.detached(priority: .userInitiated) { Self.removeWithAdminPrivileges(adminURLs) }.value
+ if adminSucceeded {
for url in needsAdminURLs {
if !FileManager.default.fileExists(atPath: url.path) {
removedURLs.insert(url)
@@ -206,15 +224,16 @@ struct OrphanListView: View {
}
}
- private enum OrphanRemoveOutcome {
+ private enum OrphanRemoveOutcome: Sendable {
case removed
case needsAdmin
case failed
}
- private func removeOrphan(_ url: URL) -> OrphanRemoveOutcome {
+ private nonisolated static func removeOrphan(_ url: URL) -> OrphanRemoveOutcome {
+ guard OrphanSafetyPolicy.isSafeCandidate(url) else { return .failed }
do {
- try FileManager.default.removeItem(at: url)
+ try FileManager.default.trashItem(at: url, resultingItemURL: nil)
return .removed
} catch {
let nsError = error as NSError
@@ -252,14 +271,7 @@ struct OrphanListView: View {
}
}
- private func removeSingleOrphan(_ url: URL) async {
- let previous = selectedOrphans
- selectedOrphans = [url]
- await removeSelectedOrphans()
- selectedOrphans = previous.subtracting([url])
- }
-
- private func removeWithAdminPrivileges(_ urls: [URL]) -> Bool {
+ private nonisolated static func removeWithAdminPrivileges(_ urls: [URL]) -> Bool {
guard !urls.isEmpty else { return true }
guard urls.allSatisfy({ OrphanSafetyPolicy.isSafeCandidate($0) }) else { return false }
diff --git a/PureMac/Views/Settings/SettingsView.swift b/PureMac/Views/Settings/SettingsView.swift
index f288168..d27ef93 100644
--- a/PureMac/Views/Settings/SettingsView.swift
+++ b/PureMac/Views/Settings/SettingsView.swift
@@ -235,6 +235,26 @@ struct CleaningSettingsView: View {
Button("Add Folder…") { addExcludedFolder() }
}
+ Section("Cleanup Exclusions") {
+ Text("Excluded paths and folders containing them stay out of manual and scheduled cleanup. Right-click a cleanup result to exclude it.")
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ if appState.excludedCleanupPaths.isEmpty {
+ Text("No excluded paths").foregroundStyle(.secondary)
+ }
+ ForEach(appState.excludedCleanupPaths, id: \.self) { path in
+ HStack {
+ Text((path as NSString).abbreviatingWithTildeInPath)
+ .lineLimit(1)
+ .truncationMode(.middle)
+ .help(path)
+ Spacer()
+ Button("Remove") { appState.removeCleanupExclusion(path) }
+ .disabled(appState.scanState.isActive)
+ }
+ }
+ }
+
Section("Orphan Finder") {
HStack {
// Read the live count directly (it's a UserDefaults-backed
diff --git a/PureMac/Views/Tools/AppUpdatesView.swift b/PureMac/Views/Tools/AppUpdatesView.swift
new file mode 100644
index 0000000..5e71af0
--- /dev/null
+++ b/PureMac/Views/Tools/AppUpdatesView.swift
@@ -0,0 +1,443 @@
+import SwiftUI
+
+enum AppUpdateIdentityMatcher {
+ static func baseToken(_ token: String) -> String {
+ let cask = token.split(separator: "/", omittingEmptySubsequences: true).last.map(String.init) ?? token
+ return cask.split(separator: "@", maxSplits: 1, omittingEmptySubsequences: false).first.map(String.init) ?? cask
+ }
+
+ static func normalizedKey(_ value: String) -> String {
+ value.lowercased().unicodeScalars
+ .filter(CharacterSet.alphanumerics.contains)
+ .map(String.init)
+ .joined()
+ }
+
+ static func matchingIndex(for token: String, appNames: [String]) -> Int? {
+ let key = normalizedKey(baseToken(token))
+ guard !key.isEmpty else { return nil }
+ let matches = appNames.indices.filter { normalizedKey(appNames[$0]) == key }
+ return matches.count == 1 ? matches[0] : nil
+ }
+
+ static func fallbackDisplayName(for token: String) -> String {
+ let words = baseToken(token)
+ .split(whereSeparator: { $0 == "-" || $0 == "_" })
+ .map { $0.prefix(1).uppercased() + $0.dropFirst() }
+ return words.isEmpty ? token : words.joined(separator: " ")
+ }
+
+ static func shouldShowTokenDetail(_ token: String) -> Bool {
+ token.contains("@") || token.contains("/")
+ }
+}
+
+@MainActor
+struct AppUpdatesView: View {
+ @EnvironmentObject private var appState: AppState
+ @StateObject private var updater: ApplicationUpdater
+ @State private var showingUpgradeConfirmation = false
+ @State private var confirmationSelection: [ManagedAppUpdate] = []
+
+ init() {
+ _updater = StateObject(wrappedValue: ApplicationUpdater())
+ }
+
+ init(updater: ApplicationUpdater) {
+ _updater = StateObject(wrappedValue: updater)
+ }
+
+ var body: some View {
+ ZStack {
+ Color(nsColor: .windowBackgroundColor)
+ .ignoresSafeArea()
+
+ ScrollView {
+ VStack(alignment: .leading, spacing: 14) {
+ header
+ sourceCard
+
+ if let status = updater.statusMessage {
+ statusCard(status)
+ }
+
+ content
+ unmanagedAppsCard
+ }
+ .padding(24)
+ .frame(maxWidth: 920, alignment: .leading)
+ .frame(maxWidth: .infinity)
+ }
+ }
+ .navigationTitle("App Updates")
+ .toolbar {
+ ToolbarItem {
+ Button {
+ Task { await updater.checkForUpdates() }
+ } label: {
+ Label(updater.hasChecked ? "Check Again" : "Check for Updates", systemImage: "arrow.clockwise")
+ }
+ .disabled(updater.isBusy || !updater.isHomebrewAvailable)
+ }
+ }
+ .safeAreaInset(edge: .bottom) {
+ if !updater.updates.isEmpty {
+ upgradeBar
+ }
+ }
+ .alert("Upgrade selected apps?", isPresented: $showingUpgradeConfirmation) {
+ Button("Cancel", role: .cancel) {}
+ Button(upgradeConfirmationLabel(count: confirmationSelection.count)) {
+ let selection = confirmationSelection
+ Task { await updater.upgrade(selection) }
+ }
+ } message: {
+ Text(upgradeConfirmationMessage)
+ }
+ .onAppear {
+ updater.refreshAvailability()
+ }
+ }
+
+ private var header: some View {
+ HStack(alignment: .center, spacing: 16) {
+ IconTile(systemName: "arrow.down.app.fill", tint: Tint.accent, size: 48, corner: 13, vivid: true)
+
+ VStack(alignment: .leading, spacing: 4) {
+ Text("App Updates")
+ .font(.system(size: 25, weight: .bold))
+ Text("Review and update apps installed as Homebrew casks.")
+ .font(.callout)
+ .foregroundStyle(.secondary)
+ }
+
+ Spacer()
+
+ if let date = updater.lastCheckedAt {
+ VStack(alignment: .trailing, spacing: 2) {
+ Text("Last checked")
+ .font(.caption)
+ .foregroundStyle(.tertiary)
+ Text(date, style: .relative)
+ .font(.caption.weight(.medium))
+ .foregroundStyle(.secondary)
+ }
+ }
+ }
+ }
+
+ private var sourceCard: some View {
+ CardSurface(padding: 16, elevation: .flat, tint: Tint.accent) {
+ HStack(alignment: .top, spacing: 12) {
+ IconTile(systemName: "shippingbox.fill", tint: Tint.accent, size: 32, corner: 9)
+ VStack(alignment: .leading, spacing: 4) {
+ Text("Updates from Homebrew")
+ .font(.system(size: 14, weight: .semibold))
+ Text("Checking asks Homebrew to refresh its package data as needed and contacts Homebrew's configured sources. PureMac only lists cask apps managed by this Homebrew installation.")
+ .font(.callout)
+ .foregroundStyle(.secondary)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ }
+ }
+ }
+
+ @ViewBuilder
+ private var content: some View {
+ if !updater.isHomebrewAvailable {
+ stateCard(
+ title: "Homebrew not found",
+ message: "Install Homebrew to check cask apps here. Apps from the App Store and direct downloads use their own update channels.",
+ systemImage: "shippingbox",
+ tint: Tint.orange
+ )
+ } else if updater.isChecking {
+ CardSurface(padding: 28, elevation: .standard) {
+ HStack(spacing: 14) {
+ ProgressView()
+ .controlSize(.small)
+ VStack(alignment: .leading, spacing: 3) {
+ Text("Checking Homebrew casks")
+ .font(.headline)
+ Text("Refreshing package data and comparing installed versions.")
+ .font(.callout)
+ .foregroundStyle(.secondary)
+ }
+ Spacer()
+ }
+ }
+ } else if let error = updater.errorMessage {
+ CardSurface(padding: 22, elevation: .standard, tint: Tint.red) {
+ HStack(alignment: .top, spacing: 14) {
+ IconTile(systemName: "exclamationmark.triangle.fill", tint: Tint.red, size: 36, corner: 10)
+ VStack(alignment: .leading, spacing: 7) {
+ Text("Couldn't check for updates")
+ .font(.headline)
+ Text(error)
+ .font(.callout)
+ .foregroundStyle(.secondary)
+ .textSelection(.enabled)
+ Button("Try Again") {
+ Task { await updater.checkForUpdates() }
+ }
+ .buttonStyle(.bordered)
+ .disabled(updater.isBusy)
+ }
+ Spacer()
+ }
+ }
+ } else if updater.hasChecked && updater.updates.isEmpty {
+ stateCard(
+ title: "Homebrew apps are up to date",
+ message: "No updates are currently available for the cask apps Homebrew manages.",
+ systemImage: "checkmark.circle.fill",
+ tint: Tint.green
+ )
+ } else if updater.updates.isEmpty {
+ CardSurface(padding: 28, elevation: .standard) {
+ VStack(spacing: 14) {
+ IconTile(systemName: "arrow.triangle.2.circlepath", tint: Tint.accent, size: 48, corner: 13)
+ Text("Check installed cask apps")
+ .font(.title3.weight(.semibold))
+ Text("PureMac will ask Homebrew for available versions when you start the check.")
+ .font(.callout)
+ .foregroundStyle(.secondary)
+ .multilineTextAlignment(.center)
+ Button("Check for Updates") {
+ Task { await updater.checkForUpdates() }
+ }
+ .buttonStyle(.borderedProminent)
+ .tint(Tint.accent)
+ }
+ .frame(maxWidth: .infinity)
+ .padding(.vertical, 12)
+ }
+ } else {
+ updatesCard
+ }
+ }
+
+ private var updatesCard: some View {
+ CardSurface(padding: 0, elevation: .standard) {
+ VStack(spacing: 0) {
+ HStack {
+ VStack(alignment: .leading, spacing: 2) {
+ Text(updateCountTitle)
+ .font(.headline)
+ Text("Select the apps Homebrew should upgrade.")
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ }
+ Spacer()
+ }
+ .padding(16)
+
+ Divider()
+
+ LazyVStack(spacing: 0) {
+ ForEach(Array(updater.updates.enumerated()), id: \.element.id) { index, update in
+ updateRow(update)
+ if index < updater.updates.count - 1 {
+ Divider()
+ .padding(.leading, 56)
+ }
+ }
+ }
+ }
+ }
+ }
+
+ private func updateRow(_ update: ManagedAppUpdate) -> some View {
+ let app = installedApp(for: update.token)
+ let presentation = updater.caskPresentations[update.token]
+ let displayName = app?.appName
+ ?? presentation?.displayName
+ ?? AppUpdateIdentityMatcher.fallbackDisplayName(for: update.token)
+
+ return HStack(spacing: 12) {
+ Toggle("", isOn: Binding(
+ get: { updater.selectedTokens.contains(update.token) },
+ set: { updater.setSelected($0, token: update.token) }
+ ))
+ .labelsHidden()
+ .toggleStyle(AnimatedCheckboxStyle(tint: Tint.accent))
+ .disabled(update.isPinned || updater.isBusy)
+ .accessibilityLabel("Select \(displayName)")
+
+ appIcon(app?.icon ?? presentation?.icon, isPinned: update.isPinned)
+
+ VStack(alignment: .leading, spacing: 3) {
+ HStack(spacing: 7) {
+ Text(displayName)
+ .font(.system(size: 14, weight: .semibold))
+ .lineLimit(1)
+ if update.isPinned {
+ StatusChip(label: "Pinned", systemImage: "pin.fill", tint: Tint.orange)
+ }
+ }
+ Text(updateDetail(update))
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ .lineLimit(1)
+ if presentation?.isBundleMissing == true {
+ Text("App bundle missing")
+ .font(.caption2.weight(.medium))
+ .foregroundStyle(Tint.orange)
+ }
+ }
+
+ Spacer(minLength: 18)
+
+ VStack(alignment: .trailing, spacing: 3) {
+ Text("Available")
+ .font(.caption2)
+ .foregroundStyle(.tertiary)
+ Text(update.currentVersion)
+ .font(.system(.callout, design: .monospaced, weight: .medium))
+ .lineLimit(1)
+ }
+ }
+ .padding(.horizontal, 16)
+ .padding(.vertical, 12)
+ .contentShape(Rectangle())
+ }
+
+ @ViewBuilder
+ private func appIcon(_ icon: NSImage?, isPinned: Bool) -> some View {
+ if let icon {
+ Image(nsImage: icon)
+ .resizable()
+ .scaledToFit()
+ .frame(width: 32, height: 32)
+ .accessibilityHidden(true)
+ } else {
+ IconTile(systemName: "app.fill", tint: isPinned ? Tint.orange : Tint.accent, size: 32, corner: 8)
+ }
+ }
+
+ private func installedApp(for token: String) -> InstalledApp? {
+ let names = appState.installedApps.map(\.appName)
+ guard let index = AppUpdateIdentityMatcher.matchingIndex(for: token, appNames: names) else { return nil }
+ return appState.installedApps[index]
+ }
+
+ private func displayName(for token: String) -> String {
+ installedApp(for: token)?.appName
+ ?? updater.caskPresentations[token]?.displayName
+ ?? AppUpdateIdentityMatcher.fallbackDisplayName(for: token)
+ }
+
+ private func updateDetail(_ update: ManagedAppUpdate) -> String {
+ let installed = "Installed \(update.installedVersion)"
+ guard AppUpdateIdentityMatcher.shouldShowTokenDetail(update.token) else { return installed }
+ return "\(update.token) · \(installed)"
+ }
+
+ private var unmanagedAppsCard: some View {
+ CardSurface(padding: 16, elevation: .flat) {
+ HStack(spacing: 12) {
+ IconTile(systemName: "storefront.fill", tint: Tint.blue, size: 32, corner: 9)
+ VStack(alignment: .leading, spacing: 3) {
+ Text("Apps outside Homebrew")
+ .font(.system(size: 14, weight: .semibold))
+ Text("Open the App Store updates page. Direct-download apps may provide their own updater.")
+ .font(.callout)
+ .foregroundStyle(.secondary)
+ }
+ Spacer()
+ Button("Open App Store Updates") {
+ updater.openAppStoreUpdates()
+ }
+ .buttonStyle(.bordered)
+ }
+ }
+ }
+
+ private func stateCard(title: String, message: String, systemImage: String, tint: Color) -> some View {
+ CardSurface(padding: 28, elevation: .standard, tint: tint) {
+ VStack(spacing: 12) {
+ IconTile(systemName: systemImage, tint: tint, size: 48, corner: 13)
+ Text(title)
+ .font(.title3.weight(.semibold))
+ Text(message)
+ .font(.callout)
+ .foregroundStyle(.secondary)
+ .multilineTextAlignment(.center)
+ .frame(maxWidth: 520)
+ }
+ .frame(maxWidth: .infinity)
+ .padding(.vertical, 12)
+ }
+ }
+
+ private func statusCard(_ status: String) -> some View {
+ CardSurface(padding: 14, elevation: .flat, tint: Tint.green) {
+ HStack(spacing: 10) {
+ Image(systemName: "checkmark.circle.fill")
+ .foregroundStyle(Tint.green)
+ Text(status)
+ .font(.callout.weight(.medium))
+ Spacer()
+ }
+ }
+ }
+
+ private var upgradeBar: some View {
+ HStack {
+ Text(updater.selectedCount == 0 ? "Select apps to update" : selectedCountTitle)
+ .font(.callout.weight(.medium))
+ .foregroundStyle(updater.selectedCount == 0 ? Color.secondary : Color.primary)
+ Spacer()
+ Button {
+ confirmationSelection = updater.updates.filter {
+ updater.selectedTokens.contains($0.token) && !$0.isPinned
+ }
+ showingUpgradeConfirmation = true
+ } label: {
+ if updater.isUpgrading {
+ HStack(spacing: 8) {
+ ProgressView()
+ .controlSize(.small)
+ Text("Updating…")
+ }
+ } else {
+ Text(upgradeConfirmationLabel(count: updater.selectedCount))
+ }
+ }
+ .buttonStyle(.borderedProminent)
+ .tint(Tint.accent)
+ .disabled(updater.selectedCount == 0 || updater.isBusy)
+ }
+ .padding(.horizontal, 24)
+ .padding(.vertical, 12)
+ .background(.regularMaterial)
+ .overlay(alignment: .top) {
+ Divider()
+ }
+ }
+
+ private var updateCountTitle: String {
+ updater.updates.count == 1 ? "1 update available" : "\(updater.updates.count) updates available"
+ }
+
+ private var selectedCountTitle: String {
+ updater.selectedCount == 1 ? "1 app selected" : "\(updater.selectedCount) apps selected"
+ }
+
+ private func upgradeConfirmationLabel(count: Int) -> String {
+ count == 1 ? "Upgrade 1 App" : "Upgrade \(count) Apps"
+ }
+
+ private var upgradeConfirmationMessage: String {
+ let versions = confirmationSelection.map {
+ "\(displayName(for: $0.token)) \($0.installedVersion) to \($0.currentVersion)"
+ }
+ let selectionSummary: String
+ if versions.count <= 5 {
+ selectionSummary = versions.joined(separator: ", ")
+ } else {
+ selectionSummary = versions.prefix(5).joined(separator: ", ") + ", and \(versions.count - 5) more"
+ }
+ return "Homebrew will upgrade \(selectionSummary). It may quit running apps and remove superseded cask versions as part of its normal upgrade process."
+ }
+}
diff --git a/PureMac/Views/Tools/DuplicateFinderView.swift b/PureMac/Views/Tools/DuplicateFinderView.swift
new file mode 100644
index 0000000..ab2b76c
--- /dev/null
+++ b/PureMac/Views/Tools/DuplicateFinderView.swift
@@ -0,0 +1,711 @@
+import AppKit
+import SwiftUI
+
+struct DuplicateFinderView: View {
+ private enum ScreenState: Equatable {
+ case idle
+ case scanning
+ case finished
+ case failed(String)
+ }
+
+ private let finder: DuplicateFinder
+ @State private var state: ScreenState = .idle
+ @State private var result: DuplicateScanResult?
+ @State private var selectedFolder: URL?
+ @State private var progress = DuplicateScanProgress(
+ phase: .discovering,
+ filesInspected: 0,
+ filesToHash: 0,
+ filesHashed: 0,
+ bytesHashed: 0,
+ currentURL: nil
+ )
+ @State private var selectedIDs: Set<URL> = []
+ @State private var expandedGroupIDs: Set<String> = []
+ @State private var scanGeneration = UUID()
+ @State private var scanTask: Task<Void, Never>?
+ @State private var trashTask: Task<Void, Never>?
+ @State private var isMovingToTrash = false
+ @State private var showsTrashConfirmation = false
+ @State private var actionMessage: ActionMessage?
+
+ init(finder: DuplicateFinder = DuplicateFinder()) {
+ self.finder = finder
+ }
+
+ var body: some View {
+ ZStack {
+ Color(nsColor: .windowBackgroundColor)
+ .ignoresSafeArea()
+ VStack(spacing: 14) {
+ header
+ content
+ if result?.groups.isEmpty == false {
+ selectionBar
+ }
+ }
+ .padding(24)
+ }
+ .confirmationDialog(
+ "Move selected duplicates to Trash?",
+ isPresented: $showsTrashConfirmation,
+ titleVisibility: .visible
+ ) {
+ Button("Move to Trash", role: .destructive) {
+ moveSelectedToTrash()
+ }
+ Button("Cancel", role: .cancel) {}
+ } message: {
+ Text("\(selectedIDs.count) files totaling \(format(selectedSize)) will be moved to Trash. The protected copy in every group stays in place.")
+ }
+ .alert(item: $actionMessage) { message in
+ Alert(
+ title: Text(message.title),
+ message: Text(message.detail),
+ dismissButton: .default(Text("OK"))
+ )
+ }
+ .onDisappear {
+ scanGeneration = UUID()
+ scanTask?.cancel()
+ trashTask?.cancel()
+ }
+ }
+
+ private var header: some View {
+ CardSurface(padding: 18, elevation: .flat, tint: Tint.accent) {
+ HStack(spacing: 14) {
+ IconTile(systemName: "square.on.square", tint: Tint.accent, size: 42, corner: 11)
+ VStack(alignment: .leading, spacing: 4) {
+ Text("Duplicate Finder")
+ .font(.system(size: 22, weight: .bold, design: .rounded))
+ Text(headerSubtitle)
+ .font(.callout)
+ .foregroundStyle(.secondary)
+ .lineLimit(1)
+ .truncationMode(.middle)
+ }
+ Spacer(minLength: 16)
+ if state == .scanning {
+ Button("Cancel", role: .cancel) {
+ scanTask?.cancel()
+ }
+ .buttonStyle(.bordered)
+ .keyboardShortcut(.cancelAction)
+ .accessibilityHint("Stops scanning without changing any files")
+ } else {
+ Button {
+ chooseFolder()
+ } label: {
+ Label(result == nil ? "Choose Folder" : "Scan Another Folder", systemImage: "folder.badge.plus")
+ }
+ .buttonStyle(.borderedProminent)
+ .tint(Tint.accent)
+ .disabled(isMovingToTrash)
+ .accessibilityHint("Opens a folder picker")
+ }
+ }
+ }
+ }
+
+ @ViewBuilder
+ private var content: some View {
+ switch state {
+ case .idle:
+ idleState
+ case .scanning:
+ scanningState
+ case .failed(let message):
+ failureState(message)
+ case .finished:
+ if let result, result.groups.isEmpty {
+ emptyResult(result)
+ } else if let result {
+ resultContent(result)
+ } else {
+ idleState
+ }
+ }
+ }
+
+ private var idleState: some View {
+ CardSurface(padding: 0, elevation: .flat) {
+ VStack(spacing: 15) {
+ Spacer()
+ ZStack {
+ RoundedRectangle(cornerRadius: 24, style: .continuous)
+ .fill(Tint.accent.opacity(0.09))
+ .frame(width: 116, height: 100)
+ Image(systemName: "doc.on.doc")
+ .font(.system(size: 44, weight: .light))
+ .symbolRenderingMode(.hierarchical)
+ .foregroundStyle(Tint.accent)
+ }
+ Text("Find copies that are exactly the same")
+ .font(.system(size: 18, weight: .semibold))
+ Text("Choose a folder. PureMac compares file sizes first, then verifies matching files byte for byte. Nothing is selected or removed automatically.")
+ .font(.callout)
+ .foregroundStyle(.secondary)
+ .multilineTextAlignment(.center)
+ .frame(maxWidth: 480)
+ Button {
+ chooseFolder()
+ } label: {
+ Label("Choose a Folder", systemImage: "folder")
+ }
+ .buttonStyle(.borderedProminent)
+ .tint(Tint.accent)
+ .controlSize(.large)
+ .disabled(isMovingToTrash)
+ .padding(.top, 3)
+ Spacer()
+ }
+ .padding(24)
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ }
+ }
+
+ private var scanningState: some View {
+ CardSurface(padding: 28, elevation: .flat, tint: Tint.accent) {
+ VStack(spacing: 20) {
+ Spacer()
+ ZStack {
+ Circle()
+ .stroke(Tint.accent.opacity(0.14), lineWidth: 9)
+ .frame(width: 104, height: 104)
+ if let fraction = progress.fractionCompleted {
+ Circle()
+ .trim(from: 0, to: fraction)
+ .stroke(Tint.accent, style: StrokeStyle(lineWidth: 9, lineCap: .round))
+ .rotationEffect(.degrees(-90))
+ .frame(width: 104, height: 104)
+ } else {
+ ProgressView()
+ .controlSize(.large)
+ .tint(Tint.accent)
+ }
+ Image(systemName: progress.phase == .discovering ? "folder" : "number")
+ .font(.system(size: 25, weight: .medium))
+ .foregroundStyle(Tint.accent)
+ }
+ VStack(spacing: 7) {
+ Text(progress.phase == .discovering ? "Looking through files" : "Verifying possible matches")
+ .font(.system(size: 18, weight: .semibold))
+ Text(progressSummary)
+ .font(.callout.monospacedDigit())
+ .foregroundStyle(.secondary)
+ if let currentURL = progress.currentURL {
+ Text(currentURL.path)
+ .font(.caption)
+ .foregroundStyle(.tertiary)
+ .lineLimit(1)
+ .truncationMode(.middle)
+ .frame(maxWidth: 520)
+ }
+ }
+ Spacer()
+ }
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ .accessibilityElement(children: .combine)
+ .accessibilityLabel(progressSummary)
+ }
+ }
+
+ private func failureState(_ message: String) -> some View {
+ CardSurface(padding: 0, elevation: .flat, tint: Tint.red) {
+ VStack(spacing: 14) {
+ Spacer()
+ IconTile(systemName: "exclamationmark.triangle.fill", tint: Tint.red, size: 54, corner: 14)
+ Text("Scan could not finish")
+ .font(.system(size: 18, weight: .semibold))
+ Text(message)
+ .font(.callout)
+ .foregroundStyle(.secondary)
+ .multilineTextAlignment(.center)
+ .frame(maxWidth: 480)
+ HStack {
+ if let folder = selectedFolder {
+ Button("Try Again") { startScan(folder) }
+ .buttonStyle(.borderedProminent)
+ .tint(Tint.accent)
+ .disabled(isMovingToTrash)
+ }
+ Button("Choose Another Folder") { chooseFolder() }
+ .buttonStyle(.bordered)
+ .disabled(isMovingToTrash)
+ }
+ Spacer()
+ }
+ .padding(24)
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ }
+ }
+
+ private func emptyResult(_ result: DuplicateScanResult) -> some View {
+ CardSurface(padding: 0, elevation: .flat, tint: Tint.green) {
+ VStack(spacing: 14) {
+ Spacer()
+ IconTile(systemName: "checkmark.seal.fill", tint: Tint.green, size: 58, corner: 16)
+ Text("No exact duplicates found")
+ .font(.system(size: 19, weight: .semibold))
+ Text("Inspected \(result.filesInspected.formatted()) files in \(result.folder.lastPathComponent). \(skippedSummary(result.skippedFiles))")
+ .font(.callout)
+ .foregroundStyle(.secondary)
+ .multilineTextAlignment(.center)
+ .frame(maxWidth: 500)
+ Button("Scan Again") { startScan(result.folder) }
+ .buttonStyle(.bordered)
+ .disabled(isMovingToTrash)
+ Spacer()
+ }
+ .padding(24)
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ }
+ }
+
+ private func resultContent(_ result: DuplicateScanResult) -> some View {
+ VStack(spacing: 14) {
+ summaryCard(result)
+ ScrollView {
+ LazyVStack(spacing: 14) {
+ ForEach(result.groups) { group in
+ groupCard(group)
+ }
+ if !result.skippedFiles.isEmpty {
+ skippedCard(result.skippedFiles)
+ }
+ }
+ .padding(.vertical, 1)
+ }
+ }
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ }
+
+ private func summaryCard(_ result: DuplicateScanResult) -> some View {
+ CardSurface(padding: 14, elevation: .flat) {
+ HStack(spacing: 0) {
+ summaryMetric(value: result.groups.count.formatted(), label: "Duplicate groups", icon: "square.stack.3d.up", tint: Tint.accent)
+ Divider().frame(height: 38)
+ summaryMetric(value: result.duplicateFileCount.formatted(), label: "Matching files", icon: "doc.on.doc", tint: Tint.purple)
+ Divider().frame(height: 38)
+ summaryMetric(value: format(result.reclaimableSize), label: "Available to review", icon: "internaldrive", tint: Tint.green)
+ Spacer(minLength: 10)
+ Button("Rescan") { startScan(result.folder) }
+ .buttonStyle(.bordered)
+ .disabled(isMovingToTrash)
+ }
+ }
+ }
+
+ private func summaryMetric(value: String, label: String, icon: String, tint: Color) -> some View {
+ HStack(spacing: 9) {
+ IconTile(systemName: icon, tint: tint, size: 30, corner: 8)
+ VStack(alignment: .leading, spacing: 1) {
+ Text(value)
+ .font(.system(size: 15, weight: .semibold).monospacedDigit())
+ Text(label)
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ }
+ }
+ .padding(.horizontal, 14)
+ .accessibilityElement(children: .combine)
+ }
+
+ private func groupCard(_ group: DuplicateGroup) -> some View {
+ CardSurface(padding: 0, elevation: .flat, tint: Tint.accent) {
+ VStack(spacing: 0) {
+ HStack(spacing: 12) {
+ IconTile(systemName: "doc.on.doc.fill", tint: Tint.accent, size: 34, corner: 9)
+ VStack(alignment: .leading, spacing: 2) {
+ Text(group.keeper.url.lastPathComponent)
+ .font(.system(size: 14, weight: .semibold))
+ .lineLimit(1)
+ Text("\(group.files.count) exact copies · \(format(group.fileSize)) each")
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ }
+ Spacer()
+ StatusChip(label: "\(format(group.reclaimableSize)) reviewable", systemImage: "arrow.down.circle", tint: Tint.green)
+ Button(groupCandidatesSelected(group) ? "Clear" : "Select copies") {
+ toggleGroupSelection(group)
+ }
+ .buttonStyle(.bordered)
+ .disabled(isMovingToTrash)
+ Button {
+ toggleExpanded(group)
+ } label: {
+ Image(systemName: expandedGroupIDs.contains(group.id) ? "chevron.up" : "chevron.down")
+ .frame(width: 16, height: 16)
+ }
+ .buttonStyle(.plain)
+ .accessibilityLabel(expandedGroupIDs.contains(group.id) ? "Collapse duplicate group" : "Expand duplicate group")
+ }
+ .padding(14)
+
+ if expandedGroupIDs.contains(group.id) {
+ Divider()
+ VStack(spacing: 0) {
+ ForEach(Array(group.files.enumerated()), id: \.element.id) { index, file in
+ fileRow(file, keeper: index == 0)
+ if index < group.files.count - 1 {
+ Divider().padding(.leading, 49)
+ }
+ }
+ }
+ .transition(.opacity.combined(with: .move(edge: .top)))
+ }
+ }
+ }
+ }
+
+ private func fileRow(_ file: DuplicateFile, keeper: Bool) -> some View {
+ HStack(spacing: 11) {
+ if keeper {
+ Image(systemName: "checkmark.shield.fill")
+ .font(.system(size: 16, weight: .semibold))
+ .foregroundStyle(Tint.green)
+ .frame(width: 18)
+ .accessibilityLabel("Protected copy")
+ } else {
+ Toggle("", isOn: selectionBinding(for: file.url))
+ .labelsHidden()
+ .toggleStyle(AnimatedCheckboxStyle(tint: Tint.accent))
+ .disabled(isMovingToTrash)
+ .accessibilityLabel("Select \(file.url.lastPathComponent)")
+ }
+ Image(nsImage: NSWorkspace.shared.icon(forFile: file.url.path))
+ .resizable()
+ .interpolation(.high)
+ .frame(width: 24, height: 24)
+ .accessibilityHidden(true)
+ VStack(alignment: .leading, spacing: 2) {
+ HStack(spacing: 7) {
+ Text(file.url.lastPathComponent)
+ .font(.system(size: 13, weight: keeper ? .semibold : .regular))
+ .lineLimit(1)
+ if keeper {
+ StatusChip(label: "Keep", systemImage: "lock.fill", tint: Tint.green)
+ }
+ }
+ Text(file.url.deletingLastPathComponent().path)
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ .lineLimit(1)
+ .truncationMode(.middle)
+ }
+ Spacer()
+ if let modifiedAt = file.modifiedAt {
+ Text(modifiedAt, style: .date)
+ .font(.caption)
+ .foregroundStyle(.tertiary)
+ }
+ Button {
+ NSWorkspace.shared.activateFileViewerSelecting([file.url])
+ } label: {
+ Image(systemName: "arrow.forward.square")
+ .frame(width: 18, height: 18)
+ }
+ .buttonStyle(.plain)
+ .accessibilityLabel("Reveal \(file.url.lastPathComponent) in Finder")
+ .help("Reveal in Finder")
+ }
+ .padding(.horizontal, 14)
+ .padding(.vertical, 10)
+ .contentShape(Rectangle())
+ .accessibilityElement(children: .contain)
+ }
+
+ private func skippedCard(_ skippedFiles: [DuplicateSkippedFile]) -> some View {
+ CardSurface(padding: 14, elevation: .flat, tint: Tint.orange) {
+ DisclosureGroup {
+ VStack(spacing: 8) {
+ ForEach(skippedFiles) { file in
+ HStack(spacing: 10) {
+ Image(systemName: "exclamationmark.circle")
+ .foregroundStyle(Tint.orange)
+ .frame(width: 16)
+ VStack(alignment: .leading, spacing: 2) {
+ Text(file.url.path)
+ .font(.caption)
+ .lineLimit(1)
+ .truncationMode(.middle)
+ Text(file.detail.map { "\(file.reason.label): \($0)" } ?? file.reason.label)
+ .font(.caption2)
+ .foregroundStyle(.secondary)
+ }
+ Spacer()
+ Button {
+ NSWorkspace.shared.activateFileViewerSelecting([file.url])
+ } label: {
+ Image(systemName: "arrow.forward.square")
+ }
+ .buttonStyle(.plain)
+ .accessibilityLabel("Reveal skipped item in Finder")
+ }
+ }
+ }
+ .padding(.top, 10)
+ } label: {
+ HStack {
+ IconTile(systemName: "exclamationmark.triangle", tint: Tint.orange, size: 30, corner: 8)
+ VStack(alignment: .leading, spacing: 1) {
+ Text("Skipped items")
+ .font(.system(size: 14, weight: .semibold))
+ Text("\(skippedFiles.count) unsafe or unavailable items were not scanned")
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ }
+ }
+ }
+ }
+ }
+
+ private var selectionBar: some View {
+ CardSurface(padding: 14, elevation: .raised, tint: selectedIDs.isEmpty ? nil : Tint.accent) {
+ HStack(spacing: 12) {
+ VStack(alignment: .leading, spacing: 2) {
+ Text(selectedIDs.isEmpty ? "Nothing selected" : "\(selectedIDs.count) selected")
+ .font(.system(size: 14, weight: .semibold).monospacedDigit())
+ Text(selectedIDs.isEmpty ? "Select the extra copies you want to review" : "\(format(selectedSize)) will move to Trash")
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ }
+ Spacer()
+ if !selectedIDs.isEmpty {
+ Button("Clear Selection") { selectedIDs.removeAll() }
+ .buttonStyle(.borderless)
+ .disabled(isMovingToTrash)
+ }
+ Button {
+ showsTrashConfirmation = true
+ } label: {
+ if isMovingToTrash {
+ ProgressView()
+ .controlSize(.small)
+ .frame(minWidth: 100)
+ } else {
+ Label("Move to Trash", systemImage: "trash")
+ }
+ }
+ .buttonStyle(.borderedProminent)
+ .tint(Tint.red)
+ .disabled(selectedIDs.isEmpty || isMovingToTrash || state == .scanning)
+ .accessibilityHint("Shows a confirmation before moving the selected copies")
+ }
+ }
+ }
+
+ private var headerSubtitle: String {
+ if state == .scanning, let current = progress.currentURL {
+ return current.deletingLastPathComponent().path
+ }
+ return selectedFolder?.path ?? "Exact-match cleanup with a protected copy in every group"
+ }
+
+ private var progressSummary: String {
+ switch progress.phase {
+ case .discovering:
+ return "\(progress.filesInspected.formatted()) files inspected"
+ case .hashing:
+ return "\(progress.filesHashed.formatted()) of \(progress.filesToHash.formatted()) candidates · \(format(progress.bytesHashed)) verified"
+ }
+ }
+
+ private var selectedSize: Int64 {
+ guard let result else { return 0 }
+ return result.groups
+ .flatMap(\.files)
+ .filter { selectedIDs.contains($0.url) }
+ .reduce(0) { $0 + $1.size }
+ }
+
+ private func selectionBinding(for url: URL) -> Binding<Bool> {
+ Binding(
+ get: { selectedIDs.contains(url) },
+ set: { selected in
+ if selected {
+ selectedIDs.insert(url)
+ } else {
+ selectedIDs.remove(url)
+ }
+ }
+ )
+ }
+
+ private func groupCandidatesSelected(_ group: DuplicateGroup) -> Bool {
+ group.files.dropFirst().allSatisfy { selectedIDs.contains($0.url) }
+ }
+
+ private func toggleGroupSelection(_ group: DuplicateGroup) {
+ let candidateIDs = Set(group.files.dropFirst().map(\.url))
+ if candidateIDs.isSubset(of: selectedIDs) {
+ selectedIDs.subtract(candidateIDs)
+ } else {
+ selectedIDs.formUnion(candidateIDs)
+ }
+ }
+
+ private func toggleExpanded(_ group: DuplicateGroup) {
+ withAnimation(MotionTokens.gentle) {
+ if expandedGroupIDs.contains(group.id) {
+ expandedGroupIDs.remove(group.id)
+ } else {
+ expandedGroupIDs.insert(group.id)
+ }
+ }
+ }
+
+ private func chooseFolder() {
+ guard !isMovingToTrash else { return }
+ let panel = NSOpenPanel()
+ panel.title = "Choose a folder to check for duplicate files"
+ panel.prompt = "Scan Folder"
+ panel.message = "PureMac reads the selected folder and does not change anything during a scan."
+ panel.canChooseFiles = false
+ panel.canChooseDirectories = true
+ panel.allowsMultipleSelection = false
+ panel.canCreateDirectories = false
+ panel.resolvesAliases = false
+ panel.treatsFilePackagesAsDirectories = false
+ if panel.runModal() == .OK, let folder = panel.url {
+ startScan(folder)
+ }
+ }
+
+ private func startScan(_ folder: URL) {
+ guard !isMovingToTrash else { return }
+ scanTask?.cancel()
+ let generation = UUID()
+ scanGeneration = generation
+ selectedFolder = folder
+ selectedIDs.removeAll()
+ expandedGroupIDs.removeAll()
+ result = nil
+ progress = DuplicateScanProgress(
+ phase: .discovering,
+ filesInspected: 0,
+ filesToHash: 0,
+ filesHashed: 0,
+ bytesHashed: 0,
+ currentURL: folder
+ )
+ state = .scanning
+ scanTask = Task { @MainActor in
+ let usesScopedAccess = folder.startAccessingSecurityScopedResource()
+ defer {
+ if usesScopedAccess {
+ folder.stopAccessingSecurityScopedResource()
+ }
+ }
+ do {
+ let scanResult = try await finder.scan(folder: folder) { update in
+ await MainActor.run {
+ guard scanGeneration == generation else { return }
+ progress = update
+ }
+ }
+ try Task.checkCancellation()
+ guard scanGeneration == generation else { return }
+ result = scanResult
+ expandedGroupIDs = Set(scanResult.groups.prefix(3).map(\.id))
+ state = .finished
+ } catch is CancellationError {
+ guard scanGeneration == generation else { return }
+ state = .idle
+ } catch {
+ guard scanGeneration == generation else { return }
+ state = .failed(error.localizedDescription)
+ }
+ if scanGeneration == generation {
+ scanTask = nil
+ }
+ }
+ }
+
+ private func moveSelectedToTrash() {
+ guard let currentResult = result, !selectedIDs.isEmpty else { return }
+ let generation = scanGeneration
+ let folder = currentResult.folder
+ let selectionSnapshot = selectedIDs
+ isMovingToTrash = true
+ trashTask = Task { @MainActor in
+ let usesScopedAccess = currentResult.folder.startAccessingSecurityScopedResource()
+ defer {
+ if usesScopedAccess {
+ currentResult.folder.stopAccessingSecurityScopedResource()
+ }
+ if scanGeneration == generation {
+ isMovingToTrash = false
+ trashTask = nil
+ }
+ }
+ var movedFiles: [DuplicateFile] = []
+ var failures: [String] = []
+ for group in currentResult.groups {
+ if Task.isCancelled { return }
+ let groupSelection = selectionSnapshot.filter { group.contains($0) }
+ guard !groupSelection.isEmpty else { continue }
+ do {
+ let report = try await finder.moveToTrash(group: group, selectedIDs: groupSelection)
+ movedFiles.append(contentsOf: report.trashedFiles)
+ failures.append(contentsOf: report.failures.map { "\($0.url.lastPathComponent): \($0.message)" })
+ } catch {
+ failures.append(error.localizedDescription)
+ }
+ }
+ guard scanGeneration == generation,
+ selectedFolder == folder,
+ result?.folder == folder,
+ !Task.isCancelled else { return }
+ applyTrashResult(movedFiles)
+ if failures.isEmpty {
+ actionMessage = ActionMessage(
+ title: "Moved to Trash",
+ detail: "\(movedFiles.count) files totaling \(format(movedFiles.reduce(0) { $0 + $1.size })) were moved. Every protected copy remains in place."
+ )
+ } else {
+ actionMessage = ActionMessage(
+ title: movedFiles.isEmpty ? "Nothing was moved" : "Some files were not moved",
+ detail: failures.joined(separator: "\n")
+ )
+ }
+ }
+ }
+
+ private func applyTrashResult(_ movedFiles: [DuplicateFile]) {
+ guard let currentResult = result else { return }
+ let movedIDs = Set(movedFiles.map(\.url))
+ let remainingGroups = currentResult.groups.compactMap { group -> DuplicateGroup? in
+ let remaining = group.files.filter { !movedIDs.contains($0.url) }
+ guard remaining.count > 1 else { return nil }
+ return DuplicateGroup(digest: group.digest, files: remaining)
+ }
+ result = DuplicateScanResult(
+ folder: currentResult.folder,
+ groups: remainingGroups,
+ skippedFiles: currentResult.skippedFiles,
+ filesInspected: currentResult.filesInspected,
+ bytesHashed: currentResult.bytesHashed
+ )
+ selectedIDs.subtract(movedIDs)
+ expandedGroupIDs.formIntersection(Set(remainingGroups.map(\.id)))
+ }
+
+ private func skippedSummary(_ skippedFiles: [DuplicateSkippedFile]) -> String {
+ skippedFiles.isEmpty
+ ? "Every eligible file was checked."
+ : "\(skippedFiles.count) unsafe or unavailable items were skipped."
+ }
+
+ private func format(_ bytes: Int64) -> String {
+ ByteCountFormatter.string(fromByteCount: bytes, countStyle: .file)
+ }
+}
+
+private struct ActionMessage: Identifiable {
+ let id = UUID()
+ let title: String
+ let detail: String
+}
diff --git a/PureMac/Views/Tools/PerformanceView.swift b/PureMac/Views/Tools/PerformanceView.swift
new file mode 100644
index 0000000..a93ebf9
--- /dev/null
+++ b/PureMac/Views/Tools/PerformanceView.swift
@@ -0,0 +1,546 @@
+import AppKit
+import SwiftUI
+
+struct PerformanceView: View {
+ private enum LoadState {
+ case idle
+ case loading
+ case loaded(PerformanceInspection)
+ case failed(String)
+ }
+
+ @ObservedObject private var monitor = SystemMonitor.shared
+ @State private var state: LoadState = .idle
+ @State private var snapshotPendingDeletion: PerformanceSnapshot?
+ @State private var deletingSnapshotID: String?
+ @State private var deletionError: String?
+ private let inspector = PerformanceInspector()
+
+ var body: some View {
+ ZStack {
+ Color(nsColor: .windowBackgroundColor)
+ .ignoresSafeArea()
+
+ ScrollView {
+ LazyVStack(alignment: .leading, spacing: 14) {
+ header
+ liveResources
+ inspectionContent
+ }
+ .padding(24)
+ .frame(maxWidth: 1040)
+ .frame(maxWidth: .infinity)
+ }
+ }
+ .navigationTitle("Performance")
+ .toolbar {
+ ToolbarItem {
+ Button {
+ Task { await refresh() }
+ } label: {
+ Label("Refresh", systemImage: "arrow.clockwise")
+ }
+ .disabled(isLoading)
+ .help("Inspect startup items and local snapshots again")
+ }
+ }
+ .task {
+ monitor.start(interval: 1.5)
+ await refresh()
+ }
+ .onDisappear {
+ monitor.stop()
+ }
+ .alert("Delete local snapshot?", isPresented: deletionConfirmationPresented) {
+ Button("Cancel", role: .cancel) {
+ snapshotPendingDeletion = nil
+ }
+ Button("Delete Snapshot", role: .destructive) {
+ guard let snapshot = snapshotPendingDeletion else { return }
+ snapshotPendingDeletion = nil
+ Task { await delete(snapshot) }
+ }
+ } message: {
+ Text(snapshotDeletionMessage)
+ }
+ .alert("Snapshot could not be deleted", isPresented: deletionErrorPresented) {
+ Button("OK", role: .cancel) {
+ deletionError = nil
+ }
+ } message: {
+ Text(deletionError ?? "Unknown error")
+ }
+ }
+
+ private var header: some View {
+ HStack(alignment: .center, spacing: 14) {
+ IconTile(systemName: "gauge.with.dots.needle.67percent", tint: Tint.accent, size: 44, corner: 12)
+ VStack(alignment: .leading, spacing: 3) {
+ Text("Performance")
+ .font(.system(size: 26, weight: .bold))
+ Text("See current resource use and review what starts in the background.")
+ .font(.system(size: 13))
+ .foregroundStyle(.secondary)
+ }
+ Spacer()
+ Button("Open Activity Monitor") {
+ openActivityMonitor()
+ }
+ .buttonStyle(.bordered)
+ }
+ .padding(.bottom, 2)
+ }
+
+ private var liveResources: some View {
+ CardSurface(padding: 18, elevation: .standard, tint: Tint.accent) {
+ VStack(alignment: .leading, spacing: 16) {
+ HStack {
+ SectionHeader("Live resources")
+ Spacer()
+ StatusChip(label: "Live", systemImage: "circle.fill", tint: Tint.green)
+ }
+
+ HStack(spacing: 26) {
+ ResourceMeter(
+ title: "CPU",
+ value: monitor.cpuUsage,
+ detail: "\(Int((monitor.cpuUsage * 100).rounded()))%",
+ tint: Tint.accent
+ )
+ Divider()
+ .frame(height: 52)
+ ResourceMeter(
+ title: "Memory pressure use",
+ value: monitor.memoryFraction,
+ detail: memoryDetail,
+ tint: Tint.purple
+ )
+ }
+ }
+ }
+ }
+
+ @ViewBuilder
+ private var inspectionContent: some View {
+ switch state {
+ case .idle, .loading:
+ CardSurface(padding: 28, elevation: .flat) {
+ HStack(spacing: 12) {
+ ProgressView()
+ .controlSize(.small)
+ Text("Inspecting startup items and local snapshots…")
+ .foregroundStyle(.secondary)
+ Spacer()
+ }
+ }
+ case .loaded(let inspection):
+ if !inspection.issues.isEmpty {
+ issuesCard(inspection.issues)
+ }
+ startupCard(inspection.startupItems)
+ snapshotsCard(inspection.snapshots)
+ case .failed(let message):
+ CardSurface(padding: 18, elevation: .standard, tint: Tint.orange) {
+ HStack(alignment: .top, spacing: 12) {
+ IconTile(systemName: "exclamationmark.triangle.fill", tint: Tint.orange, size: 32, corner: 9)
+ VStack(alignment: .leading, spacing: 5) {
+ Text("Inspection stopped")
+ .font(.system(size: 14, weight: .semibold))
+ Text(message)
+ .font(.system(size: 12))
+ .foregroundStyle(.secondary)
+ }
+ Spacer()
+ Button("Try Again") {
+ Task { await refresh() }
+ }
+ .buttonStyle(.bordered)
+ }
+ }
+ }
+ }
+
+ private func issuesCard(_ issues: [PerformanceInspectionIssue]) -> some View {
+ CardSurface(padding: 16, elevation: .flat, tint: Tint.orange) {
+ DisclosureGroup {
+ VStack(alignment: .leading, spacing: 10) {
+ ForEach(issues) { issue in
+ VStack(alignment: .leading, spacing: 2) {
+ Text(issue.title)
+ .font(.system(size: 12, weight: .medium))
+ Text(issue.detail)
+ .font(.system(size: 11))
+ .foregroundStyle(.secondary)
+ .textSelection(.enabled)
+ }
+ }
+ }
+ .padding(.top, 10)
+ } label: {
+ Label(
+ "Some information could not be read (\(issues.count))",
+ systemImage: "exclamationmark.triangle.fill"
+ )
+ .font(.system(size: 13, weight: .semibold))
+ .foregroundStyle(Tint.orange)
+ }
+ }
+ }
+
+ private func startupCard(_ items: [PerformanceStartupItem]) -> some View {
+ CardSurface(padding: 0, elevation: .standard) {
+ VStack(alignment: .leading, spacing: 0) {
+ HStack(spacing: 10) {
+ IconTile(systemName: "switch.2", tint: Tint.accent, size: 30, corner: 8)
+ VStack(alignment: .leading, spacing: 2) {
+ Text("Startup and background items")
+ .font(.system(size: 15, weight: .semibold))
+ Text("Launch agents and daemons installed outside macOS system folders")
+ .font(.system(size: 11.5))
+ .foregroundStyle(.secondary)
+ }
+ Spacer()
+ StatusChip(label: "\(items.count) found", tint: Tint.accent)
+ Button("Login Items Settings") {
+ openLoginItemsSettings()
+ }
+ .buttonStyle(.bordered)
+ .controlSize(.small)
+ }
+ .padding(18)
+
+ Divider()
+
+ if items.isEmpty {
+ EmptyInspectionRow(
+ systemImage: "checkmark.circle.fill",
+ title: "No launchd items found",
+ detail: "The inspected user and third-party launch folders are empty."
+ )
+ } else {
+ LazyVStack(spacing: 0) {
+ ForEach(Array(items.enumerated()), id: \.element.id) { index, item in
+ StartupItemRow(item: item) {
+ reveal(item.sourceURL)
+ }
+ if index < items.count - 1 {
+ Divider()
+ .padding(.leading, 58)
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ private func snapshotsCard(_ snapshots: [PerformanceSnapshot]) -> some View {
+ CardSurface(padding: 0, elevation: .standard) {
+ VStack(alignment: .leading, spacing: 0) {
+ HStack(spacing: 10) {
+ IconTile(systemName: "clock.arrow.circlepath", tint: Tint.purple, size: 30, corner: 8)
+ VStack(alignment: .leading, spacing: 2) {
+ Text("Local snapshots")
+ .font(.system(size: 15, weight: .semibold))
+ Text("Time Machine snapshots can be reviewed and removed individually")
+ .font(.system(size: 11.5))
+ .foregroundStyle(.secondary)
+ }
+ Spacer()
+ StatusChip(label: "\(snapshots.count) found", tint: Tint.purple)
+ Button("Time Machine Settings") {
+ openTimeMachineSettings()
+ }
+ .buttonStyle(.bordered)
+ .controlSize(.small)
+ }
+ .padding(18)
+
+ Divider()
+
+ if snapshots.isEmpty {
+ EmptyInspectionRow(
+ systemImage: "clock.badge.checkmark.fill",
+ title: "No local snapshots reported",
+ detail: "Time Machine did not report any snapshots for the startup disk."
+ )
+ } else {
+ LazyVStack(spacing: 0) {
+ ForEach(Array(snapshots.enumerated()), id: \.element.id) { index, snapshot in
+ SnapshotRow(
+ snapshot: snapshot,
+ isDeleting: deletingSnapshotID == snapshot.id,
+ deletionInProgress: deletingSnapshotID != nil
+ ) {
+ snapshotPendingDeletion = snapshot
+ }
+ if index < snapshots.count - 1 {
+ Divider()
+ .padding(.leading, 58)
+ }
+ }
+ }
+
+ HStack(spacing: 6) {
+ Image(systemName: "info.circle")
+ Text("macOS does not report reliable per-snapshot sizes in this listing.")
+ }
+ .font(.system(size: 11))
+ .foregroundStyle(.secondary)
+ .padding(.horizontal, 18)
+ .padding(.vertical, 12)
+ .background(Color.primary.opacity(0.025))
+ }
+ }
+ }
+ }
+
+ private var isLoading: Bool {
+ if case .loading = state { return true }
+ return false
+ }
+
+ private var memoryDetail: String {
+ let formatter = ByteCountFormatter()
+ formatter.countStyle = .memory
+ formatter.allowedUnits = [.useGB, .useMB]
+ return "\(formatter.string(fromByteCount: monitor.memoryUsed)) of \(formatter.string(fromByteCount: monitor.memoryTotal))"
+ }
+
+ private var deletionConfirmationPresented: Binding<Bool> {
+ Binding(
+ get: { snapshotPendingDeletion != nil },
+ set: { if !$0 { snapshotPendingDeletion = nil } }
+ )
+ }
+
+ private var snapshotDeletionMessage: String {
+ guard let snapshot = snapshotPendingDeletion else {
+ return "This permanently removes the selected Time Machine snapshot."
+ }
+ return "This permanently removes \(snapshot.identifier). Its size is unknown, and the action cannot be undone."
+ }
+
+ private var deletionErrorPresented: Binding<Bool> {
+ Binding(
+ get: { deletionError != nil },
+ set: { if !$0 { deletionError = nil } }
+ )
+ }
+
+ @MainActor
+ private func refresh() async {
+ guard !isLoading else { return }
+ state = .loading
+ do {
+ state = .loaded(try await inspector.inspect())
+ } catch is CancellationError {
+ return
+ } catch {
+ state = .failed(error.localizedDescription)
+ }
+ }
+
+ @MainActor
+ private func delete(_ snapshot: PerformanceSnapshot) async {
+ guard deletingSnapshotID == nil else { return }
+ deletingSnapshotID = snapshot.id
+ defer { deletingSnapshotID = nil }
+ do {
+ try await inspector.deleteSnapshot(snapshot)
+ state = .loaded(try await inspector.inspect())
+ } catch is CancellationError {
+ return
+ } catch {
+ deletionError = error.localizedDescription
+ }
+ }
+
+ private func reveal(_ url: URL) {
+ if FileManager.default.fileExists(atPath: url.path) {
+ NSWorkspace.shared.activateFileViewerSelecting([url])
+ } else {
+ NSWorkspace.shared.open(url.deletingLastPathComponent())
+ }
+ }
+
+ private func openActivityMonitor() {
+ NSWorkspace.shared.open(URL(fileURLWithPath: "/System/Applications/Utilities/Activity Monitor.app"))
+ }
+
+ private func openLoginItemsSettings() {
+ guard let url = URL(string: "x-apple.systempreferences:com.apple.LoginItems-Settings.extension") else { return }
+ NSWorkspace.shared.open(url)
+ }
+
+ private func openTimeMachineSettings() {
+ guard let url = URL(string: "x-apple.systempreferences:com.apple.TimeMachine-Settings.extension") else { return }
+ NSWorkspace.shared.open(url)
+ }
+}
+
+private struct ResourceMeter: View {
+ let title: String
+ let value: Double
+ let detail: String
+ let tint: Color
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 8) {
+ HStack {
+ Text(title)
+ .font(.system(size: 12, weight: .medium))
+ .foregroundStyle(.secondary)
+ Spacer()
+ Text(detail)
+ .font(.system(size: 12, weight: .semibold, design: .rounded))
+ .monospacedDigit()
+ }
+ ProgressView(value: min(1, max(0, value)))
+ .tint(tint)
+ }
+ .frame(maxWidth: .infinity)
+ }
+}
+
+private struct StartupItemRow: View {
+ let item: PerformanceStartupItem
+ let onReveal: () -> Void
+ @State private var hovering = false
+
+ var body: some View {
+ HStack(alignment: .top, spacing: 12) {
+ IconTile(
+ systemName: item.domain == .systemDaemon ? "gearshape.2.fill" : "bolt.horizontal.circle.fill",
+ tint: item.isDisabled ? Color.secondary : Tint.accent,
+ size: 28,
+ corner: 8
+ )
+
+ VStack(alignment: .leading, spacing: 5) {
+ HStack(spacing: 7) {
+ Text(item.label)
+ .font(.system(size: 13, weight: .medium))
+ .lineLimit(1)
+ StatusChip(
+ label: item.isDisabled ? "Disabled" : item.domain.title,
+ tint: item.isDisabled ? Color.secondary : Tint.accent
+ )
+ ForEach(item.triggers.prefix(2), id: \.self) { trigger in
+ StatusChip(label: trigger, tint: Tint.purple)
+ }
+ }
+
+ Text(item.program ?? "Program not declared in this plist")
+ .font(.system(size: 11.5, design: .monospaced))
+ .foregroundStyle(item.program == nil ? Tint.orange : .secondary)
+ .lineLimit(1)
+ .truncationMode(.middle)
+ .textSelection(.enabled)
+
+ Text(item.sourceURL.path)
+ .font(.system(size: 10.5, design: .monospaced))
+ .foregroundStyle(.tertiary)
+ .lineLimit(1)
+ .truncationMode(.middle)
+ .textSelection(.enabled)
+ }
+
+ Spacer(minLength: 8)
+
+ Button(action: onReveal) {
+ Image(systemName: "folder")
+ .frame(width: 18, height: 18)
+ }
+ .buttonStyle(.plain)
+ .foregroundStyle(.secondary)
+ .help("Reveal plist in Finder")
+ .opacity(hovering ? 1 : 0.55)
+ }
+ .padding(.horizontal, 18)
+ .padding(.vertical, 12)
+ .background(hovering ? Color.primary.opacity(0.025) : Color.clear)
+ .onHover { hovering = $0 }
+ }
+}
+
+private struct SnapshotRow: View {
+ let snapshot: PerformanceSnapshot
+ let isDeleting: Bool
+ let deletionInProgress: Bool
+ let onDelete: () -> Void
+
+ var body: some View {
+ HStack(alignment: .top, spacing: 12) {
+ IconTile(
+ systemName: snapshot.kind == .systemUpdate ? "macbook.and.iphone" : "clock.arrow.circlepath",
+ tint: snapshot.kind == .systemUpdate ? Tint.orange : Tint.purple,
+ size: 28,
+ corner: 8
+ )
+
+ VStack(alignment: .leading, spacing: 4) {
+ HStack(spacing: 7) {
+ Text(snapshot.kind.title)
+ .font(.system(size: 13, weight: .medium))
+ if let date = snapshot.date {
+ Text(date.formatted(date: .abbreviated, time: .shortened))
+ .font(.system(size: 11.5))
+ .foregroundStyle(.secondary)
+ }
+ }
+ Text(snapshot.identifier)
+ .font(.system(size: 10.5, design: .monospaced))
+ .foregroundStyle(.tertiary)
+ .lineLimit(1)
+ .truncationMode(.middle)
+ .textSelection(.enabled)
+ }
+ Spacer()
+ VStack(alignment: .trailing, spacing: 7) {
+ Text("Size unavailable")
+ .font(.system(size: 11))
+ .foregroundStyle(.secondary)
+ if PerformanceInspector.deletionTimestamp(for: snapshot) != nil {
+ Button(role: .destructive, action: onDelete) {
+ if isDeleting {
+ ProgressView()
+ .controlSize(.small)
+ } else {
+ Label("Delete", systemImage: "trash")
+ }
+ }
+ .buttonStyle(.bordered)
+ .controlSize(.small)
+ .disabled(deletionInProgress)
+ }
+ }
+ }
+ .padding(.horizontal, 18)
+ .padding(.vertical, 12)
+ }
+}
+
+private struct EmptyInspectionRow: View {
+ let systemImage: String
+ let title: String
+ let detail: String
+
+ var body: some View {
+ HStack(spacing: 12) {
+ Image(systemName: systemImage)
+ .font(.system(size: 22))
+ .foregroundStyle(Tint.green)
+ .frame(width: 30)
+ VStack(alignment: .leading, spacing: 3) {
+ Text(title)
+ .font(.system(size: 13, weight: .medium))
+ Text(detail)
+ .font(.system(size: 11.5))
+ .foregroundStyle(.secondary)
+ }
+ Spacer()
+ }
+ .padding(18)
+ }
+}
diff --git a/PureMac/Views/Tools/ProtectionView.swift b/PureMac/Views/Tools/ProtectionView.swift
new file mode 100644
index 0000000..b68831e
--- /dev/null
+++ b/PureMac/Views/Tools/ProtectionView.swift
@@ -0,0 +1,399 @@
+import AppKit
+import SwiftUI
+
+struct ProtectionView: View {
+ private enum Phase {
+ case idle
+ case running
+ case complete(ProtectionSnapshot)
+ }
+
+ private let audit: ProtectionAudit
+ @State private var phase: Phase = .idle
+ @State private var auditTask: Task<Void, Never>?
+
+ init(audit: ProtectionAudit = ProtectionAudit()) {
+ self.audit = audit
+ }
+
+ var body: some View {
+ ZStack {
+ Color(nsColor: .windowBackgroundColor)
+ .ignoresSafeArea()
+
+ ScrollView {
+ VStack(alignment: .leading, spacing: 14) {
+ header
+ auditContent
+ permissionsCard
+ browserPrivacyCard
+ }
+ .frame(maxWidth: 920, alignment: .leading)
+ .padding(24)
+ .frame(maxWidth: .infinity)
+ }
+ }
+ .navigationTitle("Protection")
+ .onDisappear {
+ auditTask?.cancel()
+ auditTask = nil
+ if case .running = phase {
+ phase = .idle
+ }
+ }
+ }
+
+ private var header: some View {
+ HStack(alignment: .top, spacing: 24) {
+ VStack(alignment: .leading, spacing: 7) {
+ Text("Protection")
+ .font(.system(size: 28, weight: .bold))
+ Text("Review the macOS safeguards that protect apps, disks, network access, and system files.")
+ .font(.system(size: 13))
+ .foregroundStyle(.secondary)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+
+ Spacer(minLength: 20)
+
+ Button(action: runAudit) {
+ HStack(spacing: 8) {
+ if case .running = phase {
+ ProgressView()
+ .controlSize(.small)
+ .tint(.white)
+ } else {
+ Image(systemName: "checkmark.shield")
+ }
+ Text(auditButtonTitle)
+ }
+ }
+ .buttonStyle(GlowProminentButtonStyle(tint: Tint.accent, gradient: TintGradient.of(Tint.accent)))
+ .disabled(isRunning)
+ .accessibilityLabel(auditButtonTitle)
+ }
+ }
+
+ @ViewBuilder
+ private var auditContent: some View {
+ switch phase {
+ case .idle:
+ CardSurface(padding: 22, elevation: .standard, tint: Tint.accent) {
+ HStack(spacing: 18) {
+ IconTile(systemName: "shield.checkered", tint: Tint.accent, size: 44, corner: 12)
+ VStack(alignment: .leading, spacing: 6) {
+ Text("Check built-in safeguards")
+ .font(.system(size: 17, weight: .semibold))
+ Text("The audit reads current settings and does not change your Mac. It is a configuration review, not a malware scan.")
+ .font(.system(size: 12.5))
+ .foregroundStyle(.secondary)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ Spacer(minLength: 0)
+ }
+ }
+ case .running:
+ CardSurface(padding: 0, elevation: .standard, tint: Tint.accent) {
+ VStack(spacing: 0) {
+ ForEach(Array(ProtectionCheck.allCases.enumerated()), id: \.element.id) { index, check in
+ HStack(spacing: 12) {
+ ProgressView()
+ .controlSize(.small)
+ .frame(width: 24)
+ Text(check.title)
+ .font(.system(size: 13, weight: .medium))
+ Spacer()
+ Text("Checking")
+ .font(.system(size: 11.5))
+ .foregroundStyle(.secondary)
+ }
+ .padding(.horizontal, 18)
+ .padding(.vertical, 13)
+
+ if index < ProtectionCheck.allCases.count - 1 {
+ Divider().padding(.leading, 54)
+ }
+ }
+ }
+ }
+ case .complete(let snapshot):
+ VStack(alignment: .leading, spacing: 8) {
+ CardSurface(padding: 0, elevation: .standard) {
+ VStack(spacing: 0) {
+ ForEach(Array(snapshot.findings.enumerated()), id: \.element.id) { index, finding in
+ ProtectionFindingRow(finding: finding)
+ .padding(.horizontal, 18)
+ .padding(.vertical, 13)
+
+ if index < snapshot.findings.count - 1 {
+ Divider().padding(.leading, 58)
+ }
+ }
+ }
+ }
+
+ Text("Checked \(snapshot.checkedAt.formatted(date: .abbreviated, time: .shortened)). Unknown means the setting could not be confirmed.")
+ .font(.system(size: 11.5))
+ .foregroundStyle(.secondary)
+ .padding(.horizontal, 4)
+ }
+ }
+ }
+
+ private var permissionsCard: some View {
+ CardSurface(padding: 18, elevation: .flat) {
+ VStack(alignment: .leading, spacing: 14) {
+ HStack(spacing: 10) {
+ IconTile(systemName: "hand.raised.fill", tint: Tint.purple, size: 31, corner: 8)
+ VStack(alignment: .leading, spacing: 2) {
+ Text("App permissions")
+ .font(.system(size: 15, weight: .semibold))
+ Text("Review which apps can access private data and hardware.")
+ .font(.system(size: 11.5))
+ .foregroundStyle(.secondary)
+ }
+ }
+
+ HStack(spacing: 8) {
+ SettingsButton(title: "Full Disk Access", icon: "externaldrive.badge.person.crop") {
+ ProtectionNavigation.openSettings("com.apple.preference.security?Privacy_AllFiles")
+ }
+ SettingsButton(title: "Location", icon: "location") {
+ ProtectionNavigation.openSettings("com.apple.preference.security?Privacy_LocationServices")
+ }
+ SettingsButton(title: "Camera", icon: "video") {
+ ProtectionNavigation.openSettings("com.apple.preference.security?Privacy_Camera")
+ }
+ SettingsButton(title: "Microphone", icon: "mic") {
+ ProtectionNavigation.openSettings("com.apple.preference.security?Privacy_Microphone")
+ }
+ }
+ }
+ }
+ }
+
+ private var browserPrivacyCard: some View {
+ CardSurface(padding: 18, elevation: .flat) {
+ VStack(alignment: .leading, spacing: 14) {
+ HStack(alignment: .top, spacing: 10) {
+ IconTile(systemName: "safari", tint: Tint.blue, size: 31, corner: 8)
+ VStack(alignment: .leading, spacing: 3) {
+ Text("Browser privacy")
+ .font(.system(size: 15, weight: .semibold))
+ Text("Browser controls must be reviewed inside each browser. PureMac does not change cookies, history, site permissions, or extensions.")
+ .font(.system(size: 11.5))
+ .foregroundStyle(.secondary)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ }
+
+ HStack(spacing: 10) {
+ Link(destination: URL(string: "https://support.apple.com/guide/safari/sfri35610/mac")!) {
+ Label("Safari privacy guide", systemImage: "arrow.up.right.square")
+ }
+ Link(destination: URL(string: "https://support.google.com/chrome/answer/17561599?hl=en")!) {
+ Label("Chrome privacy guide", systemImage: "arrow.up.right.square")
+ }
+ Spacer()
+ Text("Safari: Settings > Privacy")
+ .font(.system(size: 11.5))
+ .foregroundStyle(.secondary)
+ }
+ .buttonStyle(.link)
+ }
+ }
+ }
+
+ private var isRunning: Bool {
+ if case .running = phase { return true }
+ return false
+ }
+
+ private var auditButtonTitle: String {
+ switch phase {
+ case .idle:
+ return "Run audit"
+ case .running:
+ return "Checking"
+ case .complete:
+ return "Check again"
+ }
+ }
+
+ private func runAudit() {
+ guard !isRunning else { return }
+ auditTask?.cancel()
+ phase = .running
+ auditTask = Task {
+ let snapshot = await audit.run()
+ guard !Task.isCancelled else { return }
+ withAnimation(MotionTokens.gentle) {
+ phase = .complete(snapshot)
+ }
+ auditTask = nil
+ }
+ }
+}
+
+private struct ProtectionFindingRow: View {
+ let finding: ProtectionFinding
+
+ var body: some View {
+ HStack(alignment: .center, spacing: 12) {
+ Image(systemName: finding.status.icon)
+ .font(.system(size: 19, weight: .semibold))
+ .foregroundStyle(finding.status.tint)
+ .frame(width: 28)
+
+ VStack(alignment: .leading, spacing: 3) {
+ HStack(spacing: 7) {
+ Text(finding.check.title)
+ .font(.system(size: 13, weight: .semibold))
+ StatusChip(
+ label: finding.status.label(for: finding.check),
+ systemImage: finding.status.chipIcon,
+ tint: finding.status.tint
+ )
+ if let version = finding.version {
+ Text(version)
+ .font(.system(size: 10.5, design: .monospaced))
+ .foregroundStyle(.secondary)
+ }
+ }
+ Text(finding.detail)
+ .font(.system(size: 11.5))
+ .foregroundStyle(.secondary)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+
+ Spacer(minLength: 12)
+
+ Button(finding.check.actionTitle) {
+ ProtectionNavigation.openAction(for: finding.check)
+ }
+ .controlSize(.small)
+ }
+ }
+}
+
+private struct SettingsButton: View {
+ let title: String
+ let icon: String
+ let action: () -> Void
+
+ var body: some View {
+ Button(action: action) {
+ Label(title, systemImage: icon)
+ .font(.system(size: 11.5, weight: .medium))
+ .frame(maxWidth: .infinity)
+ }
+ .buttonStyle(.bordered)
+ .controlSize(.small)
+ }
+}
+
+private enum ProtectionNavigation {
+ static func openAction(for check: ProtectionCheck) {
+ switch check {
+ case .gatekeeper:
+ openSettings("com.apple.preference.security")
+ case .fileVault:
+ openSettings("com.apple.preference.security?FileVault")
+ case .firewall:
+ openSettings("com.apple.Network-Settings.extension?Firewall")
+ case .systemIntegrityProtection:
+ openWeb("https://support.apple.com/guide/security/secb7ea06b49/web")
+ case .xProtect:
+ openSettings("com.apple.Software-Update-Settings.extension")
+ }
+ }
+
+ static func openSettings(_ destination: String) {
+ openWeb("x-apple.systempreferences:\(destination)")
+ }
+
+ private static func openWeb(_ address: String) {
+ guard let url = URL(string: address) else { return }
+ NSWorkspace.shared.open(url)
+ }
+}
+
+private extension ProtectionCheck {
+ var title: String {
+ switch self {
+ case .gatekeeper:
+ return "Gatekeeper"
+ case .fileVault:
+ return "FileVault"
+ case .firewall:
+ return "Application Firewall"
+ case .systemIntegrityProtection:
+ return "System Integrity Protection"
+ case .xProtect:
+ return "XProtect"
+ }
+ }
+
+ var actionTitle: String {
+ switch self {
+ case .gatekeeper:
+ return "Security Settings"
+ case .fileVault:
+ return "FileVault Settings"
+ case .firewall:
+ return "Firewall Settings"
+ case .systemIntegrityProtection:
+ return "Apple Guide"
+ case .xProtect:
+ return "Software Update"
+ }
+ }
+}
+
+private extension ProtectionStatus {
+ var icon: String {
+ switch self {
+ case .enabled:
+ return "checkmark.circle.fill"
+ case .disabled:
+ return "exclamationmark.circle.fill"
+ case .unknown:
+ return "questionmark.circle.fill"
+ }
+ }
+
+ var chipIcon: String {
+ switch self {
+ case .enabled:
+ return "checkmark"
+ case .disabled:
+ return "exclamationmark"
+ case .unknown:
+ return "questionmark"
+ }
+ }
+
+ var tint: Color {
+ switch self {
+ case .enabled:
+ return Tint.green
+ case .disabled:
+ return Tint.orange
+ case .unknown:
+ return .secondary
+ }
+ }
+
+ func label(for check: ProtectionCheck) -> String {
+ switch (self, check) {
+ case (.enabled, .xProtect):
+ return "Installed"
+ case (.enabled, _):
+ return "On"
+ case (.disabled, _):
+ return "Off"
+ case (.unknown, _):
+ return "Unknown"
+ }
+ }
+}
diff --git a/PureMac/Views/Tools/SimilarPhotosView.swift b/PureMac/Views/Tools/SimilarPhotosView.swift
new file mode 100644
index 0000000..fbb35fc
--- /dev/null
+++ b/PureMac/Views/Tools/SimilarPhotosView.swift
@@ -0,0 +1,524 @@
+import AppKit
+import SwiftUI
+
+@MainActor
+final class SimilarPhotosViewModel: ObservableObject {
+ enum Phase {
+ case idle
+ case scanning
+ case loaded
+ case failed(String)
+ case cancelled
+ }
+
+ @Published private(set) var phase: Phase = .idle
+ @Published private(set) var folder: URL?
+ @Published private(set) var result: SimilarPhotoScanResult?
+ @Published private(set) var progress: SimilarPhotoScanProgress?
+
+ private let finder: SimilarPhotoFinder
+ private var scanTask: Task<Void, Never>?
+ private var scanID = UUID()
+
+ init(finder: SimilarPhotoFinder = SimilarPhotoFinder()) {
+ self.finder = finder
+ }
+
+ var isScanning: Bool {
+ if case .scanning = phase { return true }
+ return false
+ }
+
+ func chooseFolder() {
+ let panel = NSOpenPanel()
+ panel.title = "Choose a photo folder"
+ panel.message = "PureMac compares local image thumbnails without changing your photos."
+ panel.prompt = "Scan Photos"
+ panel.canChooseFiles = false
+ panel.canChooseDirectories = true
+ panel.allowsMultipleSelection = false
+ panel.canCreateDirectories = false
+ panel.resolvesAliases = true
+ panel.treatsFilePackagesAsDirectories = false
+
+ guard panel.runModal() == .OK, let url = panel.url else { return }
+ startScan(folder: url.standardizedFileURL)
+ }
+
+ func rescan() {
+ guard let folder else { return }
+ startScan(folder: folder)
+ }
+
+ func cancel() {
+ guard isScanning else { return }
+ scanTask?.cancel()
+ phase = .cancelled
+ progress = nil
+ }
+
+ func reveal(_ url: URL) {
+ NSWorkspace.shared.activateFileViewerSelecting([url])
+ }
+
+ private func startScan(folder: URL) {
+ scanTask?.cancel()
+ let id = UUID()
+ scanID = id
+ self.folder = folder
+ result = nil
+ progress = SimilarPhotoScanProgress(
+ phase: .discovering,
+ entriesVisited: 0,
+ candidatesFound: 0,
+ photosAnalyzed: 0,
+ currentURL: folder
+ )
+ phase = .scanning
+
+ scanTask = Task { [weak self, finder] in
+ do {
+ let result = try await finder.scan(folder: folder) { [weak self] progress in
+ await self?.receive(progress, scanID: id)
+ }
+ guard let self, self.scanID == id, !Task.isCancelled else { return }
+ self.result = result
+ self.progress = nil
+ self.phase = .loaded
+ } catch is CancellationError {
+ guard let self, self.scanID == id, self.isScanning else { return }
+ self.progress = nil
+ self.phase = .cancelled
+ } catch {
+ guard let self, self.scanID == id else { return }
+ self.progress = nil
+ self.phase = .failed(error.localizedDescription)
+ }
+ }
+ }
+
+ private func receive(_ progress: SimilarPhotoScanProgress, scanID: UUID) {
+ guard self.scanID == scanID, isScanning else { return }
+ self.progress = progress
+ }
+}
+
+struct SimilarPhotosView: View {
+ @StateObject private var model: SimilarPhotosViewModel
+
+ init(finder: SimilarPhotoFinder = SimilarPhotoFinder()) {
+ _model = StateObject(wrappedValue: SimilarPhotosViewModel(finder: finder))
+ }
+
+ var body: some View {
+ ZStack {
+ Color(nsColor: .windowBackgroundColor)
+ .ignoresSafeArea()
+
+ ScrollView {
+ LazyVStack(alignment: .leading, spacing: 14) {
+ header
+ if let folder = model.folder {
+ locationCard(folder)
+ }
+ content
+ }
+ .padding(24)
+ .frame(maxWidth: 1040, alignment: .leading)
+ .frame(maxWidth: .infinity)
+ }
+ }
+ .navigationTitle("Similar Photos")
+ .onDisappear {
+ model.cancel()
+ }
+ }
+
+ private var header: some View {
+ HStack(alignment: .center, spacing: 16) {
+ IconTile(systemName: "photo.stack.fill", tint: Tint.pink, size: 48, corner: 13, vivid: true)
+
+ VStack(alignment: .leading, spacing: 4) {
+ Text("Similar Photos")
+ .font(.system(size: 25, weight: .bold))
+ Text("Find visually related shots in a folder and review them side by side.")
+ .font(.callout)
+ .foregroundStyle(.secondary)
+ }
+
+ Spacer()
+
+ Button {
+ model.chooseFolder()
+ } label: {
+ Label(model.folder == nil ? "Choose Folder" : "Choose Another Folder", systemImage: "folder.badge.plus")
+ }
+ .buttonStyle(.borderedProminent)
+ .tint(Tint.pink)
+ .controlSize(.large)
+ .disabled(model.isScanning)
+ }
+ }
+
+ private func locationCard(_ folder: URL) -> some View {
+ CardSurface(padding: 11, elevation: .flat, tint: Tint.pink) {
+ HStack(spacing: 10) {
+ Image(systemName: "folder.fill")
+ .foregroundStyle(Tint.pink)
+ Text(folder.path)
+ .font(.system(size: 12, weight: .medium, design: .monospaced))
+ .lineLimit(1)
+ .truncationMode(.middle)
+ .textSelection(.enabled)
+ Spacer(minLength: 8)
+ Button {
+ model.reveal(folder)
+ } label: {
+ Label("Show in Finder", systemImage: "arrow.forward.square")
+ }
+ .buttonStyle(.borderless)
+ Button {
+ model.rescan()
+ } label: {
+ Label("Rescan", systemImage: "arrow.clockwise")
+ }
+ .buttonStyle(.borderless)
+ .disabled(model.isScanning)
+ }
+ }
+ }
+
+ @ViewBuilder
+ private var content: some View {
+ switch model.phase {
+ case .idle:
+ idleState
+ case .scanning:
+ scanningState
+ case .loaded:
+ if let result = model.result {
+ resultView(result)
+ } else {
+ idleState
+ }
+ case .failed(let message):
+ messageState(
+ title: "Photos could not be compared",
+ message: message,
+ systemImage: "exclamationmark.triangle.fill",
+ tint: Tint.orange
+ )
+ case .cancelled:
+ messageState(
+ title: "Scan stopped",
+ message: "No photos were changed. You can scan the folder again at any time.",
+ systemImage: "stop.circle",
+ tint: .secondary
+ )
+ }
+ }
+
+ private var idleState: some View {
+ CardSurface(padding: 32, elevation: .standard, tint: Tint.pink) {
+ VStack(spacing: 15) {
+ IconTile(systemName: "photo.on.rectangle.angled", tint: Tint.pink, size: 62, corner: 17)
+ Text("Choose a folder of photos")
+ .font(.system(size: 19, weight: .semibold))
+ Text("PureMac builds small local thumbnails, compares their visual structure and color, then groups likely matches for review.")
+ .font(.system(size: 13))
+ .foregroundStyle(.secondary)
+ .multilineTextAlignment(.center)
+ .frame(maxWidth: 520)
+ HStack(spacing: 8) {
+ StatusChip(label: "Review only", systemImage: "eye", tint: Tint.green)
+ StatusChip(label: "500 photo limit", systemImage: "photo.stack", tint: Tint.pink)
+ StatusChip(label: "Local files", systemImage: "lock.shield", tint: Tint.blue)
+ }
+ Text("Symbolic links, app packages, hidden files and cloud-only placeholders are skipped. Photos are never uploaded or deleted.")
+ .font(.system(size: 11.5))
+ .foregroundStyle(.tertiary)
+ .multilineTextAlignment(.center)
+ }
+ .frame(maxWidth: .infinity, minHeight: 300)
+ }
+ }
+
+ private var scanningState: some View {
+ CardSurface(padding: 24, elevation: .standard, tint: Tint.pink) {
+ VStack(alignment: .leading, spacing: 16) {
+ HStack(spacing: 13) {
+ ProgressView()
+ .controlSize(.small)
+ VStack(alignment: .leading, spacing: 3) {
+ Text(progressTitle)
+ .font(.system(size: 16, weight: .semibold))
+ Text(model.progress?.currentURL?.lastPathComponent ?? "Preparing visual comparison")
+ .font(.system(size: 12))
+ .foregroundStyle(.secondary)
+ .lineLimit(1)
+ .truncationMode(.middle)
+ }
+ Spacer()
+ Button("Stop") {
+ model.cancel()
+ }
+ .buttonStyle(.bordered)
+ }
+
+ ProgressView()
+ .progressViewStyle(.linear)
+ .tint(Tint.pink)
+
+ HStack(spacing: 8) {
+ StatusChip(
+ label: "\(model.progress?.entriesVisited ?? 0) items",
+ systemImage: "doc.on.doc",
+ tint: Tint.pink
+ )
+ StatusChip(
+ label: "\(model.progress?.candidatesFound ?? 0) photos",
+ systemImage: "photo",
+ tint: Tint.pink
+ )
+ if let progress = model.progress, progress.photosAnalyzed > 0 {
+ StatusChip(
+ label: "\(progress.photosAnalyzed) compared",
+ systemImage: "viewfinder",
+ tint: Tint.blue
+ )
+ }
+ }
+ }
+ }
+ }
+
+ private var progressTitle: String {
+ switch model.progress?.phase {
+ case .discovering, .none:
+ return "Finding local photos"
+ case .analyzing:
+ return "Building visual signatures"
+ case .comparing:
+ return "Grouping similar shots"
+ }
+ }
+
+ private func resultView(_ result: SimilarPhotoScanResult) -> some View {
+ VStack(alignment: .leading, spacing: 14) {
+ summaryCard(result)
+
+ CardSurface(padding: 14, elevation: .flat, tint: Tint.blue) {
+ HStack(alignment: .top, spacing: 11) {
+ IconTile(systemName: "eye.fill", tint: Tint.blue, size: 30, corner: 8)
+ VStack(alignment: .leading, spacing: 3) {
+ Text("Review the groups before acting")
+ .font(.system(size: 13.5, weight: .semibold))
+ Text("Similarity is a visual estimate, not proof that two files are identical. Use Show in Finder to compare originals at full quality.")
+ .font(.system(size: 11.5))
+ .foregroundStyle(.secondary)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ }
+ }
+
+ if result.groups.isEmpty {
+ CardSurface(padding: 28, elevation: .standard) {
+ VStack(spacing: 12) {
+ IconTile(systemName: "checkmark.circle.fill", tint: Tint.green, size: 52, corner: 14)
+ Text("No similar groups found")
+ .font(.system(size: 18, weight: .semibold))
+ Text("The analyzed photos did not meet PureMac's visual similarity threshold.")
+ .font(.system(size: 13))
+ .foregroundStyle(.secondary)
+ }
+ .frame(maxWidth: .infinity, minHeight: 180)
+ }
+ } else {
+ SectionHeader("Suggested groups")
+ ForEach(Array(result.groups.enumerated()), id: \.element.id) { index, group in
+ SimilarPhotoGroupCard(index: index + 1, group: group, onReveal: model.reveal)
+ }
+ }
+ }
+ }
+
+ private func summaryCard(_ result: SimilarPhotoScanResult) -> some View {
+ CardSurface(padding: 18, elevation: .standard, tint: Tint.pink) {
+ HStack(spacing: 20) {
+ VStack(alignment: .leading, spacing: 3) {
+ Text("\(result.groups.count)")
+ .font(.system(size: 32, weight: .bold, design: .rounded))
+ .monospacedDigit()
+ .foregroundStyle(Tint.pink)
+ Text(result.groups.count == 1 ? "similar group" : "similar groups")
+ .font(.system(size: 12.5))
+ .foregroundStyle(.secondary)
+ }
+
+ Divider()
+ .frame(height: 50)
+
+ VStack(alignment: .leading, spacing: 8) {
+ HStack(spacing: 8) {
+ StatusChip(label: "\(result.photosAnalyzed) analyzed", systemImage: "viewfinder", tint: Tint.pink)
+ StatusChip(label: "\(result.matchedPhotoCount) matched", systemImage: "photo.stack", tint: Tint.blue)
+ }
+ HStack(spacing: 8) {
+ StatusChip(label: Self.format(result.matchedPhotoSize), systemImage: "internaldrive", tint: Tint.purple)
+ if result.skippedItems > 0 {
+ StatusChip(label: "\(result.skippedItems) skipped", systemImage: "forward", tint: Tint.orange)
+ }
+ }
+ }
+
+ Spacer()
+
+ StatusChip(
+ label: result.isPartial ? "Sample limit reached" : "Scan complete",
+ systemImage: result.isPartial ? "exclamationmark.triangle" : "checkmark.circle",
+ tint: result.isPartial ? Tint.orange : Tint.green
+ )
+ }
+ }
+ }
+
+ private func messageState(title: String, message: String, systemImage: String, tint: Color) -> some View {
+ CardSurface(padding: 30, elevation: .standard, tint: tint) {
+ VStack(spacing: 13) {
+ IconTile(systemName: systemImage, tint: tint, size: 54, corner: 15)
+ Text(title)
+ .font(.system(size: 18, weight: .semibold))
+ Text(message)
+ .font(.system(size: 13))
+ .foregroundStyle(.secondary)
+ .multilineTextAlignment(.center)
+ .frame(maxWidth: 480)
+ if model.folder != nil {
+ Button("Scan Again") {
+ model.rescan()
+ }
+ .buttonStyle(.borderedProminent)
+ .tint(Tint.pink)
+ }
+ }
+ .frame(maxWidth: .infinity, minHeight: 220)
+ }
+ }
+
+ private static func format(_ bytes: Int64) -> String {
+ ByteCountFormatter.string(fromByteCount: bytes, countStyle: .file)
+ }
+}
+
+private struct SimilarPhotoGroupCard: View {
+ let index: Int
+ let group: SimilarPhotoGroup
+ let onReveal: (URL) -> Void
+
+ private let columns = [GridItem(.adaptive(minimum: 190, maximum: 250), spacing: 12)]
+
+ var body: some View {
+ CardSurface(padding: 0, elevation: .standard) {
+ VStack(alignment: .leading, spacing: 0) {
+ HStack(spacing: 10) {
+ IconTile(systemName: "photo.stack.fill", tint: Tint.pink, size: 32, corner: 9)
+ VStack(alignment: .leading, spacing: 2) {
+ Text("Group \(index)")
+ .font(.system(size: 15, weight: .semibold))
+ Text("\(group.photos.count) photos · \(Self.format(group.totalSize))")
+ .font(.system(size: 11.5))
+ .foregroundStyle(.secondary)
+ }
+ Spacer()
+ StatusChip(
+ label: "\(Int((group.similarity * 100).rounded()))% visual score",
+ systemImage: "viewfinder",
+ tint: Tint.pink
+ )
+ }
+ .padding(16)
+
+ Divider()
+
+ LazyVGrid(columns: columns, alignment: .leading, spacing: 12) {
+ ForEach(group.photos) { photo in
+ SimilarPhotoTile(photo: photo, onReveal: { onReveal(photo.url) })
+ }
+ }
+ .padding(14)
+ }
+ }
+ }
+
+ private static func format(_ bytes: Int64) -> String {
+ ByteCountFormatter.string(fromByteCount: bytes, countStyle: .file)
+ }
+}
+
+private struct SimilarPhotoTile: View {
+ let photo: SimilarPhoto
+ let onReveal: () -> Void
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 9) {
+ ZStack {
+ RoundedRectangle(cornerRadius: 10, style: .continuous)
+ .fill(Color.secondary.opacity(0.08))
+ if let image = NSImage(data: photo.thumbnailData) {
+ Image(nsImage: image)
+ .resizable()
+ .scaledToFill()
+ } else {
+ Image(systemName: "photo")
+ .font(.system(size: 28))
+ .foregroundStyle(.tertiary)
+ }
+ }
+ .frame(height: 132)
+ .clipShape(RoundedRectangle(cornerRadius: 10, style: .continuous))
+ .overlay {
+ RoundedRectangle(cornerRadius: 10, style: .continuous)
+ .strokeBorder(Color.primary.opacity(0.08), lineWidth: 0.5)
+ }
+
+ Text(photo.url.lastPathComponent)
+ .font(.system(size: 12.5, weight: .semibold))
+ .lineLimit(1)
+ .truncationMode(.middle)
+ .help(photo.url.path)
+
+ HStack(spacing: 5) {
+ Text("\(photo.pixelWidth) × \(photo.pixelHeight)")
+ Text("·")
+ Text(Self.format(photo.size))
+ Spacer(minLength: 0)
+ }
+ .font(.system(size: 10.5, design: .monospaced))
+ .foregroundStyle(.secondary)
+
+ Button(action: onReveal) {
+ Label("Show in Finder", systemImage: "arrow.forward.square")
+ .frame(maxWidth: .infinity)
+ }
+ .buttonStyle(.bordered)
+ .controlSize(.small)
+ .accessibilityLabel("Show \(photo.url.lastPathComponent) in Finder")
+ }
+ .padding(10)
+ .background {
+ RoundedRectangle(cornerRadius: 12, style: .continuous)
+ .fill(Color(nsColor: .controlBackgroundColor).opacity(0.7))
+ }
+ .overlay {
+ RoundedRectangle(cornerRadius: 12, style: .continuous)
+ .strokeBorder(Color.primary.opacity(0.07), lineWidth: 0.5)
+ }
+ .contextMenu {
+ Button("Show in Finder", action: onReveal)
+ }
+ }
+
+ private static func format(_ bytes: Int64) -> String {
+ ByteCountFormatter.string(fromByteCount: bytes, countStyle: .file)
+ }
+}
diff --git a/PureMac/Views/Tools/SpaceExplorerView.swift b/PureMac/Views/Tools/SpaceExplorerView.swift
new file mode 100644
index 0000000..bdf8611
--- /dev/null
+++ b/PureMac/Views/Tools/SpaceExplorerView.swift
@@ -0,0 +1,555 @@
+import AppKit
+import SwiftUI
+
+@MainActor
+final class SpaceExplorerViewModel: ObservableObject {
+ enum Phase {
+ case idle
+ case scanning
+ case loaded
+ case failed(String)
+ case cancelled
+ }
+
+ @Published private(set) var phase: Phase = .idle
+ @Published private(set) var result: StorageScanResult?
+ @Published private(set) var progress: StorageScanProgress?
+ @Published private(set) var path: [URL] = []
+
+ private let explorer: StorageExplorer
+ private var scanTask: Task<Void, Never>?
+ private var scanID = UUID()
+
+ init(explorer: StorageExplorer = StorageExplorer()) {
+ self.explorer = explorer
+ }
+
+ var currentURL: URL? { path.last }
+ var canGoBack: Bool { path.count > 1 && !isScanning }
+ var isScanning: Bool {
+ if case .scanning = phase { return true }
+ return false
+ }
+
+ func chooseFolder() {
+ let panel = NSOpenPanel()
+ panel.title = "Choose a folder to inspect"
+ panel.message = "PureMac measures allocated disk space without changing files."
+ panel.prompt = "Inspect"
+ panel.canChooseFiles = false
+ panel.canChooseDirectories = true
+ panel.allowsMultipleSelection = false
+ panel.canCreateDirectories = false
+ panel.resolvesAliases = true
+ panel.treatsFilePackagesAsDirectories = false
+
+ guard panel.runModal() == .OK, let url = panel.url else { return }
+ path = [url.standardizedFileURL]
+ startScan(at: url)
+ }
+
+ func open(_ entry: StorageEntry) {
+ guard entry.isDirectory, !isScanning else { return }
+ let url = entry.url.standardizedFileURL
+ path.append(url)
+ startScan(at: url)
+ }
+
+ func goBack() {
+ guard canGoBack else { return }
+ path.removeLast()
+ guard let url = path.last else { return }
+ startScan(at: url)
+ }
+
+ func rescan() {
+ guard let url = currentURL else { return }
+ startScan(at: url)
+ }
+
+ func cancel() {
+ guard isScanning else { return }
+ scanTask?.cancel()
+ phase = .cancelled
+ }
+
+ func reveal(_ url: URL) {
+ NSWorkspace.shared.activateFileViewerSelecting([url])
+ }
+
+ private func startScan(at url: URL) {
+ scanTask?.cancel()
+ let id = UUID()
+ scanID = id
+ result = nil
+ progress = StorageScanProgress(
+ rootURL: url,
+ currentURL: url,
+ allocatedSize: 0,
+ scannedItemCount: 0,
+ inaccessibleCount: 0,
+ skippedCount: 0
+ )
+ phase = .scanning
+
+ scanTask = Task { [self, explorer] in
+ do {
+ let result = try await explorer.scan(at: url) { progress in
+ Task { @MainActor [self] in
+ guard self.scanID == id, self.isScanning else { return }
+ self.progress = progress
+ }
+ }
+ guard self.scanID == id else { return }
+ self.result = result
+ self.progress = nil
+ self.phase = .loaded
+ } catch is CancellationError {
+ guard self.scanID == id, self.isScanning else { return }
+ self.phase = .cancelled
+ } catch {
+ guard self.scanID == id else { return }
+ self.progress = nil
+ self.phase = .failed(error.localizedDescription)
+ }
+ }
+ }
+}
+
+struct SpaceExplorerView: View {
+ @StateObject private var model = SpaceExplorerViewModel()
+
+ var body: some View {
+ VStack(spacing: 14) {
+ header
+
+ if let currentURL = model.currentURL {
+ locationBar(currentURL)
+ }
+
+ content
+ }
+ .padding(24)
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ .background(Color(nsColor: .windowBackgroundColor))
+ .navigationTitle("Space Explorer")
+ .onDisappear {
+ model.cancel()
+ }
+ }
+
+ private var header: some View {
+ HStack(alignment: .center, spacing: 14) {
+ IconTile(systemName: "internaldrive", tint: Tint.accent, size: 44, corner: 12)
+
+ VStack(alignment: .leading, spacing: 3) {
+ Text("Space Explorer")
+ .font(.system(size: 24, weight: .bold))
+ Text("Inspect a folder by allocated disk space. Your files are never changed.")
+ .font(.system(size: 12.5))
+ .foregroundStyle(.secondary)
+ }
+
+ Spacer()
+
+ Button {
+ model.chooseFolder()
+ } label: {
+ Label(model.currentURL == nil ? "Choose Folder" : "Choose Another Folder", systemImage: "folder.badge.plus")
+ }
+ .buttonStyle(.borderedProminent)
+ .tint(Tint.accent)
+ .controlSize(.large)
+ .disabled(model.isScanning)
+ }
+ }
+
+ private func locationBar(_ url: URL) -> some View {
+ CardSurface(padding: 10, elevation: .flat, tint: Tint.accent) {
+ HStack(spacing: 10) {
+ Button {
+ model.goBack()
+ } label: {
+ Image(systemName: "chevron.left")
+ .frame(width: 20, height: 20)
+ }
+ .buttonStyle(.borderless)
+ .disabled(!model.canGoBack)
+ .help("Back")
+
+ Image(systemName: "folder.fill")
+ .foregroundStyle(Tint.accent)
+
+ Text(url.path)
+ .font(.system(size: 12, weight: .medium, design: .monospaced))
+ .lineLimit(1)
+ .truncationMode(.middle)
+ .textSelection(.enabled)
+
+ Spacer(minLength: 8)
+
+ Button {
+ model.reveal(url)
+ } label: {
+ Label("Show in Finder", systemImage: "arrow.forward.square")
+ }
+ .buttonStyle(.borderless)
+
+ Button {
+ model.rescan()
+ } label: {
+ Label("Rescan", systemImage: "arrow.clockwise")
+ }
+ .buttonStyle(.borderless)
+ .disabled(model.isScanning)
+ }
+ }
+ }
+
+ @ViewBuilder
+ private var content: some View {
+ switch model.phase {
+ case .idle:
+ idleState
+ case .scanning:
+ scanningState
+ case .loaded:
+ if let result = model.result {
+ resultView(result)
+ } else {
+ idleState
+ }
+ case .failed(let message):
+ messageState(
+ title: "Folder could not be inspected",
+ message: message,
+ systemImage: "exclamationmark.folder",
+ tint: Tint.orange
+ )
+ case .cancelled:
+ messageState(
+ title: "Scan stopped",
+ message: "No files were changed. Rescan this folder when you are ready.",
+ systemImage: "stop.circle",
+ tint: .secondary
+ )
+ }
+ }
+
+ private var idleState: some View {
+ CardSurface(padding: 28, elevation: .standard, tint: Tint.accent) {
+ VStack(spacing: 12) {
+ IconTile(systemName: "folder", tint: Tint.accent, size: 58, corner: 16)
+ Text("Choose where to look")
+ .font(.system(size: 18, weight: .semibold))
+ Text("Select any folder to see which files and subfolders occupy the most disk space.")
+ .font(.system(size: 13))
+ .foregroundStyle(.secondary)
+ .multilineTextAlignment(.center)
+ .frame(maxWidth: 420)
+ Text("Symbolic links and cloud-only items are excluded.")
+ .font(.system(size: 11.5))
+ .foregroundStyle(.tertiary)
+ }
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ }
+ }
+
+ private var scanningState: some View {
+ CardSurface(padding: 24, elevation: .standard, tint: Tint.accent) {
+ VStack(alignment: .leading, spacing: 16) {
+ HStack(spacing: 12) {
+ ProgressView()
+ .controlSize(.small)
+ VStack(alignment: .leading, spacing: 2) {
+ Text("Measuring allocated space")
+ .font(.system(size: 16, weight: .semibold))
+ Text(model.progress?.currentURL.lastPathComponent ?? "Preparing scan")
+ .font(.system(size: 12))
+ .foregroundStyle(.secondary)
+ .lineLimit(1)
+ .truncationMode(.middle)
+ }
+ Spacer()
+ Button("Stop") {
+ model.cancel()
+ }
+ .buttonStyle(.bordered)
+ }
+
+ ProgressView()
+ .progressViewStyle(.linear)
+ .tint(Tint.accent)
+
+ HStack(spacing: 8) {
+ StatusChip(
+ label: "\(model.progress?.scannedItemCount ?? 0) items",
+ systemImage: "doc.on.doc",
+ tint: Tint.accent
+ )
+ StatusChip(
+ label: Self.format(model.progress?.allocatedSize ?? 0),
+ systemImage: "internaldrive",
+ tint: Tint.accent
+ )
+ if let progress = model.progress, progress.skippedCount > 0 {
+ StatusChip(label: "\(progress.skippedCount) skipped", systemImage: "forward", tint: Tint.orange)
+ }
+ if let progress = model.progress, progress.inaccessibleCount > 0 {
+ StatusChip(label: "\(progress.inaccessibleCount) inaccessible", systemImage: "lock", tint: Tint.orange)
+ }
+ }
+ }
+ .frame(maxWidth: .infinity)
+ }
+ }
+
+ private func resultView(_ result: StorageScanResult) -> some View {
+ ScrollView {
+ LazyVStack(alignment: .leading, spacing: 14) {
+ summaryCard(result)
+
+ if result.entries.isEmpty {
+ CardSurface(padding: 24, elevation: .flat) {
+ HStack(spacing: 12) {
+ IconTile(systemName: "folder", tint: Tint.accent, size: 36, corner: 10)
+ VStack(alignment: .leading, spacing: 3) {
+ Text("No measurable items")
+ .font(.system(size: 14, weight: .semibold))
+ Text("This folder is empty or its contents were excluded from the scan.")
+ .font(.system(size: 12))
+ .foregroundStyle(.secondary)
+ }
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+ } else {
+ SectionHeader("Largest items")
+ ForEach(result.entries) { entry in
+ StorageEntryRow(
+ entry: entry,
+ totalSize: result.totalAllocatedSize,
+ onOpen: { model.open(entry) },
+ onReveal: { model.reveal(entry.url) }
+ )
+ }
+ }
+ }
+ .padding(.bottom, 2)
+ }
+ }
+
+ private func summaryCard(_ result: StorageScanResult) -> some View {
+ CardSurface(padding: 18, elevation: .standard, tint: Tint.accent) {
+ HStack(alignment: .center, spacing: 18) {
+ VStack(alignment: .leading, spacing: 3) {
+ Text(Self.format(result.totalAllocatedSize))
+ .font(.system(size: 30, weight: .bold, design: .rounded))
+ .monospacedDigit()
+ .foregroundStyle(Tint.accent)
+ Text("allocated in this folder")
+ .font(.system(size: 12.5))
+ .foregroundStyle(.secondary)
+ }
+
+ Divider()
+ .frame(height: 48)
+
+ VStack(alignment: .leading, spacing: 8) {
+ HStack(spacing: 8) {
+ StatusChip(label: "\(result.fileCount) files", systemImage: "doc", tint: Tint.accent)
+ StatusChip(label: "\(result.directoryCount) folders", systemImage: "folder", tint: Tint.accent)
+ }
+ HStack(spacing: 8) {
+ StatusChip(
+ label: "\(result.skippedCount) skipped",
+ systemImage: "forward",
+ tint: result.skippedCount == 0 ? Tint.green : Tint.orange
+ )
+ StatusChip(
+ label: "\(result.inaccessibleCount) inaccessible",
+ systemImage: "lock",
+ tint: result.inaccessibleCount == 0 ? Tint.green : Tint.orange
+ )
+ }
+ }
+
+ Spacer()
+
+ StatusChip(
+ label: result.isPartial ? "Partial result" : "Complete",
+ systemImage: result.isPartial ? "exclamationmark.triangle" : "checkmark.circle",
+ tint: result.isPartial ? Tint.orange : Tint.green
+ )
+ }
+ }
+ }
+
+ private func messageState(title: String, message: String, systemImage: String, tint: Color) -> some View {
+ CardSurface(padding: 28, elevation: .standard, tint: tint) {
+ VStack(spacing: 12) {
+ IconTile(systemName: systemImage, tint: tint, size: 54, corner: 15)
+ Text(title)
+ .font(.system(size: 18, weight: .semibold))
+ Text(message)
+ .font(.system(size: 13))
+ .foregroundStyle(.secondary)
+ .multilineTextAlignment(.center)
+ .frame(maxWidth: 460)
+ Button("Rescan") {
+ model.rescan()
+ }
+ .buttonStyle(.borderedProminent)
+ .tint(Tint.accent)
+ }
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ }
+ }
+
+ private static func format(_ bytes: Int64) -> String {
+ ByteCountFormatter.string(fromByteCount: bytes, countStyle: .file)
+ }
+}
+
+private struct StorageEntryRow: View {
+ let entry: StorageEntry
+ let totalSize: Int64
+ let onOpen: () -> Void
+ let onReveal: () -> Void
+
+ var body: some View {
+ CardSurface(padding: 12, elevation: .flat) {
+ HStack(spacing: 12) {
+ Group {
+ if entry.isDirectory {
+ Button(action: onOpen) {
+ entryContent
+ }
+ .buttonStyle(.plain)
+ } else {
+ entryContent
+ }
+ }
+ .frame(maxWidth: .infinity)
+
+ Button(action: onReveal) {
+ Image(systemName: "arrow.forward.square")
+ .frame(width: 24, height: 24)
+ }
+ .buttonStyle(.borderless)
+ .help("Show in Finder")
+ .accessibilityLabel("Show \(entry.name) in Finder")
+ }
+ }
+ .contextMenu {
+ if entry.isDirectory {
+ Button("Open Folder", action: onOpen)
+ }
+ Button("Show in Finder", action: onReveal)
+ }
+ }
+
+ private var entryContent: some View {
+ HStack(spacing: 12) {
+ IconTile(
+ systemName: entry.isDirectory ? "folder.fill" : (entry.isPackage ? "app.fill" : "doc.fill"),
+ tint: Tint.accent,
+ size: 34,
+ corner: 9
+ )
+
+ VStack(alignment: .leading, spacing: 6) {
+ HStack(spacing: 7) {
+ Text(entry.name)
+ .font(.system(size: 13.5, weight: .semibold))
+ .lineLimit(1)
+ .truncationMode(.middle)
+ if entry.isPartial {
+ Image(systemName: "exclamationmark.triangle.fill")
+ .font(.system(size: 10))
+ .foregroundStyle(Tint.orange)
+ .help("Some contents were skipped or inaccessible")
+ }
+ }
+
+ HStack(spacing: 8) {
+ Text(detailText)
+ .font(.system(size: 11.5))
+ .foregroundStyle(.secondary)
+ if entry.skippedCount > 0 {
+ Text("\(entry.skippedCount) skipped")
+ .foregroundStyle(Tint.orange)
+ }
+ if entry.inaccessibleCount > 0 {
+ Text("\(entry.inaccessibleCount) inaccessible")
+ .foregroundStyle(Tint.orange)
+ }
+ }
+ .font(.system(size: 11.5))
+
+ StorageUsageBar(value: entry.allocatedSize, total: totalSize)
+ }
+
+ Text(Self.format(entry.allocatedSize))
+ .font(.system(size: 13, weight: .semibold, design: .rounded))
+ .monospacedDigit()
+ .foregroundStyle(.secondary)
+ .frame(minWidth: 76, alignment: .trailing)
+
+ if entry.isDirectory {
+ Image(systemName: "chevron.right")
+ .font(.system(size: 11, weight: .semibold))
+ .foregroundStyle(.tertiary)
+ }
+ }
+ .contentShape(Rectangle())
+ .accessibilityElement(children: .combine)
+ .accessibilityLabel("\(entry.name), \(Self.format(entry.allocatedSize))")
+ .accessibilityHint(entry.isDirectory ? "Open folder" : (entry.isPackage ? "Package" : "File"))
+ }
+
+ private var detailText: String {
+ if entry.isPackage {
+ return "Package · \(Self.countLabel(entry.fileCount, singular: "file"))"
+ }
+ if entry.isDirectory {
+ let childFolderCount = max(0, entry.directoryCount - 1)
+ return "\(Self.countLabel(entry.fileCount, singular: "file")) · \(Self.countLabel(childFolderCount, singular: "folder"))"
+ }
+ return "File"
+ }
+
+ private static func countLabel(_ count: Int, singular: String) -> String {
+ "\(count) \(singular)\(count == 1 ? "" : "s")"
+ }
+
+ private static func format(_ bytes: Int64) -> String {
+ ByteCountFormatter.string(fromByteCount: bytes, countStyle: .file)
+ }
+}
+
+private struct StorageUsageBar: View {
+ let value: Int64
+ let total: Int64
+
+ private var ratio: Double {
+ guard total > 0 else { return 0 }
+ return min(1, max(0, Double(value) / Double(total)))
+ }
+
+ var body: some View {
+ GeometryReader { proxy in
+ ZStack(alignment: .leading) {
+ Capsule()
+ .fill(Color.secondary.opacity(0.12))
+ Capsule()
+ .fill(Tint.accent)
+ .frame(width: proxy.size.width * ratio)
+ }
+ }
+ .frame(height: 5)
+ .accessibilityElement()
+ .accessibilityLabel("Share of scanned space")
+ .accessibilityValue("\(Int((ratio * 100).rounded())) percent")
+ }
+}
diff --git a/PureMacTests/AppStateTests.swift b/PureMacTests/AppStateTests.swift
index f87c6c4..e5f9762 100644
--- a/PureMacTests/AppStateTests.swift
+++ b/PureMacTests/AppStateTests.swift
@@ -41,6 +41,107 @@ final class AppStateTests: XCTestCase {
XCTAssertEqual(appState.currentAppFileSearchLocationCount, urls.count)
}
+ func testOlderAppScanCannotReplaceNewerAppResults() {
+ var completions: [((Set<URL>) -> Void)] = []
+ let state = AppState(performStartupTasks: false, appFileScanner: { _, _, completion in
+ completions.append(completion)
+ })
+ state.scanForAppFiles(makeApp())
+ state.scanForAppFiles(makeApp())
+ let latest: Set<URL> = [URL(fileURLWithPath: "/fixtures/latest")]
+ completions[1](latest)
+ completions[0]([URL(fileURLWithPath: "/fixtures/stale")])
+ XCTAssertEqual(Set(state.discoveredFiles), latest)
+ XCTAssertEqual(state.selectedFiles, latest)
+ }
+
+ func testFullDiskAccessRetryKeepsUninstallInTrashFlow() async {
+ let expectedURLs: Set<URL> = [
+ URL(fileURLWithPath: "/Applications/Fixture.app"),
+ URL(fileURLWithPath: "/Users/fixture/Library/Containers/com.fixture.app")
+ ]
+ var receivedURLs: Set<URL> = []
+ let invoked = expectation(description: "app file trasher")
+ let state = AppState(
+ performStartupTasks: false,
+ appFileTrasher: { urls, completion in
+ receivedURLs = Set(urls)
+ completion(urls, false, [], [])
+ invoked.fulfill()
+ }
+ )
+ let items = expectedURLs.map {
+ CleanableItem(
+ name: $0.lastPathComponent,
+ path: $0.path,
+ size: 100,
+ category: .systemJunk,
+ isSelected: true,
+ lastModified: nil
+ )
+ }
+
+ await state.retryAfterFullDiskAccess(
+ items: items,
+ context: .uninstall(appName: "Fixture", failedCount: items.count)
+ )
+ await fulfillment(of: [invoked], timeout: 1)
+
+ XCTAssertEqual(receivedURLs, expectedURLs)
+ }
+
+ func testVisibleSelectionPreservesHiddenRowsAndManualDefaults() {
+ let state = AppState(performStartupTasks: false)
+ let visible = cleanupItem(selected: false)
+ let hidden = cleanupItem(selected: true)
+ state.categoryResults[.userCache] = CategoryResult(category: .userCache, items: [visible, hidden], totalSize: 200)
+ state.setSelection(true, for: [visible])
+ XCTAssertTrue(state.isItemSelected(visible))
+ XCTAssertTrue(state.isItemSelected(hidden))
+ state.setSelection(false, for: [visible])
+ XCTAssertFalse(state.isItemSelected(visible))
+ XCTAssertTrue(state.isItemSelected(hidden))
+ }
+
+ func testScheduledScanWaitsForReviewToLeaveForeground() {
+ let state = AppState(performStartupTasks: false)
+ let item = cleanupItem(selected: true)
+ state.categoryResults[.userCache] = CategoryResult(category: .userCache, items: [item], totalSize: 100)
+ state.scanState = .completed
+ XCTAssertFalse(state.canRunScheduledScan(isAppActive: true))
+ XCTAssertTrue(state.canRunScheduledScan(isAppActive: false))
+ state.showCleanConfirmation = true
+ XCTAssertFalse(state.canRunScheduledScan(isAppActive: false))
+ XCTAssertEqual(state.categoryResults[.userCache]?.items.map(\.id), [item.id])
+ XCTAssertEqual(state.scanState, .completed)
+ }
+
+ func testScheduledScanWaitsForActiveOperations() {
+ let state = AppState(performStartupTasks: false)
+ state.scanState = .cleaning(progress: 0.2)
+ XCTAssertFalse(state.canRunScheduledScan(isAppActive: false))
+ state.scanState = .idle
+ state.isRemovingAppFiles = true
+ XCTAssertFalse(state.canRunScheduledScan(isAppActive: false))
+ }
+
+ func testStopScanPreservesCompletedResultsAndDoesNotStopCleaning() {
+ let state = AppState(performStartupTasks: false)
+ state.categoryResults[.userCache] = CategoryResult(category: .userCache, items: [cleanupItem(selected: true)], totalSize: 100)
+ state.scanState = .scanning(progress: 0.5, currentCategory: "User Cache")
+ state.cancelScan()
+ XCTAssertTrue(state.scanWasCancelled)
+ XCTAssertEqual(state.scanState, .completed)
+ XCTAssertEqual(state.totalItemCount, 1)
+ state.scanState = .cleaning(progress: 0.5)
+ state.cancelScan()
+ XCTAssertEqual(state.scanState, .cleaning(progress: 0.5))
+ }
+
+ private func cleanupItem(selected: Bool) -> CleanableItem {
+ CleanableItem(name: "Fixture", path: "/fixtures/\(UUID().uuidString)", size: 100, category: .userCache, isSelected: selected, lastModified: nil)
+ }
+
private func makeApp() -> InstalledApp {
InstalledApp(
id: UUID(),
diff --git a/PureMacTests/ApplicationUpdaterTests.swift b/PureMacTests/ApplicationUpdaterTests.swift
new file mode 100644
index 0000000..0edd078
--- /dev/null
+++ b/PureMacTests/ApplicationUpdaterTests.swift
@@ -0,0 +1,270 @@
+import XCTest
+@testable import PureMac
+
+final class ApplicationUpdaterTests: XCTestCase {
+ func testAppIdentityMatcherResolvesKnownCaskNamesExactly() {
+ let appNames = ["MiddleClick", "OpenSCAD", "Postman", "Pure Snitch"]
+
+ XCTAssertEqual(AppUpdateIdentityMatcher.matchingIndex(for: "middleclick", appNames: appNames), 0)
+ XCTAssertEqual(AppUpdateIdentityMatcher.matchingIndex(for: "openscad@snapshot", appNames: appNames), 1)
+ XCTAssertEqual(AppUpdateIdentityMatcher.matchingIndex(for: "postman", appNames: appNames), 2)
+ XCTAssertEqual(AppUpdateIdentityMatcher.matchingIndex(for: "puresnitch", appNames: appNames), 3)
+ }
+
+ func testAppIdentityMatcherStripsTapAndVariantBeforeMatching() {
+ XCTAssertEqual(
+ AppUpdateIdentityMatcher.matchingIndex(
+ for: "vendor/tap/openscad@snapshot",
+ appNames: ["OpenSCAD"]
+ ),
+ 0
+ )
+ XCTAssertEqual(AppUpdateIdentityMatcher.baseToken("vendor/tap/openscad@snapshot"), "openscad")
+ XCTAssertTrue(AppUpdateIdentityMatcher.shouldShowTokenDetail("openscad@snapshot"))
+ }
+
+ func testAppIdentityMatcherRejectsFuzzyAndAmbiguousMatches() {
+ XCTAssertNil(
+ AppUpdateIdentityMatcher.matchingIndex(
+ for: "postman-agent",
+ appNames: ["Postman"]
+ )
+ )
+ XCTAssertNil(
+ AppUpdateIdentityMatcher.matchingIndex(
+ for: "foo-bar",
+ appNames: ["Foo Bar", "Foo-Bar"]
+ )
+ )
+ }
+
+ func testAppIdentityFallbackProducesReadableName() {
+ XCTAssertEqual(
+ AppUpdateIdentityMatcher.fallbackDisplayName(for: "vendor/tap/visual-studio-code@insiders"),
+ "Visual Studio Code"
+ )
+ XCTAssertFalse(AppUpdateIdentityMatcher.shouldShowTokenDetail("postman"))
+ }
+
+ func testParsesCaskNamesAndTrustedApplicationTargets() throws {
+ let json = #"{"casks":[{"token":"openscad@snapshot","name":["OpenSCAD"],"artifacts":[{"app":["OpenSCAD.app"],"target":"/Applications/OpenSCAD.app"}]},{"token":"puresnitch","name":["PureSnitch"],"artifacts":[{"app":["PureSnitch.app"],"target":"/Applications/PureSnitch.app"}]}]}"#
+
+ let descriptors = try ApplicationUpdater.parseCaskPresentationDescriptors(
+ Data(json.utf8),
+ requestedTokens: ["openscad@snapshot", "puresnitch"]
+ )
+
+ XCTAssertEqual(descriptors["openscad@snapshot"]?.displayName, "OpenSCAD")
+ XCTAssertEqual(descriptors["openscad@snapshot"]?.bundlePaths, ["/Applications/OpenSCAD.app"])
+ XCTAssertEqual(descriptors["puresnitch"]?.displayName, "PureSnitch")
+ }
+
+ func testCaskPresentationParserRejectsUntrustedTargets() throws {
+ let json = #"{"casks":[{"token":"safe-app","name":["Safe App"],"artifacts":[{"app":["Safe.app"],"target":"/tmp/Safe.app"},{"app":["Default.app"]}]}]}"#
+
+ let descriptors = try ApplicationUpdater.parseCaskPresentationDescriptors(
+ Data(json.utf8),
+ requestedTokens: ["safe-app"]
+ )
+
+ XCTAssertEqual(descriptors["safe-app"]?.bundlePaths, ["/Applications/Default.app"])
+ }
+
+ func testParsesOutdatedCasksWithInstalledAndAvailableVersions() throws {
+ let json = """
+ {
+ "formulae": [],
+ "casks": [
+ {
+ "name": "visual-studio-code",
+ "installed_versions": ["1.98.0", "1.98.1"],
+ "current_version": "1.99.0",
+ "pinned": false,
+ "pinned_version": null
+ },
+ {
+ "name": "1password",
+ "installed_versions": ["8.10.68"],
+ "current_version": "8.10.70",
+ "pinned": true,
+ "pinned_version": "8.10.68"
+ }
+ ]
+ }
+ """
+
+ let updates = try ApplicationUpdater.parseOutdatedCasks(json)
+
+ XCTAssertEqual(updates.map(\.token), ["1password", "visual-studio-code"])
+ XCTAssertEqual(updates[0].installedVersion, "8.10.68")
+ XCTAssertEqual(updates[0].currentVersion, "8.10.70")
+ XCTAssertTrue(updates[0].isPinned)
+ XCTAssertEqual(updates[1].installedVersion, "1.98.0, 1.98.1")
+ XCTAssertEqual(updates[1].currentVersion, "1.99.0")
+ XCTAssertFalse(updates[1].isPinned)
+ }
+
+ func testParsesEmptyCaskList() throws {
+ let updates = try ApplicationUpdater.parseOutdatedCasks(#"{"formulae":[],"casks":[]}"#)
+ XCTAssertTrue(updates.isEmpty)
+ }
+
+ func testRejectsMalformedOrIncompletePayloads() {
+ XCTAssertThrowsError(try ApplicationUpdater.parseOutdatedCasks("not-json")) { error in
+ XCTAssertEqual(error as? ApplicationUpdaterError, .invalidResponse)
+ }
+
+ let missingVersion = #"{"casks":[{"name":"firefox","installed_versions":["1"]}]}"#
+ XCTAssertThrowsError(try ApplicationUpdater.parseOutdatedCasks(missingVersion)) { error in
+ XCTAssertEqual(error as? ApplicationUpdaterError, .invalidResponse)
+ }
+
+ let emptyInstalled = #"{"casks":[{"name":"firefox","installed_versions":[],"current_version":"2","pinned":false}]}"#
+ XCTAssertThrowsError(try ApplicationUpdater.parseOutdatedCasks(emptyInstalled)) { error in
+ XCTAssertEqual(error as? ApplicationUpdaterError, .invalidResponse)
+ }
+ }
+
+ func testCaskIdentifierValidationAllowsOnlyStrictTokens() {
+ let valid = [
+ "firefox",
+ "visual-studio-code",
+ "font-fira-code@6",
+ "app_name+preview.2"
+ ]
+ let invalid = [
+ "",
+ "Firefox",
+ "--debug",
+ "../firefox",
+ "homebrew/cask/firefox",
+ "fire fox",
+ "firefox;open",
+ "firefox\n--debug",
+ String(repeating: "a", count: 129)
+ ]
+
+ valid.forEach { XCTAssertTrue(ApplicationUpdater.isValidCaskIdentifier($0), $0) }
+ invalid.forEach { XCTAssertFalse(ApplicationUpdater.isValidCaskIdentifier($0), $0) }
+ }
+
+ func testParserRejectsUnsafeCaskIdentifier() {
+ let json = #"{"casks":[{"name":"../firefox","installed_versions":["1"],"current_version":"2","pinned":false}]}"#
+
+ XCTAssertThrowsError(try ApplicationUpdater.parseOutdatedCasks(json)) { error in
+ XCTAssertEqual(error as? ApplicationUpdaterError, .invalidCaskIdentifier("../firefox"))
+ }
+ }
+
+ func testParserRejectsDuplicateCaskIdentifiers() {
+ let json = """
+ {
+ "casks": [
+ {"name":"firefox","installed_versions":["1"],"current_version":"2","pinned":false},
+ {"name":"firefox","installed_versions":["1"],"current_version":"2","pinned":false}
+ ]
+ }
+ """
+
+ XCTAssertThrowsError(try ApplicationUpdater.parseOutdatedCasks(json)) { error in
+ XCTAssertEqual(error as? ApplicationUpdaterError, .invalidResponse)
+ }
+ }
+
+ func testUpgradeArgumentsUseOptionTerminatorAndSeparateTokens() throws {
+ let arguments = try ApplicationUpdater.upgradeArguments(
+ caskTokens: ["firefox", "visual-studio-code"]
+ )
+
+ XCTAssertEqual(arguments, ["upgrade", "--cask", "--", "firefox", "visual-studio-code"])
+ }
+
+ func testUpgradeArgumentsRejectEmptyOrUnsafeSelections() {
+ XCTAssertThrowsError(try ApplicationUpdater.upgradeArguments(caskTokens: [])) { error in
+ XCTAssertEqual(error as? ApplicationUpdaterError, .noSelection)
+ }
+ XCTAssertThrowsError(
+ try ApplicationUpdater.upgradeArguments(caskTokens: ["firefox", "--debug"])
+ ) { error in
+ XCTAssertEqual(error as? ApplicationUpdaterError, .invalidCaskIdentifier("--debug"))
+ }
+ }
+
+ func testBrewDiscoveryUsesOnlyTrustedPathsInPriorityOrder() {
+ var inspected: [String] = []
+ let url = ApplicationUpdater.findBrewExecutable { path in
+ inspected.append(path)
+ return path == "/usr/local/bin/brew"
+ }
+
+ XCTAssertEqual(url?.path, "/usr/local/bin/brew")
+ XCTAssertEqual(inspected, ApplicationUpdater.trustedBrewPaths)
+ }
+
+ func testProcessRunnerCapturesSuccessfulOutput() async throws {
+ let result = try await BrewProcessRunner.run(
+ executableURL: URL(fileURLWithPath: "/usr/bin/printf"),
+ arguments: ["hello"],
+ timeout: 2
+ )
+
+ XCTAssertEqual(result.status, 0)
+ XCTAssertEqual(String(decoding: result.stdout, as: UTF8.self), "hello")
+ XCTAssertTrue(result.stderr.isEmpty)
+ }
+
+ func testProcessRunnerReturnsNonzeroExitStatus() async throws {
+ let result = try await BrewProcessRunner.run(
+ executableURL: URL(fileURLWithPath: "/usr/bin/false"),
+ arguments: [],
+ timeout: 2
+ )
+
+ XCTAssertNotEqual(result.status, 0)
+ }
+
+ func testProcessRunnerTimesOut() async {
+ do {
+ _ = try await BrewProcessRunner.run(
+ executableURL: URL(fileURLWithPath: "/bin/sleep"),
+ arguments: ["5"],
+ timeout: 0.05
+ )
+ XCTFail("Expected timeout")
+ } catch {
+ XCTAssertEqual(error as? ApplicationUpdaterError, .timedOut)
+ }
+ }
+
+ func testProcessRunnerRejectsOutputBeyondCaptureLimit() async {
+ do {
+ _ = try await BrewProcessRunner.run(
+ executableURL: URL(fileURLWithPath: "/usr/bin/head"),
+ arguments: ["-c", "5000000", "/dev/zero"],
+ timeout: 5
+ )
+ XCTFail("Expected output limit error")
+ } catch {
+ XCTAssertEqual(error as? ApplicationUpdaterError, .outputLimitExceeded)
+ }
+ }
+
+ func testProcessRunnerRespondsToTaskCancellation() async {
+ let task = Task {
+ try await BrewProcessRunner.run(
+ executableURL: URL(fileURLWithPath: "/bin/sleep"),
+ arguments: ["5"],
+ timeout: 10
+ )
+ }
+
+ task.cancel()
+
+ do {
+ _ = try await task.value
+ XCTFail("Expected cancellation")
+ } catch {
+ XCTAssertTrue(error is CancellationError)
+ }
+ }
+}
diff --git a/PureMacTests/CleaningEngineTests.swift b/PureMacTests/CleaningEngineTests.swift
new file mode 100644
index 0000000..5529d89
--- /dev/null
+++ b/PureMacTests/CleaningEngineTests.swift
@@ -0,0 +1,150 @@
+import XCTest
+@testable import PureMac
+
+final class CleaningEngineTests: XCTestCase {
+ private let fileManager = FileManager.default
+ private var fixtureRoot: URL!
+ private var savedExclusions: [String]?
+
+ override func setUpWithError() throws {
+ try super.setUpWithError()
+ savedExclusions = UserDefaults.standard.stringArray(forKey: CleanupExclusions.defaultsKey)
+ UserDefaults.standard.set([], forKey: CleanupExclusions.defaultsKey)
+ fixtureRoot = fileManager.homeDirectoryForCurrentUser
+ .appendingPathComponent("Library/Caches/PureMacTests-\(UUID().uuidString)")
+ try fileManager.createDirectory(at: fixtureRoot, withIntermediateDirectories: true)
+ }
+
+ override func tearDownWithError() throws {
+ if let fixtureRoot {
+ try? fileManager.removeItem(at: fixtureRoot)
+ }
+ if let savedExclusions {
+ UserDefaults.standard.set(savedExclusions, forKey: CleanupExclusions.defaultsKey)
+ } else {
+ UserDefaults.standard.removeObject(forKey: CleanupExclusions.defaultsKey)
+ }
+ try super.tearDownWithError()
+ }
+
+ func testMissingFileIsHandledWithoutClaimingFreedSpace() async {
+ let path = fixtureRoot.appendingPathComponent("already-gone").path
+ let item = makeItem(path: path, size: 4096)
+
+ let result = await CleaningEngine().cleanItems([item]) { _ in }
+
+ XCTAssertTrue(result.cleanedPaths.contains(path))
+ XCTAssertEqual(result.itemsCleaned, 0)
+ XCTAssertEqual(result.freedSpace, 0)
+ XCTAssertTrue(result.errors.isEmpty)
+ }
+
+ func testProgressAdvancesAfterDeletionFinishes() async throws {
+ let file = fixtureRoot.appendingPathComponent("progress.bin")
+ try Data(repeating: 1, count: 4096).write(to: file)
+ let observed = expectation(description: "progress")
+
+ let result = await CleaningEngine().cleanItems([makeItem(path: file.path, size: 4096)]) { progress in
+ XCTAssertEqual(progress, 1)
+ XCTAssertFalse(FileManager.default.fileExists(atPath: file.path))
+ observed.fulfill()
+ }
+
+ await fulfillment(of: [observed], timeout: 1)
+ XCTAssertEqual(result.itemsCleaned, 1)
+ XCTAssertEqual(result.freedSpace, 4096)
+ }
+
+ func testSymlinkIsRefusedWithoutDeletingItsTarget() async throws {
+ let target = fixtureRoot.appendingPathComponent("target.bin")
+ let link = fixtureRoot.appendingPathComponent("linked.bin")
+ try Data(repeating: 2, count: 4096).write(to: target)
+ try fileManager.createSymbolicLink(at: link, withDestinationURL: target)
+
+ let result = await CleaningEngine().cleanItems([makeItem(path: link.path, size: 4096)]) { _ in }
+
+ XCTAssertTrue(fileManager.fileExists(atPath: target.path))
+ XCTAssertEqual(
+ try fileManager.attributesOfItem(atPath: link.path)[.type] as? FileAttributeType,
+ .typeSymbolicLink
+ )
+ XCTAssertFalse(result.cleanedPaths.contains(link.path))
+ XCTAssertTrue(result.errors.contains { $0.localizedCaseInsensitiveContains("symlink") })
+ }
+
+ func testSymlinkedParentIsRefusedWithoutDeletingItsTarget() async throws {
+ let targetDirectory = fixtureRoot.appendingPathComponent("target-directory")
+ let target = targetDirectory.appendingPathComponent("target.bin")
+ let linkedDirectory = fixtureRoot.appendingPathComponent("linked-directory")
+ try fileManager.createDirectory(at: targetDirectory, withIntermediateDirectories: true)
+ try Data(repeating: 4, count: 4096).write(to: target)
+ try fileManager.createSymbolicLink(at: linkedDirectory, withDestinationURL: targetDirectory)
+ let linkedTarget = linkedDirectory.appendingPathComponent("target.bin")
+
+ let result = await CleaningEngine().cleanItems([makeItem(path: linkedTarget.path, size: 4096)]) { _ in }
+
+ XCTAssertTrue(fileManager.fileExists(atPath: target.path))
+ XCTAssertFalse(result.cleanedPaths.contains(linkedTarget.path))
+ XCTAssertTrue(result.errors.contains { $0.localizedCaseInsensitiveContains("symlink") })
+ }
+
+ func testDanglingSymlinkIsRefusedInsteadOfReportedAsCleaned() async throws {
+ let target = fixtureRoot.appendingPathComponent("missing-target.bin")
+ let link = fixtureRoot.appendingPathComponent("dangling.bin")
+ try fileManager.createSymbolicLink(at: link, withDestinationURL: target)
+
+ let result = await CleaningEngine().cleanItems([makeItem(path: link.path, size: 4096)]) { _ in }
+
+ XCTAssertEqual(
+ try fileManager.attributesOfItem(atPath: link.path)[.type] as? FileAttributeType,
+ .typeSymbolicLink
+ )
+ XCTAssertFalse(result.cleanedPaths.contains(link.path))
+ XCTAssertTrue(result.errors.contains { $0.localizedCaseInsensitiveContains("symlink") })
+ }
+
+ func testExcludedFileIsNeverDeleted() async throws {
+ let file = fixtureRoot.appendingPathComponent("excluded.bin")
+ try Data(repeating: 3, count: 4096).write(to: file)
+ CleanupExclusions.add(file.path)
+
+ let result = await CleaningEngine().cleanItems([makeItem(path: file.path, size: 4096)]) { _ in }
+
+ XCTAssertTrue(fileManager.fileExists(atPath: file.path))
+ XCTAssertFalse(result.cleanedPaths.contains(file.path))
+ XCTAssertEqual(result.errors, ["Excluded from cleanup: excluded.bin"])
+ }
+
+ func testAppModifyingCategoriesNeverFallThroughToFileDeletion() async throws {
+ let app = fixtureRoot.appendingPathComponent("Protected.app")
+ let localization = fixtureRoot.appendingPathComponent("fr.lproj")
+ try fileManager.createDirectory(at: app, withIntermediateDirectories: true)
+ try fileManager.createDirectory(at: localization, withIntermediateDirectories: true)
+
+ let items = [
+ makeItem(path: app.path, size: 4096, category: .universalBinaries),
+ makeItem(path: localization.path, size: 4096, category: .languageFiles),
+ ]
+ let result = await CleaningEngine().cleanItems(items) { _ in }
+
+ XCTAssertTrue(fileManager.fileExists(atPath: app.path))
+ XCTAssertTrue(fileManager.fileExists(atPath: localization.path))
+ XCTAssertTrue(result.cleanedPaths.isEmpty)
+ XCTAssertEqual(result.errors.count, 2)
+ }
+
+ private func makeItem(
+ path: String,
+ size: Int64,
+ category: CleaningCategory = .userCache
+ ) -> CleanableItem {
+ CleanableItem(
+ name: (path as NSString).lastPathComponent,
+ path: path,
+ size: size,
+ category: category,
+ isSelected: true,
+ lastModified: nil
+ )
+ }
+}
diff --git a/PureMacTests/CleanupExclusionsTests.swift b/PureMacTests/CleanupExclusionsTests.swift
new file mode 100644
index 0000000..607b5d3
--- /dev/null
+++ b/PureMacTests/CleanupExclusionsTests.swift
@@ -0,0 +1,36 @@
+import XCTest
+@testable import PureMac
+
+final class CleanupExclusionsTests: XCTestCase {
+ func testExcludesChildrenAndParentDeletionButNotSiblings() {
+ let excluded = ["/Users/test/Library/Caches/App/keep"]
+ XCTAssertTrue(CleanupExclusions.excludes("/Users/test/Library/Caches/App", paths: excluded))
+ XCTAssertTrue(CleanupExclusions.excludes("/Users/test/Library/Caches/App/keep/file", paths: excluded))
+ XCTAssertFalse(CleanupExclusions.excludes("/Users/test/Library/Caches/Application", paths: excluded))
+ XCTAssertFalse(CleanupExclusions.excludes("/Users/test/Library/Caches/App/keep-other", paths: excluded))
+ XCTAssertFalse(CleanupExclusions.excludes("simctl-runtime:123", paths: excluded))
+ XCTAssertFalse(CleanupExclusions.excludes("", paths: excluded))
+ }
+
+ func testExclusionsPersistNormalizedUniqueAbsolutePaths() throws {
+ let name = "PureMacTests.Exclusions.\(UUID().uuidString)"
+ let defaults = try XCTUnwrap(UserDefaults(suiteName: name))
+ defer { defaults.removePersistentDomain(forName: name) }
+ CleanupExclusions.add("/fixtures/data/../keep", in: defaults)
+ CleanupExclusions.add("/fixtures/keep", in: defaults)
+ CleanupExclusions.add("relative", in: defaults)
+ XCTAssertEqual(CleanupExclusions.paths(in: defaults), ["/fixtures/keep"])
+ }
+
+ func testSymlinkAliasCannotBypassExclusion() throws {
+ let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
+ defer { try? FileManager.default.removeItem(at: root) }
+ let actual = root.appendingPathComponent("actual")
+ try FileManager.default.createDirectory(at: actual, withIntermediateDirectories: true)
+ let alias = root.appendingPathComponent("alias")
+ try FileManager.default.createSymbolicLink(at: alias, withDestinationURL: actual)
+ XCTAssertTrue(CleanupExclusions.excludes(alias.appendingPathComponent("file").path, paths: [actual.path]))
+ XCTAssertTrue(CleanupExclusions.excludes(actual.path, paths: [alias.path]))
+ }
+}
diff --git a/PureMacTests/CleanupReviewTests.swift b/PureMacTests/CleanupReviewTests.swift
new file mode 100644
index 0000000..ac9d664
--- /dev/null
+++ b/PureMacTests/CleanupReviewTests.swift
@@ -0,0 +1,29 @@
+import XCTest
+@testable import PureMac
+
+final class CleanupReviewTests: XCTestCase {
+ func testCombinedFiltersUseNameOrPathSizeAndAge() {
+ let now = Date(timeIntervalSince1970: 1_800_000_000)
+ let old = now.addingTimeInterval(-90 * 86_400)
+ let items = [
+ item("Archive", path: "/work/project/archive", size: 2_000_000_000, date: old),
+ item("PROJECT", size: 1_500_000_000, date: now),
+ item("project", size: 5, date: old),
+ item("project", size: 3_000_000_000, date: nil)
+ ]
+ let filter = CleanupReviewFilter(query: " Project ", size: .gigabyte1, age: .month)
+ XCTAssertEqual(filter.apply(to: items, now: now).map(\.id), [items[0].id])
+ }
+
+ func testSortUsesStableTiesAndUnknownDatesLast() {
+ let a = item("Alpha", size: 100, date: Date(timeIntervalSince1970: 1))
+ let b = item("Beta", size: 100, date: nil)
+ let c = item("Charlie", size: 200, date: Date(timeIntervalSince1970: 2))
+ XCTAssertEqual(CleanupReviewFilter().apply(to: [b, c, a]).map(\.name), ["Charlie", "Alpha", "Beta"])
+ XCTAssertEqual(CleanupReviewFilter(order: .oldest).apply(to: [b, c, a]).map(\.name), ["Alpha", "Charlie", "Beta"])
+ }
+
+ private func item(_ name: String, path: String = "/fixture", size: Int64, date: Date?) -> CleanableItem {
+ CleanableItem(name: name, path: path, size: size, category: .largeFiles, isSelected: false, lastModified: date)
+ }
+}
diff --git a/PureMacTests/DuplicateFinderTests.swift b/PureMacTests/DuplicateFinderTests.swift
new file mode 100644
index 0000000..b203c5c
--- /dev/null
+++ b/PureMacTests/DuplicateFinderTests.swift
@@ -0,0 +1,215 @@
+import Foundation
+import Darwin
+import XCTest
+@testable import PureMac
+
+final class DuplicateFinderTests: XCTestCase {
+ private var temporaryFolders: [URL] = []
+
+ override func tearDownWithError() throws {
+ for folder in temporaryFolders {
+ try? FileManager.default.removeItem(at: folder)
+ }
+ temporaryFolders = []
+ try super.tearDownWithError()
+ }
+
+ func testScanGroupsOnlyByteIdenticalFiles() async throws {
+ let folder = try makeTemporaryFolder()
+ try write("same payload", to: folder.appendingPathComponent("A.txt"))
+ try write("same payload", to: folder.appendingPathComponent("B.txt"))
+ try write("different!!!", to: folder.appendingPathComponent("C.txt"))
+
+ let result = try await DuplicateFinder().scan(folder: folder)
+
+ XCTAssertEqual(result.groups.count, 1)
+ XCTAssertEqual(Set(result.groups[0].files.map(\.url.lastPathComponent)), ["A.txt", "B.txt"])
+ XCTAssertEqual(result.groups[0].reclaimableSize, 12)
+ XCTAssertEqual(result.filesInspected, 3)
+ }
+
+ func testScanDoesNotCountHardLinksAsRecoverableCopies() async throws {
+ let folder = try makeTemporaryFolder()
+ let original = folder.appendingPathComponent("original.bin")
+ let hardLink = folder.appendingPathComponent("hard-link.bin")
+ let independentCopy = folder.appendingPathComponent("copy.bin")
+ try write("identical hard-link payload", to: original)
+ try FileManager.default.linkItem(at: original, to: hardLink)
+ try write("identical hard-link payload", to: independentCopy)
+
+ let result = try await DuplicateFinder().scan(folder: folder)
+
+ XCTAssertEqual(result.groups.count, 1)
+ XCTAssertEqual(result.groups[0].files.count, 2)
+ XCTAssertEqual(result.skippedFiles.filter { $0.reason == .hardLink }.count, 1)
+ XCTAssertEqual(result.groups[0].reclaimableSize, 27)
+ }
+
+ func testScanSkipsSymbolicLinksPackagesAndCloudPlaceholders() async throws {
+ let folder = try makeTemporaryFolder()
+ let source = folder.appendingPathComponent("source.data")
+ let copy = folder.appendingPathComponent("copy.data")
+ let symlink = folder.appendingPathComponent("linked.data")
+ let package = folder.appendingPathComponent("Archive.app", isDirectory: true)
+ try write("duplicate", to: source)
+ try write("duplicate", to: copy)
+ try FileManager.default.createSymbolicLink(at: symlink, withDestinationURL: source)
+ try FileManager.default.createDirectory(at: package, withIntermediateDirectories: true)
+ try write("duplicate", to: package.appendingPathComponent("hidden.data"))
+ try write("duplicate", to: folder.appendingPathComponent("pending.icloud"))
+
+ let result = try await DuplicateFinder().scan(folder: folder)
+
+ XCTAssertEqual(result.groups.count, 1)
+ XCTAssertEqual(Set(result.groups[0].files.map(\.url.lastPathComponent)), ["source.data", "copy.data"])
+ XCTAssertTrue(result.skippedFiles.contains { $0.url == symlink && $0.reason == .symbolicLink })
+ XCTAssertTrue(result.skippedFiles.contains { $0.url == package && $0.reason == .package })
+ XCTAssertTrue(result.skippedFiles.contains { $0.url.lastPathComponent == "pending.icloud" && $0.reason == .cloudPlaceholder })
+ XCTAssertFalse(result.groups.flatMap(\.files).contains { $0.url.path.contains("Archive.app/") })
+ }
+
+ func testDatalessFileFlagIsRecognizedWithoutReadingFileContents() {
+ XCTAssertTrue(DuplicateFinder.isDatalessFile(flags: UInt32(SF_DATALESS)))
+ XCTAssertTrue(DuplicateFinder.isDatalessFile(flags: UInt32(SF_DATALESS) | UInt32(UF_HIDDEN)))
+ XCTAssertFalse(DuplicateFinder.isDatalessFile(flags: UInt32(UF_HIDDEN)))
+ }
+
+ func testMutationAfterScanStopsTrashAction() async throws {
+ let folder = try makeTemporaryFolder()
+ let first = folder.appendingPathComponent("first.txt")
+ let second = folder.appendingPathComponent("second.txt")
+ try write("same bytes", to: first)
+ try write("same bytes", to: second)
+ let result = try await DuplicateFinder().scan(folder: folder)
+ let group = try XCTUnwrap(result.groups.first)
+ let selected = try XCTUnwrap(group.files.first { $0.url != group.keeper.url })
+ try write("new content", to: selected.url)
+ let finder = DuplicateFinder(trashHandler: { _ in
+ XCTFail("Trash must not be called after a file changes")
+ })
+
+ do {
+ _ = try await finder.moveToTrash(group: group, selectedIDs: [selected.url])
+ XCTFail("Expected changed-file validation to fail")
+ } catch let error as DuplicateFinderError {
+ guard case .fileChanged = error else {
+ return XCTFail("Unexpected error: \(error)")
+ }
+ }
+ XCTAssertTrue(FileManager.default.fileExists(atPath: selected.url.path))
+ XCTAssertTrue(FileManager.default.fileExists(atPath: group.keeper.url.path))
+ }
+
+ func testChangedKeeperStopsTrashAction() async throws {
+ let folder = try makeTemporaryFolder()
+ try write("keeper bytes", to: folder.appendingPathComponent("first.txt"))
+ try write("keeper bytes", to: folder.appendingPathComponent("second.txt"))
+ let result = try await DuplicateFinder().scan(folder: folder)
+ let group = try XCTUnwrap(result.groups.first)
+ let selected = try XCTUnwrap(group.files.first { $0.url != group.keeper.url })
+ try write("keeper moved", to: group.keeper.url)
+ let finder = DuplicateFinder(trashHandler: { _ in
+ XCTFail("Trash must not be called when the keeper changes")
+ })
+
+ do {
+ _ = try await finder.moveToTrash(group: group, selectedIDs: [selected.url])
+ XCTFail("Expected keeper validation to fail")
+ } catch let error as DuplicateFinderError {
+ guard case .keeperChanged = error else {
+ return XCTFail("Unexpected error: \(error)")
+ }
+ }
+ XCTAssertTrue(FileManager.default.fileExists(atPath: selected.url.path))
+ XCTAssertTrue(FileManager.default.fileExists(atPath: group.keeper.url.path))
+ }
+
+ func testKeeperCannotBeSelectedForTrash() async throws {
+ let folder = try makeTemporaryFolder()
+ try write("protected", to: folder.appendingPathComponent("first.txt"))
+ try write("protected", to: folder.appendingPathComponent("second.txt"))
+ let result = try await DuplicateFinder().scan(folder: folder)
+ let group = try XCTUnwrap(result.groups.first)
+ let finder = DuplicateFinder(trashHandler: { _ in
+ XCTFail("Trash must not be called for the protected copy")
+ })
+
+ do {
+ _ = try await finder.moveToTrash(group: group, selectedIDs: [group.keeper.url])
+ XCTFail("Expected protected-copy validation to fail")
+ } catch let error as DuplicateFinderError {
+ guard case .invalidSelection(let path) = error else {
+ return XCTFail("Unexpected error: \(error)")
+ }
+ XCTAssertEqual(path, group.keeper.url.path)
+ }
+ XCTAssertTrue(FileManager.default.fileExists(atPath: group.keeper.url.path))
+ }
+
+ func testPathReplacementImmediatelyBeforeTrashIsRejected() async throws {
+ let folder = try makeTemporaryFolder()
+ try write("race-safe", to: folder.appendingPathComponent("first.txt"))
+ try write("race-safe", to: folder.appendingPathComponent("second.txt"))
+ let result = try await DuplicateFinder().scan(folder: folder)
+ let group = try XCTUnwrap(result.groups.first)
+ let selected = try XCTUnwrap(group.files.first { $0.url != group.keeper.url })
+ let finder = DuplicateFinder(
+ trashHandler: { _ in XCTFail("A replaced path must never reach Trash") },
+ preTrashHandler: { url in try Data("intruder".utf8).write(to: url, options: .atomic) }
+ )
+
+ let report = try await finder.moveToTrash(group: group, selectedIDs: [selected.url])
+
+ XCTAssertTrue(report.trashedFiles.isEmpty)
+ XCTAssertEqual(report.failures.map(\.url), [selected.url])
+ XCTAssertTrue(FileManager.default.fileExists(atPath: selected.url.path))
+ XCTAssertTrue(FileManager.default.fileExists(atPath: group.keeper.url.path))
+ }
+
+ func testValidActionUsesTrashHandlerAndKeepsOriginal() async throws {
+ let folder = try makeTemporaryFolder()
+ try write("safe copy", to: folder.appendingPathComponent("first.txt"))
+ try write("safe copy", to: folder.appendingPathComponent("second.txt"))
+ let result = try await DuplicateFinder().scan(folder: folder)
+ let group = try XCTUnwrap(result.groups.first)
+ let selected = try XCTUnwrap(group.files.first { $0.url != group.keeper.url })
+ let recorder = URLRecorder()
+ let finder = DuplicateFinder(trashHandler: { recorder.append($0) })
+
+ let report = try await finder.moveToTrash(group: group, selectedIDs: [selected.url])
+
+ XCTAssertEqual(report.trashedFiles.map(\.url), [selected.url])
+ XCTAssertTrue(report.failures.isEmpty)
+ XCTAssertEqual(recorder.urls, [selected.url])
+ XCTAssertTrue(FileManager.default.fileExists(atPath: group.keeper.url.path))
+ }
+
+ private func makeTemporaryFolder() throws -> URL {
+ let folder = FileManager.default.temporaryDirectory
+ .appendingPathComponent("PureMac-DuplicateFinderTests-\(UUID().uuidString)", isDirectory: true)
+ try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
+ temporaryFolders.append(folder)
+ return folder
+ }
+
+ private func write(_ string: String, to url: URL) throws {
+ try XCTUnwrap(string.data(using: .utf8)).write(to: url, options: .atomic)
+ }
+}
+
+private final class URLRecorder: @unchecked Sendable {
+ private let lock = NSLock()
+ private var storage: [URL] = []
+
+ var urls: [URL] {
+ lock.lock()
+ defer { lock.unlock() }
+ return storage
+ }
+
+ func append(_ url: URL) {
+ lock.lock()
+ storage.append(url)
+ lock.unlock()
+ }
+}
diff --git a/PureMacTests/NodeCachePathTests.swift b/PureMacTests/NodeCachePathTests.swift
new file mode 100644
index 0000000..8302104
--- /dev/null
+++ b/PureMacTests/NodeCachePathTests.swift
@@ -0,0 +1,113 @@
+import XCTest
+@testable import PureMac
+
+final class NodeCachePathTests: XCTestCase {
+ func testApprovedManagerRootsRemainNarrow() {
+ let home = "/Users/example"
+
+ XCTAssertEqual(
+ ScanEngine.approvedNodeCacheRoots(for: .npm, home: home),
+ ["/Users/example/.npm", "/Users/example/Library/Caches/npm"]
+ )
+ XCTAssertEqual(
+ ScanEngine.approvedNodeCacheRoots(for: .yarn, home: home),
+ ["/Users/example/Library/Caches/Yarn", "/Users/example/.cache/yarn"]
+ )
+ XCTAssertEqual(
+ ScanEngine.approvedNodeCacheRoots(for: .pnpm, home: home),
+ [
+ "/Users/example/Library/pnpm/store",
+ "/Users/example/.local/share/pnpm/store",
+ "/Users/example/.pnpm-store",
+ "/Users/example/.cache/pnpm",
+ ]
+ )
+ }
+
+ func testValidationAcceptsOnlyManagerRootOrDescendant() {
+ let home = "/Users/example"
+
+ XCTAssertEqual(
+ ScanEngine.validatedNodeCachePath(
+ "/Users/example/.npm/_cacache",
+ manager: .npm,
+ home: home
+ ),
+ "/Users/example/.npm/_cacache"
+ )
+ XCTAssertEqual(
+ ScanEngine.validatedNodeCachePath(
+ "/Users/example/Library/pnpm/store/v10",
+ manager: .pnpm,
+ home: home
+ ),
+ "/Users/example/Library/pnpm/store/v10"
+ )
+ XCTAssertNil(
+ ScanEngine.validatedNodeCachePath(
+ "/Users/example/.npm",
+ manager: .pnpm,
+ home: home
+ )
+ )
+ }
+
+ func testValidationRejectsBroadParentsRelativePathsAndTraversal() {
+ let home = "/Users/example"
+ let rejected = [
+ "/",
+ home,
+ "~/.npm",
+ "/Users/example/Library/Application Support",
+ "/Users/example/Library/Application Support/.cache",
+ "/Users/example/.cache",
+ "/Users/example/.npm/../../Library/Application Support",
+ "/Users/example/.npm\n/Library",
+ ]
+
+ for candidate in rejected {
+ XCTAssertNil(
+ ScanEngine.validatedNodeCachePath(candidate, manager: .npm, home: home),
+ candidate
+ )
+ }
+ }
+
+ func testValidationRejectsSymlinkEscapingApprovedRoot() throws {
+ let fileManager = FileManager.default
+ let base = fileManager.temporaryDirectory
+ .appendingPathComponent(UUID().uuidString, isDirectory: true)
+ let homeURL = base.appendingPathComponent("home", isDirectory: true)
+ let cacheURL = homeURL.appendingPathComponent(".npm", isDirectory: true)
+ let outsideURL = base.appendingPathComponent("outside", isDirectory: true)
+ let aliasURL = cacheURL.appendingPathComponent("redirect", isDirectory: true)
+ try fileManager.createDirectory(at: cacheURL, withIntermediateDirectories: true)
+ try fileManager.createDirectory(at: outsideURL, withIntermediateDirectories: true)
+ try fileManager.createSymbolicLink(at: aliasURL, withDestinationURL: outsideURL)
+ defer { try? fileManager.removeItem(at: base) }
+
+ let home = homeURL.resolvingSymlinksInPath().path
+ XCTAssertNil(
+ ScanEngine.validatedNodeCachePath(
+ aliasURL.path,
+ manager: .npm,
+ home: home
+ )
+ )
+ }
+
+ func testPruningKeepsCanonicalParentAndRemovesDuplicateDescendants() {
+ let paths = [
+ "/Users/example/.npm/_cacache",
+ "/Users/example/Library/Caches/npm",
+ "/Users/example/.npm",
+ "/Users/example/.npm",
+ "/Users/example/Library/Caches/npm/content-v2",
+ ]
+
+ XCTAssertEqual(
+ ScanEngine.prunedNodeCachePaths(paths),
+ ["/Users/example/.npm", "/Users/example/Library/Caches/npm"]
+ )
+ }
+}
diff --git a/PureMacTests/PerformanceInspectorTests.swift b/PureMacTests/PerformanceInspectorTests.swift
new file mode 100644
index 0000000..07b5a8f
--- /dev/null
+++ b/PureMacTests/PerformanceInspectorTests.swift
@@ -0,0 +1,138 @@
+import XCTest
+@testable import PureMac
+
+final class PerformanceInspectorTests: XCTestCase {
+ func testParseLaunchItemUsesProgramArgumentsAndActualFlags() throws {
+ let plist = """
+ <?xml version="1.0" encoding="UTF-8"?>
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+ <plist version="1.0">
+ <dict>
+ <key>Label</key><string>com.example.sync</string>
+ <key>ProgramArguments</key>
+ <array>
+ <string>/Applications/Example.app/Contents/MacOS/helper</string>
+ <string>--background</string>
+ </array>
+ <key>RunAtLoad</key><true/>
+ <key>KeepAlive</key><dict><key>SuccessfulExit</key><false/></dict>
+ <key>StartInterval</key><integer>300</integer>
+ <key>Disabled</key><true/>
+ </dict>
+ </plist>
+ """
+ let url = URL(fileURLWithPath: "/Users/example/Library/LaunchAgents/com.example.sync.plist")
+
+ let item = try PerformanceInspector.parseLaunchItem(
+ data: Data(plist.utf8),
+ sourceURL: url,
+ domain: .userAgent
+ )
+
+ XCTAssertEqual(item.label, "com.example.sync")
+ XCTAssertEqual(item.program, "/Applications/Example.app/Contents/MacOS/helper")
+ XCTAssertEqual(item.arguments, ["--background"])
+ XCTAssertEqual(item.domain, .userAgent)
+ XCTAssertTrue(item.isDisabled)
+ XCTAssertEqual(item.triggers, ["At login", "Conditional keep alive", "Every 300 seconds"])
+ XCTAssertEqual(item.sourceURL, url)
+ }
+
+ func testParseLaunchItemPrefersDeclaredProgramAndFallsBackToFilenameLabel() throws {
+ let value: [String: Any] = [
+ "Program": "/usr/local/bin/example-helper",
+ "ProgramArguments": ["--mode", "quiet"],
+ "WatchPaths": ["/Users/example/Library/Application Support/Example"],
+ ]
+ let data = try PropertyListSerialization.data(
+ fromPropertyList: value,
+ format: .binary,
+ options: 0
+ )
+ let url = URL(fileURLWithPath: "/Library/LaunchDaemons/com.example.helper.plist")
+
+ let item = try PerformanceInspector.parseLaunchItem(
+ data: data,
+ sourceURL: url,
+ domain: .systemDaemon
+ )
+
+ XCTAssertEqual(item.label, "com.example.helper")
+ XCTAssertEqual(item.program, "/usr/local/bin/example-helper")
+ XCTAssertEqual(item.arguments, ["--mode", "quiet"])
+ XCTAssertEqual(item.triggers, ["Watches paths"])
+ XCTAssertFalse(item.isDisabled)
+ }
+
+ func testParseLaunchItemRejectsNonDictionaryPropertyList() throws {
+ let data = try PropertyListSerialization.data(
+ fromPropertyList: ["one", "two"],
+ format: .xml,
+ options: 0
+ )
+
+ XCTAssertThrowsError(
+ try PerformanceInspector.parseLaunchItem(
+ data: data,
+ sourceURL: URL(fileURLWithPath: "/tmp/example.plist"),
+ domain: .userAgent
+ )
+ ) { error in
+ XCTAssertEqual(error as? PerformanceInspectorError, .invalidPropertyList)
+ }
+ }
+
+ func testParseTimeMachineSnapshotsClassifiesAndSortsKnownDates() throws {
+ let output = """
+ Snapshots for disk /:
+ com.apple.TimeMachine.2026-09-12-090011.local
+ com.apple.os.update-1234567890ABCDEF
+ com.apple.TimeMachine.2026-09-14-143015.local
+ custom.snapshot
+ """
+
+ let snapshots = PerformanceInspector.parseTimeMachineSnapshots(output)
+
+ XCTAssertEqual(snapshots.count, 4)
+ XCTAssertEqual(snapshots[0].identifier, "com.apple.TimeMachine.2026-09-14-143015.local")
+ XCTAssertEqual(snapshots[0].kind, .timeMachine)
+ XCTAssertNotNil(snapshots[0].date)
+ XCTAssertEqual(snapshots[1].identifier, "com.apple.TimeMachine.2026-09-12-090011.local")
+ XCTAssertEqual(snapshots[2].identifier, "com.apple.os.update-1234567890ABCDEF")
+ XCTAssertEqual(snapshots[2].kind, .systemUpdate)
+ XCTAssertNil(snapshots[2].date)
+ XCTAssertEqual(snapshots[3].kind, .local)
+ }
+
+ func testParseTimeMachineSnapshotsIgnoresBlankAndHeaderLines() {
+ XCTAssertTrue(PerformanceInspector.parseTimeMachineSnapshots("Snapshots for disk /:\n\n").isEmpty)
+ }
+
+ func testDeletionTimestampAllowsOnlyVerifiedTimeMachineSnapshots() {
+ let valid = PerformanceSnapshot(
+ identifier: "com.apple.TimeMachine.2026-09-14-143015.local",
+ kind: .timeMachine,
+ date: nil
+ )
+ let update = PerformanceSnapshot(
+ identifier: "com.apple.os.update-123456",
+ kind: .systemUpdate,
+ date: nil
+ )
+ let injected = PerformanceSnapshot(
+ identifier: "com.apple.TimeMachine.2026-09-14-143015;reboot.local",
+ kind: .timeMachine,
+ date: nil
+ )
+ let invalidDate = PerformanceSnapshot(
+ identifier: "com.apple.TimeMachine.2026-99-99-999999.local",
+ kind: .timeMachine,
+ date: nil
+ )
+
+ XCTAssertEqual(PerformanceInspector.deletionTimestamp(for: valid), "2026-09-14-143015")
+ XCTAssertNil(PerformanceInspector.deletionTimestamp(for: update))
+ XCTAssertNil(PerformanceInspector.deletionTimestamp(for: injected))
+ XCTAssertNil(PerformanceInspector.deletionTimestamp(for: invalidDate))
+ }
+}
diff --git a/PureMacTests/ProtectionAuditTests.swift b/PureMacTests/ProtectionAuditTests.swift
new file mode 100644
index 0000000..fa1d5ad
--- /dev/null
+++ b/PureMacTests/ProtectionAuditTests.swift
@@ -0,0 +1,234 @@
+import Foundation
+import XCTest
+@testable import PureMac
+
+final class ProtectionAuditTests: XCTestCase {
+ func testParsesEnabledAndDisabledGatekeeperStates() {
+ XCTAssertEqual(
+ ProtectionAudit.parse(.gatekeeper, result: result(stdout: "assessments enabled")).status,
+ .enabled
+ )
+ XCTAssertEqual(
+ ProtectionAudit.parse(.gatekeeper, result: result(stdout: "assessments disabled")).status,
+ .disabled
+ )
+ }
+
+ func testParsesFileVaultFirewallAndSIPStates() {
+ XCTAssertEqual(
+ ProtectionAudit.parse(.fileVault, result: result(stdout: "FileVault is On.")).status,
+ .enabled
+ )
+ XCTAssertEqual(
+ ProtectionAudit.parse(.fileVault, result: result(stdout: "FileVault is Off.")).status,
+ .disabled
+ )
+ XCTAssertEqual(
+ ProtectionAudit.parse(.firewall, result: result(stdout: "Firewall is enabled. (State = 1)")).status,
+ .enabled
+ )
+ XCTAssertEqual(
+ ProtectionAudit.parse(.firewall, result: result(stdout: "Firewall is disabled. (State = 0)")).status,
+ .disabled
+ )
+ XCTAssertEqual(
+ ProtectionAudit.parse(
+ .systemIntegrityProtection,
+ result: result(stdout: "System Integrity Protection status: enabled.")
+ ).status,
+ .enabled
+ )
+ XCTAssertEqual(
+ ProtectionAudit.parse(
+ .systemIntegrityProtection,
+ result: result(stdout: "System Integrity Protection status: disabled.")
+ ).status,
+ .disabled
+ )
+ }
+
+ func testUnrecognizedOutputIsUnknown() {
+ let finding = ProtectionAudit.parse(
+ .systemIntegrityProtection,
+ result: result(stdout: "System Integrity Protection status: unknown (Custom Configuration).")
+ )
+
+ XCTAssertEqual(finding.status, .unknown)
+ XCTAssertEqual(finding.detail, "The system returned an unrecognized status.")
+ }
+
+ func testCommandFailureCannotBeReportedAsEnabled() {
+ let finding = ProtectionAudit.parse(
+ .gatekeeper,
+ result: ProtectionCommandResult(
+ exitCode: 1,
+ stdout: "assessments enabled",
+ stderr: "operation failed",
+ timedOut: false,
+ cancelled: false,
+ launchError: nil
+ )
+ )
+
+ XCTAssertEqual(finding.status, .unknown)
+ XCTAssertEqual(finding.detail, "PureMac could not read this setting.")
+ }
+
+ func testTimeoutIsUnknown() {
+ let finding = ProtectionAudit.parse(
+ .firewall,
+ result: ProtectionCommandResult(
+ exitCode: nil,
+ stdout: "",
+ stderr: "",
+ timedOut: true,
+ cancelled: false,
+ launchError: nil
+ )
+ )
+
+ XCTAssertEqual(finding.status, .unknown)
+ XCTAssertEqual(finding.detail, "The check timed out.")
+ }
+
+ func testAuditPreservesCheckOrder() async {
+ let xProtect = ProtectionFinding(
+ check: .xProtect,
+ status: .enabled,
+ detail: "Installed.",
+ version: "definitions 1"
+ )
+ let audit = ProtectionAudit(
+ commandExecutor: { command in
+ switch command {
+ case .gatekeeper:
+ return ProtectionCommandResult(
+ exitCode: 0,
+ stdout: "assessments enabled",
+ stderr: "",
+ timedOut: false,
+ cancelled: false,
+ launchError: nil
+ )
+ case .fileVault:
+ return ProtectionCommandResult(
+ exitCode: 0,
+ stdout: "FileVault is On.",
+ stderr: "",
+ timedOut: false,
+ cancelled: false,
+ launchError: nil
+ )
+ case .firewall:
+ return ProtectionCommandResult(
+ exitCode: 0,
+ stdout: "Firewall is enabled. (State = 1)",
+ stderr: "",
+ timedOut: false,
+ cancelled: false,
+ launchError: nil
+ )
+ case .systemIntegrityProtection:
+ return ProtectionCommandResult(
+ exitCode: 0,
+ stdout: "System Integrity Protection status: enabled.",
+ stderr: "",
+ timedOut: false,
+ cancelled: false,
+ launchError: nil
+ )
+ }
+ },
+ xProtectInspector: { xProtect }
+ )
+
+ let snapshot = await audit.run()
+
+ XCTAssertEqual(snapshot.findings.map(\.check), ProtectionCheck.allCases)
+ XCTAssertTrue(snapshot.findings.allSatisfy { $0.status == .enabled })
+ }
+
+ func testCommandsUseFixedAbsoluteExecutablesWithoutAShell() {
+ let expected: [ProtectionCommand: (String, [String])] = [
+ .gatekeeper: ("/usr/sbin/spctl", ["--status"]),
+ .fileVault: ("/usr/bin/fdesetup", ["status"]),
+ .firewall: ("/usr/libexec/ApplicationFirewall/socketfilterfw", ["--getglobalstate"]),
+ .systemIntegrityProtection: ("/usr/bin/csrutil", ["status"])
+ ]
+
+ for command in ProtectionCommand.allCases {
+ XCTAssertEqual(command.executableURL.path, expected[command]?.0)
+ XCTAssertEqual(command.arguments, expected[command]?.1)
+ XCTAssertNotEqual(command.executableURL.path, "/bin/sh")
+ XCTAssertNotEqual(command.executableURL.path, "/bin/zsh")
+ }
+ }
+
+ func testRunnerPassesArgumentsDirectlyWithoutShellExpansion() async {
+ let request = ProtectionProcessRequest(
+ executableURL: URL(fileURLWithPath: "/usr/bin/printf"),
+ arguments: ["%s", "$(echo injected); *"]
+ )
+
+ let output = await ProtectionCommandRunner.run(request, timeout: 1)
+
+ XCTAssertTrue(output.succeeded)
+ XCTAssertEqual(output.stdout, "$(echo injected); *")
+ }
+
+ func testRunnerTimeoutIsBounded() async {
+ let request = ProtectionProcessRequest(
+ executableURL: URL(fileURLWithPath: "/bin/sleep"),
+ arguments: ["5"]
+ )
+ let start = Date()
+
+ let output = await ProtectionCommandRunner.run(request, timeout: 0.05)
+
+ XCTAssertTrue(output.timedOut)
+ XCTAssertLessThan(Date().timeIntervalSince(start), 1.5)
+ }
+
+ func testRunnerReturnsWhenADescendantKeepsOutputPipeOpen() async {
+ let request = ProtectionProcessRequest(
+ executableURL: URL(fileURLWithPath: "/bin/sh"),
+ arguments: ["-c", "/bin/sleep 2 & /usr/bin/printf done"]
+ )
+ let start = Date()
+
+ let output = await ProtectionCommandRunner.run(request, timeout: 1)
+
+ XCTAssertFalse(output.timedOut)
+ XCTAssertEqual(output.stdout, "done")
+ XCTAssertLessThan(Date().timeIntervalSince(start), 1.5)
+ }
+
+ func testCancellingRunnerStopsTheProcess() async {
+ let request = ProtectionProcessRequest(
+ executableURL: URL(fileURLWithPath: "/bin/sleep"),
+ arguments: ["5"]
+ )
+ let start = Date()
+ let task = Task {
+ await ProtectionCommandRunner.run(request, timeout: 10)
+ }
+
+ try? await Task.sleep(nanoseconds: 50_000_000)
+ task.cancel()
+ let output = await task.value
+
+ XCTAssertTrue(output.cancelled)
+ XCTAssertLessThan(Date().timeIntervalSince(start), 1.5)
+ }
+
+ private func result(stdout: String) -> ProtectionCommandResult {
+ ProtectionCommandResult(
+ exitCode: 0,
+ stdout: stdout,
+ stderr: "",
+ timedOut: false,
+ cancelled: false,
+ launchError: nil
+ )
+ }
+}
diff --git a/PureMacTests/SimilarPhotoFinderTests.swift b/PureMacTests/SimilarPhotoFinderTests.swift
new file mode 100644
index 0000000..e422f1a
--- /dev/null
+++ b/PureMacTests/SimilarPhotoFinderTests.swift
@@ -0,0 +1,148 @@
+import CoreGraphics
+import Foundation
+import ImageIO
+import UniformTypeIdentifiers
+import XCTest
+@testable import PureMac
+
+final class SimilarPhotoFinderTests: XCTestCase {
+ private var temporaryFolders: [URL] = []
+
+ override func tearDownWithError() throws {
+ for folder in temporaryFolders {
+ try? FileManager.default.removeItem(at: folder)
+ }
+ temporaryFolders = []
+ try super.tearDownWithError()
+ }
+
+ func testScanGroupsVisuallySimilarImagesAndLeavesDifferentImageOut() async throws {
+ let folder = try makeTemporaryFolder()
+ try writePatternImage(to: folder.appendingPathComponent("first.png"), variation: 0)
+ try writePatternImage(to: folder.appendingPathComponent("second.png"), variation: 1)
+ try writePatternImage(to: folder.appendingPathComponent("different.png"), variation: 2)
+
+ let result = try await SimilarPhotoFinder().scan(folder: folder)
+
+ XCTAssertEqual(result.groups.count, 1)
+ XCTAssertEqual(Set(result.groups[0].photos.map(\.url.lastPathComponent)), ["first.png", "second.png"])
+ XCTAssertEqual(result.photosAnalyzed, 3)
+ XCTAssertFalse(result.isPartial)
+ }
+
+ func testScanSkipsSymbolicLinksPackagesAndCloudPlaceholderFiles() async throws {
+ let folder = try makeTemporaryFolder()
+ let first = folder.appendingPathComponent("first.png")
+ let second = folder.appendingPathComponent("second.png")
+ let symlink = folder.appendingPathComponent("linked.png")
+ let package = folder.appendingPathComponent("Hidden.app", isDirectory: true)
+ try writePatternImage(to: first, variation: 0)
+ try writePatternImage(to: second, variation: 0)
+ try FileManager.default.createSymbolicLink(at: symlink, withDestinationURL: first)
+ try FileManager.default.createDirectory(at: package, withIntermediateDirectories: true)
+ try writePatternImage(to: package.appendingPathComponent("inside.png"), variation: 0)
+ try Data("placeholder".utf8).write(to: folder.appendingPathComponent("pending.icloud"))
+
+ let result = try await SimilarPhotoFinder().scan(folder: folder)
+
+ XCTAssertEqual(result.groups.count, 1)
+ XCTAssertEqual(Set(result.groups[0].photos.map(\.url.lastPathComponent)), ["first.png", "second.png"])
+ XCTAssertEqual(result.photosAnalyzed, 2)
+ XCTAssertGreaterThanOrEqual(result.skippedItems, 3)
+ }
+
+ func testPhotoLimitProducesExplicitPartialResult() async throws {
+ let folder = try makeTemporaryFolder()
+ try writePatternImage(to: folder.appendingPathComponent("one.png"), variation: 0)
+ try writePatternImage(to: folder.appendingPathComponent("two.png"), variation: 0)
+ try writePatternImage(to: folder.appendingPathComponent("three.png"), variation: 0)
+ let finder = SimilarPhotoFinder(limits: SimilarPhotoScanLimits(maxPhotos: 2, maxEntries: 100))
+
+ let result = try await finder.scan(folder: folder)
+
+ XCTAssertEqual(result.photosAnalyzed, 2)
+ XCTAssertTrue(result.photoLimitReached)
+ XCTAssertTrue(result.isPartial)
+ }
+
+ func testCancelledScanThrowsCancellationError() async throws {
+ let folder = try makeTemporaryFolder()
+ for index in 0..<20 {
+ try writePatternImage(to: folder.appendingPathComponent("image-\(index).png"), variation: 0)
+ }
+ let finder = SimilarPhotoFinder()
+ let task = Task {
+ try await finder.scan(folder: folder)
+ }
+ task.cancel()
+
+ do {
+ _ = try await task.value
+ XCTFail("Expected cancellation")
+ } catch is CancellationError {
+ }
+ }
+
+ private func makeTemporaryFolder() throws -> URL {
+ let folder = FileManager.default.temporaryDirectory
+ .appendingPathComponent("PureMac-SimilarPhotoFinderTests-\(UUID().uuidString)", isDirectory: true)
+ try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
+ temporaryFolders.append(folder)
+ return folder
+ }
+
+ private func writePatternImage(to url: URL, variation: Int) throws {
+ let width = 96
+ let height = 72
+ var pixels = [UInt8](repeating: 255, count: width * height * 4)
+
+ for y in 0..<height {
+ for x in 0..<width {
+ let offset = (y * width + x) * 4
+ switch variation {
+ case 2:
+ let light = ((x / 8) + (y / 8)).isMultiple(of: 2)
+ pixels[offset] = light ? 245 : 20
+ pixels[offset + 1] = light ? 210 : 35
+ pixels[offset + 2] = light ? 40 : 210
+ default:
+ pixels[offset] = UInt8(min(255, 35 + x * 2))
+ pixels[offset + 1] = UInt8(min(255, 55 + y * 2))
+ pixels[offset + 2] = 145
+ if variation == 1 && x > 82 && y > 60 {
+ pixels[offset] = 210
+ pixels[offset + 1] = 205
+ pixels[offset + 2] = 190
+ }
+ }
+ pixels[offset + 3] = 255
+ }
+ }
+
+ let data = Data(pixels)
+ guard let provider = CGDataProvider(data: data as CFData),
+ let image = CGImage(
+ width: width,
+ height: height,
+ bitsPerComponent: 8,
+ bitsPerPixel: 32,
+ bytesPerRow: width * 4,
+ space: CGColorSpaceCreateDeviceRGB(),
+ bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue),
+ provider: provider,
+ decode: nil,
+ shouldInterpolate: false,
+ intent: .defaultIntent
+ ),
+ let destination = CGImageDestinationCreateWithURL(
+ url as CFURL,
+ UTType.png.identifier as CFString,
+ 1,
+ nil
+ ) else {
+ return XCTFail("Could not create test image")
+ }
+ CGImageDestinationAddImage(destination, image, nil)
+ XCTAssertTrue(CGImageDestinationFinalize(destination))
+ }
+}
diff --git a/PureMacTests/StorageExplorerTests.swift b/PureMacTests/StorageExplorerTests.swift
new file mode 100644
index 0000000..7d53ede
--- /dev/null
+++ b/PureMacTests/StorageExplorerTests.swift
@@ -0,0 +1,143 @@
+import Darwin
+import XCTest
+@testable import PureMac
+
+final class StorageExplorerTests: XCTestCase {
+ private var temporaryRoot: URL!
+
+ override func setUpWithError() throws {
+ temporaryRoot = FileManager.default.temporaryDirectory
+ .appendingPathComponent("PureMacStorageExplorerTests-\(UUID().uuidString)", isDirectory: true)
+ try FileManager.default.createDirectory(at: temporaryRoot, withIntermediateDirectories: true)
+ }
+
+ override func tearDownWithError() throws {
+ if let temporaryRoot {
+ try? FileManager.default.removeItem(at: temporaryRoot)
+ }
+ temporaryRoot = nil
+ }
+
+ func testScanSortsImmediateEntriesAndAggregatesDescendants() async throws {
+ let nested = temporaryRoot.appendingPathComponent("Nested", isDirectory: true)
+ try FileManager.default.createDirectory(at: nested, withIntermediateDirectories: true)
+ try Data(repeating: 0x41, count: 1_200_000)
+ .write(to: nested.appendingPathComponent("large.bin"), options: .withoutOverwriting)
+ try Data(repeating: 0x42, count: 8_000)
+ .write(to: temporaryRoot.appendingPathComponent("small.bin"), options: .withoutOverwriting)
+
+ let result = try await StorageExplorer().scan(at: temporaryRoot)
+
+ XCTAssertEqual(result.rootURL, temporaryRoot.standardizedFileURL)
+ XCTAssertEqual(result.fileCount, 2)
+ XCTAssertEqual(result.directoryCount, 1)
+ XCTAssertEqual(result.entries.map(\.name), ["Nested", "small.bin"])
+ XCTAssertEqual(result.entries.reduce(Int64(0)) { $0 + $1.allocatedSize }, result.totalAllocatedSize)
+ XCTAssertGreaterThan(result.totalAllocatedSize, 0)
+ XCTAssertFalse(result.isPartial)
+ }
+
+ func testScanMeasuresPackagesAndSkipsSymbolicLinksAndDuplicateHardLinks() async throws {
+ let source = temporaryRoot.appendingPathComponent("source.bin")
+ let hardLink = temporaryRoot.appendingPathComponent("source-hardlink.bin")
+ try Data(repeating: 0x4A, count: 512_000).write(to: source, options: .withoutOverwriting)
+ try FileManager.default.linkItem(at: source, to: hardLink)
+
+ let outside = temporaryRoot.deletingLastPathComponent()
+ .appendingPathComponent("PureMacStorageExplorerOutside-\(UUID().uuidString)", isDirectory: true)
+ try FileManager.default.createDirectory(at: outside, withIntermediateDirectories: true)
+ defer { try? FileManager.default.removeItem(at: outside) }
+ try Data(repeating: 0x7F, count: 2_000_000)
+ .write(to: outside.appendingPathComponent("outside.bin"), options: .withoutOverwriting)
+ try FileManager.default.createSymbolicLink(
+ at: temporaryRoot.appendingPathComponent("linked-outside"),
+ withDestinationURL: outside
+ )
+
+ let package = temporaryRoot.appendingPathComponent("Excluded.app", isDirectory: true)
+ let contents = package.appendingPathComponent("Contents", isDirectory: true)
+ try FileManager.default.createDirectory(at: contents, withIntermediateDirectories: true)
+ try Data(repeating: 0x55, count: 1_000_000)
+ .write(to: contents.appendingPathComponent("payload.bin"), options: .withoutOverwriting)
+
+ let result = try await StorageExplorer().scan(at: temporaryRoot)
+
+ XCTAssertEqual(result.fileCount, 2)
+ XCTAssertEqual(result.directoryCount, 2)
+ XCTAssertEqual(result.skippedCount, 2)
+ XCTAssertEqual(result.entries.count, 2)
+ XCTAssertTrue(result.entries.contains { $0.name == "Excluded.app" })
+ XCTAssertEqual(result.entries.filter { $0.kind == .file }.count, 1)
+ XCTAssertEqual(result.entries.filter { $0.kind == .file && $0.allocatedSize > 0 }.count, 1)
+ let packageEntry = try XCTUnwrap(result.entries.first { $0.kind == .package })
+ XCTAssertGreaterThan(packageEntry.allocatedSize, 0)
+ XCTAssertFalse(packageEntry.isDirectory)
+ XCTAssertTrue(packageEntry.isPackage)
+ XCTAssertTrue(result.isPartial)
+ }
+
+ func testScanReportsAllocatedSizeInsteadOfLogicalSizeForSparseFile() async throws {
+ let sparseFile = temporaryRoot.appendingPathComponent("sparse.bin")
+ XCTAssertTrue(FileManager.default.createFile(atPath: sparseFile.path, contents: nil))
+ let handle = try FileHandle(forWritingTo: sparseFile)
+ try handle.truncate(atOffset: 64 * 1_024 * 1_024)
+ try handle.close()
+
+ let result = try await StorageExplorer().scan(at: temporaryRoot)
+ let entry = try XCTUnwrap(result.entries.first)
+
+ XCTAssertEqual(entry.allocatedSize, result.totalAllocatedSize)
+ XCTAssertLessThan(entry.allocatedSize, 64 * 1_024 * 1_024)
+ XCTAssertEqual(result.fileCount, 1)
+ }
+
+ func testScanMarksUnreadableDirectoryAsPartial() async throws {
+ let locked = temporaryRoot.appendingPathComponent("Locked", isDirectory: true)
+ try FileManager.default.createDirectory(at: locked, withIntermediateDirectories: true)
+ try Data(repeating: 0x33, count: 4_096)
+ .write(to: locked.appendingPathComponent("private.bin"), options: .withoutOverwriting)
+ XCTAssertEqual(chmod(locked.path, 0), 0)
+ defer { _ = chmod(locked.path, S_IRWXU) }
+
+ let result = try await StorageExplorer().scan(at: temporaryRoot)
+
+ XCTAssertEqual(result.inaccessibleCount, 1)
+ XCTAssertTrue(result.isPartial)
+ XCTAssertEqual(result.entries.first?.inaccessibleCount, 1)
+ }
+
+ func testCancelledTaskStopsTraversal() async throws {
+ for index in 0..<100 {
+ let url = temporaryRoot.appendingPathComponent("file-\(index).bin")
+ try Data(repeating: UInt8(index % 255), count: 4_096).write(to: url, options: .withoutOverwriting)
+ }
+
+ let explorer = StorageExplorer()
+ let task = Task {
+ try await explorer.scan(at: temporaryRoot)
+ }
+ task.cancel()
+
+ do {
+ _ = try await task.value
+ XCTFail("Expected scan cancellation")
+ } catch is CancellationError {
+ } catch {
+ XCTFail("Expected CancellationError, got \(error)")
+ }
+ }
+
+ func testRejectsSymbolicLinkAsScanRoot() async throws {
+ let target = temporaryRoot.appendingPathComponent("Target", isDirectory: true)
+ let link = temporaryRoot.appendingPathComponent("Target Link")
+ try FileManager.default.createDirectory(at: target, withIntermediateDirectories: true)
+ try FileManager.default.createSymbolicLink(at: link, withDestinationURL: target)
+
+ do {
+ _ = try await StorageExplorer().scan(at: link)
+ XCTFail("Expected symbolic-link rejection")
+ } catch let error as StorageExplorerError {
+ XCTAssertEqual(error, .symbolicLink(link.standardizedFileURL.path))
+ }
+ }
+}
diff --git a/README.md b/README.md
index 678bcdd..6073abc 100644
--- a/README.md
+++ b/README.md
@@ -1,9 +1,9 @@
<p align="center">
- <img src="screenshots/smart-care.png" alt="PureMac Smart Care - one scan covering 12 cleanup checks, with free-space meter" width="820">
+ <img src="screenshots/smart-care.png" alt="PureMac Smart Care - storage overview and cleanup review" width="820">
</p>
<p align="center">
- <img src="screenshots/scanning.png" alt="PureMac scanning - live progress with categories and sizes as they are found" width="820">
+ <img src="screenshots/smart-care-dark.png" alt="PureMac Smart Care in dark appearance" width="820">
</p>
<p align="center">
@@ -20,7 +20,7 @@
<p align="center">
<b>Reclaim your Mac.</b><br>
- Free, open-source uninstaller and cleaner for macOS. No subscription, no telemetry, no upsell.
+ Free, open-source Mac care: cleanup, app management, storage exploration, and system checks. No subscription or telemetry.
</p>
<p align="center">
@@ -104,11 +104,11 @@ See [`cli/README.md`](cli/README.md) for the full command reference.
A Mac cleaner asks for the deepest permission macOS grants - Full Disk Access - and then deletes your files. That demands a level of trust the category has spent twenty years burning. Here's the contract PureMac holds itself to, and you can verify every line of it in the source:
-- **Deletion behavior is explicit.** App-uninstaller flows attempt to move selected app files to the Trash. Dashboard/category cleanup, scheduled auto-clean, orphan removal, Trash emptying, Docker/Xcode runtime cleanup, administrator-authorized cleanup, and CLI cleanup can permanently delete data. Review selections carefully and use CLI dry runs.
+- **Deletion behavior is explicit.** App uninstalls, orphan removal, and exact-duplicate removal use the Trash at user level. Dashboard/category cleanup, scheduled auto-clean, Trash emptying, Docker/Xcode runtime cleanup, administrator-authorized removal, local snapshot deletion, and CLI cleanup can permanently delete data. Review selections carefully and use CLI dry runs.
- **No telemetry, ever.** No analytics, no crash reporting, no "anonymous usage stats," no network calls to us. The app doesn't know you exist.
- **No fake urgency.** No dramatized "47 GB of junk detected!" badge, no red alarm counters, no "your Mac is at risk." We show you neutral facts and let you decide.
- **No overpromising.** We don't claim to "reclaim purgeable space," "boost RAM," or "speed up your Mac" - things no app can reliably do. See the purgeable-space note below.
-- **Reviewable selection.** Dashboard/category cleanup and single-file app removal prompt before acting. Bulk app-file and orphan removal act on the explicit selection without another prompt. Scheduled auto-clean is unattended once enabled, and tool-backed rows such as Docker cleanup may not have a revealable path.
+- **Reviewable selection.** Manual cleanup, app-file removal, orphan removal, duplicate removal, and local snapshot deletion require confirmation. Cleanup filters show when selected items are hidden; select-visible controls affect only the rows on screen. Scheduled auto-clean remains unattended once enabled.
- **Auditable.** It's MIT. The exact code that decides what gets removed is in [`PureMac/Services`](PureMac/Services) and [`PureMac/Logic/Scanning`](PureMac/Logic/Scanning). Read it. Fork it. Ship your own.
If PureMac ever adds telemetry, a paywall on core features, or a fear-based scan, it will have become the thing it was built to replace. Hold us to this.
@@ -128,13 +128,13 @@ Most Mac cleaners are subscription apps that hide their disk usage behind a payw
## What it does
### App Uninstaller
-Discovers everything in `/Applications` and `~/Applications`, then uses a 10-level matching engine (bundle ID, team identifier, entitlements, Spotlight metadata, container discovery, company-name heuristics, partial path matches) to find every file the app dropped on your disk. Three sensitivity tiers - Strict, Enhanced, Deep - let you choose how aggressive that match is. Apple system apps are excluded from the uninstall list automatically. You can also right-click any app in Finder and choose **Services → Uninstall with PureMac** to jump straight into its related-files scan.
+Discovers everything in `/Applications` and `~/Applications`, then uses a 10-level matching engine (bundle ID, team identifier, entitlements, Spotlight metadata, container discovery, company-name heuristics, partial path matches) to find related files on your disk. Matching is heuristic, so review the results before removal. Three sensitivity tiers - Strict, Enhanced, Deep - let you choose how aggressive that match is. Apple system apps are excluded from the uninstall list automatically. You can also right-click any app in Finder and choose **Services → Uninstall with PureMac** to jump straight into its related-files scan.
### Orphan Finder
Walks `~/Library` and surfaces files left behind by apps that no longer exist on disk. The matcher compares against bundle identifiers and normalized names of every installed app, so a leftover `~/Library/Containers/com.foo.bar` from an app you deleted in 2022 shows up clearly.
### System Cleaner
-Smart Scan runs every category in parallel. Each category is its own deliberate scanner:
+Smart Scan checks each category in sequence and reports progress as files are found. You can stop a scan and keep the categories already completed:
- **System Junk** - system caches, logs, temp files
- **User Cache** - dynamically discovered, no hardcoded app list
@@ -143,24 +143,44 @@ Smart Scan runs every category in parallel. Each category is its own deliberate
- **Trash Bins** - empties all bins, including external volumes
- **Large & Old Files** - >100 MB or older than 1 year (never auto-selected)
- **Xcode Junk** - DerivedData, Archives, simulator caches, and downloaded simulator runtimes (deleted via `simctl runtime delete`; never auto-selected)
-- **Brew Cache** - respects custom `HOMEBREW_CACHE`
+- **Brew Cache** - Homebrew download caches within approved cache locations
- **Node Cache** - npm, yarn classic, pnpm content-addressable store
- **Docker Cache** - images, containers, build cache
> **On "purgeable space":** PureMac shows your APFS purgeable space in the storage breakdown for transparency, but it deliberately does **not** list it as junk to delete. Purgeable space is reserved and reclaimed by macOS itself - no third-party app can reliably free it, and even the Finder's purgeable figure is known to be inaccurate. Cleaners that claim to "reclaim purgeable space" are overpromising. We'd rather be honest than impressive.
+### Storage and file review
+
+**Space Explorer** measures the allocated space inside a folder you choose. Drill into directories, compare their sizes, and reveal an item in Finder. Packages are measured without exposing their contents as navigable folders. Skipped and inaccessible items are reported.
+
+**Duplicate Finder** groups files with matching sizes and SHA-256 content hashes. Hard links are not counted as separate recoverable copies. Every group keeps one protected copy; selected extras move to the Trash only after confirmation and a fresh identity/content check. Emptying the Trash is a separate step.
+
+**Similar Photos** compares image thumbnails using perceptual hashes, color, and aspect ratio. Review likely matches side by side and reveal them in Finder. Similarity is an estimate, so this tool does not remove photos. Each scan checks up to 500 images and 10,000 directory entries, with a visible notice when a limit is reached. Photo libraries, app packages, symbolic links, and cloud-only files are skipped.
+
+Cleanup results support name/path search, size and age filters, sorting, and selection of visible rows. Right-click a cleanup result to always exclude its path. Exclusions also protect containing folders from cleanup and apply to scheduled runs; manage them in Settings.
+
+### Protection and performance
+
+**Protection** checks Gatekeeper, FileVault, the application firewall, System Integrity Protection, and installed XProtect metadata. A failed or unavailable check stays unknown. It also provides shortcuts to privacy and permission settings. This is a configuration audit, not an antivirus or malware scanner.
+
+**Performance** shows CPU and memory information, lists third-party launch-agent/daemon definitions, and lists local snapshots. A launch definition is not proof that a process is running. You can open Login Items or Activity Monitor and delete a specific Time Machine local snapshot after confirmation. Snapshot sizes are not estimated, and system update snapshots cannot be removed here.
+
+### App updates
+
+Check for updates to Homebrew-managed cask apps and choose which ones to upgrade. PureMac runs Homebrew with analytics disabled and shows command failures. These actions use the network and Homebrew's package sources. Apps installed outside Homebrew are not covered; an App Store shortcut is provided for those managed by Apple.
+
### Scheduled Cleaning
Optional. Configurable interval (hourly to monthly), with auto-clean threshold so background runs only fire when there's something meaningful to remove.
## Permissions
-PureMac needs **Full Disk Access** to read the locations macOS hides from every app by default - Mail downloads, Safari data, the TCC database, protected app containers. Without it, the cleanup categories miss roughly 70% of what they could find and app uninstalls leave behind everything in `~/Library/Containers`.
+PureMac needs **Full Disk Access** to read the locations macOS hides from every app by default - Mail downloads, Safari data, the TCC database, protected app containers. Without it, some cleanup categories and app-container scans will be incomplete. The locations available depend on your macOS version and permissions.
The first-launch onboarding walks you through granting it with an animated preview of the exact toggle you need to flip. If you skip it, the dashboard surfaces a single-click "Set up" pill. If a cleanup fails because of a permission issue, PureMac opens System Settings, reveals its bundle in Finder so you can drag it into the FDA list, polls the permission state every second, and auto-retries the failed batch the moment you grant access. You never have to re-select anything.
What PureMac does *not* do:
- It does not collect telemetry, crash reports, or usage analytics.
-- It does not require a network connection to operate.
+- Local scans and cleanup work offline. Checking for or installing Homebrew app updates requires a network connection.
- It does not upload or transmit scanned paths or deleted data.
## Troubleshooting
@@ -179,21 +199,23 @@ Give it a minute to re-seed, then open PureMac once. If it still sticks, a resta
## Screenshots
-| Smart Care | Live scan |
+| Smart Care | Dark appearance |
|---|---|
-| ![Smart Care](screenshots/smart-care.png) | ![Live scan](screenshots/scanning.png) |
+| ![Smart Care](screenshots/smart-care.png) | ![Dark appearance](screenshots/smart-care-dark.png) |
-| Scan breakdown | App Uninstaller |
+| Space Explorer | Duplicate Finder |
|---|---|
-| ![Scan breakdown](screenshots/breakdown.png) | ![App Uninstaller](screenshots/app-uninstaller.png) |
+| ![Space Explorer](screenshots/space-explorer.png) | ![Duplicate Finder](screenshots/duplicate-finder.png) |
-| System Junk | Xcode Junk |
+| Protection | App Updates |
|---|---|
-| ![System Junk](screenshots/system-junk.png) | ![Xcode Junk](screenshots/xcode-junk.png) |
+| ![Protection](screenshots/protection.png) | ![App Updates](screenshots/app-updates.png) |
-| User Cache | Onboarding |
-|---|---|
-| ![User Cache](screenshots/user-cache.png) | ![Onboarding](screenshots/onboarding.png) |
+<p align="center">
+ <img src="screenshots/similar-photos.png" alt="Similar Photos comparing sample images for manual review" width="820">
+</p>
+
+Screenshots show the running macOS app. File tools use sample files and images.
## Architecture
@@ -202,12 +224,13 @@ PureMac/
Logic/Scanning/ - Heuristic scan engine, locations database, conditions
Logic/Utilities/ - Structured logging
Models/ - Data models, typed errors
- Services/ - Scan engine, cleaning engine, permission coordinator, scheduler
+ Services/ - Scanning, cleanup, file tools, protection, updates, scheduler
ViewModels/ - Centralized app state
Views/ - Native SwiftUI views
Apps/ - App uninstaller views
Components/ - Shared components (FDA demo, permission sheet, theme)
Orphans/ - Orphan finder
+ Tools/ - Space, duplicates, similar photos, protection, performance, updates
Settings/ - Native Form-based settings
```
@@ -225,7 +248,7 @@ Key components:
- Core-cleaner allow-list: `CleaningEngine` refuses a user-level path outside its explicit safe roots. App-uninstaller and orphan flows use their own policies.
- Admin escalation is gated by its own explicit allow-list; root-owned items outside those permitted roots are refused.
- System app protection: Apple's bundles cannot be uninstalled, regardless of selection.
-- Confirmation varies by workflow: dashboard/category cleanup and single-file app removal prompt; bulk app-file and orphan removal act on the explicit selection without another prompt; scheduled auto-clean is unattended after enablement.
+- Manual destructive workflows require confirmation. Exact duplicates retain one protected copy and recheck files before moving extras to the Trash. Scheduled auto-clean remains unattended after enablement.
If you find a vulnerability, please open a private security advisory rather than a public issue.
diff --git a/project.yml b/project.yml
index 8aff5ff..f11cc71 100644
--- a/project.yml
+++ b/project.yml
@@ -23,8 +23,8 @@ settings:
CODE_SIGN_ENTITLEMENTS: "PureMac/PureMac.entitlements"
INFOPLIST_FILE: "PureMac/Info.plist"
PRODUCT_BUNDLE_IDENTIFIER: "com.puremac.app"
- MARKETING_VERSION: "2.9.8"
- CURRENT_PROJECT_VERSION: "28"
+ MARKETING_VERSION: "3.0.0"
+ CURRENT_PROJECT_VERSION: "29"
GENERATE_INFOPLIST_FILE: "NO"
ASSETCATALOG_COMPILER_APPICON_NAME: "AppIcon"
COMBINE_HIDPI_IMAGES: "YES"
diff --git a/screenshots/app-updates.png b/screenshots/app-updates.png
new file mode 100644
index 0000000..45130d8
Binary files /dev/null and b/screenshots/app-updates.png differ
diff --git a/screenshots/duplicate-finder.png b/screenshots/duplicate-finder.png
new file mode 100644
index 0000000..63193e7
Binary files /dev/null and b/screenshots/duplicate-finder.png differ
diff --git a/screenshots/protection.png b/screenshots/protection.png
new file mode 100644
index 0000000..f681849
Binary files /dev/null and b/screenshots/protection.png differ
diff --git a/screenshots/similar-photos.png b/screenshots/similar-photos.png
new file mode 100644
index 0000000..041bcab
Binary files /dev/null and b/screenshots/similar-photos.png differ
diff --git a/screenshots/smart-care-dark.png b/screenshots/smart-care-dark.png
new file mode 100644
index 0000000..b9ee52e
Binary files /dev/null and b/screenshots/smart-care-dark.png differ
diff --git a/screenshots/smart-care.png b/screenshots/smart-care.png
index 540cee3..dfd890a 100644
Binary files a/screenshots/smart-care.png and b/screenshots/smart-care.png differ
diff --git a/screenshots/space-explorer.png b/screenshots/space-explorer.png
new file mode 100644
index 0000000..9c93ba5
Binary files /dev/null and b/screenshots/space-explorer.png differ
diff --git a/scripts/SECRETS.md b/scripts/SECRETS.md
index 726fcbe..bb0d7e5 100644
--- a/scripts/SECRETS.md
+++ b/scripts/SECRETS.md
@@ -8,7 +8,7 @@ The pipeline uses an **App Store Connect API key** for notarization (modern,
no rotation, scoped to one team) instead of the legacy
`APPLE_ID + app-specific-password` flow.
-## Required secrets (6)
+## Required secrets (7)
| Secret | Source | Notes |
|--------|--------|-------|
@@ -19,11 +19,13 @@ no rotation, scoped to one team) instead of the legacy
| `APP_STORE_CONNECT_ISSUER_ID` | UUID from <https://appstoreconnect.apple.com/access/integrations/api> | e.g. `5de3898a-cd31-4061-850f-ae17b389e46a` |
| `APP_STORE_CONNECT_PRIVATE_KEY` | Full contents of the `.p8` file (`-----BEGIN PRIVATE KEY-----` ... `-----END PRIVATE KEY-----`) | Paste raw, including the BEGIN/END lines |
-## Optional secret (1)
+## Homebrew tap access
| Secret | Source | Notes |
|--------|--------|-------|
-| `HOMEBREW_TAP_TOKEN` | Fine-grained PAT with `Contents: read+write` on `momenbasel/homebrew-tap` | Without this the tap formula bump step is skipped (in-repo `homebrew/puremac.rb` still bumps via the default `GITHUB_TOKEN`) |
+| `HOMEBREW_TAP_DEPLOY_KEY` | SSH private key for a write-enabled deploy key on `momenbasel/homebrew-tap` | Required by release preflight and the external tap update. The in-repo cask uses `GITHUB_TOKEN`. |
+
+The official `Homebrew/homebrew-cask` entry is updated separately through a cask bump pull request after the release is published.
## Extracting your Developer ID cert as a filtered `.p12`
@@ -97,8 +99,8 @@ gh secret set APP_STORE_CONNECT_KEY_ID --repo momenbasel/PureMac --body "5
gh secret set APP_STORE_CONNECT_ISSUER_ID --repo momenbasel/PureMac --body "5de3898a-cd31-4061-850f-ae17b389e46a"
gh secret set APP_STORE_CONNECT_PRIVATE_KEY --repo momenbasel/PureMac < ~/.appstoreconnect/private_keys/AuthKey_5G7R52L8RK.p8
-# Optional:
-gh secret set HOMEBREW_TAP_TOKEN --repo momenbasel/PureMac --body "<your fine-grained PAT>"
+# Required tap deploy key:
+gh secret set HOMEBREW_TAP_DEPLOY_KEY --repo momenbasel/PureMac < /path/to/tap-deploy-key
# Verify:
gh secret list --repo momenbasel/PureMac
@@ -117,15 +119,15 @@ rm -P ~/Desktop/PureMac-secrets/PureMac-DeveloperID.p12* \
Dry run first (build + sign + notarize, no upload, no homebrew bump):
```bash
-gh workflow run release.yml --repo momenbasel/PureMac -f version=2.2.0 -f dry_run=true
+gh workflow run release.yml --repo momenbasel/PureMac -f version=3.0.0 -f dry_run=true
gh run watch --repo momenbasel/PureMac
```
Real release (after dry run is green):
```bash
-git tag v2.2.0
-git push origin v2.2.0
+git tag v3.0.0
+git push origin v3.0.0
```
## What ships