Repository Public License
1// ORIX Secure2// File: App/Sources/Features/PhotoCleanup/PhotoCleanupView.swift3// Description: Photo Cleanup: scan, review candidates by category with previews, choose what to delete, confirm, and see the4// verified result. States plainly that deleted photos stay in Recently Deleted and that some sizes are not measured.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import ORIXDesign9import ORIXMediaCleanup10import ORIXSecureModel11import Photos12import SwiftUI1314extension CleanupCategoryKind {15 var systemImage: String {16 switch self {17 case .exactDuplicates: "square.on.square"18 case .probableDuplicates: "square.on.square.dashed"19 case .similar: "photo.stack"20 case .bursts, .burstLike: "square.stack.3d.down.right"21 case .screenshots, .oldScreenshots: "camera.viewfinder"22 case .largeVideos, .longVideos: "video"23 case .livePhotos: "livephoto"24 }25 }26}2728struct PhotoCleanupView: View {29 @Environment(AppModel.self) private var model30 private var controller: PhotoCleanupController { model.photos }31 @State private var showReview = false32 @State private var openCategory: CleanupCategory?3334 var body: some View {35 ScreenScroll {36 switch controller.access {37 case .notDetermined: accessPrompt38 case .denied, .restricted: accessDenied39 case .limited, .authorized: content40 }41 }42 .accessibilityIdentifier("photos")43 .safeAreaInset(edge: .bottom) { if !controller.selection.isEmpty, controller.phase == .results { reviewBar } }44 .navigationTitle("Photo Cleanup")45 .sheet(isPresented: $showReview) {46 CleanupReviewView(controller: controller) { result in47 var report = result.report(generator: ReportBuilder.generator)48 report.generator = ReportBuilder.generator49 model.store.save(report)50 model.refresh()51 }52 }53 .sheet(item: $openCategory) { category in54 NavigationStack { CleanupCategoryView(kind: category.kind, controller: controller) }55 }56 .onAppear { controller.refreshAccess() }57 }5859 private var accessPrompt: some View {60 VStack(alignment: .leading, spacing: ORIX.Space.md) {61 ORIXGlyph("photo.stack", size: 52)62 Text("Find what you can remove").font(.orixTitle).foregroundStyle(ORIX.Palette.textPrimary)63 Text("ORIX Secure compares your photos on this device to find exact duplicates, similar shots, screenshots and large videos. Nothing is uploaded. Nothing is deleted unless you select it and confirm.")64 .font(.orixBody).foregroundStyle(ORIX.Palette.textSecondary)65 Text("You can give access to selected photos only: the analysis then covers those.").font(.orixCaption).foregroundStyle(ORIX.Palette.textTertiary)66 Button { Task { await controller.requestAccess() } } label: { Text("Choose Photo Access") }.buttonStyle(.orixPrimary)67 .accessibilityIdentifier("photos.requestAccess")68 }69 .orixCard(padding: ORIX.Space.lg)70 }7172 private var accessDenied: some View {73 VStack(alignment: .leading, spacing: ORIX.Space.md) {74 ORIXBanner(.info, title: Text("Photo access is off"), message: Text(verbatim: controller.access.title))75 Text("Photo Cleanup needs access to your photos to compare them. The rest of ORIX Secure works without it.").font(.orixCallout).foregroundStyle(ORIX.Palette.textSecondary)76 Button { openSettings() } label: { Label("Open Settings", systemImage: "gear") }.buttonStyle(.orixSecondary)77 }78 .orixCard()79 .accessibilityElement(children: .combine)80 .accessibilityIdentifier("photos.denied")81 }8283 @ViewBuilder private var content: some View {84 if let note = controller.access.coverageNote {85 ORIXBanner(.info, title: Text("Limited access"), message: Text(verbatim: note))86 }87 switch controller.phase {88 case .scanning(let message, let fraction):89 if let result = controller.lastResult { resultBanner(result) }90 VStack(alignment: .leading, spacing: ORIX.Space.md) {91 Text(verbatim: message).font(.orixHeadline).foregroundStyle(ORIX.Palette.textPrimary)92 if let fraction { ORIXProgressBar(value: fraction) } else { ProgressView() }93 Button("Cancel") { controller.cancel() }.buttonStyle(.orixSecondary).accessibilityIdentifier("photos.cancel")94 }95 .orixCard()96 .accessibilityElement(children: .combine)97 .accessibilityIdentifier("photos.progress")98 case .failed(let message):99 ORIXBanner(.error, title: Text("The scan did not finish"), message: Text(verbatim: message))100 scanButton101 case .idle:102 if controller.output == nil {103 VStack(alignment: .leading, spacing: ORIX.Space.sm) {104 Text("Ready to scan").font(.orixTitle).foregroundStyle(ORIX.Palette.textPrimary)105 Text("The first scan fingerprints every photo from a small preview; later scans only process what changed.")106 .font(.orixCallout).foregroundStyle(ORIX.Palette.textSecondary)107 }108 .frame(maxWidth: .infinity, alignment: .leading)109 .orixCard()110 }111 scanButton112 case .results, .deleting:113 if let result = controller.lastResult { resultBanner(result) }114 if let output = controller.output { results(output) }115 scanButton116 }117 }118119 private var scanButton: some View {120 Button {121 controller.scan { output in122 let totals = output.analysis.totals123 model.photoOpportunity = CleanupOpportunity(candidateCount: totals.candidateCount, measuredBytes: totals.measuredCount > 0 ? totals.measuredBytes : nil,124 unmeasuredCount: totals.notMeasuredCount, scannedAt: Date())125 }126 } label: { Label(controller.output == nil ? "Scan Photos" : "Scan Again", systemImage: "sparkle.magnifyingglass") }127 .buttonStyle(.orixPrimary)128 .accessibilityIdentifier("photos.scan")129 }130131 private func resultBanner(_ result: CleanupResult) -> some View {132 VStack(alignment: .leading, spacing: ORIX.Space.xs) {133 ORIXBanner(result.outcome == .completed ? .success : (result.outcome == .cancelledByUser ? .info : .warning), title: Text(verbatim: result.summary),134 message: Text(verbatim: result.freedNow))135 if !result.failed.isEmpty {136 Text("\(result.failed.count) item(s) could not be deleted.").font(.orixCaption).foregroundStyle(ORIX.Palette.textSecondary)137 }138 }139 .accessibilityElement(children: .combine)140 .accessibilityIdentifier("photos.result")141 }142143 @ViewBuilder private func results(_ output: CleanupPipelineOutput) -> some View {144 let analysis = output.analysis145 let totals = analysis.totals146 VStack(alignment: .leading, spacing: ORIX.Space.sm) {147 Text("\(totals.candidateCount) cleanup candidates").font(.orixTitle).foregroundStyle(ORIX.Palette.textPrimary)148 if totals.measuredCount > 0 {149 Text("\(ORIXFormat.bytes(totals.measuredBytes)) measured across \(totals.measuredCount) of them").font(.orixCallout).foregroundStyle(ORIX.Palette.textPrimary)150 }151 if totals.notMeasuredCount > 0 {152 Text("\(totals.notMeasuredCount) could not be measured (for example, originals kept in iCloud). Their size is not included and not estimated.")153 .font(.orixCaption).foregroundStyle(ORIX.Palette.textSecondary)154 }155 if output.scan.fingerprintFailures > 0 {156 Text("\(output.scan.fingerprintFailures) item(s) have no preview on this device and could not be compared.")157 .font(.orixCaption).foregroundStyle(ORIX.Palette.textSecondary)158 }159 Text("\(analysis.statistics.itemsScanned) items scanned in \(output.scan.duration.formatted(.number.precision(.fractionLength(1)))) s · \(output.scan.fingerprintCacheHits) fingerprints from cache")160 .font(.orixCaption).foregroundStyle(ORIX.Palette.textTertiary)161 }162 .frame(maxWidth: .infinity, alignment: .leading)163 .orixCard()164 .accessibilityElement(children: .combine)165 .accessibilityIdentifier("photos.totals")166167 ForEach(analysis.categories.filter { !$0.groups.isEmpty }) { category in168 Button { openCategory = category } label: {169 HStack(spacing: ORIX.Space.sm) {170 ORIXGlyph(category.kind.systemImage)171 VStack(alignment: .leading, spacing: 2) {172 Text(verbatim: category.kind.title).font(.orixHeadline).foregroundStyle(ORIX.Palette.textPrimary)173 Text(verbatim: countText(category)).font(.orixCaption).foregroundStyle(ORIX.Palette.textSecondary)174 }175 Spacer(minLength: 0)176 if category.kind.confidence == .heuristic { ORIXChip(Text("Heuristic")) }177 Image(systemName: "chevron.right").font(.footnote.weight(.semibold)).foregroundStyle(ORIX.Palette.textTertiary).accessibilityHidden(true)178 }179 .frame(maxWidth: .infinity, alignment: .leading)180 .orixCard(padding: ORIX.Space.sm)181 }182 .buttonStyle(.plain)183 .accessibilityIdentifier("photos.category." + category.kind.rawValue)184 }185 if analysis.categories.allSatisfy({ $0.groups.isEmpty }) {186 ORIXBanner(.info, title: Text("No cleanup candidates found"), message: Text("Among the \(analysis.statistics.itemsFingerprinted) of \(analysis.statistics.itemsScanned) items ORIX Secure could compare."))187 }188 LimitsCard(title: "How candidates are found, and the limits", items: [189 String(localized: "Exact duplicates are byte-identical originals (SHA-256). Similar photos are matched by perceptual fingerprints of small previews: review them, the match can be wrong."),190 String(localized: "Sizes are measured from the files on the device. Originals stored only in iCloud are not downloaded, so their size is unknown."),191 analysis.recentlyDeletedNote,192 String(localized: "Thresholds were tuned on generated test images, not on a real library."),193 ])194 }195196 private func countText(_ category: CleanupCategory) -> String {197 let items = category.groups.reduce(0) { $0 + $1.items.count }198 let size = category.totals.measuredCount > 0 ? " · " + String(localized: "\(ORIXFormat.bytes(category.totals.measuredBytes)) measured") : ""199 return String(localized: "\(category.groups.count) group(s), \(items) item(s)") + size200 }201202 private var reviewBar: some View {203 Button { showReview = true } label: { Label("Review \(controller.selection.count) Selected", systemImage: "checklist") }204 .buttonStyle(.orixPrimary)205 .padding(.horizontal, ORIX.Space.md)206 .padding(.vertical, ORIX.Space.xs)207 .background(.bar)208 .accessibilityIdentifier("photos.review")209 }210}211212struct CleanupCategoryView: View {213 let kind: CleanupCategoryKind214 @Bindable var controller: PhotoCleanupController215 @Environment(\.dismiss) private var dismiss216217 var body: some View {218 let groups = controller.analysis?.groups(in: kind) ?? []219 ScreenScroll {220 Text(verbatim: kind.explanation).font(.orixCallout).foregroundStyle(ORIX.Palette.textSecondary)221 ForEach(groups) { group in222 VStack(alignment: .leading, spacing: ORIX.Space.sm) {223 HStack {224 Text(verbatim: groupTitle(group)).font(.orixHeadline).foregroundStyle(ORIX.Palette.textPrimary)225 Spacer()226 if !group.isInformational {227 let allSelected = group.candidateIDs.allSatisfy { controller.selection.contains($0) }228 Button(allSelected ? "Deselect" : (group.keeperID == nil ? "Select All" : "Select All but Kept")) {229 if allSelected { controller.selection.deselectAll(of: group) } else { controller.selection.selectCandidates(of: group) }230 }231 .font(.orixCallout)232 }233 }234 if let rule = group.keeperRule { Text(verbatim: rule.explanation).font(.orixCaption).foregroundStyle(ORIX.Palette.textTertiary) }235 LazyVGrid(columns: [GridItem(.adaptive(minimum: 96), spacing: 6)], spacing: 6) {236 ForEach(group.items) { item in237 AssetCell(item: item, isKeeper: item.id == group.keeperID, isSelected: controller.selection.contains(item.id),238 estimate: group.sizeEstimates[item.id], selectable: !group.isInformational) {239 controller.selection.toggle(item.id)240 ORIXHaptics.tick()241 }242 }243 }244 }245 .orixCard(padding: ORIX.Space.sm)246 }247 }248 .navigationTitle(Text(verbatim: kind.title))249 .navigationBarTitleDisplayMode(.inline)250 .toolbar { ToolbarItem(placement: .confirmationAction) { Button("Done") { dismiss() }.accessibilityIdentifier("category.done") } }251 .accessibilityIdentifier("photos.categoryDetail")252 }253254 private func groupTitle(_ group: CleanupGroup) -> String {255 let date = group.items.compactMap(\.creationDate).min().map { $0.formatted(date: .abbreviated, time: .shortened) } ?? ""256 return String(localized: "\(group.items.count) item(s)") + (date.isEmpty ? "" : " · " + date)257 }258}259260/// One photo or video: preview, measured size (or "not measured"), keep / delete marks as symbol and text.261struct AssetCell: View {262 let item: MediaItem263 let isKeeper: Bool264 let isSelected: Bool265 var estimate: VideoSizeEstimate?266 var selectable = true267 let toggle: () -> Void268269 var body: some View {270 Button(action: toggle) {271 VStack(spacing: 3) {272 AssetThumbnail(id: item.id)273 .aspectRatio(1, contentMode: .fill)274 .clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous))275 .overlay(alignment: .topTrailing) {276 if selectable {277 Image(systemName: isSelected ? "trash.circle.fill" : "circle")278 .font(.title3).symbolRenderingMode(.palette)279 .foregroundStyle(.white, isSelected ? ORIX.Palette.danger : .black.opacity(0.25))280 .padding(4)281 }282 }283 .overlay(alignment: .bottomLeading) {284 if isKeeper {285 Label("Keep", systemImage: "checkmark.seal.fill").font(.caption2.weight(.semibold)).foregroundStyle(.white)286 .padding(.horizontal, 5).padding(.vertical, 2).background(ORIX.Palette.success, in: Capsule()).padding(4)287 }288 }289 .overlay(RoundedRectangle(cornerRadius: 8, style: .continuous).strokeBorder(isSelected ? ORIX.Palette.danger : .clear, lineWidth: 2))290 Text(verbatim: sizeText).font(.caption2).foregroundStyle(ORIX.Palette.textSecondary).lineLimit(1).minimumScaleFactor(0.8)291 }292 }293 .buttonStyle(.plain)294 .disabled(!selectable)295 .accessibilityLabel(Text(verbatim: accessibilityText))296 .accessibilityAddTraits(isSelected ? .isSelected : [])297 .accessibilityIdentifier("asset.cell")298 }299300 private var sizeText: String {301 if let bytes = item.byteSize.value { return ORIXFormat.bytes(bytes) }302 if item.isVideo, item.duration > 0 { return Duration.seconds(item.duration).formatted(.time(pattern: .minuteSecond)) }303 return String(localized: "Not measured")304 }305306 private var accessibilityText: String {307 var parts = [item.isVideo ? String(localized: "Video") : String(localized: "Photo")]308 if let date = item.creationDate { parts.append(date.formatted(date: .abbreviated, time: .shortened)) }309 parts.append(item.byteSize.value.map { ORIXFormat.bytes($0) } ?? String(localized: "size not measured"))310 if let estimate { parts.append(estimate.title) }311 if isKeeper { parts.append(String(localized: "proposed to keep")) }312 if isSelected { parts.append(String(localized: "selected for deletion")) }313 return parts.joined(separator: ", ")314 }315}316317/// A small preview loaded from Photos by identifier. Never loads the full-resolution original.318struct AssetThumbnail: View {319 let id: String320 @State private var image: UIImage?321322 var body: some View {323 ZStack {324 ORIX.Palette.surfaceRaised325 if let image { Image(uiImage: image).resizable().scaledToFill() } else { Image(systemName: "photo").foregroundStyle(ORIX.Palette.textTertiary) }326 }327 .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity)328 .clipped()329 .task(id: id) { image = await Self.load(id) }330 .accessibilityHidden(true)331 }332333 static func load(_ id: String) async -> UIImage? {334 guard let asset = PHAsset.fetchAssets(withLocalIdentifiers: [id], options: nil).firstObject else { return nil }335 let options = PHImageRequestOptions()336 options.deliveryMode = .highQualityFormat337 options.resizeMode = .fast338 options.isNetworkAccessAllowed = false339 return await withCheckedContinuation { continuation in340 PHImageManager.default().requestImage(for: asset, targetSize: CGSize(width: 240, height: 240), contentMode: .aspectFill, options: options) { image, _ in341 continuation.resume(returning: image)342 }343 }344 }345}346347/// The last step before deletion: exactly what will be deleted, what is known about its size, and what happens next.348struct CleanupReviewView: View {349 @Bindable var controller: PhotoCleanupController350 let onResult: (CleanupResult) -> Void351 @Environment(\.dismiss) private var dismiss352 @State private var working = false353354 var body: some View {355 NavigationStack {356 if let plan = controller.plan(), let analysis = controller.analysis {357 let items = analysis.itemsByID358 ScreenScroll {359 VStack(alignment: .leading, spacing: ORIX.Space.sm) {360 Text(verbatim: plan.summary).font(.orixHeadline).foregroundStyle(ORIX.Palette.textPrimary)361 ReadingRow(label: String(localized: "Items selected"), value: .measured("\(plan.count)"))362 ReadingRow(label: String(localized: "Measured size"), value: plan.measuredCount > 0 ? .measured(ORIXFormat.bytes(plan.measuredBytes)) : .unavailable(.notRequested, String(localized: "No selected item has a measured size.")))363 if !plan.unknownSizeIDs.isEmpty {364 ReadingRow(label: String(localized: "Items of unknown size"), value: .measured("\(plan.unknownSizeIDs.count)"))365 }366 }367 .orixCard()368 .accessibilityElement(children: .combine)369 .accessibilityIdentifier("review.plan")370 ForEach(plan.warnings, id: \.self) { warning in371 ORIXBanner(.warning, title: Text(verbatim: warning))372 }373 ORIXBanner(.info, title: Text("What happens when you delete"), message: Text(verbatim: plan.recentlyDeletedNote))374 LazyVGrid(columns: [GridItem(.adaptive(minimum: 96), spacing: 6)], spacing: 6) {375 ForEach(plan.itemIDs.compactMap { items[$0] }) { item in376 AssetCell(item: item, isKeeper: false, isSelected: true) { controller.selection.toggle(item.id) }377 }378 }379 Button(role: .destructive) {380 working = true381 Task {382 let result = await controller.delete(plan)383 working = false384 onResult(result)385 dismiss()386 }387 } label: { Label("Delete \(plan.count) Item(s)…", systemImage: "trash") }388 .buttonStyle(.orixPrimary)389 .disabled(plan.isEmpty || working)390 .accessibilityIdentifier("review.delete")391 Text("iOS will ask you to confirm. Declining deletes nothing.").font(.orixCaption).foregroundStyle(ORIX.Palette.textTertiary)392 }393 .navigationTitle("Review Deletion")394 .navigationBarTitleDisplayMode(.inline)395 .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() }.accessibilityIdentifier("review.cancel") } }396 }397 }398 .accessibilityIdentifier("photos.reviewSheet")399 }400}401