From aaceaee74fbac728248f5b2203504ee600e6b741 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Wed, 25 Nov 2026 16:43:50 +0700 Subject: [PATCH 1/2] fix(transfer): show progress and results inside the import, export and transfer sheets --- .../SQLImportOptionsView.swift | 40 ++- .../PluginInstallProgressPresenter.swift | 52 +--- .../Core/Plugins/PluginInstallPrompt.swift | 135 +++++++-- .../Components/TransferProgressView.swift | 30 +- .../Views/Components/TransferResult.swift | 179 ++++++++++++ ...esultAlert.swift => TransferResults.swift} | 263 +++++++----------- .../TablePro/Views/Export/ExportDialog.swift | 168 ++++++----- .../Views/Export/ExportProgressView.swift | 41 +++ .../Views/Export/TableTransferSheet.swift | 76 +++-- .../TablePro/Views/Import/ImportDialog.swift | 198 +++++++------ .../Views/Import/ImportProgressView.swift | 59 ++-- .../Views/Import/RowImportBatchSheet.swift | 157 ++++++----- .../Views/Import/RowImportSheet.swift | 153 +++++----- .../ObjectCopy/CopyObjectsProgressView.swift | 2 +- .../Core/Plugins/PluginInstallRunTests.swift | 84 ++++++ .../ImportServiceSessionScopeTests.swift | 2 +- .../Services/ImportServiceStopTests.swift | 12 +- .../Views/ImportCancelledTextTests.swift | 16 +- .../Views/ImportSummaryTextTests.swift | 4 +- .../Views/TransferFailureReportTests.swift | 28 +- .../Views/TransferResultsTests.swift | 143 ++++++++++ .../RowImportUpdateUITests.swift | 4 + 22 files changed, 1203 insertions(+), 643 deletions(-) create mode 100644 apple/TablePro/Views/Components/TransferResult.swift rename apple/TablePro/Views/Components/{TransferResultAlert.swift => TransferResults.swift} (66%) create mode 100644 apple/TableProTests/Core/Plugins/PluginInstallRunTests.swift create mode 100644 apple/TableProTests/Views/TransferResultsTests.swift diff --git a/apple/Plugins/SQLImportPlugin/SQLImportOptionsView.swift b/apple/Plugins/SQLImportPlugin/SQLImportOptionsView.swift index 33aef2fefa..83503cb639 100644 --- a/apple/Plugins/SQLImportPlugin/SQLImportOptionsView.swift +++ b/apple/Plugins/SQLImportPlugin/SQLImportOptionsView.swift @@ -9,31 +9,27 @@ import TableProPluginKit struct SQLImportOptionsView: View { @ObservedObject var plugin: SQLImportPlugin + // Flat rows, so the host's Form lines them up with its own; a VStack would make them one row. var body: some View { - VStack(alignment: .leading, spacing: 12) { - Picker("On error:", selection: $plugin.settings.errorHandling) { - Text("Stop and Rollback").tag(ImportErrorHandling.stopAndRollback) - Text("Stop and Commit").tag(ImportErrorHandling.stopAndCommit) - Text("Skip and Continue").tag(ImportErrorHandling.skipAndContinue) - } - .pickerStyle(.menu) - .font(.system(size: 13)) + Picker("On error:", selection: $plugin.settings.errorHandling) { + Text("Stop and Rollback").tag(ImportErrorHandling.stopAndRollback) + Text("Stop and Commit").tag(ImportErrorHandling.stopAndCommit) + Text("Skip and Continue").tag(ImportErrorHandling.skipAndContinue) + } + .pickerStyle(.menu) - Toggle("Wrap in transaction (BEGIN/COMMIT)", isOn: $plugin.settings.wrapInTransaction) - .font(.system(size: 13)) - .disabled(plugin.settings.errorHandling == .skipAndContinue) - .help(plugin.settings.errorHandling == .skipAndContinue - ? String(localized: "Not available in skip-and-continue mode") - : String( - localized: "Runs every statement in one transaction, so a failure rolls back what the import changed. A database that commits CREATE, ALTER and DROP as they run, such as MySQL, keeps those statements and everything before them." - )) + Toggle("Wrap in transaction (BEGIN/COMMIT)", isOn: $plugin.settings.wrapInTransaction) + .disabled(plugin.settings.errorHandling == .skipAndContinue) + .help(plugin.settings.errorHandling == .skipAndContinue + ? String(localized: "Not available in skip-and-continue mode") + : String( + localized: "Runs every statement in one transaction, so a failure rolls back what the import changed. A database that commits CREATE, ALTER and DROP as they run, such as MySQL, keeps those statements and everything before them." + )) - Toggle("Disable foreign key checks", isOn: $plugin.settings.disableForeignKeyChecks) - .font(.system(size: 13)) - .help( - "Temporarily disable foreign key constraints during import. Useful for importing data with circular dependencies." - ) - } + Toggle("Disable foreign key checks", isOn: $plugin.settings.disableForeignKeyChecks) + .help( + "Temporarily disable foreign key constraints during import. Useful for importing data with circular dependencies." + ) } } diff --git a/apple/TablePro/Core/Plugins/PluginInstallProgressPresenter.swift b/apple/TablePro/Core/Plugins/PluginInstallProgressPresenter.swift index 07d85f62c3..567b0907fe 100644 --- a/apple/TablePro/Core/Plugins/PluginInstallProgressPresenter.swift +++ b/apple/TablePro/Core/Plugins/PluginInstallProgressPresenter.swift @@ -31,8 +31,7 @@ internal final class PluginInstallProgressPresenter: NSObject { } } - private let pluginName: String - private let tracker: PluginInstallTracker + private let install: PluginInstallRun private var panel: NSPanel? private var sheetParent: NSWindow? private let indicator = NSProgressIndicator() @@ -42,14 +41,10 @@ internal final class PluginInstallProgressPresenter: NSObject { target: self, action: #selector(cancelInstall) ) - private var followed: AnyCancellable? - private var pluginId: String? - private var cancelTask: (() -> Void)? - private(set) var didCancel = false + private var rendered: AnyCancellable? private init(pluginName: String, tracker: PluginInstallTracker) { - self.pluginName = pluginName - self.tracker = tracker + install = PluginInstallRun(pluginName: pluginName, tracker: tracker) super.init() } @@ -61,46 +56,22 @@ internal final class PluginInstallProgressPresenter: NSObject { _ install: @escaping Install ) async throws { let presenter = PluginInstallProgressPresenter(pluginName: pluginName, tracker: tracker) - let task = Task { @MainActor in - try await install { pluginId in presenter.follow(pluginId: pluginId) } - } - presenter.cancelTask = { task.cancel() } presenter.begin(window: window) defer { presenter.end() } - do { - try await withTaskCancellationHandler { - try await task.value - } onCancel: { - task.cancel() - } - } catch { - guard !presenter.didCancel, !PluginInstallTracker.isCancellation(error) else { throw CancellationError() } - throw error - } - } - - private func follow(pluginId: String) { - self.pluginId = pluginId - followed = tracker.$entries.sink { [weak self] entries in - guard let self else { return } - render(Display.make(pluginName: pluginName, phase: entries[pluginId]?.phase)) - } + try await presenter.install.run(install) } @objc private func cancelInstall() { - didCancel = true - cancelButton.isEnabled = false - if let pluginId { - tracker.cancel(pluginId: pluginId) - } - cancelTask?() + install.cancel() } private func begin(window: NSWindow?) { guard panel == nil else { return } let panel = makePanel() self.panel = panel - render(Display.make(pluginName: pluginName, phase: nil)) + rendered = install.$display.combineLatest(install.$didCancel).sink { [weak self] display, cancelled in + self?.render(display, cancelled: cancelled) + } guard let parent = AlertHelper.resolveWindow(window) else { panel.center() @@ -111,11 +82,12 @@ internal final class PluginInstallProgressPresenter: NSObject { parent.beginSheet(panel) } - private func render(_ display: Display) { + // @Published delivers before the property changes, so the cancel state comes in with the display. + private func render(_ display: Display, cancelled: Bool) { label.stringValue = display.message indicator.setAccessibilityLabel(display.message) panel?.setAccessibilityLabel(display.message) - cancelButton.isEnabled = display.canCancel && !didCancel + cancelButton.isEnabled = display.canCancel && !cancelled if let fraction = display.fraction { if indicator.isIndeterminate { indicator.stopAnimation(nil) @@ -129,7 +101,7 @@ internal final class PluginInstallProgressPresenter: NSObject { } private func end() { - followed = nil + rendered = nil indicator.stopAnimation(nil) guard let panel else { return } self.panel = nil diff --git a/apple/TablePro/Core/Plugins/PluginInstallPrompt.swift b/apple/TablePro/Core/Plugins/PluginInstallPrompt.swift index 4ad9906417..a25d620287 100644 --- a/apple/TablePro/Core/Plugins/PluginInstallPrompt.swift +++ b/apple/TablePro/Core/Plugins/PluginInstallPrompt.swift @@ -1,4 +1,5 @@ import AppKit +import Combine import os @MainActor @@ -7,13 +8,17 @@ internal enum PluginInstallPrompt { internal typealias Install = PluginInstallProgressPresenter.Install - internal static func ensureInstalled(_ format: InstallableExportFormat, window: NSWindow?) async -> Bool { - await confirmAndRun( - pluginName: format.displayName, + // Only asks: a sheet that offers the format runs the install in place, so no panel opens on top of it. + internal static func confirmInstall(_ format: InstallableExportFormat, window: NSWindow?) async -> Bool { + await confirm( title: String(format: String(localized: "Install the %@ plugin?"), format.displayName), message: String(localized: "TablePro writes this format with a plugin it downloads from the plugin registry."), window: window - ) { onBegin in + ) + } + + internal static func install(_ format: InstallableExportFormat) -> Install { + { onBegin in try await PluginManager.shared.installMissingExportFormat(format, onBegin: onBegin) } } @@ -45,20 +50,53 @@ internal enum PluginInstallPrompt { internal static func run(pluginName: String, window: NSWindow?, _ install: @escaping Install) async -> Bool { do { try await PluginInstallProgressPresenter.run(pluginName: pluginName, window: window, install) - logger.info("Installed the \(pluginName, privacy: .public) plugin") - return true - } catch is CancellationError { - logger.info("Install of the \(pluginName, privacy: .public) plugin was cancelled") + } catch { + reportFailure(error, pluginName: pluginName, window: window) return false + } + logger.info("Installed the \(pluginName, privacy: .public) plugin") + return true + } + + // The caller shows `progress` as its sheet's root. `onEnd` takes it down before a failure alert goes on that sheet. + internal static func run( + _ progress: PluginInstallRun, + window: NSWindow?, + onEnd: () -> Void, + _ install: @escaping Install + ) async -> Bool { + do { + try await progress.run(install) } catch { - logger.error("Install failed for \(pluginName, privacy: .public): \(error.publicLogShape, privacy: .public)") - AlertHelper.showErrorSheet( - title: String(localized: "Plugin Installation Failed"), - message: error.localizedDescription, - window: window - ) + onEnd() + reportFailure(error, pluginName: progress.pluginName, window: window) return false } + onEnd() + logger.info("Installed the \(progress.pluginName, privacy: .public) plugin") + return true + } + + private static func reportFailure(_ error: any Error, pluginName: String, window: NSWindow?) { + guard !(error is CancellationError) else { + logger.info("Install of the \(pluginName, privacy: .public) plugin was cancelled") + return + } + logger.error("Install failed for \(pluginName, privacy: .public): \(error.publicLogShape, privacy: .public)") + AlertHelper.showErrorSheet( + title: String(localized: "Plugin Installation Failed"), + message: error.localizedDescription, + window: window + ) + } + + private static func confirm(title: String, message: String, window: NSWindow?) async -> Bool { + await AlertHelper.confirm( + title: title, + message: message, + confirmButton: String(localized: "Install"), + window: window + ) } private static func confirmAndRun( @@ -68,13 +106,68 @@ internal enum PluginInstallPrompt { window: NSWindow?, install: @escaping Install ) async -> Bool { - let confirmed = await AlertHelper.confirm( - title: title, - message: message, - confirmButton: String(localized: "Install"), - window: window - ) - guard confirmed else { return false } + guard await confirm(title: title, message: message, window: window) else { return false } return await run(pluginName: pluginName, window: window, install) } } + +// An install shown inside the caller's own sheet, with the panel presenter's tracker entry, cancel and errors. +@MainActor +internal final class PluginInstallRun: ObservableObject { + @Published internal private(set) var display: PluginInstallProgressPresenter.Display + @Published internal private(set) var didCancel = false + internal let pluginName: String + private let tracker: PluginInstallTracker + private var followed: AnyCancellable? + private var pluginId: String? + private var task: Task? + + internal var canCancel: Bool { + display.canCancel && !didCancel + } + + internal init(pluginName: String, tracker: PluginInstallTracker = .shared) { + self.pluginName = pluginName + self.tracker = tracker + display = .make(pluginName: pluginName, phase: nil) + } + + // Throws `CancellationError` when the user cancelled, here or through the tracker entry. + internal func run(_ install: @escaping PluginInstallPrompt.Install) async throws { + let task = Task { @MainActor in + try await install { pluginId in self.follow(pluginId: pluginId) } + } + self.task = task + defer { + self.task = nil + followed = nil + } + do { + try await withTaskCancellationHandler { + try await task.value + } onCancel: { + task.cancel() + } + } catch { + guard !didCancel, !PluginInstallTracker.isCancellation(error) else { throw CancellationError() } + throw error + } + } + + internal func cancel() { + guard canCancel else { return } + didCancel = true + if let pluginId { + tracker.cancel(pluginId: pluginId) + } + task?.cancel() + } + + private func follow(pluginId: String) { + self.pluginId = pluginId + followed = tracker.$entries.sink { [weak self] entries in + guard let self else { return } + display = .make(pluginName: pluginName, phase: entries[pluginId]?.phase) + } + } +} diff --git a/apple/TablePro/Views/Components/TransferProgressView.swift b/apple/TablePro/Views/Components/TransferProgressView.swift index 4a09272df4..c622007987 100644 --- a/apple/TablePro/Views/Components/TransferProgressView.swift +++ b/apple/TablePro/Views/Components/TransferProgressView.swift @@ -6,6 +6,8 @@ import SwiftUI internal struct TransferProgressView: View { + internal static let sheetWidth: CGFloat = 420 + internal let progress: TransferProgress internal var body: some View { @@ -83,31 +85,39 @@ internal struct TransferStopButton: View { } } -internal struct TransferProgressSheet: View { - internal static let width: CGFloat = 420 - +// The root of a transfer sheet while its job runs. A job whose stop needs more than one question passes its own control. +internal struct TransferProgressSheet: View { internal let progress: TransferProgress - internal let onStop: () -> Void + private let stopControl: StopControl + + internal init(progress: TransferProgress, @ViewBuilder stopControl: () -> StopControl) { + self.progress = progress + self.stopControl = stopControl() + } internal var body: some View { VStack(alignment: .leading, spacing: 16) { TransferProgressView(progress: progress) HStack { Spacer() - TransferStopButton( - policy: progress.stopPolicy, - isStopping: progress.isStopping, - onStop: onStop - ) + stopControl } } .controlSize(.regular) .padding(20) - .frame(width: Self.width) + .frame(width: TransferProgressView.sheetWidth) .interactiveDismissDisabled() } } +internal extension TransferProgressSheet where StopControl == TransferStopButton { + init(progress: TransferProgress, onStop: @escaping () -> Void) { + self.init(progress: progress) { + TransferStopButton(policy: progress.stopPolicy, isStopping: progress.isStopping, onStop: onStop) + } + } +} + #Preview("Export") { TransferProgressSheet( progress: TransferProgress( diff --git a/apple/TablePro/Views/Components/TransferResult.swift b/apple/TablePro/Views/Components/TransferResult.swift new file mode 100644 index 0000000000..8296ba32d8 --- /dev/null +++ b/apple/TablePro/Views/Components/TransferResult.swift @@ -0,0 +1,179 @@ +// +// TransferResult.swift +// TablePro +// + +import AppKit +import SwiftUI +import TableProPluginKit + +internal struct TransferResult: Sendable { + internal enum Outcome: Equatable, Sendable { + case succeeded + case succeededWithIssues + case stopped + case failed + } + + internal struct Details: Hashable, Sendable { + internal let shown: String + internal let copied: String + } + + internal struct ErrorReport: Sendable { + internal let errors: [PluginImportResult.ImportStatementError] + internal let totalSkipped: Int + } + + internal let outcome: Outcome + internal let title: String + internal let message: String + internal let details: Details? + internal let errorReport: ErrorReport? + + internal init( + outcome: Outcome, + title: String, + message: String = "", + details: Details? = nil, + errorReport: ErrorReport? = nil + ) { + self.outcome = outcome + self.title = title + self.message = message + self.details = details + self.errorReport = errorReport + } + + internal var severity: NoticeSeverity { + switch outcome { + case .succeeded: return .success + case .succeededWithIssues, .stopped: return .warning + case .failed: return .error + } + } + + // A failed or stopped job keeps its form, so the user can change it and run it again. + internal var returnsToForm: Bool { + outcome == .failed || outcome == .stopped + } +} + +// The root of a transfer sheet once its job ended, in place of an alert on top of the sheet. +internal struct TransferResultView: View { + private let result: TransferResult + private let onBack: (() -> Void)? + private let onDone: () -> Void + private let accessory: Accessory + private let actions: Actions + + internal init( + _ result: TransferResult, + onBack: (() -> Void)? = nil, + onDone: @escaping () -> Void, + @ViewBuilder accessory: () -> Accessory, + @ViewBuilder actions: () -> Actions + ) { + self.result = result + self.onBack = onBack + self.onDone = onDone + self.accessory = accessory() + self.actions = actions() + } + + internal var body: some View { + VStack(alignment: .leading, spacing: 16) { + VStack(alignment: .leading, spacing: 6) { + Label { + Text(result.title) + .font(.headline) + } icon: { + Image(systemName: result.severity.symbolName) + .foregroundStyle(result.severity.tint) + .accessibilityHidden(true) + } + if !result.message.isEmpty { + Text(result.message) + .font(.callout) + .foregroundStyle(.secondary) + .textSelection(.enabled) + .fixedSize(horizontal: false, vertical: true) + } + } + + if let details = result.details { + TransferReportBox(details: details) + .id(details) + } + + accessory + + DialogFooter { + actions + if let onBack { + Button(String(localized: "Back"), action: onBack) + } + Button(String(localized: "Done"), action: onDone) + .keyboardShortcut(.defaultAction) + } + } + .controlSize(.regular) + .padding(20) + .frame(width: TransferProgressView.sheetWidth) + .accessibilityElement(children: .contain) + .accessibilityIdentifier("transfer-result") + } +} + +internal extension TransferResultView where Accessory == EmptyView { + init( + _ result: TransferResult, + onBack: (() -> Void)? = nil, + onDone: @escaping () -> Void, + @ViewBuilder actions: () -> Actions + ) { + self.init(result, onBack: onBack, onDone: onDone, accessory: { EmptyView() }, actions: actions) + } +} + +internal extension TransferResultView where Accessory == EmptyView, Actions == EmptyView { + init(_ result: TransferResult, onBack: (() -> Void)? = nil, onDone: @escaping () -> Void) { + self.init(result, onBack: onBack, onDone: onDone, accessory: { EmptyView() }, actions: { EmptyView() }) + } +} + +// The bezeled AppKit text view the result alerts carried, so a long report scrolls and selects the same way. +private struct TransferReportBox: NSViewRepresentable { + let details: TransferResult.Details + + func makeNSView(context: Context) -> TransferReportView { + TransferReportView(shown: details.shown, copied: details.copied) + } + + func updateNSView(_ nsView: TransferReportView, context: Context) {} +} + +#Preview("Import completed with errors") { + TransferResultView( + TransferResult( + outcome: .succeededWithIssues, + title: "Import completed with errors", + message: "100,013 statements executed, 2 failed\n12.40 seconds", + details: TransferResult.Details( + shown: "Line 412: Duplicate entry\nINSERT INTO users VALUES (1)", + copied: "Line 412: Duplicate entry\nINSERT INTO users VALUES (1)" + ) + ), + onDone: {} + ) { + Button("Save Report…") {} + } +} + +#Preview("Import failed") { + TransferResultView( + TransferResult(outcome: .failed, title: "Import failed", message: "Failed at line 7. relation \"x\" does not exist"), + onBack: {}, + onDone: {} + ) +} diff --git a/apple/TablePro/Views/Components/TransferResultAlert.swift b/apple/TablePro/Views/Components/TransferResults.swift similarity index 66% rename from apple/TablePro/Views/Components/TransferResultAlert.swift rename to apple/TablePro/Views/Components/TransferResults.swift index 41747e67df..14acfd8144 100644 --- a/apple/TablePro/Views/Components/TransferResultAlert.swift +++ b/apple/TablePro/Views/Components/TransferResults.swift @@ -1,66 +1,45 @@ // -// TransferResultAlert.swift +// TransferResults.swift // TablePro // import AppKit +import os import TableProPluginKit import UniformTypeIdentifiers +// What a finished export, transfer or import reports in its own sheet. @MainActor -internal enum TransferResultAlert { - internal static let exportSuppressionKey = "hideExportSuccessDialog" - - internal enum ExportChoice { - case openFolder - case close - } +internal enum TransferResults { + private static let logger = Logger(subsystem: "com.TablePro", category: "TransferResults") - internal static func presentExportSuccess( - warnings: [String], - notes: [String] = [], - window: NSWindow?, - completion: @escaping @MainActor (ExportChoice) -> Void - ) { - let alert = NSAlert() - alert.messageText = warnings.isEmpty - ? String(localized: "Export completed") - : String(localized: "Export completed with warnings") - alert.alertStyle = warnings.isEmpty ? .informational : .warning - alert.informativeText = (notes + warnings).joined(separator: "\n\n") - alert.addButton(withTitle: String(localized: "Open in Finder")) - AlertHelper.addCancelButton(to: alert, title: String(localized: "Done")) - alert.showsSuppressionButton = warnings.isEmpty - alert.suppressionButton?.title = String(localized: "Do not show this again") - - let deliver: @MainActor (NSApplication.ModalResponse) -> Void = { response in - if alert.suppressionButton?.state == .on { - AppStorageEnvironment.shared.defaults.set(true, forKey: exportSuppressionKey) - } - completion(response == .alertFirstButtonReturn ? .openFolder : .close) - } + internal static let exportSuppressionKey = "hideExportSuccessDialog" - AlertHelper.present(alert, in: window, completion: deliver) + internal static func exportSucceeded(warnings: [String], notes: [String] = []) -> TransferResult { + TransferResult( + outcome: warnings.isEmpty ? .succeeded : .succeededWithIssues, + title: warnings.isEmpty + ? String(localized: "Export completed") + : String(localized: "Export completed with warnings"), + message: (notes + warnings).joined(separator: "\n\n") + ) } - internal static func presentTransferSuccess( + internal static func transferSucceeded( tableCount: Int, rowCount: Int, destinationName: String, - warnings: [String], - window: NSWindow?, - completion: @escaping @MainActor () -> Void - ) { - let alert = NSAlert() - alert.messageText = warnings.isEmpty - ? String(localized: "Transfer completed") - : String(localized: "Transfer completed with warnings") - alert.alertStyle = warnings.isEmpty ? .informational : .warning - alert.informativeText = ([transferSummary( - tableCount: tableCount, rowCount: rowCount, destinationName: destinationName - )] + warnings).joined(separator: "\n\n") - AlertHelper.addCancelButton(to: alert, title: String(localized: "Done")) - AlertHelper.present(alert, in: window) { _ in completion() } + warnings: [String] + ) -> TransferResult { + TransferResult( + outcome: warnings.isEmpty ? .succeeded : .succeededWithIssues, + title: warnings.isEmpty + ? String(localized: "Transfer completed") + : String(localized: "Transfer completed with warnings"), + message: ([transferSummary( + tableCount: tableCount, rowCount: rowCount, destinationName: destinationName + )] + warnings).joined(separator: "\n\n") + ) } private static func transferSummary( @@ -74,20 +53,15 @@ internal enum TransferResultAlert { return String(format: template, Int64(rowCount), destinationName, Int64(tableCount)) } - internal static func presentImportCancelled( - result: ImportStopResult, - window: NSWindow?, - completion: @escaping @MainActor () -> Void - ) { - let alert = NSAlert() - alert.messageText = String(localized: "Import stopped") - alert.alertStyle = .warning - alert.informativeText = String(localized: "The details below show what happened to the import.") - if !result.completionNotes.isEmpty { alert.informativeText += "\n" + shownErrors(result.completionNotes) } - alert.accessoryView = TransferReportView(shown: result.text, copied: result.details) - AlertHelper.addCancelButton(to: alert, title: String(localized: "Done")) - alert.layout() - AlertHelper.present(alert, in: window) { _ in completion() } + internal static func importStopped(_ result: ImportStopResult) -> TransferResult { + var message = String(localized: "The details below show what happened to the import.") + if !result.completionNotes.isEmpty { message += "\n" + shownErrors(result.completionNotes) } + return TransferResult( + outcome: .stopped, + title: String(localized: "Import stopped"), + message: message, + details: TransferResult.Details(shown: result.text, copied: result.details) + ) } internal static func importCancelledText(executedStatements: Int, transaction: ImportTransactionOutcome) -> String { @@ -118,61 +92,43 @@ internal enum TransferResultAlert { return String(format: template, Int64(executedStatements)) } - internal static func presentImportSuccess( + internal static func importSucceeded( result: PluginImportResult?, rowTally: ImportRowTally? = nil, - runResult: ImportStopResult? = nil, - window: NSWindow?, - sourceFileName: String = "", - targetTable: String? = nil, - completion: @escaping @MainActor () -> Void - ) { - let alert = NSAlert() + runResult: ImportStopResult? = nil + ) -> TransferResult { let skipped = result?.skippedStatements ?? 0 - alert.messageText = skipped > 0 - ? String(localized: "Import completed with errors") - : String(localized: "Import completed") - alert.alertStyle = skipped > 0 ? .warning : .informational - alert.informativeText = importSummary(result, rowTally: rowTally) - AlertHelper.addCancelButton(to: alert, title: String(localized: "Done")) + var message = importSummary(result, rowTally: rowTally) + var details: TransferResult.Details? if let runResult, !runResult.completionNotes.isEmpty { - alert.informativeText += "\n" + shownErrors(runResult.completionNotes) - alert.accessoryView = TransferReportView(shown: runResult.text, copied: runResult.details) - alert.layout() + message += "\n" + shownErrors(runResult.completionNotes) + details = TransferResult.Details(shown: runResult.text, copied: runResult.details) } let errors = result?.errors ?? [] + var errorReport: TransferResult.ErrorReport? if !errors.isEmpty { - alert.addButton(withTitle: String(localized: "Save Report…")) - let details = failureReport(for: errors) + (runResult.map { "\n\n" + $0.details } ?? "") - alert.accessoryView = TransferReportView(report: details) - alert.layout() + let report = failureReport(for: errors) + (runResult.map { "\n\n" + $0.details } ?? "") + details = TransferResult.Details(shown: report, copied: report) + errorReport = TransferResult.ErrorReport(errors: errors, totalSkipped: skipped) } - AlertHelper.present(alert, in: window) { response in - guard !errors.isEmpty, response == .alertSecondButtonReturn else { - completion() - return - } - saveErrorReport( - errors: errors, - totalSkipped: skipped, - sourceFileName: sourceFileName, - targetTable: targetTable, - window: window, - completion: completion - ) - } + return TransferResult( + outcome: skipped > 0 ? .succeededWithIssues : .succeeded, + title: skipped > 0 + ? String(localized: "Import completed with errors") + : String(localized: "Import completed"), + message: message, + details: details, + errorReport: errorReport + ) } - @MainActor - private static func saveErrorReport( - errors: [PluginImportResult.ImportStatementError], - totalSkipped: Int, + internal static func saveErrorReport( + _ report: TransferResult.ErrorReport, sourceFileName: String, targetTable: String?, - window: NSWindow?, - completion: @escaping @MainActor () -> Void + window: NSWindow? ) { let panel = NSSavePanel() panel.canCreateDirectories = true @@ -182,15 +138,23 @@ internal enum TransferResultAlert { panel.title = String(localized: "Save Import Errors") let handler: @MainActor (NSApplication.ModalResponse) -> Void = { response in - defer { completion() } guard response == .OK, let url = panel.url else { return } let csv = ImportErrorReport.makeCSV( sourceFileName: sourceFileName, targetTable: targetTable, - errors: errors, - totalSkipped: totalSkipped + errors: report.errors, + totalSkipped: report.totalSkipped ) - try? csv.write(to: url, atomically: true, encoding: .utf8) + do { + try csv.write(to: url, atomically: true, encoding: .utf8) + } catch { + logger.error("Failed to save the import error report: \(error.publicLogShape, privacy: .public)") + AlertHelper.showErrorSheet( + title: String(localized: "Couldn't Save File"), + message: error.localizedDescription, + window: window + ) + } } guard let window else { @@ -202,36 +166,34 @@ internal enum TransferResultAlert { } } - internal static func presentBatchImportResult( - _ report: RowImportBatchReport, - window: NSWindow?, - completion: @escaping @MainActor () -> Void - ) { - let alert = NSAlert() + internal static func batchImport(_ report: RowImportBatchReport) -> TransferResult { + let outcome: TransferResult.Outcome + let title: String switch report.ending { case .completed: - alert.messageText = report.hasFailures + outcome = report.hasFailures ? .succeededWithIssues : .succeeded + title = report.hasFailures ? String(localized: "Import completed with errors") : String(localized: "Import completed") - alert.alertStyle = report.hasFailures ? .warning : .informational case .failed: - alert.messageText = String(localized: "Import failed") - alert.alertStyle = .critical + outcome = .failed + title = String(localized: "Import failed") case .stopped: - alert.messageText = String(localized: "Import stopped") - alert.alertStyle = .warning + outcome = .stopped + title = String(localized: "Import stopped") } - alert.informativeText = shownErrors(batchImportSummary(report)) - AlertHelper.addCancelButton(to: alert, title: String(localized: "Done")) let lines = batchImportLines(report) let preparation = report.stopResult?.ledger.preparationNote.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" - alert.accessoryView = TransferReportView( - shown: ([preparation] + lines).filter { !$0.isEmpty }.joined(separator: "\n"), - copied: ([lines.joined(separator: "\n")] + batchImportErrors(report) - + [report.stopResult?.details ?? ""]).joined(separator: "\n\n") + return TransferResult( + outcome: outcome, + title: title, + message: shownErrors(batchImportSummary(report)), + details: TransferResult.Details( + shown: ([preparation] + lines).filter { !$0.isEmpty }.joined(separator: "\n"), + copied: ([lines.joined(separator: "\n")] + batchImportErrors(report) + + [report.stopResult?.details ?? ""]).joined(separator: "\n\n") + ) ) - alert.layout() - AlertHelper.present(alert, in: window) { _ in completion() } } internal static func batchImportSummary(_ report: RowImportBatchReport) -> String { @@ -337,33 +299,22 @@ internal enum TransferResultAlert { } } - internal static func presentImportFailure( - error: (any Error)?, - result: ImportStopResult? = nil, - window: NSWindow?, - completion: @escaping @MainActor () -> Void - ) { - let alert = NSAlert() - alert.messageText = String(localized: "Import failed") - alert.alertStyle = .critical - alert.addButton(withTitle: String(localized: "Done")) - alert.informativeText = importFailureDisplay(error: error, result: result) - + internal static func importFailed(error: (any Error)?, result: ImportStopResult? = nil) -> TransferResult { + var details: TransferResult.Details? if let result { - let details = importFailureSummary(error: error, result: result) + let shown = importFailureSummary(error: error, result: result) + "\n\n" + (failureReport(for: error) ?? "") - alert.accessoryView = TransferReportView(shown: details, copied: details + "\n\n" + result.details) - alert.layout() + details = TransferResult.Details(shown: shown, copied: shown + "\n\n" + result.details) } else if let pluginError = error as? PluginImportError, case .statementFailed(let statement, _, _) = pluginError { - alert.accessoryView = TransferReportView( - shown: statement, - copied: (failureReport(for: error) ?? statement) + "\n\n" + (result?.details ?? "") - ) - alert.layout() + details = TransferResult.Details(shown: statement, copied: failureReport(for: error) ?? statement) } - - AlertHelper.present(alert, in: window) { _ in completion() } + return TransferResult( + outcome: .failed, + title: String(localized: "Import failed"), + message: importFailureDisplay(error: error, result: result), + details: details + ) } internal static func importFailureDisplay(error: (any Error)?, result: ImportStopResult?) -> String { @@ -464,10 +415,15 @@ internal final class TransferReportView: NSView { internal static let shownLengthLimit = 10_000 internal static func shownText(_ text: String) -> String { - TransferResultAlert.cut(text, toUnits: shownLengthLimit) ?? text + TransferResults.cut(text, toUnits: shownLengthLimit) ?? text } private let report: String + private let height: CGFloat + + override internal var intrinsicContentSize: NSSize { + NSSize(width: Self.width, height: height) + } internal convenience init(report: String) { self.init(shown: report, copied: report) @@ -478,12 +434,8 @@ internal final class TransferReportView: NSView { let button = NSButton(title: String(localized: "Copy Details"), target: nil, action: nil) button.bezelStyle = .push button.sizeToFit() - super.init(frame: NSRect( - x: 0, - y: 0, - width: Self.width, - height: Self.textHeight + Self.spacing + button.frame.height - )) + height = Self.textHeight + Self.spacing + button.frame.height + super.init(frame: NSRect(x: 0, y: 0, width: Self.width, height: height)) let scroll = AlertHelper.scrollingTextAccessory(RevealedText(Self.shownText(shown)).plainText) scroll.frame = NSRect( @@ -504,6 +456,7 @@ internal final class TransferReportView: NSView { internal required init?(coder: NSCoder) { report = "" + height = 0 super.init(coder: coder) } diff --git a/apple/TablePro/Views/Export/ExportDialog.swift b/apple/TablePro/Views/Export/ExportDialog.swift index 565a3a9d90..8b7a3dd906 100644 --- a/apple/TablePro/Views/Export/ExportDialog.swift +++ b/apple/TablePro/Views/Export/ExportDialog.swift @@ -20,25 +20,28 @@ struct ExportDialog: View { @State private var config = ExportConfiguration() @State private var databaseItems: [ExportDatabaseItem] = [] @State private var isLoading = true - @State private var isExporting = false + @State private var phase: Phase = .form + @State private var suppressesSuccess = false @State private var exportStartedAt: ContinuousClock.Instant? - @State private var showProgressDialog = false - @State private var showSuccessDialog = false @State private var exportedFileURL: URL? @State private var settingsSnapshot: PluginSettingsSnapshot? @State private var exportSucceeded = false - /// Which object kinds the last load actually read, so a format switch knows whether the tree it - /// already holds can answer for the new format without another round trip. + private enum Phase { + case form + case installing(PluginInstallRun) + case running + case finished(TransferResult) + } + + // Lets a format switch tell whether the tree it holds answers for the new format without another load. @State private var loadedObjectKinds: Set = [] @State private var formatReconciliation: Task? - /// Bumped each time a reload replaces the tree, so a container read started against the old - /// tree cannot land in the new one. + // Bumped per reload, so a container read started against the old tree cannot land in the new one. @State private var treeGeneration = 0 - /// A container read in flight. A second ask for the same container, from a profile or another - /// expansion, waits for it rather than reading twice or acting before it lands. + // A second ask for a container being read, from a profile or an expansion, waits for that read. @State private var objectReads: [UUID: ObjectRead] = [:] private struct ObjectRead { @@ -53,9 +56,7 @@ struct ExportDialog: View { @State private var isNamingProfile = false @State private var profileApplication = 0 - /// The window this dialog is hosted in, used for presenting its alerts and panels. - /// Avoids `NSApp.keyWindow`, which when a result is presented is the progress sheet being - /// torn down in the same transaction, and AppKit ends a sheet's children with it (#2314). + // Alerts and panels go on this sheet's window, not `NSApp.keyWindow`, which can be a closing sheet (#2314). @State private var hostWindow: NSWindow? // MARK: - User Preferences @@ -110,33 +111,29 @@ struct ExportDialog: View { return .tables(names: [], scope: nil) } + private var isExporting: Bool { + if case .running = phase { return true } + return false + } + // MARK: - Body + // A ZStack, not a Group, whose modifiers reach each phase view: a phase switch must not run onDisappear. var body: some View { - VStack(spacing: 0) { - HStack(spacing: 0) { - if !exportsSingleResult { - tableSelectionView - .frame(minWidth: leftPanelWidth, maxWidth: .infinity) - - Divider() + ZStack { + switch phase { + case .form: + formView + case .installing(let install): + PluginInstallProgressSheet(install: install) + case .running: + ExportProgressSheet(service: exportService ?? waitingService, fileName: config.fileName) { + run.stop() } - - exportOptionsView - .frame(width: Self.optionsPanelWidth) + case .finished(let result): + resultView(result) } - .frame(minHeight: 320, idealHeight: 420, maxHeight: .infinity) - - Divider() - - footerView } - .frame( - minWidth: dialogWidth, - idealWidth: dialogWidth, - maxWidth: exportsSingleResult ? dialogWidth : .infinity - ) - .background(Color(nsColor: .windowBackgroundColor)) .background { WindowAccessor { window in hostWindow = window @@ -164,9 +161,15 @@ struct ExportDialog: View { restoreSettingsSnapshot() } } + // Stop and the install's Cancel own Escape while they show. .onExitCommand { - if !isExporting { + switch phase { + case .form: isPresented = false + case .installing, .running: + break + case .finished: + closeFromResult() } } .task { @@ -180,27 +183,61 @@ struct ExportDialog: View { populateFromSidebarTables(of: connection) await loadDatabaseItems(of: connection) } - .sheet(isPresented: $showProgressDialog) { - ExportProgressSheet(service: exportService ?? waitingService, fileName: config.fileName) { - run.stop() + } + + private var formView: some View { + VStack(spacing: 0) { + HStack(spacing: 0) { + if !exportsSingleResult { + tableSelectionView + .frame(minWidth: leftPanelWidth, maxWidth: .infinity) + + Divider() + } + + exportOptionsView + .frame(width: Self.optionsPanelWidth) } + .frame(minHeight: 320, idealHeight: 420, maxHeight: .infinity) + + Divider() + + footerView } - .onChange(of: showSuccessDialog) { isShowing in - guard isShowing else { return } - TransferResultAlert.presentExportSuccess( - warnings: exportService?.state.warnings ?? [], - notes: exportService?.state.notes ?? [], - window: hostWindow - ) { choice in - showSuccessDialog = false - if choice == .openFolder { + .frame( + minWidth: dialogWidth, + idealWidth: dialogWidth, + maxWidth: exportsSingleResult ? dialogWidth : .infinity + ) + .background(Color(nsColor: .windowBackgroundColor)) + } + + @ViewBuilder + private func resultView(_ result: TransferResult) -> some View { + if result.returnsToForm { + TransferResultView(result, onBack: { phase = .form }, onDone: { closeFromResult() }) + } else { + TransferResultView(result, onDone: { closeFromResult() }) { + if result.outcome == .succeeded { + Toggle("Do not show this again", isOn: $suppressesSuccess) + .toggleStyle(.checkbox) + } + } actions: { + Button("Show in Finder") { openContainingFolder() + closeFromResult() } - isPresented = false } } } + private func closeFromResult() { + if suppressesSuccess { + hideSuccessDialog = true + } + isPresented = false + } + // MARK: - Plugin Helpers private var availableFormats: [any ExportFormatPlugin] { @@ -245,9 +282,18 @@ struct ExportDialog: View { @MainActor private func installOfferedFormat(_ format: InstallableExportFormat) async { - guard await PluginInstallPrompt.ensureInstalled(format, window: hostWindow), - let plugin = pluginManager.exportPlugin(forFormat: format.formatId) + guard case .form = phase, + await PluginInstallPrompt.confirmInstall(format, window: hostWindow) else { return } + let install = PluginInstallRun(pluginName: format.displayName) + phase = .installing(install) + let installed = await PluginInstallPrompt.run( + install, + window: hostWindow, + onEnd: { phase = .form }, + PluginInstallPrompt.install(format) + ) + guard installed, let plugin = pluginManager.exportPlugin(forFormat: format.formatId) else { return } if let settable = plugin as? any SettablePluginDiscoverable { settingsSnapshot?.include(settable) } @@ -933,11 +979,11 @@ struct ExportDialog: View { private func showExportError(_ error: Error) { reportExportFinished(.failed(reason: error.localizedDescription)) - AlertHelper.showErrorSheet( + phase = .finished(TransferResult( + outcome: .failed, title: String(localized: "Export Error"), - message: error.localizedDescription, - window: hostWindow - ) + message: error.localizedDescription + )) } @MainActor @@ -967,7 +1013,6 @@ struct ExportDialog: View { } private func beginExport(to url: URL) { - isExporting = true exportStartedAt = .now exportedFileURL = url exportService = nil @@ -981,7 +1026,7 @@ struct ExportDialog: View { connectionIds: Set([connection?.id].compactMap { $0 }), scope: sheetWork ) { stopper.stop() } - showProgressDialog = true + phase = .running } private func endRunningWork() { @@ -998,25 +1043,22 @@ struct ExportDialog: View { } private func finishSuccessfulExport() { - showProgressDialog = false - isExporting = false recordSuccessfulExport() - - if hideSuccessDialog, exportService?.state.warnings.isEmpty ?? true { + let warnings = exportService?.state.warnings ?? [] + if hideSuccessDialog, warnings.isEmpty { isPresented = false - } else { - showSuccessDialog = true + return } + phase = .finished(TransferResults.exportSucceeded(warnings: warnings, notes: exportService?.state.notes ?? [])) } // A driver can report a stop as an error of its own, so a requested stop decides first. private func finishExport(throwing error: any Error) { - showProgressDialog = false - isExporting = false let wasStopped = run.isStopRequested || error is PluginExportCancellationError || error is CancellationError guard !wasStopped else { + phase = .form reportExportFinished(.cancelled) return } diff --git a/apple/TablePro/Views/Export/ExportProgressView.swift b/apple/TablePro/Views/Export/ExportProgressView.swift index 5f3ea20de4..4a2334121c 100644 --- a/apple/TablePro/Views/Export/ExportProgressView.swift +++ b/apple/TablePro/Views/Export/ExportProgressView.swift @@ -16,6 +16,47 @@ struct ExportProgressSheet: View { } } +// The export sheet's root while an offered format's plugin installs, in place of a panel on top of the sheet. +struct PluginInstallProgressSheet: View { + @ObservedObject var install: PluginInstallRun + + var body: some View { + VStack(alignment: .leading, spacing: 16) { + VStack(alignment: .leading, spacing: 8) { + Text(install.display.message) + .lineLimit(1) + .truncationMode(.middle) + bar + .accessibilityLabel(install.display.message) + } + HStack { + Spacer() + Button(String(localized: "Cancel")) { + install.cancel() + } + .keyboardShortcut(.cancelAction) + .disabled(!install.canCancel) + } + } + .controlSize(.regular) + .padding(20) + .frame(width: TransferProgressView.sheetWidth) + .accessibilityElement(children: .contain) + .accessibilityIdentifier("plugin-install-progress") + } + + @ViewBuilder + private var bar: some View { + if let fraction = install.display.fraction { + ProgressView(value: min(max(fraction, 0), 1)) + .progressViewStyle(.linear) + } else { + ProgressView() + .progressViewStyle(.linear) + } + } +} + extension ExportState { // A streaming query has no current table, so it is named by the file it is written to. func transferProgress(fileName: String) -> TransferProgress { diff --git a/apple/TablePro/Views/Export/TableTransferSheet.swift b/apple/TablePro/Views/Export/TableTransferSheet.swift index a4e70f6c4c..860875db62 100644 --- a/apple/TablePro/Views/Export/TableTransferSheet.swift +++ b/apple/TablePro/Views/Export/TableTransferSheet.swift @@ -8,11 +8,7 @@ import os import SwiftUI import TableProPluginKit -/// Copies rows from the open connection into another one, with no file in between. -/// -/// Rows only: the destination table has to exist. Creating it would mean translating one engine's -/// DDL into another's, which is a different problem, and getting it half right would leave tables -/// whose column types quietly disagree with the data now in them. +// Rows only, into tables that exist: creating them means translating one engine's DDL into another's. struct TableTransferSheet: View { @ObservedObject private var databaseManager = DatabaseManager.shared private static let logger = Logger(subsystem: "com.TablePro", category: "TableTransferSheet") @@ -37,12 +33,17 @@ struct TableTransferSheet: View { @State private var deleteExistingRows = false @State private var wrapInTransaction = true @State private var isLoading = true - @State private var isRunning = false + @State private var phase: Phase = .form @State private var errorMessage: String? @State private var hostWindow: NSWindow? - /// Source and destination columns per table, plus the user's overrides, so the sheet can show - /// what will map before anything is written. + private enum Phase { + case form + case running + case finished(TransferResult) + } + + // Read before anything is written, so the sheet can show what will map. @State private var sourceColumns: [String: [String]] = [:] @State private var destinationColumns: [String: [String]] = [:] @State private var overrides: [String: [String: String?]] = [:] @@ -58,6 +59,11 @@ struct TableTransferSheet: View { sourceTables.filter(\.isSelected) } + private var isRunning: Bool { + if case .running = phase { return true } + return false + } + private var canTransfer: Bool { !isRunning && !selectedTables.isEmpty && destinationScope != nil && !hasContestedMapping } @@ -68,7 +74,34 @@ struct TableTransferSheet: View { selectedTables.contains { !resolvedMatch(for: $0.name).contestedDestinations.isEmpty } } + // A ZStack, not a Group, whose modifiers reach each phase view: a phase switch must not run onDisappear. var body: some View { + ZStack { + switch phase { + case .form: + formView + case .running: + TransferProgressSheet(progress: transferProgress, onStop: { service.cancel() }) + case .finished(let result): + TransferResultView(result, onDone: { isPresented = false }) + } + } + .background { + WindowAccessor { window in hostWindow = window } + } + .task { await load() } + // Stop owns Escape while the transfer runs. + .onExitCommand { + switch phase { + case .form, .finished: + isPresented = false + case .running: + break + } + } + } + + private var formView: some View { VStack(spacing: 0) { header @@ -87,17 +120,6 @@ struct TableTransferSheet: View { } .frame(minWidth: 460, minHeight: 420, idealHeight: 460, maxHeight: .infinity) .background(Color(nsColor: .windowBackgroundColor)) - .background { - WindowAccessor { window in hostWindow = window } - } - .task { await load() } - .onExitCommand { - guard !isRunning else { return } - isPresented = false - } - .sheet(isPresented: $isRunning) { - TransferProgressSheet(progress: transferProgress) { service.cancel() } - } } private var header: some View { @@ -554,7 +576,7 @@ struct TableTransferSheet: View { errorMessage = nil service.prepareForRun() - isRunning = true + phase = .running let transferService = service let job = SheetJob( .tableTransfer, @@ -567,8 +589,11 @@ struct TableTransferSheet: View { ) { transferService.cancel() } + // Anything but a success returns to the form, which shows the error inline. defer { - isRunning = false + if isRunning { + phase = .form + } job.end() } @@ -645,15 +670,12 @@ struct TableTransferSheet: View { // Counted from the run, since the selection is the form's and could differ from what ran. @MainActor private func presentResult(destination: DatabaseConnection) { - TransferResultAlert.presentTransferSuccess( + phase = .finished(TransferResults.transferSucceeded( tableCount: service.state.totalTables, rowCount: service.state.transferredRows, destinationName: destination.name, - warnings: service.state.warnings, - window: hostWindow - ) { - isPresented = false - } + warnings: service.state.warnings + )) } @MainActor diff --git a/apple/TablePro/Views/Import/ImportDialog.swift b/apple/TablePro/Views/Import/ImportDialog.swift index caa8fc3732..d11f358026 100644 --- a/apple/TablePro/Views/Import/ImportDialog.swift +++ b/apple/TablePro/Views/Import/ImportDialog.swift @@ -39,11 +39,7 @@ struct ImportDialog: View { @State private var selectedFormatId: String = "sql" @State private var settingsSnapshot: PluginSettingsSnapshot? @State private var importSucceeded = false - @State private var showProgressDialog = false - @State private var showSuccessDialog = false - @State private var showErrorDialog = false - @State private var importResult: PluginImportResult? - @State private var importError: (any Error)? + @State private var phase: Phase = .form @State private var hostWindow: NSWindow? @@ -57,30 +53,42 @@ struct ImportDialog: View { @State private var importService: ImportService? + private enum Phase { + case form + case running + case finished(TransferResult) + } + // MARK: - Body + // A ZStack, not a Group, whose modifiers reach each phase view: a phase switch must not run onDisappear. var body: some View { - VStack(spacing: 0) { - VStack(spacing: 16) { - fileInfoView - - Divider() - - if availableFormats.count > 1 { - formatPickerView - Divider() + ZStack { + switch phase { + case .form: + formView + case .running: + if let service = importService { + ImportProgressView(service: service) + } + case .finished(let result): + TransferResultView( + result, + onBack: result.returnsToForm ? { phase = .form } : nil, + onDone: { closeAfterRun() } + ) { + if let report = result.errorReport { + Button("Save Report…") { + TransferResults.saveErrorReport( + report, + sourceFileName: fileURL?.lastPathComponent ?? "", + targetTable: nil, + window: hostWindow + ) + } + } } - - filePreviewView - - optionsView } - .padding(16) - .frame(width: 600, height: 550) - - Divider() - - footerView } .background { WindowAccessor { window in @@ -96,9 +104,15 @@ struct ImportDialog: View { } captureSettingsSnapshot() } + // While running, the Stop button owns Escape and asks first. .onExitCommand { - if !(importService?.state.isImporting ?? false) { + switch phase { + case .form: isPresented = false + case .running: + break + case .finished: + closeAfterRun() } } .task { @@ -109,6 +123,14 @@ struct ImportDialog: View { await load.value } } + .onChange(of: selectedEncoding) { _ in + loadFileTask?.cancel() + if let url = fileURL { + loadFileTask = Task { + await loadFile(url) + } + } + } .onDisappear { loadFileTask?.cancel() countStatementsTask?.cancel() @@ -118,31 +140,26 @@ struct ImportDialog: View { restoreSettingsSnapshot() } } - .sheet(isPresented: $showProgressDialog) { - if let service = importService { - ImportProgressView(service: service) - } - } - .onChange(of: showSuccessDialog) { isShowing in - guard isShowing else { return } - TransferResultAlert.presentImportSuccess( - result: importResult, - runResult: importService?.stopResult, - window: hostWindow, - sourceFileName: fileURL?.lastPathComponent ?? "", - targetTable: nil - ) { - showSuccessDialog = false - isPresented = false - AppCommands.shared.refreshData.send(DataRefreshRequest(connectionId: connection.id)) - } - } - .onChange(of: showErrorDialog) { isShowing in - guard isShowing else { return } - TransferResultAlert.presentImportFailure(error: importError, result: importService?.stopResult, window: hostWindow) { - showErrorDialog = false + } + + private var formView: some View { + VStack(spacing: 0) { + VStack(spacing: 16) { + fileInfoView + + Divider() + + filePreviewView + + optionsView } + .padding(16) + + Divider() + + footerView } + .frame(width: 600) } // MARK: - Plugin Helpers @@ -216,25 +233,6 @@ struct ImportDialog: View { .frame(maxWidth: .infinity, alignment: .leading) } - private var formatPickerView: some View { - HStack(spacing: 8) { - Text("Format:") - .font(.body) - .frame(width: 80, alignment: .leading) - - Picker(String(localized: "Format"), selection: $selectedFormatId) { - ForEach(availableFormats.map { (id: type(of: $0).formatId, name: type(of: $0).formatDisplayName) }, id: \.id) { item in - Text(item.name).tag(item.id) - } - } - .pickerStyle(.menu) - .labelsHidden() - .frame(width: 120) - - Spacer() - } - } - private var filePreviewView: some View { VStack(alignment: .leading, spacing: 6) { Text("Preview") @@ -242,7 +240,7 @@ struct ImportDialog: View { .foregroundStyle(.primary) SQLCodePreview(text: $filePreview) - .frame(height: availableFormats.count > 1 ? 220 : 280) + .frame(height: 280) .clipShape(RoundedRectangle(cornerRadius: 6)) .overlay( RoundedRectangle(cornerRadius: 6) @@ -267,37 +265,30 @@ struct ImportDialog: View { .font(.callout) } - VStack(alignment: .leading, spacing: 12) { - HStack(spacing: 8) { - Text("Encoding:") - .font(.body) - .frame(width: 80, alignment: .leading) - - Picker(String(localized: "Encoding"), selection: $selectedEncoding) { - ForEach(ImportEncoding.allCases) { enc in - Text(enc.label).tag(enc) + // A plugin view of flat rows lines up with these rows; one wrapped in a VStack is a single row. + Form { + if availableFormats.count > 1 { + Picker("Format:", selection: $selectedFormatId) { + ForEach(availableFormats.map { (id: type(of: $0).formatId, name: type(of: $0).formatDisplayName) }, id: \.id) { item in + Text(item.name).tag(item.id) } } .pickerStyle(.menu) - .labelsHidden() - .frame(width: 120) - .onChange(of: selectedEncoding) { _ in - loadFileTask?.cancel() - if let url = fileURL { - loadFileTask = Task { - await loadFile(url) - } - } - } + } - Spacer() + Picker("Encoding:", selection: $selectedEncoding) { + ForEach(ImportEncoding.allCases) { enc in + Text(enc.label).tag(enc) + } } + .pickerStyle(.menu) if let settable = currentPlugin as? any SettablePluginDiscoverable, let pluginView = settable.settingsView() { pluginView } } + .formStyle(.columns) } .frame(maxWidth: .infinity, alignment: .leading) } @@ -347,6 +338,12 @@ struct ImportDialog: View { settingsSnapshot = nil } + private func closeAfterRun() { + isPresented = false + guard importSucceeded else { return } + AppCommands.shared.refreshData.send(DataRefreshRequest(connectionId: connection.id)) + } + @MainActor private func selectFile() async { guard let window = hostWindow else { @@ -509,7 +506,7 @@ struct ImportDialog: View { let ownsDecompressedFile = decompressedURL != nil tempPreviewURL = nil - showProgressDialog = true + phase = .running importTask = Task { do { @@ -527,32 +524,25 @@ struct ImportDialog: View { ) await MainActor.run { - showProgressDialog = false - importResult = result recordSuccessfulImport() - showSuccessDialog = true + phase = .finished(TransferResults.importSucceeded(result: result, runResult: service.stopResult)) } } catch is PluginImportCancellationError { await MainActor.run { - showProgressDialog = false - TransferResultAlert.presentImportCancelled( - result: service.stopResult, - window: hostWindow - ) {} + phase = .finished(TransferResults.importStopped(service.stopResult)) } } catch let refusal as ExecutionGateError { await MainActor.run { - showProgressDialog = false - guard case .denied = refusal else { return } - importError = refusal - showErrorDialog = true + guard case .denied = refusal else { + phase = .form + return + } + phase = .finished(TransferResults.importFailed(error: refusal, result: service.stopResult)) } return } catch { await MainActor.run { - showProgressDialog = false - importError = error - showErrorDialog = true + phase = .finished(TransferResults.importFailed(error: error, result: service.stopResult)) } } CatalogChangeService.post(.changed(CatalogChange(connectionId: connection.id, kinds: .everything))) diff --git a/apple/TablePro/Views/Import/ImportProgressView.swift b/apple/TablePro/Views/Import/ImportProgressView.swift index 939bd6d089..88b9e4aba2 100644 --- a/apple/TablePro/Views/Import/ImportProgressView.swift +++ b/apple/TablePro/Views/Import/ImportProgressView.swift @@ -9,39 +9,40 @@ struct ImportProgressView: View { @ObservedObject var service: ImportService var body: some View { - VStack(alignment: .leading, spacing: 16) { - TransferProgressView(progress: service.state.transferProgress) - HStack { - Spacer() - Button(buttonTitle) { service.requestStop() } - .disabled(service.stopPhase != .running) - .keyboardShortcut(.cancelAction) - } + TransferProgressSheet(progress: service.state.transferProgress) { + ImportStopButton(service: service) } - .controlSize(.regular) - .padding(20) - .frame(width: TransferProgressSheet.width) - .interactiveDismissDisabled() - .alert(String(localized: "Stop Import?"), isPresented: questionPresented, presenting: service.stopQuestion) { question in - if question.ledger.canChooseCommit { - Button(String(localized: "Stop and Rollback"), role: .destructive) { - service.answerStop(.rollBack, generation: question.generation) - } - Button(String(localized: "Stop and Commit")) { - service.answerStop(.commit, generation: question.generation) + } +} + +// An import pauses before it asks, since whether it can still commit depends on where the pause landed. +struct ImportStopButton: View { + @ObservedObject var service: ImportService + + var body: some View { + Button(buttonTitle) { service.requestStop() } + .disabled(service.stopPhase != .running) + .keyboardShortcut(.cancelAction) + .alert(String(localized: "Stop Import?"), isPresented: questionPresented, presenting: service.stopQuestion) { question in + if question.ledger.canChooseCommit { + Button(String(localized: "Stop and Rollback"), role: .destructive) { + service.answerStop(.rollBack, generation: question.generation) + } + Button(String(localized: "Stop and Commit")) { + service.answerStop(.commit, generation: question.generation) + } + } else { + Button(String(localized: "Stop Import"), role: .destructive) { + service.answerStop(.rollBack, generation: question.generation) + } } - } else { - Button(String(localized: "Stop Import"), role: .destructive) { - service.answerStop(.rollBack, generation: question.generation) + Button(String(localized: "Continue"), role: .cancel) { + service.answerStop(nil, generation: question.generation) } + } message: { question in + Text(question.ledger.question) } - Button(String(localized: "Continue"), role: .cancel) { - service.answerStop(nil, generation: question.generation) - } - } message: { question in - Text(question.ledger.question) - } - .onDisappear { service.stopUnansweredQuestion() } + .onDisappear { service.stopUnansweredQuestion() } } private var questionPresented: Binding { diff --git a/apple/TablePro/Views/Import/RowImportBatchSheet.swift b/apple/TablePro/Views/Import/RowImportBatchSheet.swift index 1abd1cb007..78e408b837 100644 --- a/apple/TablePro/Views/Import/RowImportBatchSheet.swift +++ b/apple/TablePro/Views/Import/RowImportBatchSheet.swift @@ -10,8 +10,16 @@ import TableProPluginKit import UniformTypeIdentifiers struct RowImportBatchSheet: View { - private struct EditRequest: Identifiable { - let id: RowImportBatch.File.ID + private enum Phase { + case list + case editing(RowImportBatch.File.ID) + case running(ImportService) + case finished(TransferResult, changes: [DatabaseObjectChange]) + + var editedFile: RowImportBatch.File.ID? { + if case .editing(let id) = self { return id } + return nil + } } @ObservedObject private var pluginManager = PluginManager.shared @@ -19,17 +27,14 @@ struct RowImportBatchSheet: View { let connection: DatabaseConnection @StateObject private var batch: RowImportBatch + @State private var phase: Phase = .list @State private var shownFormat: String? - @State private var editing: EditRequest? @State private var isDropTargeted = false @State private var settingsSnapshot: PluginSettingsSnapshot? @State private var importSucceeded = false - @State private var importService: ImportService? - @State private var showProgressDialog = false @State private var importTask: Task? - @State private var hostWindow: NSWindow? init( isPresented: Binding, @@ -48,7 +53,50 @@ struct RowImportBatchSheet: View { )) } + // A ZStack, not a Group, whose modifiers reach each phase view: a phase switch must not run onDisappear. var body: some View { + ZStack { + switch phase { + case .list: + listView + case .editing(let id): + editView(for: id) + case .running(let service): + ImportProgressView(service: service) + case .finished(let result, let changes): + TransferResultView( + result, + onBack: result.returnsToForm ? { backToList(posting: changes) } : nil, + onDone: { done(posting: changes) } + ) + } + } + .background { signatureObservers } + .task { + settingsSnapshot = PluginSettingsSnapshot(plugins: batch.formatIds.compactMap { + plugin(for: $0) as? any SettablePluginDiscoverable + }) + for formatId in batch.formatIds { + batch.setSignature(plugin(for: formatId)?.fieldDetectionSignature ?? "", for: formatId) + } + await batch.loadTables() + } + .task(id: batch.readRequest) { + await batch.readFiles() + } + .onDisappear { + importTask?.cancel() + if !importSucceeded { settingsSnapshot?.restore() } + settingsSnapshot = nil + } + // The result's only shortcut is Return. Cancel, the editor's Cancel and Stop own Escape in the other phases. + .onExitCommand { + guard case .finished(_, let changes) = phase else { return } + done(posting: changes) + } + } + + private var listView: some View { VStack(spacing: 0) { headerView .padding() @@ -56,9 +104,6 @@ struct RowImportBatchSheet: View { fileTable .frame(maxWidth: .infinity, minHeight: 200, maxHeight: .infinity) - .sheet(item: $editing) { request in - editSheet(for: request.id) - } .onDrop(of: [.fileURL], isTargeted: $isDropTargeted) { providers in accept(providers) } @@ -85,34 +130,6 @@ struct RowImportBatchSheet: View { .padding() } .frame(minWidth: 780, minHeight: 600, idealHeight: 680, maxHeight: .infinity) - .background { - WindowAccessor { window in - hostWindow = window - } - } - .background { signatureObservers } - .task { - settingsSnapshot = PluginSettingsSnapshot(plugins: batch.formatIds.compactMap { - plugin(for: $0) as? any SettablePluginDiscoverable - }) - for formatId in batch.formatIds { - batch.setSignature(plugin(for: formatId)?.fieldDetectionSignature ?? "", for: formatId) - } - await batch.loadTables() - } - .task(id: batch.readRequest) { - await batch.readFiles() - } - .onDisappear { - importTask?.cancel() - if !importSucceeded { settingsSnapshot?.restore() } - settingsSnapshot = nil - } - .sheet(isPresented: $showProgressDialog) { - if let service = importService { - ImportProgressView(service: service) - } - } } // MARK: - Header @@ -216,7 +233,7 @@ struct RowImportBatchSheet: View { Button(String(localized: "Try Again")) { batch.retryRead(of: file.id) } .buttonStyle(.link) } else { - Button(String(localized: "Edit…")) { editing = EditRequest(id: file.id) } + Button(String(localized: "Edit…")) { phase = .editing(file.id) } .buttonStyle(.link) .disabled(batch.scope == nil) .accessibilityLabel(Text(String(format: String(localized: "Edit the import of %@"), file.sourceName))) @@ -285,12 +302,12 @@ struct RowImportBatchSheet: View { } @ViewBuilder - private func editSheet(for id: RowImportBatch.File.ID) -> some View { + private func editView(for id: RowImportBatch.File.ID) -> some View { if let file = batch.file(id), let edit = batch.edit(for: id, onDone: { batch.apply($0, to: id) }) { RowImportSheet( isPresented: Binding( - get: { editing?.id == id }, - set: { if !$0 { editing = nil } } + get: { phase.editedFile == id }, + set: { if !$0 { phase = .list } } ), connection: connection, fileURL: file.url, @@ -298,6 +315,8 @@ struct RowImportBatchSheet: View { formatId: file.formatId, edit: edit ) + } else { + listView } } @@ -370,7 +389,7 @@ struct RowImportBatchSheet: View { .keyboardShortcut(.cancelAction) Button("Import") { performImport() } .buttonStyle(.borderedProminent) - .disabled(!batch.canImport || importService?.state.isImporting == true) + .disabled(!batch.canImport) .keyboardShortcut(.defaultAction) } } @@ -402,13 +421,12 @@ struct RowImportBatchSheet: View { private func performImport() { guard let scope = batch.scope else { - TransferResultAlert.presentImportFailure(error: DatabaseError.notConnected, window: hostWindow) {} + phase = .finished(TransferResults.importFailed(error: DatabaseError.notConnected), changes: []) return } guard let plan = batch.plan(), let policy = batch.policy else { return } let service = ImportService(connection: connection) - importService = service - showProgressDialog = true + phase = .running(service) importTask = Task { do { @@ -441,37 +459,40 @@ struct RowImportBatchSheet: View { policy: policy, authorization: authorization ) - showProgressDialog = false - present(report, scope: scope) + show(report, scope: scope) } catch ExecutionGateError.cancelledByUser { - showProgressDialog = false - } catch is PluginImportCancellationError { - showProgressDialog = false - TransferResultAlert.presentImportCancelled(result: service.stopResult, window: hostWindow) {} - } catch is CancellationError { - showProgressDialog = false - TransferResultAlert.presentImportCancelled(result: service.stopResult, window: hostWindow) {} + phase = .list + } catch is PluginImportCancellationError, is CancellationError { + phase = .finished(TransferResults.importStopped(service.stopResult), changes: []) } catch { - showProgressDialog = false - TransferResultAlert.presentImportFailure(error: error, result: service.stopResult, window: hostWindow) {} + phase = .finished(TransferResults.importFailed(error: error, result: service.stopResult), changes: []) } } } - private func present(_ report: RowImportBatchReport, scope: DatabaseScope) { - let completed = report.ending == .completed - if completed { + private func show(_ report: RowImportBatchReport, scope: DatabaseScope) { + if report.ending == .completed { importSucceeded = true } - TransferResultAlert.presentBatchImportResult(report, window: hostWindow) { - for table in Set(report.files.map(\.targetTable)) { - AppCommands.shared.objectChanged.send( - DatabaseObjectChange(connectionId: connection.id, scope: scope, name: table, kind: .rows) - ) - } - if completed { - isPresented = false - } + let changes = Set(report.files.map(\.targetTable)).map { table in + DatabaseObjectChange(connectionId: connection.id, scope: scope, name: table, kind: .rows) + } + phase = .finished(TransferResults.batchImport(report), changes: changes) + } + + private func backToList(posting changes: [DatabaseObjectChange]) { + post(changes) + phase = .list + } + + private func done(posting changes: [DatabaseObjectChange]) { + post(changes) + isPresented = false + } + + private func post(_ changes: [DatabaseObjectChange]) { + for change in changes { + AppCommands.shared.objectChanged.send(change) } } } diff --git a/apple/TablePro/Views/Import/RowImportSheet.swift b/apple/TablePro/Views/Import/RowImportSheet.swift index 6dc4b45a03..e73a228152 100644 --- a/apple/TablePro/Views/Import/RowImportSheet.swift +++ b/apple/TablePro/Views/Import/RowImportSheet.swift @@ -29,6 +29,12 @@ struct RowImportSheet: View { private typealias Destination = RowImportDestination + private enum Phase { + case form + case running + case finished(TransferResult) + } + private struct SourceRead: Hashable { let destination: Destination let scope: DatabaseScope? @@ -77,14 +83,9 @@ struct RowImportSheet: View { @State private var importSucceeded = false @State private var importService: ImportService? - @State private var importResult: PluginImportResult? - @State private var importTally: ImportRowTally? @State private var importedRows: DatabaseObjectChange? - @State private var importError: (any Error)? - @State private var showProgressDialog = false - @State private var showSuccessDialog = false - @State private var showErrorDialog = false @State private var importTask: Task? + @State private var phase: Phase = .form @State private var newTablePlanner = NewTableImportPlanner() @@ -143,32 +144,35 @@ struct RowImportSheet: View { return nil } + // A ZStack, not a Group, whose modifiers reach each phase view: a phase switch must not run onDisappear. var body: some View { - VStack(spacing: 0) { - headerView - .padding() - Divider() - - destinationForm - .padding(.horizontal) - .padding(.vertical, 10) - Divider() - - contentArea - .frame(maxWidth: .infinity, maxHeight: .infinity) - Divider() - - if edit == nil { - optionsForm - .padding(.horizontal) - .padding(.vertical, 10) - Divider() + ZStack { + switch phase { + case .form: + formView + case .running: + if let service = importService { + ImportProgressView(service: service) + } + case .finished(let result): + TransferResultView( + result, + onBack: result.returnsToForm ? { phase = .form } : nil, + onDone: { closeAfterRun() } + ) { + if let report = result.errorReport { + Button("Save Report…") { + TransferResults.saveErrorReport( + report, + sourceFileName: sourceName, + targetTable: importedRows?.name ?? selectedTargetTable, + window: hostWindow + ) + } + } + } } - - footerView - .padding() } - .frame(minWidth: 720, minHeight: 560, idealHeight: 640, maxHeight: .infinity) .background { WindowAccessor { window in hostWindow = window @@ -197,38 +201,50 @@ struct RowImportSheet: View { .onChange(of: currentPlugin?.fieldDetectionSignature) { newValue in detectionSignature = newValue ?? "" } + // The form's Cancel and, while running, the Stop button own Escape; Stop asks first. + .onExitCommand { + guard case .finished = phase else { return } + closeAfterRun() + } .onDisappear { importTask?.cancel() if !importSucceeded { settingsSnapshot?.restore() } settingsSnapshot = nil } - .sheet(isPresented: $showProgressDialog) { - if let service = importService { - ImportProgressView(service: service) - } - } - .onChange(of: showSuccessDialog) { isShowing in - guard isShowing else { return } - TransferResultAlert.presentImportSuccess( - result: importResult, - rowTally: importTally, - runResult: importService?.stopResult, - window: hostWindow, - sourceFileName: sourceName, - targetTable: selectedTargetTable - ) { - showSuccessDialog = false - isPresented = false - if let importedRows { - AppCommands.shared.objectChanged.send(importedRows) - } + } + + private var formView: some View { + VStack(spacing: 0) { + headerView + .padding() + Divider() + + destinationForm + .padding(.horizontal) + .padding(.vertical, 10) + Divider() + + contentArea + .frame(maxWidth: .infinity, maxHeight: .infinity) + Divider() + + if edit == nil { + optionsForm + .padding(.horizontal) + .padding(.vertical, 10) + Divider() } + + footerView + .padding() } - .onChange(of: showErrorDialog) { isShowing in - guard isShowing else { return } - TransferResultAlert.presentImportFailure(error: importError, result: importService?.stopResult, window: hostWindow) { - showErrorDialog = false - } + .frame(minWidth: 720, minHeight: 560, idealHeight: 640, maxHeight: .infinity) + } + + private func closeAfterRun() { + isPresented = false + if let importedRows { + AppCommands.shared.objectChanged.send(importedRows) } } @@ -879,8 +895,7 @@ struct RowImportSheet: View { return } guard let scope else { - importError = DatabaseError.notConnected - showErrorDialog = true + phase = .finished(TransferResults.importFailed(error: DatabaseError.notConnected)) return } guard currentReadIsReady else { @@ -906,8 +921,7 @@ struct RowImportSheet: View { case .newTable: let name = newTableName.trimmingCharacters(in: .whitespaces) guard !name.isEmpty, let definition = newTable.definition(tableName: name) else { - importError = RowImportTableMaker.statementError - showErrorDialog = true + phase = .finished(TransferResults.importFailed(error: RowImportTableMaker.statementError)) return } let columnMapping = newTable.columnMapping @@ -951,7 +965,7 @@ struct RowImportSheet: View { private func runImport(_ plan: ImportPlan, scope: DatabaseScope) { let service = ImportService(connection: connection) importService = service - showProgressDialog = true + phase = .running let targetTable = plan.targetTable importTask = Task { @@ -986,33 +1000,28 @@ struct RowImportSheet: View { authorization: authorization ) await MainActor.run { - showProgressDialog = false importSucceeded = true - importResult = result - importTally = service.state.rowTally importedRows = DatabaseObjectChange( connectionId: connection.id, scope: scope, name: targetTable, kind: .rows ) - showSuccessDialog = true + phase = .finished(TransferResults.importSucceeded( + result: result, + rowTally: service.state.rowTally, + runResult: service.stopResult + )) } } catch is PluginImportCancellationError { await MainActor.run { - showProgressDialog = false - TransferResultAlert.presentImportCancelled( - result: service.stopResult, - window: hostWindow - ) {} + phase = .finished(TransferResults.importStopped(service.stopResult)) } } catch ExecutionGateError.cancelledByUser { - await MainActor.run { showProgressDialog = false } + await MainActor.run { phase = .form } } catch { await MainActor.run { - showProgressDialog = false - importError = error - showErrorDialog = true + phase = .finished(TransferResults.importFailed(error: error, result: service.stopResult)) } } } diff --git a/apple/TablePro/Views/ObjectCopy/CopyObjectsProgressView.swift b/apple/TablePro/Views/ObjectCopy/CopyObjectsProgressView.swift index c0daf5e4b0..16e85c1d64 100644 --- a/apple/TablePro/Views/ObjectCopy/CopyObjectsProgressView.swift +++ b/apple/TablePro/Views/ObjectCopy/CopyObjectsProgressView.swift @@ -10,7 +10,7 @@ internal struct CopyObjectsProgressView: View { internal var body: some View { TransferProgressView(progress: session.transferProgress) - .frame(maxWidth: TransferProgressSheet.width) + .frame(maxWidth: TransferProgressView.sheetWidth) .frame(maxWidth: .infinity, maxHeight: .infinity) .padding(24) .accessibilityElement(children: .contain) diff --git a/apple/TableProTests/Core/Plugins/PluginInstallRunTests.swift b/apple/TableProTests/Core/Plugins/PluginInstallRunTests.swift new file mode 100644 index 0000000000..fefaeffe7c --- /dev/null +++ b/apple/TableProTests/Core/Plugins/PluginInstallRunTests.swift @@ -0,0 +1,84 @@ +import Foundation +@testable import TablePro +import TableProTestSupport +import Testing + +@MainActor +struct PluginInstallRunTests { + private let pluginId = "com.example.parquet" + + @Test("The display follows the tracker entry the install reports, and a failure passes through") + func followsTheEntryAndPassesAFailureThrough() async throws { + let tracker = PluginInstallTracker() + let install = PluginInstallRun(pluginName: "Parquet", tracker: tracker) + let gate = AsyncGate() + let pluginId = self.pluginId + + let running = Task { + try await install.run { onBegin in + onBegin(pluginId) + try await tracker.track(pluginId: pluginId, displayName: "Parquet", trigger: .user, retry: nil) { ticket in + await ticket.reportProgress(0.5) + await gate.wait() + throw PluginError.downloadFailed("HTTP 503") + } + } + } + await gate.arrived(1) + #expect(install.display == .make(pluginName: "Parquet", phase: .downloading(fraction: 0.5))) + #expect(install.canCancel) + + await gate.open() + await #expect(throws: PluginError.self) { try await running.value } + } + + @Test("Cancel before the install names its plugin ends the run as cancelled") + func cancelBeforeBegin() async throws { + let install = PluginInstallRun(pluginName: "Parquet", tracker: PluginInstallTracker()) + let gate = AsyncGate() + + let running = Task { + try await install.run { _ in + await withTaskCancellationHandler { + await gate.wait() + } onCancel: { + Task { await gate.open() } + } + try Task.checkCancellation() + } + } + await gate.arrived(1) + install.cancel() + + await #expect(throws: CancellationError.self) { try await running.value } + #expect(install.didCancel) + #expect(!install.canCancel) + } + + @Test("Cancel through the tracker entry ends the run as cancelled and removes the entry") + func cancelThroughTheTracker() async throws { + let tracker = PluginInstallTracker() + let install = PluginInstallRun(pluginName: "Parquet", tracker: tracker) + let gate = AsyncGate() + let pluginId = self.pluginId + + let running = Task { + try await install.run { onBegin in + onBegin(pluginId) + try await tracker.track(pluginId: pluginId, displayName: "Parquet", trigger: .user, retry: nil) { _ in + await withTaskCancellationHandler { + await gate.wait() + } onCancel: { + Task { await gate.open() } + } + try Task.checkCancellation() + } + } + } + await gate.arrived(1) + install.cancel() + + await #expect(throws: CancellationError.self) { try await running.value } + #expect(tracker.entries[pluginId] == nil) + } +} diff --git a/apple/TableProTests/Core/Services/ImportServiceSessionScopeTests.swift b/apple/TableProTests/Core/Services/ImportServiceSessionScopeTests.swift index bfbd9f6f2b..fe601ac10c 100644 --- a/apple/TableProTests/Core/Services/ImportServiceSessionScopeTests.swift +++ b/apple/TableProTests/Core/Services/ImportServiceSessionScopeTests.swift @@ -345,7 +345,7 @@ struct ImportCommittedTransactionErrorTests { #expect(statement == "INSERT INTO courses VALUES ('0000-00-00')") #expect(line == 8_264) #expect(underlying.localizedDescription == "[1292] Incorrect date value\n" + ImportCommittedTransactionError.note) - let text = TransferResultAlert.importFailureText(for: noted) + let text = TransferResults.importFailureText(for: noted) #expect(text.hasPrefix("Failed at line 8264. [1292] Incorrect date value")) #expect(text.contains(ImportCommittedTransactionError.note)) } diff --git a/apple/TableProTests/Core/Services/ImportServiceStopTests.swift b/apple/TableProTests/Core/Services/ImportServiceStopTests.swift index 724074b102..ce4c60f2b5 100644 --- a/apple/TableProTests/Core/Services/ImportServiceStopTests.swift +++ b/apple/TableProTests/Core/Services/ImportServiceStopTests.swift @@ -618,7 +618,7 @@ extension ImportServiceStopTests { columnMapping: file.columnMapping, sourceFields: file.sourceFields) Issue.record("The failed write must be reported") } catch { failure = error } - let text = TransferResultAlert.importFailureSummary(error: failure, result: fixture.service.stopResult) + let text = TransferResults.importFailureSummary(error: failure, result: fixture.service.stopResult) #expect(text.contains("injected write failure")) #expect(text.contains("injected rollback failure")) #expect(text.contains("injected cleanup failure")) @@ -661,7 +661,7 @@ extension ImportServiceStopTests { #expect(result.completionNotes.contains("still open")) let report = RowImportBatchReport(files: [], outcomes: [], ending: .completed, transaction: .untracked, executionTime: 0, stopResult: result) - #expect(TransferResultAlert.batchImportSummary(report).contains("still open")) + #expect(TransferResults.batchImportSummary(report).contains("still open")) } @Test("Stop after a preparation failure preserves the error but reports cancellation", arguments: [false, true]) @@ -701,9 +701,9 @@ extension ImportServiceStopTests { ledger.cleanupErrors = ["rollback failed"] ledger.currentState = .open let result = ImportStopResult(ledger: ledger) - let display = TransferResultAlert.importFailureDisplay(error: error, result: result) - #expect(display.utf16.count < TransferResultAlert.shownErrorLengthLimit + 100) - #expect(display.components(separatedBy: "\n").count <= TransferResultAlert.shownErrorLineLimit + 1) + let display = TransferResults.importFailureDisplay(error: error, result: result) + #expect(display.utf16.count < TransferResults.shownErrorLengthLimit + 100) + #expect(display.components(separatedBy: "\n").count <= TransferResults.shownErrorLineLimit + 1) #expect(display.contains("still open")) #expect(display.contains("rollback failed")) #expect(result.details.contains(marker)) @@ -730,7 +730,7 @@ extension ImportServiceStopTests { ending: stopped ? .stopped(file: 0) : .failed(file: 0), transaction: .untracked, executionTime: 0, stopResult: ImportStopResult(ledger: ledger)) - let shown = TransferResultAlert.shownErrors(TransferResultAlert.batchImportSummary(report)) + let shown = TransferResults.shownErrors(TransferResults.batchImportSummary(report)) #expect(shown.hasPrefix("A transaction is still open")) #expect(shown.contains("rollback failed")) } diff --git a/apple/TableProTests/Views/ImportCancelledTextTests.swift b/apple/TableProTests/Views/ImportCancelledTextTests.swift index a203833180..01d6035312 100644 --- a/apple/TableProTests/Views/ImportCancelledTextTests.swift +++ b/apple/TableProTests/Views/ImportCancelledTextTests.swift @@ -12,11 +12,11 @@ struct ImportCancelledTextTests { @Test("A rolled back import says so") func rolledBack() { #expect( - TransferResultAlert.importCancelledText(executedStatements: 12, transaction: .rolledBack) + TransferResults.importCancelledText(executedStatements: 12, transaction: .rolledBack) == "12 statements had already run and were rolled back." ) #expect( - TransferResultAlert.importCancelledText(executedStatements: 1, transaction: .rolledBack) + TransferResults.importCancelledText(executedStatements: 1, transaction: .rolledBack) == "1 statement had already run and was rolled back." ) } @@ -24,12 +24,12 @@ struct ImportCancelledTextTests { @Test("An import the database committed part way says some of it was kept, and why") func committedBeforeRollback() { #expect( - TransferResultAlert.importCancelledText(executedStatements: 848, transaction: .committedBeforeRollback) + TransferResults.importCancelledText(executedStatements: 848, transaction: .committedBeforeRollback) == "848 statements had already run. Some were kept, because a statement in the file, such as " + "COMMIT, CREATE, ALTER or DROP, committed the import's transaction as it ran." ) #expect( - TransferResultAlert.importCancelledText(executedStatements: 1, transaction: .committedBeforeRollback) + TransferResults.importCancelledText(executedStatements: 1, transaction: .committedBeforeRollback) == "1 statement had already run and was kept, because a statement in the file, such as COMMIT, " + "CREATE, ALTER or DROP, committed the import's transaction as it ran." ) @@ -38,11 +38,11 @@ struct ImportCancelledTextTests { @Test("An import with no known transaction outcome makes no durability claim") func untracked() { #expect( - TransferResultAlert.importCancelledText(executedStatements: 3, transaction: .untracked) + TransferResults.importCancelledText(executedStatements: 3, transaction: .untracked) == "Anything already imported may stay." ) #expect( - TransferResultAlert.importCancelledText(executedStatements: 1, transaction: .committed) + TransferResults.importCancelledText(executedStatements: 1, transaction: .committed) == "1 statement had already run and stays committed." ) } @@ -50,11 +50,11 @@ struct ImportCancelledTextTests { @Test("A transaction the server or the file ended makes no claim about rolled back or kept") func endedOutsideTheImport() { #expect( - TransferResultAlert.importCancelledText(executedStatements: 5, transaction: .endedByServer) + TransferResults.importCancelledText(executedStatements: 5, transaction: .endedByServer) == "Anything already imported may stay." ) #expect( - TransferResultAlert.importCancelledText(executedStatements: 5, transaction: .endedByFile) + TransferResults.importCancelledText(executedStatements: 5, transaction: .endedByFile) == "Anything already imported may stay." ) } diff --git a/apple/TableProTests/Views/ImportSummaryTextTests.swift b/apple/TableProTests/Views/ImportSummaryTextTests.swift index acbb525d4b..91c237b515 100644 --- a/apple/TableProTests/Views/ImportSummaryTextTests.swift +++ b/apple/TableProTests/Views/ImportSummaryTextTests.swift @@ -17,7 +17,7 @@ struct ImportSummaryTextTests { tally.inserted = 500 let result = PluginImportResult(executedStatements: 10_000, executionTime: 1.5, skippedStatements: 1) - let lines = TransferResultAlert.importSummary(result, rowTally: tally).components(separatedBy: "\n") + let lines = TransferResults.importSummary(result, rowTally: tally).components(separatedBy: "\n") #expect(lines == tally.summaryLines(failed: 1) + ["1.50 seconds"]) } @@ -25,6 +25,6 @@ struct ImportSummaryTextTests { @Test("A SQL file import still counts statements") func statementSummary() { let result = PluginImportResult(executedStatements: 12, executionTime: 0.25) - #expect(TransferResultAlert.importSummary(result) == "12 statements executed\n0.25 seconds") + #expect(TransferResults.importSummary(result) == "12 statements executed\n0.25 seconds") } } diff --git a/apple/TableProTests/Views/TransferFailureReportTests.swift b/apple/TableProTests/Views/TransferFailureReportTests.swift index 6457ab4aa2..52e1a69f37 100644 --- a/apple/TableProTests/Views/TransferFailureReportTests.swift +++ b/apple/TableProTests/Views/TransferFailureReportTests.swift @@ -14,7 +14,7 @@ extension GlobalStateSuites { @Test("The failing statement is reported alongside the line and the message") func statementIsIncluded() { - let report = TransferResultAlert.failureReport(for: [ + let report = TransferResults.failureReport(for: [ failure(line: 12, message: "syntax error", statement: "INSERT INTO users VALUES (") ]) #expect(report.contains("12")) @@ -25,7 +25,7 @@ extension GlobalStateSuites { /// A row import names its entry `row 12`, which the line number already says. @Test("A statement that only repeats the line number is left out") func rowPlaceholderIsSkipped() { - let report = TransferResultAlert.failureReport(for: [ + let report = TransferResults.failureReport(for: [ failure(line: 12, message: "not null violation", statement: "row 12") ]) #expect(report.contains("not null violation")) @@ -34,7 +34,7 @@ extension GlobalStateSuites { @Test("An empty statement adds no trailing line") func emptyStatementIsSkipped() { - let report = TransferResultAlert.failureReport(for: [ + let report = TransferResults.failureReport(for: [ failure(line: 3, message: "duplicate key", statement: " ") ]) #expect(report.hasSuffix("duplicate key")) @@ -42,7 +42,7 @@ extension GlobalStateSuites { @Test("Failures are separated from one another") func failuresAreSeparated() { - let report = TransferResultAlert.failureReport(for: [ + let report = TransferResults.failureReport(for: [ failure(line: 1, message: "first", statement: "SELECT 1"), failure(line: 2, message: "second", statement: "SELECT 2") ]) @@ -55,7 +55,7 @@ extension GlobalStateSuites { @Test("A failed statement reports its line, its reason and the statement") func failedStatementReportsEverything() throws { - let report = try #require(TransferResultAlert.failureReport( + let report = try #require(TransferResults.failureReport( for: PluginImportError.statementFailed( statement: "INSERT INTO users VALUES (1)", line: 412, @@ -69,8 +69,8 @@ extension GlobalStateSuites { @Test("An error with no failing statement carries no report") func unstructuredErrorHasNoReport() { - #expect(TransferResultAlert.failureReport(for: PluginImportError.importFailed("disk full")) == nil) - #expect(TransferResultAlert.failureReport(for: nil) == nil) + #expect(TransferResults.failureReport(for: PluginImportError.importFailed("disk full")) == nil) + #expect(TransferResults.failureReport(for: nil) == nil) } /// The report is what the user has to send on to whoever can fix the data, so copying it must @@ -159,13 +159,13 @@ extension GlobalStateSuites { underlyingError: TransferReportStubError(message: errors.joined(separator: "\n")) ) - let text = TransferResultAlert.importFailureText(for: failure) - let limit = TransferResultAlert.shownErrorLineLimit + let text = TransferResults.importFailureText(for: failure) + let limit = TransferResults.shownErrorLineLimit #expect(text.components(separatedBy: "\n").count == limit + 1) #expect(text.contains(errors[limit - 1])) #expect(!text.contains(errors[limit])) - let copied = try #require(TransferResultAlert.failureReport(for: failure)) + let copied = try #require(TransferResults.failureReport(for: failure)) #expect(copied.contains(errors[999])) } @@ -178,11 +178,11 @@ extension GlobalStateSuites { underlyingError: TransferReportStubError(message: reason) ) - let text = TransferResultAlert.importFailureText(for: failure) - #expect((text as NSString).length < TransferResultAlert.shownErrorLengthLimit + 200) + let text = TransferResults.importFailureText(for: failure) + #expect((text as NSString).length < TransferResults.shownErrorLengthLimit + 200) #expect(text.contains("Line 4: Incorrect syntax near 'xxx")) - let copied = try #require(TransferResultAlert.failureReport(for: failure)) + let copied = try #require(TransferResults.failureReport(for: failure)) #expect(copied.contains(reason)) } @@ -193,7 +193,7 @@ extension GlobalStateSuites { line: 3, underlyingError: TransferReportStubError(message: "Line 4: first\nLine 5: second") ) - let text = TransferResultAlert.importFailureText(for: failure) + let text = TransferResults.importFailureText(for: failure) #expect(text.hasSuffix("Line 4: first\nLine 5: second")) } } diff --git a/apple/TableProTests/Views/TransferResultsTests.swift b/apple/TableProTests/Views/TransferResultsTests.swift new file mode 100644 index 0000000000..283eb11b86 --- /dev/null +++ b/apple/TableProTests/Views/TransferResultsTests.swift @@ -0,0 +1,143 @@ +// +// TransferResultsTests.swift +// TableProTests +// + +import Foundation +@testable import TablePro +import TableProPluginKit +import Testing + +@MainActor +struct TransferResultsTests { + @Test("A clean import reports its counts and nothing to keep") + func importSucceeded() { + let result = TransferResults.importSucceeded( + result: PluginImportResult(executedStatements: 100_015, executionTime: 12.4) + ) + + #expect(result.outcome == .succeeded) + #expect(result.title == "Import completed") + #expect(result.message == "100015 statements executed\n12.40 seconds") + #expect(result.details == nil) + #expect(result.errorReport == nil) + #expect(!result.returnsToForm) + #expect(result.severity == .success) + } + + @Test("An import that skipped statements shows them and offers the report") + func importSucceededWithErrors() throws { + let errors = [ + PluginImportResult.ImportStatementError( + statement: "INSERT INTO users VALUES (1)", + line: 412, + errorMessage: "Duplicate entry" + ), + ] + let result = TransferResults.importSucceeded( + result: PluginImportResult(executedStatements: 9, executionTime: 1, skippedStatements: 1, errors: errors) + ) + + #expect(result.outcome == .succeededWithIssues) + #expect(result.title == "Import completed with errors") + let details = try #require(result.details) + #expect(details.shown == "Line 412: Duplicate entry\nINSERT INTO users VALUES (1)") + #expect(details.copied == details.shown) + let report = try #require(result.errorReport) + #expect(report.totalSkipped == 1) + #expect(report.errors.map(\.line) == [412]) + #expect(result.severity == .warning) + } + + @Test("A failed statement keeps the form and shows the statement") + func importFailedOnAStatement() throws { + let failure = PluginImportError.statementFailed( + statement: "INSERT t VALUES (1)", + line: 7, + underlyingError: TransferResultsStubError(message: "relation \"t\" does not exist") + ) + let result = TransferResults.importFailed(error: failure) + + #expect(result.outcome == .failed) + #expect(result.title == "Import failed") + #expect(result.message == "Failed at line 7. relation \"t\" does not exist") + let details = try #require(result.details) + #expect(details.shown == "INSERT t VALUES (1)") + #expect(details.copied == TransferResults.failureReport(for: failure)) + #expect(result.returnsToForm) + #expect(result.severity == .error) + } + + @Test("A failure that is not a statement carries no details") + func importFailedWithoutAStatement() { + let result = TransferResults.importFailed(error: TransferResultsStubError(message: "Not connected")) + + #expect(result.message == "Not connected") + #expect(result.details == nil) + #expect(result.returnsToForm) + } + + @Test("A completed batch with a failed file is done with issues, a stopped one returns to its list") + func batchOutcomes() { + let file = RowImportRunItem( + url: URL(fileURLWithPath: "/tmp/a.csv"), + sourceName: "a.csv", + formatId: "csv", + targetTable: "a", + columnMapping: [:], + sourceFields: [] + ) + let failed = RowImportBatchReport( + files: [file], + outcomes: [.imported(PluginImportResult(executedStatements: 3, executionTime: 1, skippedStatements: 1))], + ending: .completed, + transaction: .untracked, + executionTime: 1 + ) + let stopped = RowImportBatchReport( + files: [file], + outcomes: [.stopped(rowsBefore: 2)], + ending: .stopped(file: 0), + transaction: .untracked, + executionTime: 1 + ) + + #expect(TransferResults.batchImport(failed).outcome == .succeededWithIssues) + #expect(TransferResults.batchImport(failed).title == "Import completed with errors") + #expect(!TransferResults.batchImport(failed).returnsToForm) + #expect(TransferResults.batchImport(stopped).outcome == .stopped) + #expect(TransferResults.batchImport(stopped).returnsToForm) + #expect(TransferResults.batchImport(stopped).details?.shown.contains("a.csv") == true) + } + + @Test("An export with warnings says so and lists them after its notes") + func exportSucceeded() { + let clean = TransferResults.exportSucceeded(warnings: [], notes: ["Wrote 3 files."]) + #expect(clean.outcome == .succeeded) + #expect(clean.title == "Export completed") + #expect(clean.message == "Wrote 3 files.") + + let warned = TransferResults.exportSucceeded(warnings: ["Column x was cut."], notes: ["Wrote 3 files."]) + #expect(warned.outcome == .succeededWithIssues) + #expect(warned.title == "Export completed with warnings") + #expect(warned.message == "Wrote 3 files.\n\nColumn x was cut.") + } + + @Test("A transfer reports its rows, tables and destination") + func transferSucceeded() { + let result = TransferResults.transferSucceeded( + tableCount: 2, + rowCount: 40, + destinationName: "staging", + warnings: [] + ) + #expect(result.outcome == .succeeded) + #expect(result.title == "Transfer completed") + #expect(result.message == "40 rows from 2 tables written to staging.") + } +} + +private struct TransferResultsStubError: LocalizedError { + let message: String + var errorDescription: String? { message } +} diff --git a/apple/TableProUITests/RowImportUpdateUITests.swift b/apple/TableProUITests/RowImportUpdateUITests.swift index 23133b7b30..ffce45527d 100644 --- a/apple/TableProUITests/RowImportUpdateUITests.swift +++ b/apple/TableProUITests/RowImportUpdateUITests.swift @@ -44,6 +44,10 @@ final class RowImportUpdateUITests: UITestCase { (summary.value as? String)?.contains("Skipped: 1") == true, "The summary must count the skipped row, it reads \(summary.value ?? "nothing")" ) + XCTAssertEqual( + sheet.children(matching: .sheet).count, 0, + "The result belongs in the import sheet itself, never in a sheet over it" + ) } // A pop-up's menu is built when it opens, so a list still loading is opened again. From b7be284583db1f237ce7d5dfc4c7f33faf743ac2 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Wed, 25 Nov 2026 16:44:19 +0700 Subject: [PATCH 2/2] docs(changelog): note the transfer sheet fixes --- apple/changelog.d/4495.fixed.1.md | 1 + apple/changelog.d/4495.fixed.2.md | 1 + apple/changelog.d/4495.fixed.md | 1 + 3 files changed, 3 insertions(+) create mode 100644 apple/changelog.d/4495.fixed.1.md create mode 100644 apple/changelog.d/4495.fixed.2.md create mode 100644 apple/changelog.d/4495.fixed.md diff --git a/apple/changelog.d/4495.fixed.1.md b/apple/changelog.d/4495.fixed.1.md new file mode 100644 index 0000000000..b73a6e51a6 --- /dev/null +++ b/apple/changelog.d/4495.fixed.1.md @@ -0,0 +1 @@ +The SQL import dialog cut off its edges and did not line up the Encoding and On error options. diff --git a/apple/changelog.d/4495.fixed.2.md b/apple/changelog.d/4495.fixed.2.md new file mode 100644 index 0000000000..fce7bae2a3 --- /dev/null +++ b/apple/changelog.d/4495.fixed.2.md @@ -0,0 +1 @@ +Save Report… after an import showed nothing when the report could not be written. diff --git a/apple/changelog.d/4495.fixed.md b/apple/changelog.d/4495.fixed.md new file mode 100644 index 0000000000..b39265cade --- /dev/null +++ b/apple/changelog.d/4495.fixed.md @@ -0,0 +1 @@ +Import, export and table transfer stacked their progress, results and file editor as sheets on top of their own sheet.