Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
135 changes: 129 additions & 6 deletions PureMac.xcodeproj/project.pbxproj

Large diffs are not rendered by default.

116 changes: 116 additions & 0 deletions PureMac.xcodeproj/xcshareddata/xcschemes/PureMac.xcscheme
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1640"
version = "1.7">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES"
runPostActionsOnFailure = "NO">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "B19E38DEAA0144A77120F39C"
BuildableName = "PureMac.app"
BlueprintName = "PureMac"
ReferencedContainer = "container:PureMac.xcodeproj">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "NO"
buildForProfiling = "NO"
buildForArchiving = "NO"
buildForAnalyzing = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "FBA8B0DE95746207A043B802"
BuildableName = "PureMacTests.xctest"
BlueprintName = "PureMacTests"
ReferencedContainer = "container:PureMac.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"
onlyGenerateCoverageForSpecifiedTargets = "NO">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "B19E38DEAA0144A77120F39C"
BuildableName = "PureMac.app"
BlueprintName = "PureMac"
ReferencedContainer = "container:PureMac.xcodeproj">
</BuildableReference>
</MacroExpansion>
<Testables>
<TestableReference
skipped = "NO"
parallelizable = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "FBA8B0DE95746207A043B802"
BuildableName = "PureMacTests.xctest"
BlueprintName = "PureMacTests"
ReferencedContainer = "container:PureMac.xcodeproj">
</BuildableReference>
</TestableReference>
</Testables>
<CommandLineArguments>
</CommandLineArguments>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "B19E38DEAA0144A77120F39C"
BuildableName = "PureMac.app"
BlueprintName = "PureMac"
ReferencedContainer = "container:PureMac.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "B19E38DEAA0144A77120F39C"
BuildableName = "PureMac.app"
BlueprintName = "PureMac"
ReferencedContainer = "container:PureMac.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
56 changes: 56 additions & 0 deletions PureMac/Models/AppLanguage.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import Foundation

enum AppLanguage: String, CaseIterable, Identifiable {
case system = "system"
case english = "en"
case spanish = "es"
case japanese = "ja"
case arabic = "ar"
case portugueseBrazil = "pt-BR"
case simplifiedChinese = "zh-Hans"
case traditionalChinese = "zh-Hant"

static let preferenceKey = "settings.general.appLanguage"

var id: String { rawValue }

var displayName: String {
switch self {
case .system: return "System Default"
case .english: return "English"
case .spanish: return "Spanish"
case .japanese: return "Japanese"
case .arabic: return "Arabic"
case .portugueseBrazil: return "Portuguese (Brazil)"
case .simplifiedChinese: return "Chinese (Simplified)"
case .traditionalChinese: return "Chinese (Traditional)"
}
}

static var current: AppLanguage {
if let selectedLanguage = UserDefaults.standard.string(forKey: preferenceKey),
let language = AppLanguage(rawValue: selectedLanguage) {
return language
}

guard let bundleIdentifier = Bundle.main.bundleIdentifier,
let appDefaults = UserDefaults.standard.persistentDomain(forName: bundleIdentifier),
let preferredLanguages = appDefaults["AppleLanguages"] as? [String],
let preferredLanguage = preferredLanguages.first else {
return .system
}

let normalized = preferredLanguage.replacingOccurrences(of: "_", with: "-")
return allCases.first { $0.rawValue == normalized } ?? .system
}
}

