Skip to content
Open
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
1 change: 1 addition & 0 deletions .claude/rules/data-sync-storage.md
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,7 @@ This path holds user data. A silent wrong answer here looks exactly like an empt
| Server Dashboard tiles, per connection | UserDefaults, device-local | `ServerDashboardTileStorage` |
| Table Health history, per connection and database: when each finding was first and last seen, resolved findings, ignored findings | JSON, one file per connection under `TableHealth/`, device-local, never synced | `TableHealthHistoryStorage` |
| Module on/off (Settings > Extensions) | UserDefaults, device-local, never synced | `AppModuleSettings` |
| A module's default on this Mac, for one that was core before: on when an earlier build ran here, written once at the first launch that knows the module, restored by Reset All Settings | UserDefaults `com.TablePro.modules.<id>.default`, device-local, never synced | `AppModule.recordDefaults`, called first in `applicationWillFinishLaunching` |
| Routine debugger start options, per connection and field | UserDefaults, device-local | `RoutineDebugOptionStore` |
| Whether the toolbar arrangement already carries the debug items | UserDefaults, device-local | `MainWindowToolbar` |
| Trusted external links (loopback only) | UserDefaults | `ExternalConnectionTrustStore` |
Expand Down
9 changes: 6 additions & 3 deletions apple/TablePro/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,16 @@ class AppDelegate: NSObject, NSApplicationDelegate {

func applicationWillFinishLaunching(_ notification: Notification) {
LaunchTracer.shared.mark(.willFinishLaunchingBegan)
// First: the migration below writes the flag that tells an existing install from a new one.
AppModule.recordDefaults(
in: AppStorageEnvironment.shared.defaults,
isExistingInstall: AppSettingsStorage.shared.hasLaunchedBefore()
)
AppSettingsStorage.shared.migrateStartupBehaviorToReopenLastIfNeeded()
AppSettingsStorage.shared.removeRetiredFieldHeightKeys()
AIProviderRegistration.registerAll()

/// Installed before any window exists, so the bar is correct from the first frame.
/// Nothing else owns it now that the app no longer runs a SwiftUI `App`.
// Before any window exists, so the bar is right from the first frame.
MainMenuBuilder.install(keyboard: AppSettingsManager.shared.keyboard)
MainMenuBuilder.syncKeyEquivalentsOnKeyWindowChange()
LaunchTracer.shared.mark(.menuInstalled)
Expand Down Expand Up @@ -81,7 +85,6 @@ class AppDelegate: NSObject, NSApplicationDelegate {
WindowOpener.shared.setConnectionFormPresenter { ConnectionFormWindowController.present($0) }
WindowOpener.shared.setIntegrationsActivityPresenter { IntegrationsActivityWindowController.present() }
WindowOpener.shared.setSettingsPresenter { SettingsWindowController.present(pane: $0) }
WindowOpener.shared.setCompareSyncPresenter { CompareSyncWindowController.present(prefillSource: $0) }
KeyRepeatFilter.shared.install()
TableClickFocus.shared.install()
RecentTabSwitcherController.installEditorKeyClaim()
Expand Down
31 changes: 25 additions & 6 deletions apple/TablePro/Core/Compare/CompareSyncLauncher.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,39 @@
// CompareSyncLauncher.swift
// TablePro
//
// Single entry point for opening Compare & Sync, so the license gate is
// enforced in one place no matter which menu or context menu was used.
//

import AppKit
import Foundation
import os

// Every way into Compare & Sync passes here, so the module switch and the license gate are checked in one place.
@MainActor
internal enum CompareSyncLauncher {
internal enum Launch: Equatable {
case moduleOff
case needsLicense
case open
}

private static let logger = Logger(subsystem: "com.TablePro", category: "CompareSync")

// The license is not read while the module is off.
internal static func launch(moduleEnabled: Bool, isLicensed: () -> Bool) -> Launch {
guard moduleEnabled else { return .moduleOff }
return isLicensed() ? .open : .needsLicense
}

internal static func open(prefillSource connectionId: UUID? = nil) {
guard FeatureAccess.shared.isAvailable(.compareSync) else {
let decision = launch(moduleEnabled: AppModuleSettings.shared.isEnabled(.compareSync)) {
FeatureAccess.shared.isAvailable(.compareSync)
}
switch decision {
case .moduleOff:
logger.notice("Compare & Sync was asked to open while its module is off")
case .needsLicense:
LicenseGateAlert.present(for: .compareSync, in: NSApp.keyWindow)
return
case .open:
CompareSyncWindowController.present(prefillSource: connectionId)
}
WindowOpener.shared.openCompareSync(prefillSource: connectionId)
}
}
14 changes: 12 additions & 2 deletions apple/TablePro/Core/Compare/CompareSyncRunRegistry.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,15 @@ internal final class CompareSyncRunRegistry {
private struct Entry {
weak var session: CompareSyncSession?
let windowId: UUID
let close: @MainActor () -> Void
}

private var entries: [ObjectIdentifier: Entry] = [:]

internal init() {}

internal func track(_ session: CompareSyncSession, windowId: UUID) {
entries[ObjectIdentifier(session)] = Entry(session: session, windowId: windowId)
internal func track(_ session: CompareSyncSession, windowId: UUID, close: @escaping @MainActor () -> Void) {
entries[ObjectIdentifier(session)] = Entry(session: session, windowId: windowId, close: close)
}

internal func windowId(of session: CompareSyncSession) -> UUID? {
Expand All @@ -34,6 +35,15 @@ internal final class CompareSyncRunRegistry {
}
}

// The module was turned off: every run stops and every window closes, without the close prompt.
internal func endAll() {
entries = entries.filter { $0.value.session != nil }
for entry in entries.values {
entry.session?.cancelRunningWork()
entry.close()
}
}

internal static func runningWork(for session: CompareSyncSession) -> RunningWork? {
guard session.isBusy else { return nil }
let endpoints = [session.source, session.target].compactMap { $0 }
Expand Down
40 changes: 30 additions & 10 deletions apple/TablePro/Core/Menu/DatabaseMenuBuilder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import AppKit
enum DatabaseMenuBuilder {
static let identifier = NSUserInterfaceItemIdentifier("menu.database")
static let liveMessagesIdentifier = NSUserInterfaceItemIdentifier("menu.database.liveMessages")
static let compareIdentifier = NSUserInterfaceItemIdentifier("menu.database.compare")
static let compareSeparatorIdentifier = NSUserInterfaceItemIdentifier("menu.database.compareSeparator")
static let manualCommitFootnoteIdentifier = NSUserInterfaceItemIdentifier("menu.database.manualCommitFootnote")
static let manualCommitUnavailableFootnoteIdentifier = NSUserInterfaceItemIdentifier(
"menu.database.manualCommitUnavailableFootnote"
Expand Down Expand Up @@ -166,9 +168,7 @@ enum DatabaseMenuBuilder {
MenuItemFactory.item(
String(localized: "Reconnect"),
action: #selector(MainSplitViewController.retryConnection)
),
MenuItemFactory.separator,
compareSubmenu()
)
])
item.identifier = identifier
if let menu = item.submenu {
Expand All @@ -177,10 +177,15 @@ enum DatabaseMenuBuilder {
return item
}

// Live Messages… sits with the other connection-wide tabs, and exists only while its module is on.
static func applyModules(_ modules: Set<AppModule>, to menu: NSMenu) {
applyLiveMessages(modules.contains(.liveMessages), to: menu)
applyCompare(modules.contains(.compareSync), to: menu)
}

// Live Messages… sits with the other connection-wide tabs, and exists only while its module is on.
private static func applyLiveMessages(_ enabled: Bool, to menu: NSMenu) {
let existing = menu.items.first { $0.identifier == liveMessagesIdentifier }
switch (modules.contains(.liveMessages), existing) {
switch (enabled, existing) {
case (true, nil):
let anchor = menu.items.firstIndex { $0.action == #selector(MainSplitViewController.showTableHealth(_:)) }
let item = MenuItemFactory.item(
Expand All @@ -196,12 +201,25 @@ enum DatabaseMenuBuilder {
}
}

/// The HIG asks that every toolbar item also be a menu-bar command. These are the Compare &
/// Sync window's toolbar, mirrored here; they route by nil target, so they reach
/// `CompareSyncWindowController` only while that window is key and validate to disabled
/// everywhere else.
// Closes the menu behind its own separator, and exists only while the Compare & Sync module is on.
private static func applyCompare(_ enabled: Bool, to menu: NSMenu) {
let existing = menu.items.filter { $0.identifier == compareIdentifier || $0.identifier == compareSeparatorIdentifier }
switch (enabled, existing.isEmpty) {
case (true, true):
let separator = MenuItemFactory.separator
separator.identifier = compareSeparatorIdentifier
menu.addItem(separator)
menu.addItem(compareSubmenu())
case (false, false):
existing.forEach { menu.removeItem($0) }
default:
return
}
}

// The window's toolbar mirrored as menu commands (HIG). Nil target, so they validate to disabled unless it is key.
private static func compareSubmenu() -> NSMenuItem {
MenuItemFactory.submenu(String(localized: "Compare"), items: [
let submenu = MenuItemFactory.submenu(String(localized: "Compare"), items: [
MenuItemFactory.item(
String(localized: "Compare & Sync Databases…"),
action: #selector(AppDelegate.compareAndSyncDatabases(_:))
Expand Down Expand Up @@ -238,6 +256,8 @@ enum DatabaseMenuBuilder {
action: #selector(CompareSyncWindowController.stopComparison(_:))
)
])
submenu.identifier = compareIdentifier
return submenu
}

private static let favoriteDatabaseDelegate = FavoriteDatabaseMenuDelegate()
Expand Down
24 changes: 22 additions & 2 deletions apple/TablePro/Core/Modules/AppModule.swift
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,28 @@ import Foundation
enum AppModule: String, CaseIterable, Sendable {
case routineDebugger
case liveMessages
case compareSync

var title: String {
switch self {
case .routineDebugger: String(localized: "Routine Debugger")
case .liveMessages: String(localized: "Live Messages")
case .compareSync: String(localized: "Compare & Sync")
}
}

var summary: String {
switch self {
case .routineDebugger: String(localized: "Step through PL/pgSQL and PL/SQL routines with breakpoints.")
case .liveMessages: String(localized: "Watch PostgreSQL notifications, Redis channels and Kafka topics as messages arrive.")
case .compareSync: String(localized: "Compare structure or data between two connections and generate the sync script.")
}
}

var defaultEnabled: Bool {
// Shipped as core before it became a module, so a Mac that ran an earlier build keeps it on.
var wasCore: Bool {
switch self {
case .compareSync: true
case .routineDebugger, .liveMessages: false
}
}
Expand All @@ -28,8 +33,23 @@ enum AppModule: String, CaseIterable, Sendable {
"com.TablePro.modules.\(rawValue).enabled"
}

var recordedDefaultKey: String {
"com.TablePro.modules.\(rawValue).default"
}

func defaultEnabled(in defaults: UserDefaults) -> Bool {
defaults.bool(forKey: recordedDefaultKey)
}

static func enabledModules(in defaults: UserDefaults) -> Set<AppModule> {
Set(allCases.filter { (defaults.object(forKey: $0.defaultsKey) as? Bool) ?? $0.defaultEnabled })
Set(allCases.filter { (defaults.object(forKey: $0.defaultsKey) as? Bool) ?? $0.defaultEnabled(in: defaults) })
}

// Once per Mac and module, at the first launch of a build that knows the module; later launches keep the answer.
static func recordDefaults(in defaults: UserDefaults, isExistingInstall: Bool) {
for module in allCases where module.wasCore && defaults.object(forKey: module.recordedDefaultKey) == nil {
defaults.set(isExistingInstall, forKey: module.recordedDefaultKey)
}
}

// For value types that cannot reach the main actor; reads the same keys `AppModuleSettings` writes.
Expand Down
4 changes: 3 additions & 1 deletion apple/TablePro/Core/Modules/AppModuleActivation.swift
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ enum AppModuleActivation {

static func resetToDefaults(settings: AppModuleSettings = .shared) {
for module in AppModule.allCases {
setEnabled(module.defaultEnabled, for: module, settings: settings)
setEnabled(settings.defaultEnabled(module), for: module, settings: settings)
}
}

Expand All @@ -33,6 +33,8 @@ enum AppModuleActivation {
Task { await RoutineDebugSessions.shared.stopAll() }
case .liveMessages:
LiveMessageSessions.shared.endAll(closingTabs: true)
case .compareSync:
CompareSyncRunRegistry.shared.endAll()
}
}
}
4 changes: 4 additions & 0 deletions apple/TablePro/Core/Modules/AppModuleSettings.swift
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@ final class AppModuleSettings: ObservableObject {
enabledModules.contains(module)
}

func defaultEnabled(_ module: AppModule) -> Bool {
module.defaultEnabled(in: defaults)
}

func setEnabled(_ enabled: Bool, for module: AppModule) {
guard isEnabled(module) != enabled else { return }
defaults.set(enabled, forKey: module.defaultsKey)
Expand Down
14 changes: 0 additions & 14 deletions apple/TablePro/Core/Services/Infrastructure/WindowOpener.swift
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ internal final class WindowOpener: ObservableObject {
private var openWelcomeAction: (() -> Void)?
private var openConnectionFormAction: ((ConnectionFormRequest) -> Void)?
private var openIntegrationsActivityAction: (() -> Void)?
private var openCompareSyncAction: ((UUID?) -> Void)?
private var openSettingsAction: ((SettingsPane?) -> Void)?
private var stagedDraftId: UUID?
private var pendingCalls: [() -> Void] = []
Expand Down Expand Up @@ -101,14 +100,6 @@ internal final class WindowOpener: ObservableObject {
}
}

internal func openCompareSync(prefillSource connectionId: UUID? = nil) {
perform { opener in
guard let present = opener.openCompareSyncAction else { return false }
present(connectionId)
return true
}
}

internal func setWelcomePresenter(_ present: @escaping () -> Void) {
openWelcomeAction = present
drainPendingCalls()
Expand All @@ -129,11 +120,6 @@ internal final class WindowOpener: ObservableObject {
drainPendingCalls()
}

internal func setCompareSyncPresenter(_ present: @escaping (UUID?) -> Void) {
openCompareSyncAction = present
drainPendingCalls()
}

/// Returns false when the presenter for that window has not been registered yet, which
/// queues the call. Each window registers independently, so one that has already migrated
/// to AppKit never waits on one that has not.
Expand Down
5 changes: 5 additions & 0 deletions apple/TablePro/Core/Storage/AppSettingsStorage.swift
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,11 @@ final class AppSettingsStorage: Sendable {
save(settings, key: Keys.general)
}

// Every launch since 0.51.0 sets the startup migration flag, with no user action; read it before this launch does.
func hasLaunchedBefore() -> Bool {
defaults.object(forKey: Keys.startupReopenMigration) != nil || defaults.bool(forKey: Keys.hasSeenWelcomeSheet)
}

func migrateStartupBehaviorToReopenLastIfNeeded() {
guard !defaults.bool(forKey: Keys.startupReopenMigration) else { return }
defaults.set(true, forKey: Keys.startupReopenMigration)
Expand Down
1 change: 1 addition & 0 deletions apple/TablePro/ViewModels/WelcomeViewModel+Library.swift
Original file line number Diff line number Diff line change
Expand Up @@ -423,6 +423,7 @@ extension WelcomeViewModel {
disconnectableConnectionIds: disconnectable,
reconnectableConnectionIds: reconnectable,
isSyncEnabled: services.appSettings.sync.enabled,
isCompareSyncEnabled: AppModuleSettings.shared.isEnabled(.compareSync),
canPublishToTeamCatalog: services.featureAccess.isAvailable(.teamCatalog),
teamLibraryTeams: services.featureAccess.isAvailable(.teamLibrary) ? TeamLibrarySync.shared.writableTeams : [],
hasTeamLibraryConflicts: !TeamLibrarySync.shared.conflicts.isEmpty
Expand Down
17 changes: 16 additions & 1 deletion apple/TablePro/Views/Compare/CompareSyncWindowController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,9 @@ internal final class CompareSyncWindowController: NSWindowController,
windowBackdrop = ThemeWindowBackdrop(window: window)
super.init(window: window)

CompareSyncRunRegistry.shared.track(session, windowId: windowId)
CompareSyncRunRegistry.shared.track(session, windowId: windowId) { [weak self] in
self?.closeWithoutAsking()
}
applyPrefill(connectionId)
window.contentViewController = makeContentController()
window.delegate = self
Expand Down Expand Up @@ -749,6 +751,19 @@ internal final class CompareSyncWindowController: NSWindowController,
return false
}

// Sheets first: a window closed under one leaves the sheet on screen with nothing behind it.
private func closeWithoutAsking() {
isCloseApproved = true
guard let window else { return }
for presented in window.contentViewController?.presentedViewControllers ?? [] {
window.contentViewController?.dismiss(presented)
}
if let sheet = window.attachedSheet {
window.endSheet(sheet)
}
window.close()
}

internal func windowWillClose(_ notification: Notification) {
// Stays listed until the run itself ends: a statement already sent can still be writing.
session.cancelRunningWork()
Expand Down
7 changes: 5 additions & 2 deletions apple/TablePro/Views/Welcome/WelcomeMenuSpec.swift
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ internal struct WelcomeMenuContext {
internal let disconnectableConnectionIds: Set<UUID>
internal let reconnectableConnectionIds: Set<UUID>
internal let isSyncEnabled: Bool
internal let isCompareSyncEnabled: Bool
internal let canPublishToTeamCatalog: Bool
internal let teamLibraryTeams: [TeamLibraryTeam]
internal let hasTeamLibraryConflicts: Bool
Expand Down Expand Up @@ -151,12 +152,14 @@ internal enum WelcomeMenuSpec {
primary.append(.command(Titles.disconnect, .disconnect(id)))
}

let manage: [WelcomeMenuItem] = [
var manage: [WelcomeMenuItem] = [
.command(Titles.edit, .edit(id)),
.command(Titles.rename, .rename(.connection(id, section: section))),
.command(Titles.duplicate, .duplicate(id)),
.command(Titles.compareAndSync, .compareAndSync(id)),
]
if context.isCompareSyncEnabled {
manage.append(.command(Titles.compareAndSync, .compareAndSync(id)))
}

let currentGroupId = validGroupId(of: connection, groups: context.groups)
var organize: [WelcomeMenuItem] = [
Expand Down
Loading