Skip to content

Commit 22e92fd

Browse files
feat: make file tools configurable
1 parent 6e9635b commit 22e92fd

34 files changed

Lines changed: 771 additions & 129 deletions

‎App/FileMint/AppDelegate.swift‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
1515
}
1616

1717
func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply {
18-
if FileMoveCoordinator.shared.isBusy { return .terminateCancel }
18+
if FileOperationCoordinator.shared.isBusy { return .terminateCancel }
1919
if UpdateModel.shared.isCommittingInstallation && !UpdateModel.shared.canSafelyRestart {
2020
return .terminateCancel
2121
}

App/FileMint/FileMoveCoordinator.swift renamed to App/FileMint/FileOperationCoordinator.swift

Lines changed: 110 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -4,20 +4,24 @@ import FileMintCore
44
/// The main app is the sole writer of pending state and user files. Requests are
55
/// serialized across URL callbacks, including native authorization dialogs.
66
@MainActor
7-
final class FileMoveCoordinator {
8-
static let shared = FileMoveCoordinator()
7+
final class FileOperationCoordinator: NSObject, NSSharingServiceDelegate {
8+
static let shared = FileOperationCoordinator()
99
private var queue: [URL] = []
1010
private(set) var isBusy = false
1111
private var access: [URL] = []
1212
private let store: PendingFileMoveStore
13-
private let tickets: FileMoveTicketStore
13+
private let tickets: FileOperationTicketStore
1414
private let preferencesFile: URL?
15+
private var sharingService: NSSharingService?
16+
private var sharingContinuation: CheckedContinuation<Void, Error>?
17+
private var operationTitle: FileMintTextKey = .moveFailed
1518

1619
init(store: PendingFileMoveStore = PendingFileMoveStore(),
17-
tickets: FileMoveTicketStore = FileMoveTicketStore(), preferencesFile: URL? = nil) {
20+
tickets: FileOperationTicketStore = FileOperationTicketStore(), preferencesFile: URL? = nil) {
1821
self.store = store
1922
self.tickets = tickets
2023
self.preferencesFile = preferencesFile
24+
super.init()
2125
}
2226

2327
func enqueue(_ url: URL) {
@@ -33,14 +37,21 @@ final class FileMoveCoordinator {
3337
let request = try await Task.detached(priority: .userInitiated) {
3438
try tickets.consume(url)
3539
}.value
36-
if let request { try await handle(request) }
40+
if let request {
41+
switch request {
42+
case .prepare, .perform: operationTitle = .moveFailed
43+
case .permanentDelete: operationTitle = .permanentDelete
44+
case .airDrop: operationTitle = .airDrop
45+
}
46+
try await handle(request)
47+
}
3748
} catch { show(error) }
3849
releaseAccess()
3950
}
4051
}
4152
}
4253

43-
private func handle(_ request: FileMoveRequest) async throws {
54+
private func handle(_ request: FileOperationRequest) async throws {
4455
switch request {
4556
case .prepare(let selection):
4657
guard FileToolsPolicy.availableTools(selection: selection, isItemMenu: true,
@@ -58,6 +69,58 @@ final class FileMoveCoordinator {
5869
try store.save(pending)
5970
}.value
6071

72+
case .permanentDelete(let items, let confirmation):
73+
let selection = items.map(\.source)
74+
try require(.permanentDelete, selection: selection)
75+
var bookmarks: [String: Data] = [:]
76+
for parent in uniqueParents(selection) {
77+
guard try authorize(parent, bookmarks: &bookmarks) else { return }
78+
}
79+
try require(.permanentDelete, selection: selection)
80+
try await Task.detached(priority: .userInitiated) { try FileDeletionService.validate(items) }.value
81+
let requiresConfirmation = DeleteConfirmation.isRequired(captured: confirmation, current: currentPreferences.fileTools.deleteConfirmation)
82+
if requiresConfirmation {
83+
let alert = NSAlert()
84+
alert.alertStyle = .warning
85+
alert.messageText = String(format: text(.deleteConfirmTitle), items.count)
86+
alert.informativeText = text(.deleteConfirmMessage)
87+
alert.addButton(withTitle: text(.cancel))
88+
alert.addButton(withTitle: text(.permanentDelete))
89+
alert.buttons[0].keyEquivalent = "\r"
90+
alert.buttons[1].keyEquivalent = ""
91+
NSApp.activate(ignoringOtherApps: true)
92+
guard alert.runModal() == .alertSecondButtonReturn else { return }
93+
}
94+
let preferencesFile = self.preferencesFile
95+
try await Task.detached(priority: .userInitiated) {
96+
try FileDeletionService.perform(items: items) {
97+
let preferences = FileMintPreferencesStore(fileURL: preferencesFile).load()
98+
return FileToolsPolicy.availableTools(selection: selection, isItemMenu: true,
99+
preferences: preferences).contains(.permanentDelete) &&
100+
(requiresConfirmation || preferences.fileTools.deleteConfirmation == .silent)
101+
}
102+
}.value
103+
104+
case .airDrop(let selection):
105+
try require(.airDrop, selection: selection)
106+
var bookmarks: [String: Data] = [:]
107+
for parent in uniqueParents(selection) {
108+
guard try authorize(parent, bookmarks: &bookmarks, readOnly: true) else { return }
109+
}
110+
try require(.airDrop, selection: selection)
111+
guard let service = NSSharingService(named: .sendViaAirDrop), service.canPerform(withItems: selection) else {
112+
showMessage(.airDropUnavailable)
113+
return
114+
}
115+
sharingService = service
116+
service.delegate = self
117+
defer { sharingService?.delegate = nil; sharingService = nil }
118+
NSApp.activate(ignoringOtherApps: true)
119+
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in
120+
sharingContinuation = continuation
121+
service.perform(withItems: selection)
122+
}
123+
61124
case .perform(let batchID, let destination):
62125
guard var pending = try store.load(), pending.id == batchID else { throw FileMoveError.staleRequest }
63126
try validate(pending, destination: destination)
@@ -81,6 +144,29 @@ final class FileMoveCoordinator {
81144
}
82145
}
83146

147+
private func text(_ key: FileMintTextKey) -> String {
148+
FileMintStrings.text(key, language: currentPreferences.language)
149+
}
150+
151+
private func require(_ tool: FileTool, selection: [URL]) throws {
152+
guard FileToolsPolicy.availableTools(selection: selection, isItemMenu: true,
153+
preferences: currentPreferences).contains(tool) else { throw FileMoveError.disabled }
154+
}
155+
156+
func sharingService(_ sharingService: NSSharingService, didShareItems items: [Any]) {
157+
let continuation = sharingContinuation
158+
sharingContinuation = nil
159+
continuation?.resume()
160+
}
161+
162+
func sharingService(_ sharingService: NSSharingService, didFailToShareItems items: [Any], error: Error) {
163+
let continuation = sharingContinuation
164+
sharingContinuation = nil
165+
if (error as NSError).code == NSUserCancelledError {
166+
continuation?.resume()
167+
} else { continuation?.resume(throwing: error) }
168+
}
169+
84170
private var currentPreferences: FileMintPreferences { FileMintPreferencesStore(fileURL: preferencesFile).load() }
85171

86172
private func validate(_ pending: PendingFileMove, destination: URL) throws {
@@ -99,7 +185,7 @@ final class FileMoveCoordinator {
99185
/// Grants never expand the configured Finder menu scope. Existing folder
100186
/// bookmarks are already held by PreferencesModel; additional grants belong
101187
/// only to this pending operation and are released after the request.
102-
private func authorize(_ directory: URL, bookmarks: inout [String: Data]) throws -> Bool {
188+
private func authorize(_ directory: URL, bookmarks: inout [String: Data], readOnly: Bool = false) throws -> Bool {
103189
if let data = bookmarks[directory.path] {
104190
var stale = false
105191
if let restored = try? URL(resolvingBookmarkData: data, options: [.withSecurityScope, .withoutUI],
@@ -114,11 +200,11 @@ final class FileMoveCoordinator {
114200
}
115201
}
116202
let manager = FileManager.default
117-
if manager.isReadableFile(atPath: directory.path) && manager.isWritableFile(atPath: directory.path) { return true }
203+
if manager.isReadableFile(atPath: directory.path) && (readOnly || manager.isWritableFile(atPath: directory.path)) { return true }
118204
let language = currentPreferences.language
119205
let panel = NSOpenPanel()
120-
panel.title = FileMintStrings.text(.moveItems, language: language)
121-
panel.message = FileMintStrings.text(.moveAuthorizeFolder, language: language)
206+
panel.title = FileMintStrings.text(operationTitle, language: language)
207+
panel.message = FileMintStrings.text(.fileOperationAuthorize, language: language)
122208
panel.canChooseFiles = false
123209
panel.canChooseDirectories = true
124210
panel.allowsMultipleSelection = false
@@ -144,6 +230,18 @@ final class FileMoveCoordinator {
144230
}
145231

146232
private func show(_ error: Error) {
233+
if let failure = error as? FileDeletionFailure {
234+
let alert = NSAlert()
235+
alert.messageText = text(.permanentDelete)
236+
alert.informativeText = String(format: text(.deleteFailedCount), failure.completed, failure.total - failure.completed)
237+
NSApp.activate(ignoringOtherApps: true)
238+
alert.runModal()
239+
return
240+
}
241+
if operationTitle != .moveFailed {
242+
showMessage(.fileOperationFailed)
243+
return
244+
}
147245
if let error = error as? FileMoveError {
148246
let key: FileMintTextKey = switch error {
149247
case .invalidSelection: .moveInvalidSelection
@@ -156,7 +254,7 @@ final class FileMoveCoordinator {
156254
showMessage(key)
157255
} else {
158256
let alert = NSAlert()
159-
alert.messageText = FileMintStrings.text(.moveFailed, language: currentPreferences.language)
257+
alert.messageText = FileMintStrings.text(operationTitle, language: currentPreferences.language)
160258
alert.informativeText = error.localizedDescription
161259
NSApp.activate(ignoringOtherApps: true)
162260
alert.runModal()
@@ -165,7 +263,7 @@ final class FileMoveCoordinator {
165263

166264
private func showMessage(_ key: FileMintTextKey) {
167265
let alert = NSAlert()
168-
alert.messageText = FileMintStrings.text(.moveFailed, language: currentPreferences.language)
266+
alert.messageText = FileMintStrings.text(operationTitle, language: currentPreferences.language)
169267
alert.informativeText = FileMintStrings.text(key, language: currentPreferences.language)
170268
NSApp.activate(ignoringOtherApps: true)
171269
alert.runModal()

‎App/FileMint/PreferencesModel.swift‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -238,7 +238,7 @@ final class PreferencesModel: ObservableObject {
238238

239239
func handle(url: URL) {
240240
if url.scheme == "filemint", url.host == "move" {
241-
FileMoveCoordinator.shared.enqueue(url)
241+
FileOperationCoordinator.shared.enqueue(url)
242242
return
243243
}
244244
if let directory = CreationRoute.directory(from: url) {

‎App/FileMint/SettingsSections.swift‎

Lines changed: 52 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ struct GeneralPane: View {
7272
.fixedSize(horizontal: false, vertical: true)
7373
Button(model.text(.viewUpdateSettings)) { model.selectedPane = .about }
7474
}
75-
}.toggleStyle(.switch).padding(1)
75+
}.toggleStyle(SmallSettingsSwitchStyle()).padding(1)
7676
}
7777
}
7878
}
@@ -91,19 +91,54 @@ struct FileToolsPane: View {
9191
}
9292
if model.preferences.fileTools.isEnabled {
9393
SettingsSection(title: model.text(.fileToolsActions)) {
94-
Toggle(model.text(.copyItemNames), isOn: $model.preferences.fileTools.copyNames)
95-
.accessibilityIdentifier("fileTools.copyNames")
96-
Toggle(model.text(.copyItemPaths), isOn: $model.preferences.fileTools.copyPaths)
97-
.accessibilityIdentifier("fileTools.copyPaths")
98-
Toggle(model.text(.moveItems), isOn: $model.preferences.fileTools.move)
99-
.accessibilityIdentifier("fileTools.move")
94+
ForEach(FileTool.allCases, id: \.self) { tool in
95+
if tool != FileTool.allCases.first { Divider() }
96+
VStack(alignment: .leading, spacing: 10) {
97+
Toggle(model.text(tool.title), isOn: Binding(
98+
get: { model.preferences.fileTools.isToolEnabled(tool) },
99+
set: { model.preferences.fileTools.setEnabled($0, for: tool) }
100+
)).accessibilityIdentifier("fileTools.\(tool.rawValue)")
101+
Toggle(model.text(.showInMainMenu), isOn: Binding(
102+
get: { model.preferences.fileTools.mainMenuTools.contains(tool) },
103+
set: { value in
104+
if value { model.preferences.fileTools.mainMenuTools.insert(tool) }
105+
else { model.preferences.fileTools.mainMenuTools.remove(tool) }
106+
}
107+
))
108+
.accessibilityLabel("\(model.text(tool.title)) — \(model.text(.showInMainMenu))")
109+
.accessibilityIdentifier("fileTools.\(tool.rawValue).mainMenu")
110+
.disabled(!model.preferences.fileTools.isToolEnabled(tool))
111+
.padding(.leading, 16)
112+
if tool == .move {
113+
Toggle(model.text(.moveHereInMainMenu), isOn: $model.preferences.fileTools.moveHereInMainMenu)
114+
.disabled(!model.preferences.fileTools.move)
115+
.accessibilityIdentifier("fileTools.moveHere.mainMenu")
116+
.padding(.leading, 16)
117+
}
118+
if tool == .permanentDelete {
119+
Picker(model.text(.deleteConfirmation), selection: $model.preferences.fileTools.deleteConfirmation) {
120+
Text(model.text(.deleteRequireConfirmation)).tag(DeleteConfirmation.required)
121+
Text(model.text(.deleteSilently)).tag(DeleteConfirmation.silent)
122+
}.pickerStyle(.menu)
123+
.disabled(!model.preferences.fileTools.permanentDelete)
124+
.accessibilityIdentifier("fileTools.deleteConfirmation")
125+
.padding(.leading, 16)
126+
Text(model.text(.permanentDeleteHint)).font(.caption).foregroundStyle(.secondary)
127+
.fixedSize(horizontal: false, vertical: true)
128+
}
129+
if tool == .airDrop {
130+
Text(model.text(.airDropHint)).font(.caption).foregroundStyle(.secondary)
131+
.fixedSize(horizontal: false, vertical: true)
132+
}
133+
}
134+
}
100135
Text(model.text(.moveItemsHint)).font(.caption).foregroundStyle(.secondary)
101136
.fixedSize(horizontal: false, vertical: true)
102137
Text(model.text(.copyItemsHint)).font(.caption).foregroundStyle(.secondary)
103138
.fixedSize(horizontal: false, vertical: true)
104139
}
105140
}
106-
}.toggleStyle(.switch).padding(1)
141+
}.toggleStyle(SmallSettingsSwitchStyle()).padding(1)
107142
}.onChange(of: model.preferences.fileTools) { _ in model.save() }
108143
}
109144
}
@@ -130,7 +165,7 @@ struct CreationSettingsPane: View {
130165
SettingsSection(title: model.text(.afterCreation)) {
131166
Toggle(isOn: $model.preferences.revealAfterCreation) {
132167
Text(model.text(.revealCreatedFile)).frame(maxWidth: .infinity, alignment: .leading)
133-
}.toggleStyle(.switch)
168+
}.toggleStyle(SmallSettingsSwitchStyle())
134169
.onChange(of: model.preferences.revealAfterCreation) { _ in model.save() }
135170
Text(model.text(.afterCreationHint)).font(.caption).foregroundStyle(.secondary)
136171
.fixedSize(horizontal: false, vertical: true)
@@ -140,3 +175,11 @@ struct CreationSettingsPane: View {
140175
}
141176
}
142177
}
178+
179+
private struct SmallSettingsSwitchStyle: ToggleStyle {
180+
func makeBody(configuration: Configuration) -> some View {
181+
Toggle(isOn: configuration.$isOn) { configuration.label }
182+
.toggleStyle(.switch)
183+
.controlSize(.small)
184+
}
185+
}

‎App/FileMint/UpdateModel.swift‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -145,7 +145,7 @@ final class UpdateModel: ObservableObject {
145145
var canSafelyRestart: Bool {
146146
UpdateInstallationPolicy.canRestart(
147147
hasDraft: CustomFileSavePanelController.shared.hasActiveDraft,
148-
pendingCreations: PreferencesModel.shared.pendingCreationCount + (FileMoveCoordinator.shared.isBusy ? 1 : 0),
148+
pendingCreations: PreferencesModel.shared.pendingCreationCount + (FileOperationCoordinator.shared.isBusy ? 1 : 0),
149149
hasModal: NSApp.modalWindow != nil || NSApp.windows.contains { $0.attachedSheet != nil })
150150
}
151151

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
import Foundation
2+
3+
public struct FileDeletionFailure: Error, Sendable {
4+
public let completed: Int
5+
public let total: Int
6+
}
7+
8+
/// No background traversal: only remove items captured by an explicit menu click.
9+
public enum FileDeletionService {
10+
public static func capture(_ selection: [URL]) throws -> [FileMoveItem] {
11+
let items = try PendingFileMove.capture(selection: selection).items
12+
try validate(items)
13+
return items
14+
}
15+
16+
public static func validate(_ items: [FileMoveItem]) throws {
17+
guard !items.isEmpty else { throw FileMoveError.invalidSelection }
18+
for item in items {
19+
guard item.source.standardizedFileURL.path != "/" else { throw FileMoveError.invalidSelection }
20+
try item.validateIdentity()
21+
// A mounted volume is not an ordinary selected directory.
22+
let parent = try FileManager.default.attributesOfItem(atPath: item.canonicalParent.path)
23+
guard (parent[.systemNumber] as? NSNumber)?.uint64Value == item.device else {
24+
throw FileMoveError.invalidSelection
25+
}
26+
}
27+
let fresh = try PendingFileMove.capture(selection: items.map(\.source)).items
28+
guard fresh == items else { throw FileMoveError.sourceChanged }
29+
}
30+
31+
public static func perform(items: [FileMoveItem], isAllowed: () -> Bool) throws {
32+
var completed = 0
33+
do {
34+
guard isAllowed() else { throw FileMoveError.disabled }
35+
// Validate the whole batch before the first irreversible action.
36+
try validate(items)
37+
for item in items {
38+
guard isAllowed() else { throw FileMoveError.disabled }
39+
try item.validateIdentity()
40+
// removeItem removes a selected symlink itself, not its target.
41+
try FileManager.default.removeItem(at: item.source)
42+
completed += 1
43+
}
44+
} catch {
45+
throw FileDeletionFailure(completed: completed, total: items.count)
46+
}
47+
}
48+
}

0 commit comments

Comments
 (0)