enum AppLanguagePreferences {
static func apply(_ language: AppLanguage, defaults: UserDefaults = .standard) {
if language == .system {
defaults.removeObject(forKey: "AppleLanguages")
} else {
defaults.set([language.rawValue], forKey: "AppleLanguages")
}
}
}
80 changes: 57 additions & 23 deletions PureMac/ViewModels/AppState.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,11 @@ enum AppSection: Hashable {

@MainActor
final class AppState: ObservableObject {
typealias AppFileScanner = @MainActor (
_ app: InstalledApp,
_ locations: Locations,
_ completion: @escaping (Set<URL>) -> Void
) -> Void

// MARK: - Scan / Clean State

Expand Down Expand Up @@ -45,12 +50,15 @@ final class AppState: ObservableObject {
@Published var isScanningAppFiles: Bool = false
@Published var removalError: String?
@Published var removalNeedsFullDiskAccess = false
@Published var appFileScanLocationCount: Int = 0

// MARK: - Services

var scheduler = SchedulerService()
private let scanEngine = ScanEngine()
private let cleaningEngine = CleaningEngine()
private let locationsProvider: () -> Locations
private let appFileScanner: AppFileScanner

// MARK: - Computed

Expand All @@ -70,21 +78,37 @@ final class AppState: ObservableObject {
allResults.flatMap { $0.items }.filter { isItemSelected($0) }.reduce(0) { $0 + $1.size }
}

var currentAppFileSearchLocationCount: Int {
if isScanningAppFiles && appFileScanLocationCount > 0 {
return appFileScanLocationCount
}
return discoveredFiles.count
}

// MARK: - Init

init() {
loadDiskInfo()
checkFullDiskAccess()
loadInstalledApps()
scheduler.setTrigger { [weak self] in
await self?.runScheduledScan()
}
// Only arm the scheduler once onboarding has completed. Before the
// first launch the defaults plist may have been attacker-planted with
// autoClean=true - waiting for onboarding ensures a human consents to
// auto-clean before we start honoring it.
if UserDefaults.standard.bool(forKey: "PureMac.OnboardingComplete") {
scheduler.start()
init(
performStartupTasks: Bool = true,
locationsProvider: @escaping () -> Locations = Locations.init,
appFileScanner: @escaping AppFileScanner = AppState.defaultAppFileScanner
) {
self.locationsProvider = locationsProvider
self.appFileScanner = appFileScanner

if performStartupTasks {
loadDiskInfo()
checkFullDiskAccess()
loadInstalledApps()
scheduler.setTrigger { [weak self] in
await self?.runScheduledScan()
}
// Only arm the scheduler once onboarding has completed. Before
// the first launch the defaults plist may have been
// attacker-planted with autoClean=true; wait for human consent
// via onboarding.
if UserDefaults.standard.bool(forKey: "PureMac.OnboardingComplete") {
scheduler.start()
}
}
}

Expand All @@ -105,21 +129,15 @@ final class AppState: ObservableObject {
discoveredFiles = []
selectedFiles = []
isScanningAppFiles = true
let locations = Locations()
let appInfo = AppPathFinder.AppInfo(
appName: app.appName,
bundleIdentifier: app.bundleIdentifier,
path: app.path,
entitlements: nil,
teamIdentifier: nil
)
let finder = AppPathFinder(appInfo: appInfo, locations: locations)
finder.findPathsAsync { [weak self] urls in
let locations = locationsProvider()
appFileScanLocationCount = locations.appSearch.paths.count
appFileScanner(app, locations) { [weak self] urls in
guard let self else { return }
let sorted = urls.sorted { $0.path < $1.path }
self.discoveredFiles = sorted
self.selectedFiles = urls
self.isScanningAppFiles = false
self.appFileScanLocationCount = 0
}
}

Expand Down Expand Up @@ -762,4 +780,20 @@ final class AppState: ObservableObject {

UNUserNotificationCenter.current().add(request)
}

private static func defaultAppFileScanner(
app: InstalledApp,
locations: Locations,
completion: @escaping (Set<URL>) -> Void
) {
let appInfo = AppPathFinder.AppInfo(
appName: app.appName,
bundleIdentifier: app.bundleIdentifier,
path: app.path,
entitlements: nil,
teamIdentifier: nil
)
let finder = AppPathFinder(appInfo: appInfo, locations: locations)
finder.findPathsAsync(completion: completion)
}
}
35 changes: 29 additions & 6 deletions PureMac/Views/Apps/AppFilesView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ struct AppFilesView: View {

if !appState.discoveredFiles.isEmpty {
VStack(alignment: .trailing, spacing: 2) {
Text("\(appState.discoveredFiles.count) files")
Text(filesCountText(count: appState.discoveredFiles.count))
.font(.callout)
.foregroundStyle(.secondary)
Text(ByteCountFormatter.string(fromByteCount: totalSelectedSize, countStyle: .file))
Expand All @@ -46,8 +46,8 @@ struct AppFilesView: View {
if appState.isScanningAppFiles {
VStack(spacing: 12) {
Spacer()
ProgressView("Scanning for related files...")
Text("Checking \(appState.discoveredFiles.count) locations...")
ProgressView(LocalizedStringKey("Scanning for related files..."))
Text(checkingLocationsText(count: appState.currentAppFileSearchLocationCount))
.font(.caption)
.foregroundStyle(.secondary)
Spacer()
Expand All @@ -57,7 +57,9 @@ struct AppFilesView: View {
EmptyStateView(
"No Related Files",
systemImage: "checkmark.circle",
description: "No additional files found for \(app.appName)."
description: LocalizedStringKey(
String(format: String(localized: "No additional files found for %@."), app.appName)
)
)
} else {
List(appState.discoveredFiles, id: \.self) { fileURL in
Expand All @@ -81,7 +83,7 @@ struct AppFilesView: View {
Spacer()

if !appState.selectedFiles.isEmpty {
Button("Remove \(appState.selectedFiles.count) files (\(ByteCountFormatter.string(fromByteCount: totalSelectedSize, countStyle: .file)))", role: .destructive) {
Button(removeFilesLabel, role: .destructive) {
appState.removeSelectedFiles()
}
.buttonStyle(.borderedProminent)
Expand Down Expand Up @@ -116,6 +118,22 @@ struct AppFilesView: View {
}
}

private func filesCountText(count: Int) -> String {
String(format: String(localized: "%lld files"), Int64(count))
}

private func checkingLocationsText(count: Int) -> String {
String(format: String(localized: "Checking %lld locations..."), Int64(count))
}

private var removeFilesLabel: String {
String(
format: String(localized: "Remove %lld files (%@)"),
Int64(appState.selectedFiles.count),
ByteCountFormatter.string(fromByteCount: totalSelectedSize, countStyle: .file)
)
}

private func fileSelectionBinding(for url: URL) -> Binding<Bool> {
Binding(
get: { appState.selectedFiles.contains(url) },
Expand Down Expand Up @@ -223,7 +241,12 @@ struct FileRow: View {
.onHover { hovering in
withAnimation(.easeInOut(duration: 0.15)) { isHovering = hovering }
}
.alert("Remove \(fileURL.lastPathComponent)?", isPresented: $showConfirmation) {
.alert(
Text(
String(format: String(localized: "Remove %@?"), fileURL.lastPathComponent)
),
isPresented: $showConfirmation
) {
Button("Cancel", role: .cancel) {}
Button("Remove", role: .destructive) { onRemove() }
} message: {
Expand Down
Loading