Skip to content

armgit / peel

Public Imported from GitHub
0

Uninstall Mac apps with every file they leave behind, and see why each belongs. Free up space, fine-tune macOS, and set up Terminal.

Show iCloud Drive's downloads in the folders Finder shows them in

Țugui Dragoș1a64f59886bd
diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/SelectableRows.swift b/Packages/PeelCore/Sources/PeelCore/Removal/SelectableRows.swift
index 4549fe19..e0121770 100644
--- a/Packages/PeelCore/Sources/PeelCore/Removal/SelectableRows.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Removal/SelectableRows.swift
@@ -43,6 +43,25 @@ public struct SelectableRows<ID: Hashable> {
let recommended = Set(recommended)
return selectable.filter { !recommended.contains($0) && !selection.contains($0) }
}
+
+ /// What a box standing for every row shows, as a folder's box does for its files.
+ public func groupSelection(in selection: Set<ID>) -> GroupSelection {
+ if isNoneSelected(in: selection) { return .none }
+ return isAllSelected(in: selection) ? .all : .some
+ }
+
+ /// A click on that box: what Peel recommends goes in, or, once all of it is selected, every row comes out. A row
+ /// Peel doesn't recommend is selected only by its own box, or by Select All, which asks first.
+ public func clickingGroup(in selection: Set<ID>) -> Set<ID> {
+ recommended.allSatisfy(selection.contains) ? deselectingAll(in: selection) : selection.union(recommended)
+ }
+}
+
+/// How many of a group's rows are selected, which its box shows as off, mixed, or on.
+public enum GroupSelection: Sendable {
+ case none
+ case some
+ case all
}
/// The rows of every page a tool lists, for one Select menu over all of them.
diff --git a/Packages/PeelCore/Sources/PeelCore/Space/CloudFolders.swift b/Packages/PeelCore/Sources/PeelCore/Space/CloudFolders.swift
new file mode 100644
index 00000000..4d7aeab8
--- /dev/null
+++ b/Packages/PeelCore/Sources/PeelCore/Space/CloudFolders.swift
@@ -0,0 +1,65 @@
+public import Foundation
+internal import PeelPrivileged
+
+/// The downloads in one folder of iCloud, with the names Finder shows from iCloud Drive or the app's folder down.
+public struct CloudFolder: Sendable, Hashable, Identifiable {
+ public let url: URL
+ public let names: [String]
+ /// The biggest first.
+ public let files: [CloudFile]
+ public let size: Int64
+
+ public var id: URL { url }
+
+ init(url: URL, names: [String], files: [CloudFile]) {
+ self.url = url
+ self.names = names
+ self.files = files.sorted { $0.size > $1.size }
+ size = files.map(\.size).cappedSum
+ }
+
+ /// The folder with only those of its files in `urls`, as a search narrows it, or nil when it holds none of them.
+ public func keeping(_ urls: Set<URL>) -> CloudFolder? {
+ let kept = files.filter { urls.contains($0.url) }
+ return kept.isEmpty ? nil : CloudFolder(url: url, names: names, files: kept)
+ }
+
+ /// The biggest first, and by name between two of the same size, so the order holds from one scan to the next.
+ public static func ordered(_ folders: [CloudFolder]) -> [CloudFolder] {
+ folders.sorted { $0.size != $1.size ? $0.size > $1.size : $0.names.lexicographicallyPrecedes($1.names) }
+ }
+}
+
+extension CloudStorage {
+ /// `files` in the folders they sit in.
+ static func folders(of files: [CloudFile], home: URL) -> [CloudFolder] {
+ let root = home.appending(path: "Library/Mobile Documents", directoryHint: .isDirectory)
+ let grouped = Dictionary(grouping: files) {
+ PathPattern.comparablePath(of: $0.url.deletingLastPathComponent())
+ }
+ return CloudFolder.ordered(grouped.values.map { files in
+ let folder = files[0].url.deletingLastPathComponent()
+ let shown = names(of: folder, container: files[0].container, under: root)
+ return CloudFolder(url: folder, names: shown, files: files)
+ })
+ }
+
+ /// The container's name, then each folder's below it as Finder shows it. Finder shows an app's `Documents` as the
+ /// app's folder itself, so that name is left out.
+ static func names(of folder: URL, container: String, under root: URL) -> [String] {
+ let rootNames = PathComponents.of(PathPattern.comparablePath(of: root))
+ let names = PathComponents.of(PathPattern.comparablePath(of: folder))
+ guard names.count > rootNames.count, names.starts(with: rootNames) else { return [folder.lastPathComponent] }
+ var place = root.appending(path: names[rootNames.count], directoryHint: .isDirectory)
+ var shown = [container]
+ for (depth, name) in names.dropFirst(rootNames.count + 1).enumerated() {
+ place = place.appending(path: name, directoryHint: .isDirectory)
+ let isAnAppsDocuments = depth == 0 && names[rootNames.count] != "com~apple~CloudDocs"
+ && name.caseInsensitiveCompare("Documents") == .orderedSame
+ if !isAnAppsDocuments {
+ shown.append(FileManager.default.displayName(atPath: place.path(percentEncoded: false)))
+ }
+ }
+ return shown
+ }
+}
diff --git a/Packages/PeelCore/Sources/PeelCore/Space/CloudStorage.swift b/Packages/PeelCore/Sources/PeelCore/Space/CloudStorage.swift
index cd3ba245..1827091e 100644
--- a/Packages/PeelCore/Sources/PeelCore/Space/CloudStorage.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Space/CloudStorage.swift
@@ -31,6 +31,8 @@ public struct CloudScan: Sendable {
/// How many downloads were left out because another copy on this Mac shares their space: each takes at least
/// `CloudStorage.minimumSize` on disk, yet removing it would free less.
public var sharedDownloads = 0
+ /// `files` in the folders Finder shows them in, the folder whose downloads take the most first.
+ public var folders: [CloudFolder] = []
}
/// A file that was not freed, and why.
@@ -123,7 +125,8 @@ public enum CloudStorage {
files: collected.files.sorted { $0.size > $1.size },
wasCutShort: finished == nil || collected.wasCutShort,
couldNotRead: collected.couldNotRead,
- sharedDownloads: collected.sharedDownloads
+ sharedDownloads: collected.sharedDownloads,
+ folders: folders(of: collected.files, home: home)
)
}
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/CloudStorageTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/CloudStorageTests.swift
index 573c3308..ecb2cfbd 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/CloudStorageTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/CloudStorageTests.swift
@@ -116,6 +116,39 @@ struct CloudStorageTests {
}
}
+ /// Each download goes in the folder Finder shows it in, named from iCloud Drive or the app's folder down, an
+ /// app's `Documents` shown as the app's folder itself. A search keeps a folder only with the files it found.
+ @Test func groupsTheDownloadsByTheFolderFinderShowsThemIn() throws {
+ let directory = try TemporaryDirectory()
+ let root = directory.url.appending(path: "Library/Mobile Documents", directoryHint: .isDirectory)
+ func file(_ path: String, _ size: Int64) throws -> CloudFile {
+ let url = try directory.file("Library/Mobile Documents/\(path)")
+ let container = CloudStorage.containerName(of: url, under: root)
+ return CloudFile(url: url, name: url.lastPathComponent, container: container, size: size, modified: nil)
+ }
+ let files = [
+ try file("com~apple~CloudDocs/Muzica/A.mp3", 20),
+ try file("iCloud~org~example~Notes/Documents/Letter.txt", 5),
+ try file("com~apple~CloudDocs/Archive.zip", 40),
+ try file("com~apple~CloudDocs/Muzica/B.mp3", 30),
+ try file("com~apple~CloudDocs/Documents/pfp/Me.png", 15),
+ try file("iCloud~org~example~Notes/documents/Drafts/Plan.txt", 2),
+ ]
+
+ let folders = CloudStorage.folders(of: files, home: directory.url)
+
+ #expect(folders.map(\.names) == [
+ ["iCloud Drive", "Muzica"], ["iCloud Drive"], ["iCloud Drive", "Documents", "pfp"], ["Notes"],
+ ["Notes", "Drafts"],
+ ])
+ #expect(folders.map(\.size) == [50, 40, 15, 5, 2])
+ #expect(folders.first?.files.map(\.name) == ["B.mp3", "A.mp3"])
+ let found = Set(files.filter { $0.name == "A.mp3" }.map(\.url))
+ #expect(folders.first?.keeping(found)?.files.map(\.name) == ["A.mp3"])
+ #expect(folders.first?.keeping(found)?.size == 20)
+ #expect(folders.last?.keeping(found) == nil)
+ }
+
/// Scans the real iCloud Drive of the Mac running the tests, which must work and change nothing.
@Test func readsThisMacWithoutFreeingAnything() async {
let scan = await CloudStorage.downloaded()
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/SelectableRowsTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/SelectableRowsTests.swift
index b2da28b6..12a1ff8e 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/SelectableRowsTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/SelectableRowsTests.swift
@@ -120,6 +120,27 @@ struct SelectableRowsTests {
#expect(!locked.isNoneSelected(in: [repository]))
}
+ /// One box for a group of rows, as a folder's for its files: it shows none, some, or every row selected. A click
+ /// adds what Peel recommends, or, once all of that is selected, takes the whole group out, so it never selects a
+ /// row Peel doesn't recommend.
+ @Test func aGroupsBoxSelectsWhatPeelRecommends() {
+ let group = SelectableRows(
+ rows: [cache, log, repository], selectable: [cache, log, repository], recommended: [cache, log]
+ )
+
+ #expect(group.groupSelection(in: [elsewhere]) == .none)
+ #expect(group.clickingGroup(in: [elsewhere]) == [cache, log, elsewhere])
+ #expect(group.groupSelection(in: [cache, log]) == .some)
+ #expect(group.clickingGroup(in: [cache, log, elsewhere]) == [elsewhere])
+ #expect(group.groupSelection(in: [repository]) == .some)
+ #expect(group.clickingGroup(in: [repository]) == [cache, log, repository])
+ #expect(group.groupSelection(in: [cache, log, repository]) == .all)
+ #expect(group.clickingGroup(in: [cache, log, repository]) == [])
+ let nothingRecommended = SelectableRows(rows: [repository], selectable: [repository], recommended: [])
+ #expect(nothingRecommended.clickingGroup(in: [repository]) == [])
+ #expect(nothingRecommended.clickingGroup(in: []) == [])
+ }
+
@Test func everyPageSelectsAsOneList() {
let first = SelectableRows(
rows: [repository, cache], selectable: [repository, cache], recommended: [cache]
diff --git a/Peel/Model/CloudLibrary.swift b/Peel/Model/CloudLibrary.swift
index ffa27f7e..610379ab 100644
--- a/Peel/Model/CloudLibrary.swift
+++ b/Peel/Model/CloudLibrary.swift
@@ -8,6 +8,7 @@ final class CloudLibrary {
didSet {
searchable = SearchableList(files ?? [], key: \.searchKey)
lastMatch = nil
+ lastFolders = nil
sizes = Dictionary((files ?? []).map { ($0.url, $0.size) }, uniquingKeysWith: { first, _ in first })
updateSelectedSize()
}
@@ -16,6 +17,11 @@ final class CloudLibrary {
/// The last search and what it found. A view asks again whenever it is drawn, a checkbox included.
@ObservationIgnored private var lastMatch: (query: String, files: [CloudFile])?
@ObservationIgnored private var sizes: [URL: Int64] = [:]
+ /// `files` in the folders Finder shows them in, from the same scan.
+ private(set) var folders: [CloudFolder] = [] {
+ didSet { lastFolders = nil }
+ }
+ @ObservationIgnored private var lastFolders: (query: String, folders: [CloudFolder])?
/// The scan this page runs, which a newer one or the Stop button ends.
let scanRun = ScanRun()
var isScanning: Bool { scanRun.isRunning }
@@ -45,6 +51,16 @@ final class CloudLibrary {
return found
}
+ /// The folders holding the files `query` finds, each with only those files; every folder for an empty one.
+ func folders(matching query: String) -> [CloudFolder] {
+ guard !query.isEmpty else { return folders }
+ if let lastFolders, lastFolders.query == query { return lastFolders.folders }
+ let found = Set(files(matching: query).map(\.url))
+ let narrowed = CloudFolder.ordered(folders.compactMap { $0.keeping(found) })
+ lastFolders = (query, narrowed)
+ return narrowed
+ }
+
private func updateSelectedSize() {
selectedSize = selectedURLs.map { sizes[$0] ?? 0 }.cappedSum
}
@@ -58,6 +74,7 @@ final class CloudLibrary {
await CloudStorage.downloaded(exclusions: ExclusionsStore.shared.exclusions, desktopPictures: pictures)
})
else { return }
+ folders = scan.folders
files = scan.files
wasCutShort = scan.wasCutShort
couldNotRead = scan.couldNotRead
diff --git a/Peel/Views/Cloud/CloudFolderRow.swift b/Peel/Views/Cloud/CloudFolderRow.swift
new file mode 100644
index 00000000..e6a2fc63
--- /dev/null
+++ b/Peel/Views/Cloud/CloudFolderRow.swift
@@ -0,0 +1,76 @@
+import PeelCore
+import SwiftUI
+
+/// A folder of the iCloud Drive page: its box selects the downloads in it Peel recommends, and the rest of the row
+/// opens the folder to list them under it.
+struct CloudFolderRow: View {
+ @Environment(\.accessibilityReduceMotion) private var reduceMotion
+ let folder: CloudFolder
+ let rows: SelectableRows<URL>
+ let isOpen: Bool
+ let isFirst: Bool
+ let selection: any RowSelection
+ let toggleOpen: () -> Void
+
+ private static let chevronWidth: CGFloat = 12
+ private static let spacing: CGFloat = 10
+ /// How far a file sits in from its folder, so its icon lines up under the folder's.
+ static let indent = chevronWidth + spacing
+
+ var body: some View {
+ let selected = selection.selectedURLs
+ let group = rows.groupSelection(in: selected)
+ HStack(alignment: .checkboxTitleLine, spacing: 5) {
+ NativeCheckbox(
+ // A click follows the folder's rule, whatever state AppKit moved the box to.
+ isOn: Binding(
+ get: { group == .all },
+ set: { _ in selection.select(rows.clickingGroup(in: selection.selectedURLs)) }
+ ),
+ label: spoken,
+ isMixed: group == .some
+ )
+ .disabled(rows.clickingGroup(in: selected) == selected)
+ Button {
+ withAnimation(reduceMotion ? nil : Motion.step.animation) { toggleOpen() }
+ } label: {
+ HStack(alignment: .firstTextBaseline, spacing: Self.spacing) {
+ Image(systemName: "chevron.right")
+ .font(.caption.weight(.bold))
+ .foregroundStyle(.secondary)
+ .rotationEffect(.degrees(isOpen ? 90 : 0))
+ .frame(width: Self.chevronWidth)
+ AppIcon(url: folder.url)
+ .frame(width: 18, height: 18)
+ // Centers the icon on the first line of text, as a file's row does.
+ .alignmentGuide(.firstTextBaseline) { $0[.bottom] - 4 }
+ .frame(width: 20)
+ // Finder's own separator between the folders of a path, the same in every language Peel speaks.
+ Text(verbatim: folder.names.joined(separator: " ▸ "))
+ .lineLimit(1)
+ .truncationMode(.middle)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .checkboxTitleLine()
+ Text("^[\(folder.files.count) file](inflect: true)")
+ .foregroundStyle(.secondary)
+ .lineLimit(1)
+ .fixedSize()
+ Text(folder.size.byteCount)
+ .monospacedDigit()
+ .foregroundStyle(.secondary)
+ .frame(width: RowColumns.size, alignment: .trailing)
+ }
+ .contentShape(.rect)
+ }
+ .buttonStyle(RowButtonStyle())
+ .accessibilityLabel(Text(verbatim: spoken))
+ .accessibilityValue(isOpen ? Text("Expanded") : Text("Collapsed"))
+ }
+ .tableRow(isFirst: isFirst)
+ }
+
+ private var spoken: String {
+ let count = String(inflecting: "^[\(folder.files.count) file](inflect: true)")
+ return (folder.names + [count, folder.size.byteCount]).joined(separator: ", ")
+ }
+}
diff --git a/Peel/Views/Cloud/CloudView.swift b/Peel/Views/Cloud/CloudView.swift
index aa2ad166..f526639b 100644
--- a/Peel/Views/Cloud/CloudView.swift
+++ b/Peel/Views/Cloud/CloudView.swift
@@ -14,9 +14,13 @@ struct CloudView: View {
@State private var leftAlone: LeftAlone?
@State private var isRescanning = false
@State private var searchText = ""
+ /// The folders opened while browsing. While a search runs, each folder with a match is open unless closed in it.
+ @State private var opened: Set<URL> = []
+ @State private var closedInSearch: Set<URL> = []
var body: some View {
let listed = cloud.files(matching: searchText)
+ let folders = cloud.folders(matching: searchText)
List {
header
.listRowSeparator(.hidden)
@@ -42,18 +46,33 @@ struct CloudView: View {
if !listed.isEmpty {
Section {
- ForEach(Array(listed.enumerated()), id: \.element.id) { index, file in
- RemovalRow(
- url: file.url,
- icon: .file(file.url),
- detail: file.isDesktopPicture
- ? "Not selected: it is the desktop picture, which macOS keeps open while it is shown, so its download can’t be removed now."
- : nil,
- size: file.size,
+ ForEach(Array(folders.enumerated()), id: \.element.id) { index, folder in
+ let open = isOpen(folder)
+ CloudFolderRow(
+ folder: folder,
+ rows: selectableRows(folder.files),
+ isOpen: open,
isFirst: index == 0,
- hasNoteColumn: false,
- selection: cloud, isSelected: cloud.isSelected(file.url)
+ selection: cloud,
+ toggleOpen: { toggle(folder) }
)
+ if open {
+ ForEach(folder.files) { file in
+ RemovalRow(
+ url: file.url,
+ name: file.name,
+ icon: .file(file.url),
+ detail: file.isDesktopPicture
+ ? "Not selected: it is the desktop picture, which macOS keeps open while it is shown, so its download can’t be removed now."
+ : nil,
+ size: file.size,
+ hasNoteColumn: false,
+ selection: cloud, isSelected: cloud.isSelected(file.url)
+ )
+ .padding(.leading, CloudFolderRow.indent)
+ }
+ .listRowSeparator(.hidden)
+ }
}
.listRowSeparator(.hidden)
} header: {
@@ -63,14 +82,7 @@ struct CloudView: View {
"Once their downloads are removed, Finder still lists these files, with a cloud beside each name. Deleting a file is different: that removes it from iCloud and from your other devices, and Peel never does it here."
)
} actions: {
- SelectMenu(
- list: SelectableRows(
- rows: listed.map(\.url), selectable: listed.map(\.url),
- recommended: listed.filter { !$0.isDesktopPicture }.map(\.url)
- ),
- place: Text(Tool.cloud.title),
- selection: cloud
- )
+ SelectMenu(list: selectableRows(listed), place: Text(Tool.cloud.title), selection: cloud)
}
} footer: {
if cloud.wasCutShort || cloud.sharedDownloads > 0 {
@@ -182,6 +194,7 @@ struct CloudView: View {
await cloud.refresh()
}
.rescanOnExclusionChange("CloudView") { await cloud.refresh() }
+ .onChange(of: searchText) { closedInSearch = [] }
.task(id: freed) {
guard freed != nil else { return }
try? await Task.sleep(for: .seconds(3))
@@ -196,6 +209,27 @@ struct CloudView: View {
}
}
+ /// Every file a click can select, and those Peel recommends: all but the desktop picture, which macOS holds open.
+ private func selectableRows(_ files: [CloudFile]) -> SelectableRows<URL> {
+ SelectableRows(
+ rows: files.map(\.url),
+ selectable: files.map(\.url),
+ recommended: files.filter { !$0.isDesktopPicture }.map(\.url)
+ )
+ }
+
+ private func isOpen(_ folder: CloudFolder) -> Bool {
+ searchText.isEmpty ? opened.contains(folder.url) : !closedInSearch.contains(folder.url)
+ }
+
+ private func toggle(_ folder: CloudFolder) {
+ if searchText.isEmpty {
+ opened.formSymmetricDifference([folder.url])
+ } else {
+ closedInSearch.formSymmetricDifference([folder.url])
+ }
+ }
+
private func phase(listed: [CloudFile]) -> ScanPhase {
if cloud.files == nil { return cloud.scanRun.wasStopped ? .stopped : .scanning(.walk) }
if !searchText.isEmpty, cloud.files?.isEmpty == false, listed.isEmpty { return .message }
diff --git a/Peel/Views/NativeCheckbox.swift b/Peel/Views/NativeCheckbox.swift
index d84c1c27..084f72c7 100644
--- a/Peel/Views/NativeCheckbox.swift
+++ b/Peel/Views/NativeCheckbox.swift
@@ -9,6 +9,8 @@ struct NativeCheckbox: NSViewRepresentable {
let label: String
var help: String?
var hint: String?
+ /// Shows the box as mixed, as one standing for several rows does while only some of them are selected.
+ var isMixed = false
func makeCoordinator() -> Coordinator {
Coordinator(isOn: $isOn)
@@ -49,7 +51,8 @@ struct NativeCheckbox: NSViewRepresentable {
}
private func update(_ button: NSButton, in context: Context) {
- let state: NSControl.StateValue = isOn ? .on : .off
+ if button.allowsMixedState != isMixed { button.allowsMixedState = isMixed }
+ let state: NSControl.StateValue = isMixed ? .mixed : isOn ? .on : .off
if button.state != state { button.state = state }
let size = NSControl.ControlSize(context.environment.controlSize) ?? .regular
if button.controlSize != size { button.controlSize = size }
@@ -86,7 +89,8 @@ struct NativeCheckbox: NSViewRepresentable {
}
@objc func toggle(_ button: NSButton) {
- isOn.wrappedValue = button.state == .on
+ // A box that allows mixed goes from off to mixed on a click (`NSButton.h`), so only off reads as off.
+ isOn.wrappedValue = button.state != .off
}
}
}
diff --git a/Peel/Views/RemovalRow.swift b/Peel/Views/RemovalRow.swift
index efe44f0e..81de7819 100644
--- a/Peel/Views/RemovalRow.swift
+++ b/Peel/Views/RemovalRow.swift
@@ -7,6 +7,8 @@ struct RemovalRow: View {
}
let url: URL
+ /// The item's name, shown and spoken in place of its path when the row sits under its folder.
+ var name: String?
let icon: Icon
let detail: LocalizedStringResource?
/// The kind of item, shown in a column of its own. Tools with nothing to show there pass nil, and the
@@ -112,7 +114,7 @@ struct RemovalRow: View {
private var spokenItem: String {
let badge = badgeKind.map { String(localized: $0.title) }
let size = isMeasured ? size.byteCount : String(localized: "Unknown")
- return [url.abbreviatedPath, badge, kind.map { String(localized: $0) }, size]
+ return [name ?? url.abbreviatedPath, badge, kind.map { String(localized: $0) }, size]
.compactMap(\.self)
.joined(separator: ", ")
}
@@ -160,7 +162,7 @@ struct RemovalRow: View {
}
private var path: some View {
- Text(url.abbreviatedPath)
+ Text(name ?? url.abbreviatedPath)
.lineLimit(1)
.truncationMode(.middle)
.help(Text(verbatim: url.path(percentEncoded: false)))