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
2 changes: 1 addition & 1 deletion .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -270,5 +270,5 @@ jobs:
echo "| SHA-256 DMG | \`${DMG_SHA256}\` |"
echo "| SHA-256 ZIP | \`${ZIP_SHA256}\` |"
echo "| Архитектуры | arm64 + x86_64 |"
echo "| Тесты | 143 XCTest |"
echo "| Тесты | 147 XCTest |"
} >> "$GITHUB_STEP_SUMMARY"
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -371,7 +371,7 @@ Headless-сканер для бенчмарков:

## Тесты

143 теста: сравнение суммы скана с `du`, агрегация мелких файлов, пакеты,
147 тестов: сравнение суммы скана с `du`, агрегация мелких файлов, пакеты,
симлинки, Unicode-имена, отказ доступа, отмена, copy-on-write удаление,
свойства squarified-раскладки, вложенные ячейки, полный цикл `AppModel`
(скан → навигация → фильтры), даты создания и изменения, правила очистки,
Expand Down
2 changes: 1 addition & 1 deletion ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
| 2.0 — Платформа | 6/6: локализация, notarization/Sparkle/Homebrew, CLI, App Intents, доступность, меню-бар |
| Backlog | 5/5: кэш, параллельный скан, бюджеты, старые файлы, APFS-клоны |

Текущая база: **143 XCTest**, 17,9 тыс. строк исходников, 398 ключей
Текущая база: **147 XCTest**, 17,9 тыс. строк исходников, 398 ключей
локализации, `main` зелёный.

