Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 18 additions & 22 deletions apple/Plugins/SQLImportPlugin/SQLImportOptionsView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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."
)
}
}

Expand Down
52 changes: 12 additions & 40 deletions apple/TablePro/Core/Plugins/PluginInstallProgressPresenter.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand All @@ -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()
}

Expand All @@ -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()
Expand All @@ -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)
Expand All @@ -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
Expand Down
135 changes: 114 additions & 21 deletions apple/TablePro/Core/Plugins/PluginInstallPrompt.swift
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import AppKit
import Combine
import os

@MainActor
Expand All @@ -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)
}
}
Expand Down Expand Up @@ -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(
Expand All @@ -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<Void, any Error>?

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)
}
}
}
30 changes: 20 additions & 10 deletions apple/TablePro/Views/Components/TransferProgressView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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<StopControl: View>: 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(
Expand Down
Loading
Loading