From 95bd458f6db0b44893d2ae1b1241779bea9df20c Mon Sep 17 00:00:00 2001 From: Rudenko Dmitry Date: Fri, 23 Oct 2026 16:37:39 +0300 Subject: [PATCH] refactor: extract TrashOperationsModel from AppModel - Move trash/collection confirmation, async deletion, undo and top-level selection - Keep TrashModel as pure confirmation/busy/undo state; operations live in a new model - Migrate UI and tests to model.trashOperations and model.trash bindings - Add TrashOperationsModelTests for availability, confirmations and undo no-op - AppModel is now 758 lines; 158 tests green Refs #66 Refs #87 --- .github/workflows/release.yml | 2 +- README.md | 2 +- ROADMAP.md | 2 +- Sources/DiskScope/DiskScopeApp.swift | 8 +- .../App/AppModel+Collection.swift | 15 +- .../App/AppModel+Duplicates.swift | 2 +- .../App/AppModel+SearchActions.swift | 2 +- .../DiskScopeKit/App/AppModel+Similar.swift | 2 +- Sources/DiskScopeKit/App/AppModel.swift | 232 +--------------- .../App/TrashOperationsModel.swift | 253 ++++++++++++++++++ Sources/DiskScopeKit/UI/CollectionView.swift | 10 +- Sources/DiskScopeKit/UI/ContentView.swift | 4 +- Sources/DiskScopeKit/UI/HeaderView.swift | 4 +- Sources/DiskScopeKit/UI/InspectorView.swift | 4 +- .../DiskScopeKit/UI/LargestFilesView.swift | 2 +- Sources/DiskScopeKit/UI/MapView.swift | 2 +- Sources/DiskScopeKit/UI/TreemapView.swift | 4 +- Sources/DiskScopeKit/UI/TypesView.swift | 2 +- Sources/DiskScopeKit/UI/WindowChrome.swift | 8 +- Tests/DiskScopeKitTests/AppModelTests.swift | 24 +- .../TrashOperationsModelTests.swift | 77 ++++++ docs/build.md | 2 +- 22 files changed, 387 insertions(+), 276 deletions(-) create mode 100644 Sources/DiskScopeKit/App/TrashOperationsModel.swift create mode 100644 Tests/DiskScopeKitTests/TrashOperationsModelTests.swift diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 72d2c8d..41c591b 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -279,5 +279,5 @@ jobs: echo "| SHA-256 DMG | \`${DMG_SHA256}\` |" echo "| SHA-256 ZIP | \`${ZIP_SHA256}\` |" echo "| Архитектуры | arm64 + x86_64 |" - echo "| Тесты | 156 XCTest |" + echo "| Тесты | 158 XCTest |" } >> "$GITHUB_STEP_SUMMARY" diff --git a/README.md b/README.md index cc44f0e..7c3dd46 100644 --- a/README.md +++ b/README.md @@ -371,7 +371,7 @@ Headless-сканер для бенчмарков: ## Тесты -156 тестов: сравнение суммы скана с `du`, агрегация мелких файлов, пакеты, +158 тестов: сравнение суммы скана с `du`, агрегация мелких файлов, пакеты, симлинки, Unicode-имена, отказ доступа, отмена, copy-on-write удаление, свойства squarified-раскладки, вложенные ячейки, полный цикл `AppModel` (скан → навигация → фильтры), даты создания и изменения, правила очистки, diff --git a/ROADMAP.md b/ROADMAP.md index 64b4404..f66d4ab 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -23,7 +23,7 @@ | 2.0 — Платформа | 6/6: локализация, notarization/Sparkle/Homebrew, CLI, App Intents, доступность, меню-бар | | Backlog | 5/5: кэш, параллельный скан, бюджеты, старые файлы, APFS-клоны | -Текущая база: **156 XCTest**, 17,9 тыс. строк исходников, 398 ключей +Текущая база: **158 XCTest**, 17,9 тыс. строк исходников, 398 ключей локализации, `main` зелёный. ## Принципы diff --git a/Sources/DiskScope/DiskScopeApp.swift b/Sources/DiskScope/DiskScopeApp.swift index d1fe1d7..43b8404 100644 --- a/Sources/DiskScope/DiskScopeApp.swift +++ b/Sources/DiskScope/DiskScopeApp.swift @@ -21,9 +21,9 @@ struct DiskScopeApp: App { CommandGroup(replacing: .newItem) {} CommandGroup(replacing: .undoRedo) { - Button("Отменить удаление") { model.undoLastTrash() } + Button("Отменить удаление") { model.trashOperations.undoLast() } .keyboardShortcut("z", modifiers: .command) - .disabled(!model.canUndoTrash) + .disabled(!model.trash.canUndo) } CommandGroup(after: .appInfo) { @@ -126,9 +126,9 @@ struct DiskScopeApp: App { } .keyboardShortcut("r", modifiers: [.command, .shift]) .disabled(model.tree == nil) - Button("Переместить в Корзину…") { model.requestTrashSelection() } + Button("Переместить в Корзину…") { model.trashOperations.requestSelection() } .keyboardShortcut(.delete, modifiers: .command) - .disabled(!model.canTrashSelection) + .disabled(!model.trashOperations.canTrashSelection) } } diff --git a/Sources/DiskScopeKit/App/AppModel+Collection.swift b/Sources/DiskScopeKit/App/AppModel+Collection.swift index 961e62f..a631602 100644 --- a/Sources/DiskScopeKit/App/AppModel+Collection.swift +++ b/Sources/DiskScopeKit/App/AppModel+Collection.swift @@ -35,10 +35,6 @@ extension AppModel { .sorted { $0.size > $1.size } } - public var canTrashCollection: Bool { - !collection.isEmpty && !fileOperationInFlight - } - public func isInCollection(_ index: Int32) -> Bool { collection.contains(index) } @@ -73,15 +69,6 @@ extension AppModel { collection = [] } - public func requestTrashCollection() { - guard canTrashCollection else { return } - if UserDefaults.standard.bool(forKey: AppSettingsKeys.confirmTrash) { - showCollectionTrashConfirmation = true - } else { - confirmCollectionTrash() - } - } - private func isAncestor(_ ancestor: Int32, of node: Int32, in tree: ScanTree) -> Bool { var cursor = tree.node(node).parent while cursor >= 0 { @@ -94,6 +81,6 @@ extension AppModel { func resetCollection() { collection = [] showCollection = false - showCollectionTrashConfirmation = false + trash.showCollectionConfirmation = false } } diff --git a/Sources/DiskScopeKit/App/AppModel+Duplicates.swift b/Sources/DiskScopeKit/App/AppModel+Duplicates.swift index ab982a3..9c46c50 100644 --- a/Sources/DiskScopeKit/App/AppModel+Duplicates.swift +++ b/Sources/DiskScopeKit/App/AppModel+Duplicates.swift @@ -12,7 +12,7 @@ extension AppModel { public func trashDuplicateFiles(_ indices: Set) { guard !indices.isEmpty else { return } selection = indices - requestTrashSelection() + trashOperations.requestSelection() } public func collectDuplicateFiles(_ indices: Set) { diff --git a/Sources/DiskScopeKit/App/AppModel+SearchActions.swift b/Sources/DiskScopeKit/App/AppModel+SearchActions.swift index 77d56bb..2e088aa 100644 --- a/Sources/DiskScopeKit/App/AppModel+SearchActions.swift +++ b/Sources/DiskScopeKit/App/AppModel+SearchActions.swift @@ -33,7 +33,7 @@ extension AppModel { search.show = false selection = [hit.index] DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) { [weak self] in - self?.requestTrashSelection() + self?.trashOperations.requestSelection() } } } diff --git a/Sources/DiskScopeKit/App/AppModel+Similar.swift b/Sources/DiskScopeKit/App/AppModel+Similar.swift index 2a497f5..ab63889 100644 --- a/Sources/DiskScopeKit/App/AppModel+Similar.swift +++ b/Sources/DiskScopeKit/App/AppModel+Similar.swift @@ -12,7 +12,7 @@ extension AppModel { public func trashSimilarImages(_ indices: Set) { guard !indices.isEmpty else { return } selection = indices - requestTrashSelection() + trashOperations.requestSelection() } public func collectSimilarImages(_ indices: Set) { diff --git a/Sources/DiskScopeKit/App/AppModel.swift b/Sources/DiskScopeKit/App/AppModel.swift index 409de17..1554053 100644 --- a/Sources/DiskScopeKit/App/AppModel.swift +++ b/Sources/DiskScopeKit/App/AppModel.swift @@ -94,6 +94,7 @@ public final class AppModel: ObservableObject { @Published public var showCommandPalette = false @Published public var showPermissionSheet = false @Published public internal(set) var trash = TrashModel() + @Published public internal(set) var trashOperations = TrashOperationsModel() @Published public internal(set) var cleanup = CleanupModel() @Published public internal(set) var collection: Set = [] @Published public var showCollection = false @@ -187,6 +188,10 @@ public final class AppModel: ObservableObject { trash.objectWillChange.sink { [weak self] _ in self?.objectWillChange.send() }.store(in: &cancellables) + trashOperations.attach(appModel: self) + trashOperations.objectWillChange.sink { [weak self] _ in + self?.objectWillChange.send() + }.store(in: &cancellables) disk.attach { [weak self] in self?.internalVolume } diskCancellable = disk.objectWillChange.sink { [weak self] _ in self?.objectWillChange.send() @@ -241,16 +246,6 @@ public final class AppModel: ObservableObject { set { trash.busy = newValue } } - public var canUndoTrash: Bool { trash.canUndo } - public var showTrashConfirmation: Bool { - get { trash.showSelectionConfirmation } - set { trash.showSelectionConfirmation = newValue } - } - public var showCollectionTrashConfirmation: Bool { - get { trash.showCollectionConfirmation } - set { trash.showCollectionConfirmation = newValue } - } - public var currentIndex: Int32 { get { nav.currentIndex } set { nav.currentIndex = newValue } @@ -460,190 +455,10 @@ public final class AppModel: ObservableObject { // MARK: - Trash - public func requestTrashSelection() { - guard canTrashSelection else { return } - if UserDefaults.standard.bool(forKey: AppSettingsKeys.confirmTrash) { - showTrashConfirmation = true - } else { - confirmTrash() - } - } - - public func confirmTrash() { - showTrashConfirmation = false - guard let tree, canTrashSelection else { return } - performTrash(indices: topLevelSelection(), tree: tree) - } - - public func confirmCollectionTrash() { - showCollectionTrashConfirmation = false - showCollection = false - guard let tree, canTrashCollection else { return } - performTrash(indices: collection.sorted(), tree: tree) - } - - private func performTrash(indices: [Int32], tree: ScanTree) { - guard !fileOperationInFlight, !indices.isEmpty else { return } - let urls = indices.map { tree.url(of: $0) } - selection = [] - fileOperationInFlight = true - - DispatchQueue.global(qos: .userInitiated).async { [weak self] in - var trashed: [(index: Int32, original: URL, trashed: URL)] = [] - var failures: [(url: URL, message: String)] = [] - for (offset, url) in urls.enumerated() { - do { - var resultingURL: NSURL? - try FileManager.default.trashItem(at: url, resultingItemURL: &resultingURL) - let trashedURL = (resultingURL as URL?) ?? url - trashed.append((indices[offset], url, trashedURL)) - } catch { - failures.append((url, error.localizedDescription)) - } - } - DispatchQueue.main.async { - guard let self else { return } - self.applyTrash(tree: tree, trashed: trashed, failures: failures) - } - } - } - - private func applyTrash( - tree scanTree: ScanTree, - trashed: [(index: Int32, original: URL, trashed: URL)], - failures: [(url: URL, message: String)] - ) { - fileOperationInFlight = false - guard !trashed.isEmpty else { - if let failure = failures.first { - errorMessage = "Не удалось переместить «\(failure.url.lastPathComponent)» в Корзину: \(failure.message)" - } - return - } - let removed = scanTree.removingSubtrees(at: trashed.map(\.index)) - recordUndo(removal: removed, trashed: trashed) - collection = collection.filter { !removed.tree.isDeleted($0) } - resetDuplicates() - resetSimilar() - fileCount = removed.tree.totalFiles - folderCount = removed.tree.directoryCount() - tree = removed.tree - selection = [] - // A package containing the current folder could be removed from the - // "largest" list; fall back to the nearest surviving ancestor. - if removed.tree.isDeleted(currentIndex) { - var cursor = currentIndex - while cursor > 0, removed.tree.isDeleted(cursor) { - cursor = removed.tree.node(cursor).parent - } - currentIndex = max(cursor, 0) - } - rebuildCurrentRows() - refreshVolumes() - stats.refresh() - invalidateCleanup() - showToast( - "В Корзину: \(Plural.items(trashed.count)) · \(ByteFormat.string(removed.bytes)) · ⌘Z — отменить", - symbol: "trash.fill" - ) - if let failure = failures.first { - errorMessage = "Часть объектов не удалось удалить. «\(failure.url.lastPathComponent)»: \(failure.message)" - } - } - - /// Moves the files of the last deletion back and restores their subtrees. - public func undoLastTrash() { - guard !fileOperationInFlight, let entry = trash.popUndo() else { return } - fileOperationInFlight = true - - DispatchQueue.global(qos: .userInitiated).async { [weak self] in - var restoredGroups: [ScanTreeRemoval.Group] = [] - var failures: [(url: URL, message: String)] = [] - var restoredCount = 0 - for file in entry.files { - let manager = FileManager.default - guard manager.fileExists(atPath: file.trashedURL.path) else { - failures.append((file.originalURL, "файл не найден в Корзине")) - continue - } - guard !manager.fileExists(atPath: file.originalURL.path) else { - failures.append((file.originalURL, "путь уже занят другим файлом")) - continue - } - do { - try manager.moveItem(at: file.trashedURL, to: file.originalURL) - restoredGroups.append(file.group) - restoredCount += 1 - } catch { - failures.append((file.originalURL, error.localizedDescription)) - } - } - DispatchQueue.main.async { - guard let self else { return } - let restoredRoots = Set(restoredGroups.map(\.root)) - self.applyUndo( - groups: restoredGroups, - collectionRoots: entry.collectionRoots.filter { restoredRoots.contains($0) }, - restoredCount: restoredCount, - failures: failures - ) - } - } - } - - private func applyUndo( - groups: [ScanTreeRemoval.Group], - collectionRoots: [Int32], - restoredCount: Int, - failures: [(url: URL, message: String)] - ) { - fileOperationInFlight = false - if !groups.isEmpty, let tree { - let restored = tree.restoringSubtrees(groups: groups) - self.tree = restored - resetDuplicates() - resetSimilar() - addToCollection(collectionRoots) - selection = [] - fileCount = restored.totalFiles - folderCount = restored.directoryCount() - if restored.isDeleted(currentIndex) { - var cursor = currentIndex - while cursor > 0, restored.isDeleted(cursor) { - cursor = restored.node(cursor).parent - } - currentIndex = max(cursor, 0) - } - rebuildCurrentRows() - refreshVolumes() - stats.refresh() - invalidateCleanup() - let bytes = groups.reduce(Int64(0)) { $0 + $1.bytes } - showToast( - "Возвращено: \(Plural.items(restoredCount)) · \(ByteFormat.string(bytes))", - symbol: "arrow.uturn.backward" - ) - } - if let failure = failures.first { - errorMessage = "Не удалось вернуть «\(failure.url.lastPathComponent)»: \(failure.message)" - } - } - - private func recordUndo( - removal: ScanTreeRemoval, - trashed: [(index: Int32, original: URL, trashed: URL)] - ) { - let roots = Array(Set(trashed.map(\.index))) - trash.record( - removal: removal, - trashed: trashed, - collectionRoots: roots.filter { collection.contains($0) } - ) - } - func resetTrashUndo() { trash.reset() } + // MARK: - Cleanup public func requestCleanup() { @@ -714,7 +529,12 @@ public final class AppModel: ObservableObject { } let removed = scanTree.removingSubtrees(at: indices) - recordUndo(removal: removed, trashed: trashed) + let roots = Array(Set(trashed.map(\.index))) + trash.record( + removal: removed, + trashed: trashed, + collectionRoots: roots.filter { collection.contains($0) } + ) collection = collection.filter { !removed.tree.isDeleted($0) } resetDuplicates() resetSimilar() @@ -748,7 +568,7 @@ public final class AppModel: ObservableObject { cleanup.reset() } - private func invalidateCleanup() { + func invalidateCleanup() { resetCleanup() if tab == .cleanup { loadCleanupSuggestionsIfNeeded() @@ -825,25 +645,6 @@ extension AppModel { func runningBundleIdentifiers() -> Set { Set(NSWorkspace.shared.runningApplications.compactMap(\.bundleIdentifier)) } - - private func topLevelSelection() -> [Int32] { - guard let tree else { return [] } - var result: [Int32] = [] - for index in selection.sorted() { - guard index > 0, Int(index) < tree.count, !tree.isDeleted(index) else { continue } - var ancestor = tree.node(index).parent - var hasSelectedAncestor = false - while ancestor >= 0 { - if selection.contains(ancestor) { - hasSelectedAncestor = true - break - } - ancestor = tree.node(ancestor).parent - } - if !hasSelectedAncestor { result.append(index) } - } - return result - } } extension AppModel { @@ -907,13 +708,6 @@ extension AppModel { public var selectedCount: Int { selection.count } - public var canTrashSelection: Bool { - guard let tree, !selection.isEmpty else { return false } - return selection.allSatisfy { index in - index > 0 && !tree.isDeleted(index) && tree.node(index).nodeKind != .aggregate - } - } - public var canRevealSelection: Bool { guard let tree, !selection.isEmpty else { return false } return selection.contains { !tree.isDeleted($0) } diff --git a/Sources/DiskScopeKit/App/TrashOperationsModel.swift b/Sources/DiskScopeKit/App/TrashOperationsModel.swift new file mode 100644 index 0000000..638b4f6 --- /dev/null +++ b/Sources/DiskScopeKit/App/TrashOperationsModel.swift @@ -0,0 +1,253 @@ +import AppKit +import Combine +import Foundation + +/// Owns destructive trash operations and their undo flow. +@MainActor +public final class TrashOperationsModel: ObservableObject { + weak var appModel: AppModel? + + public init() {} + + func attach(appModel: AppModel) { + self.appModel = appModel + } + + // MARK: - Availability + + public var canTrashSelection: Bool { + guard let model = appModel, let tree = model.tree, !model.selection.isEmpty else { + return false + } + return model.selection.allSatisfy { index in + index > 0 && !tree.isDeleted(index) && tree.node(index).nodeKind != .aggregate + } + } + + public var canTrashCollection: Bool { + guard let model = appModel else { return false } + return !model.collection.isEmpty && !model.fileOperationInFlight + } + + // MARK: - Selection + + public func requestSelection() { + guard canTrashSelection else { return } + if UserDefaults.standard.bool(forKey: AppSettingsKeys.confirmTrash) { + appModel?.trash.showSelectionConfirmation = true + } else { + confirmSelection() + } + } + + public func confirmSelection() { + guard let model = appModel else { return } + model.trash.showSelectionConfirmation = false + guard canTrashSelection, let tree = model.tree else { return } + perform(indices: topLevelSelection(), tree: tree) + } + + // MARK: - Collection + + public func requestCollection() { + guard canTrashCollection, let model = appModel else { return } + if UserDefaults.standard.bool(forKey: AppSettingsKeys.confirmTrash) { + model.trash.showCollectionConfirmation = true + } else { + confirmCollection() + } + } + + public func confirmCollection() { + guard let model = appModel else { return } + model.trash.showCollectionConfirmation = false + model.showCollection = false + guard canTrashCollection, let tree = model.tree else { return } + perform(indices: model.collection.sorted(), tree: tree) + } + + // MARK: - Trash + + private func perform(indices: [Int32], tree: ScanTree) { + guard let model = appModel, !model.fileOperationInFlight, !indices.isEmpty else { return } + let urls = indices.map { tree.url(of: $0) } + model.selection = [] + model.fileOperationInFlight = true + + DispatchQueue.global(qos: .userInitiated).async { [weak self] in + var trashed: [(index: Int32, original: URL, trashed: URL)] = [] + var failures: [(url: URL, message: String)] = [] + for (offset, url) in urls.enumerated() { + do { + var resultingURL: NSURL? + try FileManager.default.trashItem(at: url, resultingItemURL: &resultingURL) + let trashedURL = (resultingURL as URL?) ?? url + trashed.append((indices[offset], url, trashedURL)) + } catch { + failures.append((url, error.localizedDescription)) + } + } + DispatchQueue.main.async { + guard let self else { return } + self.apply(tree: tree, trashed: trashed, failures: failures) + } + } + } + + private func apply( + tree scanTree: ScanTree, + trashed: [(index: Int32, original: URL, trashed: URL)], + failures: [(url: URL, message: String)] + ) { + guard let model = appModel else { return } + model.fileOperationInFlight = false + guard !trashed.isEmpty else { + if let failure = failures.first { + model.errorMessage = "Не удалось переместить «\(failure.url.lastPathComponent)» в Корзину: \(failure.message)" + } + return + } + let removed = scanTree.removingSubtrees(at: trashed.map(\.index)) + record(removal: removed, trashed: trashed, model: model) + model.collection = model.collection.filter { !removed.tree.isDeleted($0) } + model.resetDuplicates() + model.resetSimilar() + model.fileCount = removed.tree.totalFiles + model.folderCount = removed.tree.directoryCount() + model.tree = removed.tree + model.selection = [] + // A package containing the current folder could be removed from the + // "largest" list; fall back to the nearest surviving ancestor. + if removed.tree.isDeleted(model.currentIndex) { + var cursor = model.currentIndex + while cursor > 0, removed.tree.isDeleted(cursor) { + cursor = removed.tree.node(cursor).parent + } + model.currentIndex = max(cursor, 0) + } + model.rebuildCurrentRows() + model.refreshVolumes() + model.stats.refresh() + model.invalidateCleanup() + model.showToast( + "В Корзину: \(Plural.items(trashed.count)) · \(ByteFormat.string(removed.bytes)) · ⌘Z — отменить", + symbol: "trash.fill" + ) + if let failure = failures.first { + model.errorMessage = "Часть объектов не удалось удалить. «\(failure.url.lastPathComponent)»: \(failure.message)" + } + } + + /// Moves the files of the last deletion back and restores their subtrees. + public func undoLast() { + guard let model = appModel, !model.fileOperationInFlight, let entry = model.trash.popUndo() else { + return + } + model.fileOperationInFlight = true + + DispatchQueue.global(qos: .userInitiated).async { [weak self] in + var restoredGroups: [ScanTreeRemoval.Group] = [] + var failures: [(url: URL, message: String)] = [] + var restoredCount = 0 + for file in entry.files { + let manager = FileManager.default + guard manager.fileExists(atPath: file.trashedURL.path) else { + failures.append((file.originalURL, "файл не найден в Корзине")) + continue + } + guard !manager.fileExists(atPath: file.originalURL.path) else { + failures.append((file.originalURL, "путь уже занят другим файлом")) + continue + } + do { + try manager.moveItem(at: file.trashedURL, to: file.originalURL) + restoredGroups.append(file.group) + restoredCount += 1 + } catch { + failures.append((file.originalURL, error.localizedDescription)) + } + } + DispatchQueue.main.async { + guard let self else { return } + let restoredRoots = Set(restoredGroups.map(\.root)) + self.applyUndo( + groups: restoredGroups, + collectionRoots: entry.collectionRoots.filter { restoredRoots.contains($0) }, + restoredCount: restoredCount, + failures: failures + ) + } + } + } + + private func applyUndo( + groups: [ScanTreeRemoval.Group], + collectionRoots: [Int32], + restoredCount: Int, + failures: [(url: URL, message: String)] + ) { + guard let model = appModel else { return } + model.fileOperationInFlight = false + if !groups.isEmpty, let tree = model.tree { + let restored = tree.restoringSubtrees(groups: groups) + model.tree = restored + model.resetDuplicates() + model.resetSimilar() + model.addToCollection(collectionRoots) + model.selection = [] + model.fileCount = restored.totalFiles + model.folderCount = restored.directoryCount() + if restored.isDeleted(model.currentIndex) { + var cursor = model.currentIndex + while cursor > 0, restored.isDeleted(cursor) { + cursor = restored.node(cursor).parent + } + model.currentIndex = max(cursor, 0) + } + model.rebuildCurrentRows() + model.refreshVolumes() + model.stats.refresh() + model.invalidateCleanup() + let bytes = groups.reduce(Int64(0)) { $0 + $1.bytes } + model.showToast( + "Возвращено: \(Plural.items(restoredCount)) · \(ByteFormat.string(bytes))", + symbol: "arrow.uturn.backward" + ) + } + if let failure = failures.first { + model.errorMessage = "Не удалось вернуть «\(failure.url.lastPathComponent)»: \(failure.message)" + } + } + + private func record( + removal: ScanTreeRemoval, + trashed: [(index: Int32, original: URL, trashed: URL)], + model: AppModel + ) { + let roots = Array(Set(trashed.map(\.index))) + model.trash.record( + removal: removal, + trashed: trashed, + collectionRoots: roots.filter { model.collection.contains($0) } + ) + } + + private func topLevelSelection() -> [Int32] { + guard let model = appModel, let tree = model.tree else { return [] } + var result: [Int32] = [] + for index in model.selection.sorted() { + guard index > 0, Int(index) < tree.count, !tree.isDeleted(index) else { continue } + var ancestor = tree.node(index).parent + var hasSelectedAncestor = false + while ancestor >= 0 { + if model.selection.contains(ancestor) { + hasSelectedAncestor = true + break + } + ancestor = tree.node(ancestor).parent + } + if !hasSelectedAncestor { result.append(index) } + } + return result + } +} diff --git a/Sources/DiskScopeKit/UI/CollectionView.swift b/Sources/DiskScopeKit/UI/CollectionView.swift index 115ed21..0ab0f93 100644 --- a/Sources/DiskScopeKit/UI/CollectionView.swift +++ b/Sources/DiskScopeKit/UI/CollectionView.swift @@ -38,9 +38,9 @@ struct CollectionView: View { } .frame(width: 680, height: 570) .background(Theme.background) - .alert("Переместить коллекцию в Корзину?", isPresented: $model.showCollectionTrashConfirmation) { + .alert("Переместить коллекцию в Корзину?", isPresented: $model.trash.showCollectionConfirmation) { Button("Отмена", role: .cancel) {} - Button("В Корзину", role: .destructive) { model.confirmCollectionTrash() } + Button("В Корзину", role: .destructive) { model.trashOperations.confirmCollection() } } message: { Text(model.collectionTrashMessage) } @@ -83,10 +83,10 @@ struct CollectionView: View { Spacer() AccentButton(title: "В Корзину…", symbol: "trash") { - model.requestTrashCollection() + model.trashOperations.requestCollection() } - .disabled(!model.canTrashCollection) - .opacity(model.canTrashCollection ? 1 : 0.45) + .disabled(!model.trashOperations.canTrashCollection) + .opacity(model.trashOperations.canTrashCollection ? 1 : 0.45) } .padding(.horizontal, 14) .padding(.vertical, 12) diff --git a/Sources/DiskScopeKit/UI/ContentView.swift b/Sources/DiskScopeKit/UI/ContentView.swift index e08c314..4a93bae 100644 --- a/Sources/DiskScopeKit/UI/ContentView.swift +++ b/Sources/DiskScopeKit/UI/ContentView.swift @@ -27,9 +27,9 @@ public struct ContentView: View { .frame(minWidth: 1180, minHeight: 760) .folderDropTarget() .overlay(alignment: .bottom) { toastLayer } - .alert("Переместить в Корзину?", isPresented: $model.showTrashConfirmation) { + .alert("Переместить в Корзину?", isPresented: $model.trash.showSelectionConfirmation) { Button("Отмена", role: .cancel) {} - Button("В Корзину", role: .destructive) { model.confirmTrash() } + Button("В Корзину", role: .destructive) { model.trashOperations.confirmSelection() } } message: { Text(trashMessage) } diff --git a/Sources/DiskScopeKit/UI/HeaderView.swift b/Sources/DiskScopeKit/UI/HeaderView.swift index 94f6a48..b0c0132 100644 --- a/Sources/DiskScopeKit/UI/HeaderView.swift +++ b/Sources/DiskScopeKit/UI/HeaderView.swift @@ -275,9 +275,9 @@ struct HeaderView: View { symbol: "trash", help: "Переместить в Корзину (⌘⌫)", tint: Theme.danger, - disabled: !model.canTrashSelection + disabled: !model.trashOperations.canTrashSelection ) { - model.requestTrashSelection() + model.trashOperations.requestSelection() } } } diff --git a/Sources/DiskScopeKit/UI/InspectorView.swift b/Sources/DiskScopeKit/UI/InspectorView.swift index dc6904f..a8b6916 100644 --- a/Sources/DiskScopeKit/UI/InspectorView.swift +++ b/Sources/DiskScopeKit/UI/InspectorView.swift @@ -91,7 +91,7 @@ struct InspectorView: View { } AccentButton(title: "В Корзину…", symbol: "trash") { - model.requestTrashSelection() + model.trashOperations.requestSelection() } } .padding(12) @@ -331,7 +331,7 @@ private struct InspectorDetails: View { } AccentButton(title: "В Корзину…", symbol: "trash") { model.selection = [index] - model.requestTrashSelection() + model.trashOperations.requestSelection() } .opacity(node?.nodeKind == .aggregate ? 0.4 : 1) .disabled(node?.nodeKind == .aggregate) diff --git a/Sources/DiskScopeKit/UI/LargestFilesView.swift b/Sources/DiskScopeKit/UI/LargestFilesView.swift index 0a06736..cbe4a53 100644 --- a/Sources/DiskScopeKit/UI/LargestFilesView.swift +++ b/Sources/DiskScopeKit/UI/LargestFilesView.swift @@ -149,7 +149,7 @@ struct LargestFilesView: View { Divider() Button("Переместить в Корзину…", role: .destructive) { model.selection = selection - model.requestTrashSelection() + model.trashOperations.requestSelection() } } } primaryAction: { selection in diff --git a/Sources/DiskScopeKit/UI/MapView.swift b/Sources/DiskScopeKit/UI/MapView.swift index 21cbdc7..c15868e 100644 --- a/Sources/DiskScopeKit/UI/MapView.swift +++ b/Sources/DiskScopeKit/UI/MapView.swift @@ -96,7 +96,7 @@ struct ChildrenTable: View { Divider() Button("Переместить в Корзину…", role: .destructive) { model.selection = selection - model.requestTrashSelection() + model.trashOperations.requestSelection() } .disabled(isAggregate) } diff --git a/Sources/DiskScopeKit/UI/TreemapView.swift b/Sources/DiskScopeKit/UI/TreemapView.swift index 26a0999..99507b8 100644 --- a/Sources/DiskScopeKit/UI/TreemapView.swift +++ b/Sources/DiskScopeKit/UI/TreemapView.swift @@ -155,7 +155,7 @@ struct TreemapView: View { Divider() Button("В Корзину…", role: .destructive) { model.selection = [node] - model.requestTrashSelection() + model.trashOperations.requestSelection() } } else { Button("Показать в Finder") { model.reveal(indices: [root]) } @@ -465,7 +465,7 @@ struct TreemapView: View { } GhostButton(title: "В Корзину", symbol: "trash", tint: Theme.danger) { model.selection = [node] - model.requestTrashSelection() + model.trashOperations.requestSelection() } Button { previewNode = nil diff --git a/Sources/DiskScopeKit/UI/TypesView.swift b/Sources/DiskScopeKit/UI/TypesView.swift index 5a86dc8..a4e9e68 100644 --- a/Sources/DiskScopeKit/UI/TypesView.swift +++ b/Sources/DiskScopeKit/UI/TypesView.swift @@ -319,7 +319,7 @@ private struct TopItemRow: View { Divider() Button("В Корзину…", role: .destructive) { model.selection = [row.id] - model.requestTrashSelection() + model.trashOperations.requestSelection() } } } diff --git a/Sources/DiskScopeKit/UI/WindowChrome.swift b/Sources/DiskScopeKit/UI/WindowChrome.swift index 7fe687d..f00b833 100644 --- a/Sources/DiskScopeKit/UI/WindowChrome.swift +++ b/Sources/DiskScopeKit/UI/WindowChrome.swift @@ -559,7 +559,7 @@ struct CommandPaletteView: View { ) } - if model.canTrashSelection { + if model.trashOperations.canTrashSelection { items.append( PaletteCommand( id: "trash", @@ -568,12 +568,12 @@ struct CommandPaletteView: View { symbol: "trash", shortcut: "⌘⌫" ) { - model.requestTrashSelection() + model.trashOperations.requestSelection() } ) } - if model.canUndoTrash { + if model.trash.canUndo { items.append( PaletteCommand( id: "undo-trash", @@ -582,7 +582,7 @@ struct CommandPaletteView: View { symbol: "arrow.uturn.backward", shortcut: "⌘Z" ) { - model.undoLastTrash() + model.trashOperations.undoLast() } ) } diff --git a/Tests/DiskScopeKitTests/AppModelTests.swift b/Tests/DiskScopeKitTests/AppModelTests.swift index 625db89..d722390 100644 --- a/Tests/DiskScopeKitTests/AppModelTests.swift +++ b/Tests/DiskScopeKitTests/AppModelTests.swift @@ -131,16 +131,16 @@ final class AppModelTests: XCTestCase { let aggregate = try XCTUnwrap(model.currentRows.first { $0.isAggregate }) model.selection = [aggregate.id] - XCTAssertFalse(model.canTrashSelection) - model.requestTrashSelection() - XCTAssertFalse(model.showTrashConfirmation) + XCTAssertFalse(model.trashOperations.canTrashSelection) + model.trashOperations.requestSelection() + XCTAssertFalse(model.trash.showSelectionConfirmation) let file = try XCTUnwrap(model.currentRows.first { !$0.isContainer && !$0.isAggregate }) model.selection = [file.id] - XCTAssertTrue(model.canTrashSelection) - model.requestTrashSelection() - XCTAssertTrue(model.showTrashConfirmation) - model.showTrashConfirmation = false + XCTAssertTrue(model.trashOperations.canTrashSelection) + model.trashOperations.requestSelection() + XCTAssertTrue(model.trash.showSelectionConfirmation) + model.trash.showSelectionConfirmation = false } func testUndoIsUnavailableWithoutDeletion() throws { @@ -148,9 +148,9 @@ final class AppModelTests: XCTestCase { let model = AppModel() model.preview.load(tree: tree) - XCTAssertFalse(model.canUndoTrash) - model.undoLastTrash() - XCTAssertFalse(model.canUndoTrash) + XCTAssertFalse(model.trash.canUndo) + model.trashOperations.undoLast() + XCTAssertFalse(model.trash.canUndo) } func testCleanupPreviewSelectionAndTotals() throws { @@ -191,7 +191,7 @@ final class AppModelTests: XCTestCase { model.addToCollection([sub.id]) let subSize = model.collectionSize XCTAssertEqual(model.collectionCount, 1) - XCTAssertTrue(model.canTrashCollection) + XCTAssertTrue(model.trashOperations.canTrashCollection) XCTAssertTrue(model.collectionTrashMessage.contains("⌘Z")) model.navigate(to: sub.id) @@ -212,7 +212,7 @@ final class AppModelTests: XCTestCase { XCTAssertEqual(model.collectionCount, 1) model.clearCollection() - XCTAssertFalse(model.canTrashCollection) + XCTAssertFalse(model.trashOperations.canTrashCollection) model.addToCollection([video.id]) model.preview.load(tree: tree) diff --git a/Tests/DiskScopeKitTests/TrashOperationsModelTests.swift b/Tests/DiskScopeKitTests/TrashOperationsModelTests.swift new file mode 100644 index 0000000..a751eea --- /dev/null +++ b/Tests/DiskScopeKitTests/TrashOperationsModelTests.swift @@ -0,0 +1,77 @@ +import Foundation +import XCTest +@testable import DiskScopeKit + +@MainActor +final class TrashOperationsModelTests: XCTestCase { + private var previousConfirmTrash: Any? + + override func setUpWithError() throws { + try super.setUpWithError() + previousConfirmTrash = UserDefaults.standard.object(forKey: AppSettingsKeys.confirmTrash) + UserDefaults.standard.set(true, forKey: AppSettingsKeys.confirmTrash) + } + + override func tearDownWithError() throws { + if let previousConfirmTrash { + UserDefaults.standard.set(previousConfirmTrash, forKey: AppSettingsKeys.confirmTrash) + } else { + UserDefaults.standard.removeObject(forKey: AppSettingsKeys.confirmTrash) + } + try super.tearDownWithError() + } + + private func makeTree() throws -> ScanTree { + let root = FileManager.default.temporaryDirectory + .appendingPathComponent("DiskScopeTrashOps-\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory( + at: root.appendingPathComponent("Sub"), + withIntermediateDirectories: true + ) + try Data(repeating: 0x41, count: 100_000) + .write(to: root.appendingPathComponent("big.bin")) + try Data(repeating: 0x42, count: 100) + .write(to: root.appendingPathComponent("small.txt")) + addTeardownBlock { try? FileManager.default.removeItem(at: root) } + return try DiskScanner(options: ScanOptions(minimumFileSize: 64 * 1024)).scan(path: root.path) + } + + func testSelectionAvailabilityAndConfirmation() throws { + let tree = try makeTree() + let model = AppModel() + model.preview.load(tree: tree) + + XCTAssertFalse(model.trashOperations.canTrashSelection) + + let aggregate = try XCTUnwrap(model.currentRows.first { $0.isAggregate }) + model.selection = [aggregate.id] + XCTAssertFalse(model.trashOperations.canTrashSelection) + model.trashOperations.requestSelection() + XCTAssertFalse(model.trash.showSelectionConfirmation) + + let file = try XCTUnwrap(model.currentRows.first { $0.name == "big.bin" }) + model.selection = [file.id] + XCTAssertTrue(model.trashOperations.canTrashSelection) + model.trashOperations.requestSelection() + XCTAssertTrue(model.trash.showSelectionConfirmation) + model.trash.showSelectionConfirmation = false + } + + func testCollectionConfirmationAndUndoNoOp() throws { + let tree = try makeTree() + let model = AppModel() + model.preview.load(tree: tree) + + let folder = try XCTUnwrap(model.currentRows.first { $0.name == "Sub" }) + model.addToCollection([folder.id]) + XCTAssertTrue(model.trashOperations.canTrashCollection) + + model.trashOperations.requestCollection() + XCTAssertTrue(model.trash.showCollectionConfirmation) + model.trash.showCollectionConfirmation = false + + XCTAssertFalse(model.trash.canUndo) + model.trashOperations.undoLast() + XCTAssertFalse(model.trash.canUndo) + } +} diff --git a/docs/build.md b/docs/build.md index 46b293d..19bea56 100644 --- a/docs/build.md +++ b/docs/build.md @@ -95,7 +95,7 @@ MKDOCS_SITE_URL=http://localhost:8000/ .venv/bin/mkdocs build --strict ## Тесты -156 XCTest-тестов покрывают: +158 XCTest-тестов покрывают: - сканер и точность суммы против `du`; - агрегацию мелких файлов, пакеты, симлинки, Unicode-имена;