SPB Git

Repository Public License

LargeFilesView.swift 7.3 KB 135 lines swift

1// ORIX Clean — App/Sources/Features/LargeFiles/LargeFilesView.swift2// Description: Largest files and folders with filters by size, age, type and name.3// Author: Simon-Pierre Boucher — contact@spboucher.ai4import ORIXCleanCore5import SwiftUI67struct LargeFilesView: View {8    @Environment(AppModel.self) private var model9    @AppStorage("density") private var densityName = Density.comfortable.rawValue10    @State private var mode = 011    @State private var minimumMB = 1.012    @State private var age = 013    @State private var category: FileCategory?14    @State private var name = ""15    @State private var includePackages = false16    @State private var lastUsed: [String: Date] = [:]1718    private var density: Density { Density(rawValue: densityName) ?? .comfortable }19    static let ages: [(Int, String)] = [(0, "Any age"), (30, "Not modified for 30 days"), (180, "Not modified for 6 months"), (365, "Not modified for 1 year"), (730, "Not modified for 2 years"), (-7, "Modified in the last 7 days")]2021    var body: some View {22        if let tree = model.tree {23            VStack(spacing: 0) {24                filters25                Divider()26                let hits = hits(tree)27                if hits.isEmpty {28                    EmptyState(symbol: "doc.viewfinder", title: L("Nothing matches"), message: L("No item of the scanned location passes these filters."))29                } else {30                    List {31                        Section(L("%@ items · %@ on disk", ByteFormat.count(hits.count), ByteFormat.string(hits.reduce(0) { $0 + tree[$1.node].allocatedSize }))) {32                            ForEach(hits) { h in row(h.node, tree) }33                        }34                    }35                    .listStyle(.inset)36                    .accessibilityIdentifier("large.list")37                }38                if age > 0 {39                    InfoBanner(text: L("“Not modified” is the modification date stored by the filesystem. It does not prove a file is unused: something you only read keeps its old date. The “last opened” date shown for some files comes from Spotlight, when it recorded one."))40                        .padding(ORIX.Space.s)41                }42            }43        } else {44            EmptyState(symbol: "doc.viewfinder", title: L("No scan yet"), message: L("Scan a folder or a volume to list its largest files and folders."),45                       actionTitle: L("Scan Home Folder")) { model.startScan(path: model.home) }46        }47    }4849    private var filters: some View {50        HStack(spacing: ORIX.Space.m) {51            Picker(L("Show"), selection: $mode) {52                Text(L("Files")).tag(0)53                Text(L("Folders")).tag(1)54            }.pickerStyle(.segmented).labelsHidden().frame(width: 150)55            HStack(spacing: 4) {56                Text(L("At least")).font(.callout)57                Slider(value: $minimumMB, in: 0 ... 3, step: 0.01) { Text(L("Minimum size")) }.labelsHidden().frame(width: 120)58                    .accessibilityValue(ByteFormat.string(minimumBytes))59                Text(ByteFormat.string(minimumBytes)).font(.callout.monospacedDigit()).frame(width: 70, alignment: .leading)60            }61            Picker(L("Age"), selection: $age) { ForEach(Self.ages, id: \.0) { Text(L($0.1)).tag($0.0) } }.labelsHidden().frame(width: 210).disabled(mode == 1)62            Picker(L("Type"), selection: $category) {63                Text(L("All types")).tag(FileCategory?.none)64                ForEach(FileCategory.allCases, id: \.self) { Text($0.title).tag(FileCategory?.some($0)) }65            }.labelsHidden().frame(width: 140).disabled(mode == 1)66            TextField(L("Name contains"), text: $name).textFieldStyle(.roundedBorder).frame(minWidth: 100, maxWidth: 180).disabled(mode == 1)67            Toggle(L("Inside packages"), isOn: $includePackages).toggleStyle(.checkbox).disabled(mode == 1)68                .help(L("Also list files inside applications, photo libraries and other packages"))69            Spacer()70        }71        .padding(.horizontal, ORIX.Space.m).padding(.vertical, ORIX.Space.s)72        .background(.bar)73    }7475    /// Slider position 0…3 maps to 1 MB … 1 GB on a log scale (0 = no minimum).76    private var minimumBytes: Int64 { minimumMB <= 0 ? 0 : Int64(pow(10, minimumMB) * 1_000_000 / 1) }7778    private func hits(_ tree: ScanTree) -> [FileHit] {79        _ = model.treeVersion80        if mode == 1 { return TreeQuery.largestFolders(in: tree, minimumSize: minimumBytes, limit: 300) }81        var f = FileFilter()82        f.minimumSize = minimumBytes83        if age > 0 { f.modifiedBefore = Date().addingTimeInterval(-Double(age) * 86400) }84        if age < 0 { f.modifiedAfter = Date().addingTimeInterval(Double(age) * 86400) }85        if let category { f.categories = [category] }86        f.nameContains = name87        f.includePackageContents = includePackages88        return TreeQuery.largestFiles(in: tree, filter: f, limit: 500)89    }9091    private func row(_ i: Int32, _ tree: ScanTree) -> some View {92        let n = tree[i]93        let path = tree.path(of: i)94        return HStack(spacing: ORIX.Space.s) {95            Checkbox(isOn: model.isSelected(path), label: L("Select %@ for cleanup", tree.name(of: i))) {96                if let item = model.item(forNode: i) { model.toggle(item) }97            }98            FileIcon(path: path, size: density == .compact ? 18 : 26)99            VStack(alignment: .leading, spacing: 1) {100                Text(tree.name(of: i)).lineLimit(1).truncationMode(.middle)101                if density == .comfortable { PathText(path: path) }102            }103            Spacer(minLength: ORIX.Space.s)104            if n.flags.contains(.mayShareBlocks) {105                Image(systemName: "square.on.square.dashed").foregroundStyle(ORIX.Palette.textSecondary)106                    .help(L("APFS reports that this file may share blocks with another file. Removing it may free less than its size."))107                    .accessibilityLabel(L("may share blocks"))108            }109            VStack(alignment: .trailing, spacing: 1) {110                Text(L("Modified %@", ByteFormat.date(Date(timeIntervalSince1970: TimeInterval(n.modified))))).font(.caption).foregroundStyle(ORIX.Palette.textSecondary)111                if let d = lastUsed[path] { Text(L("Last opened %@", ByteFormat.date(d))).font(.caption2).foregroundStyle(ORIX.Palette.textTertiary) }112            }113            .frame(width: 170, alignment: .trailing)114            VStack(alignment: .trailing, spacing: 1) {115                SizeText(bytes: n.allocatedSize)116                if abs(n.logicalSize - n.allocatedSize) > max(1_000_000, n.allocatedSize / 10) {117                    Text(L("%@ content", ByteFormat.string(n.logicalSize))).font(.caption2.monospacedDigit()).foregroundStyle(ORIX.Palette.textTertiary)118                }119            }120            .frame(width: 110, alignment: .trailing)121        }122        .padding(.vertical, density.rowPadding - 3)123        .contextMenu {124            FileMenu(path: path)125            Button(L("Show in Storage Map")) { model.mapFocus = n.flags.contains(.directory) ? i : n.parent; model.mapSelection = i; model.section = .map }126        }127        .task(id: path) {128            if lastUsed[path] == nil, !n.flags.contains(.directory) {129                if let d = await model.background({ AppInventory.lastUsed(path) }) { lastUsed[path] = d }130            }131        }132        .accessibilityElement(children: .combine)133    }134}135
Files main
Menu

Theme