## Принципы
Expand Down
4 changes: 2 additions & 2 deletions Sources/DiskScope/DiskScopeApp.swift
Original file line number Diff line number Diff line change
Expand Up @@ -83,9 +83,9 @@ struct DiskScopeApp: App {
Button("Инспектор") { model.showInspector.toggle() }
.keyboardShortcut("i", modifiers: [.command, .option])
.disabled(model.tree == nil)
Button("Быстрый просмотр") { model.previewSelection() }
Button("Быстрый просмотр") { model.inspector.previewSelection() }
.keyboardShortcut("y", modifiers: .command)
.disabled(!model.canQuickLook)
.disabled(!model.inspector.canQuickLook)
Divider()
Button("Карта папки") { model.tab = .map }
.keyboardShortcut("1", modifiers: .command)
Expand Down
113 changes: 36 additions & 77 deletions Sources/DiskScopeKit/App/AppModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -105,8 +105,8 @@ public final class AppModel: ObservableObject {
@Published public internal(set) var history: HistoryModel
@Published public internal(set) var duplicates = DuplicatesModel()
@Published public internal(set) var similar = SimilarModel()
@Published public internal(set) var inspector = InspectorModel()
@Published public var showInspector = false
@Published public var quickLookURL: URL?

@Published public internal(set) var budget = BudgetModel()

Expand Down Expand Up @@ -162,6 +162,16 @@ public final class AppModel: ObservableObject {
nav.objectWillChange.sink { [weak self] _ in
self?.objectWillChange.send()
}.store(in: &cancellables)
inspector.attach(
treeProvider: { [weak self] in self?.tree },
currentIndexProvider: { [weak self] in self?.currentIndex ?? 0 },
selectionProvider: { [weak self] in self?.selection ?? [] },
toast: { [weak self] text, symbol in self?.showToast(text, symbol: symbol) },
error: { [weak self] message in self?.errorMessage = message }
)
inspector.objectWillChange.sink { [weak self] _ in
self?.objectWillChange.send()
}.store(in: &cancellables)
trash.objectWillChange.sink { [weak self] _ in
self?.objectWillChange.send()
}.store(in: &cancellables)
Expand Down Expand Up @@ -246,6 +256,31 @@ public final class AppModel: ObservableObject {
set { nav.categoryFilter = newValue }
}

// MARK: - Inspector compatibility

public var inspectorNode: Int32? { inspector.inspectorNode }
public var canQuickLook: Bool { inspector.canQuickLook }
public var quickLookURL: URL? {
get { inspector.quickLookURL }
set { inspector.quickLookURL = newValue }
}

public func previewSelection() {
inspector.previewSelection()
}

public func previewNode(_ index: Int32) {
inspector.previewNode(index)
}

public func copyPaths(_ indices: [Int32]) {
inspector.copyPaths(indices)
}

public func openInTerminal(_ index: Int32) {
inspector.openInTerminal(index)
}

// MARK: - Derived state

public var filteredLargestRows: [ItemRow] {
Expand Down Expand Up @@ -952,82 +987,6 @@ extension AppModel {
}
}

extension AppModel {
// MARK: - Inspector and file actions

public var inspectorNode: Int32? {
if selection.count == 1 { return selection.first }
if selection.isEmpty { return currentIndex }
return nil
}

public var canQuickLook: Bool {
guard let tree else { return false }
return selection.contains { index in
index > 0 && Int(index) < tree.count
&& !tree.isDeleted(index)
&& tree.node(index).nodeKind == .file
}
}

public func previewSelection() {
guard let tree else { return }
let index = selection.sorted().first { candidate in
candidate > 0 && Int(candidate) < tree.count
&& !tree.isDeleted(candidate)
&& tree.node(candidate).nodeKind == .file
}
guard let index else {
quickLookURL = nil
return
}
previewNode(index)
}

public func previewNode(_ index: Int32) {
guard let tree, index > 0, Int(index) < tree.count,
!tree.isDeleted(index),
tree.node(index).nodeKind == .file else { return }
quickLookURL = tree.url(of: index)
}

public func copyPaths(_ indices: [Int32]) {
guard let tree else { return }
let paths = indices.compactMap { index -> String? in
guard index >= 0, Int(index) < tree.count, !tree.isDeleted(index) else { return nil }
return tree.path(of: index)
}
guard !paths.isEmpty else { return }
NSPasteboard.general.clearContents()
NSPasteboard.general.setString(paths.joined(separator: "\n"), forType: .string)
showToast(
paths.count == 1 ? "Путь скопирован" : "Скопировано путей: \(paths.count)",
symbol: "doc.on.doc"
)
}

public func openInTerminal(_ index: Int32) {
guard let tree, index >= 0, Int(index) < tree.count, !tree.isDeleted(index) else { return }
let url = tree.url(of: index)
let folder = tree.isDirectory(index) ? url : url.deletingLastPathComponent()
let terminal = URL(fileURLWithPath: "/System/Applications/Utilities/Terminal.app")
guard FileManager.default.fileExists(atPath: terminal.path) else {
errorMessage = "Не удалось найти Terminal.app"
return
}
NSWorkspace.shared.open(
[folder],
withApplicationAt: terminal,
configuration: NSWorkspace.OpenConfiguration()
) { [weak self] _, error in
guard let error else { return }
DispatchQueue.main.async {
self?.errorMessage = "Не удалось открыть терминал: \(error.localizedDescription)"
}
}
}
}

extension AppModel {
public var freeSpaceText: String {
guard let volume = internalVolume else { return "—" }
Expand Down
176 changes: 176 additions & 0 deletions Sources/DiskScopeKit/App/InspectorModel.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
import AppKit
import Combine
import Foundation

/// File-system metadata shown in the inspector for a single node.
public struct FileMetadata: Equatable, Sendable {
public let logicalSize: Int64?
public let created: Date?
public let modified: Date?
public let isPackage: Bool

public init(logicalSize: Int64?, created: Date?, modified: Date?, isPackage: Bool) {
self.logicalSize = logicalSize
self.created = created
self.modified = modified
self.isPackage = isPackage
}
}

/// Owns the inspector target, Quick Look, node metadata and file actions.
@MainActor
public final class InspectorModel: ObservableObject {
@Published public var quickLookURL: URL?
@Published public private(set) var metadata: FileMetadata?
@Published public private(set) var metadataIndex: Int32?

private var treeProvider: () -> ScanTree? = { nil }
private var currentIndexProvider: () -> Int32 = { 0 }
private var selectionProvider: () -> Set<Int32> = { [] }
private var toastHandler: (String, String) -> Void = { _, _ in }
private var errorHandler: (String) -> Void = { _ in }
private var metadataTreeID: ObjectIdentifier?

public init() {}

func attach(
treeProvider: @escaping () -> ScanTree?,
currentIndexProvider: @escaping () -> Int32,
selectionProvider: @escaping () -> Set<Int32>,
toast: @escaping (String, String) -> Void,
error: @escaping (String) -> Void
) {
self.treeProvider = treeProvider
self.currentIndexProvider = currentIndexProvider
self.selectionProvider = selectionProvider
self.toastHandler = toast
self.errorHandler = error
}

// MARK: - Inspector target

public var inspectorNode: Int32? {
let selection = selectionProvider()
if selection.count == 1 { return selection.first }
if selection.isEmpty { return currentIndexProvider() }
return nil
}

public var canQuickLook: Bool {
guard let tree = treeProvider() else { return false }
return selectionProvider().contains { index in
index > 0 && Int(index) < tree.count
&& !tree.isDeleted(index)
&& tree.node(index).nodeKind == .file
}
}

// MARK: - Quick Look

public func previewSelection() {
guard let tree = treeProvider() else { return }
let index = selectionProvider().sorted().first { candidate in
candidate > 0 && Int(candidate) < tree.count
&& !tree.isDeleted(candidate)
&& tree.node(candidate).nodeKind == .file
}
guard let index else {
quickLookURL = nil
return
}
previewNode(index)
}

public func previewNode(_ index: Int32) {
guard let tree = treeProvider(), index > 0, Int(index) < tree.count,
!tree.isDeleted(index),
tree.node(index).nodeKind == .file else { return }
quickLookURL = tree.url(of: index)
}

// MARK: - Metadata

/// Returns metadata only when it belongs to the current tree and node.
public func metadata(for index: Int32) -> FileMetadata? {
guard metadataIndex == index,
let tree = treeProvider(),
metadataTreeID == ObjectIdentifier(tree) else { return nil }
return metadata
}

public func loadMetadata(for index: Int32) {
guard let tree = treeProvider(), index > 0, Int(index) < tree.count else {
resetMetadata()
return
}
let node = tree.node(index)
guard node.nodeKind != .aggregate else {
resetMetadata()
return
}
let treeID = ObjectIdentifier(tree)
let url = tree.url(of: index)
metadata = nil
metadataIndex = index
metadataTreeID = treeID

let values = try? url.resourceValues(forKeys: [
.fileSizeKey,
.creationDateKey,
.contentModificationDateKey,
.isPackageKey,
])
guard metadataIndex == index, metadataTreeID == treeID else { return }
metadata = FileMetadata(
logicalSize: values?.fileSize.map(Int64.init),
created: values?.creationDate,
modified: values?.contentModificationDate,
isPackage: values?.isPackage ?? false
)
}

private func resetMetadata() {
metadata = nil
metadataIndex = nil
metadataTreeID = nil
}

// MARK: - File actions

public func copyPaths(_ indices: [Int32]) {
guard let tree = treeProvider() else { return }
let paths = indices.compactMap { index -> String? in
guard index >= 0, Int(index) < tree.count, !tree.isDeleted(index) else { return nil }
return tree.path(of: index)
}
guard !paths.isEmpty else { return }
NSPasteboard.general.clearContents()
NSPasteboard.general.setString(paths.joined(separator: "\n"), forType: .string)
toastHandler(
paths.count == 1 ? "Путь скопирован" : "Скопировано путей: \(paths.count)",
"doc.on.doc"
)
}

public func openInTerminal(_ index: Int32) {
guard let tree = treeProvider(), index >= 0, Int(index) < tree.count,
!tree.isDeleted(index) else { return }
let url = tree.url(of: index)
let folder = tree.isDirectory(index) ? url : url.deletingLastPathComponent()
let terminal = URL(fileURLWithPath: "/System/Applications/Utilities/Terminal.app")
guard FileManager.default.fileExists(atPath: terminal.path) else {
errorHandler("Не удалось найти Terminal.app")
return
}
NSWorkspace.shared.open(
[folder],
withApplicationAt: terminal,
configuration: NSWorkspace.OpenConfiguration()
) { [weak self] _, error in
guard let error else { return }
DispatchQueue.main.async {
self?.errorHandler("Не удалось открыть терминал: \(error.localizedDescription)")
}
}
}
}
2 changes: 1 addition & 1 deletion Sources/DiskScopeKit/UI/ContentView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ public struct ContentView: View {
.environmentObject(model)
}
.onAppear { model.refreshVolumes() }
.quickLookPreview($model.quickLookURL)
.quickLookPreview($model.inspector.quickLookURL)
.preferredColorScheme(AppAppearance(rawValue: appearance)?.colorScheme)
.environment(\.locale, AppLanguage(rawValue: language)?.locale ?? Locale.current)
}
Expand Down
2 changes: 1 addition & 1 deletion Sources/DiskScopeKit/UI/DuplicatesView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -273,7 +273,7 @@ private struct DuplicateGroupCard: View {
model.reveal(indices: [file.index])
}
IconActionButton(symbol: "eye", help: "Быстрый просмотр") {
model.previewNode(file.index)
model.inspector.previewNode(file.index)
}
}
.padding(.horizontal, 14)
Expand Down
Loading
Loading