diff --git a/apple/.swiftlint.yml b/apple/.swiftlint.yml index 5d4d0ea84c..75f9a2dd45 100644 --- a/apple/.swiftlint.yml +++ b/apple/.swiftlint.yml @@ -634,3 +634,22 @@ custom_rules: excluded_match_kinds: [comment, doccomment] message: "Every top-level @Suite expansion walks every other one, so compile time grows with their square. Keep @Suite only to carry a trait such as .serialized." severity: error + + # Settings + # A line that introduces a CopyableCodeBlock keeps its colon. + settings_label_trailing_colon: + name: "Settings Label Colon" + included: ['.*/TablePro/Views/Settings/'] + regex: '\b(?:Text|Label|LabeledContent|Toggle|Picker|TextField|SecureField|Stepper|DatePicker|ColorPicker|Section|SettingsNumberField|SettingsTextField|SettingsDrillRow)\((?:\s*route:[^,\n]*,)?\s*(?:title:\s*)?(?:String\(\s*localized:\s*)?("(?!e\.g\.|i\.e\.)(?:\p{Lu}|\p{Ll}[^"\\\s]*[ \t])[^"\\\n]*?\p{L}[::][ \t]?")(?!(?:[^\n]*\n){0,3}[^\n]*\bCopyableCodeBlock\()' + capture_group: 1 + excluded_match_kinds: [comment, doccomment] + message: "A grouped Form draws the label column, so a label takes no trailing colon." + severity: error + # An SF Symbol sized by a text style is not text, so its chain is left alone. + settings_caption_font: + name: "Settings Caption Font" + included: ['.*/TablePro/Views/Settings/'] + regex: '(? + CFBundleDisplayName + Beancount Driver TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesDatabaseTypeIds diff --git a/apple/Plugins/BigQueryDriverPlugin/Info.plist b/apple/Plugins/BigQueryDriverPlugin/Info.plist index d204d38817..4611353c04 100644 --- a/apple/Plugins/BigQueryDriverPlugin/Info.plist +++ b/apple/Plugins/BigQueryDriverPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + BigQuery Driver TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesDatabaseTypeIds diff --git a/apple/Plugins/BigtableDriverPlugin/Info.plist b/apple/Plugins/BigtableDriverPlugin/Info.plist index 6953716526..e1f508b75c 100644 --- a/apple/Plugins/BigtableDriverPlugin/Info.plist +++ b/apple/Plugins/BigtableDriverPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + Bigtable Driver TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesDatabaseTypeIds diff --git a/apple/Plugins/CSVExportPlugin/Info.plist b/apple/Plugins/CSVExportPlugin/Info.plist index 81a04239c9..f293006ad9 100644 --- a/apple/Plugins/CSVExportPlugin/Info.plist +++ b/apple/Plugins/CSVExportPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + CSV Export TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesExportFormatIds diff --git a/apple/Plugins/CSVImportPlugin/Info.plist b/apple/Plugins/CSVImportPlugin/Info.plist index a09c94dbca..9167aba944 100644 --- a/apple/Plugins/CSVImportPlugin/Info.plist +++ b/apple/Plugins/CSVImportPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + CSV Import TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesImportFormatIds diff --git a/apple/Plugins/CassandraDriverPlugin/Info.plist b/apple/Plugins/CassandraDriverPlugin/Info.plist index 7859b15635..7541863b74 100644 --- a/apple/Plugins/CassandraDriverPlugin/Info.plist +++ b/apple/Plugins/CassandraDriverPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + Cassandra Driver TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesDatabaseTypeIds diff --git a/apple/Plugins/ClickHouseDriverPlugin/Info.plist b/apple/Plugins/ClickHouseDriverPlugin/Info.plist index 10fa22e650..9c3877768c 100644 --- a/apple/Plugins/ClickHouseDriverPlugin/Info.plist +++ b/apple/Plugins/ClickHouseDriverPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + ClickHouse Driver TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesDatabaseTypeIds diff --git a/apple/Plugins/CloudflareD1DriverPlugin/Info.plist b/apple/Plugins/CloudflareD1DriverPlugin/Info.plist index eb66596cb4..6aea4dd1db 100644 --- a/apple/Plugins/CloudflareD1DriverPlugin/Info.plist +++ b/apple/Plugins/CloudflareD1DriverPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + Cloudflare D1 Driver TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesDatabaseTypeIds diff --git a/apple/Plugins/CloudflareR2SQLDriverPlugin/Info.plist b/apple/Plugins/CloudflareR2SQLDriverPlugin/Info.plist index 9625b89836..c86b10e02b 100644 --- a/apple/Plugins/CloudflareR2SQLDriverPlugin/Info.plist +++ b/apple/Plugins/CloudflareR2SQLDriverPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + Cloudflare R2 SQL Driver TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesDatabaseTypeIds diff --git a/apple/Plugins/DamengDriverPlugin/Info.plist b/apple/Plugins/DamengDriverPlugin/Info.plist index 024e929450..b574bed77d 100644 --- a/apple/Plugins/DamengDriverPlugin/Info.plist +++ b/apple/Plugins/DamengDriverPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + Dameng Driver TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesDatabaseTypeIds diff --git a/apple/Plugins/DataDictionaryExportPlugin/Info.plist b/apple/Plugins/DataDictionaryExportPlugin/Info.plist index dfe303774b..8ba75b3ca8 100644 --- a/apple/Plugins/DataDictionaryExportPlugin/Info.plist +++ b/apple/Plugins/DataDictionaryExportPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + Data Dictionary Export TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesExportFormatIds diff --git a/apple/Plugins/DuckDBDriverPlugin/Info.plist b/apple/Plugins/DuckDBDriverPlugin/Info.plist index 001d3ff479..7f3aa3567e 100644 --- a/apple/Plugins/DuckDBDriverPlugin/Info.plist +++ b/apple/Plugins/DuckDBDriverPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + DuckDB Driver TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesDatabaseTypeIds diff --git a/apple/Plugins/DynamoDBDriverPlugin/Info.plist b/apple/Plugins/DynamoDBDriverPlugin/Info.plist index 750e2994e2..04616ec244 100644 --- a/apple/Plugins/DynamoDBDriverPlugin/Info.plist +++ b/apple/Plugins/DynamoDBDriverPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + DynamoDB Driver TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesDatabaseTypeIds diff --git a/apple/Plugins/ElasticsearchDriverPlugin/Info.plist b/apple/Plugins/ElasticsearchDriverPlugin/Info.plist index 9e3a6cd5cc..1136a7812c 100644 --- a/apple/Plugins/ElasticsearchDriverPlugin/Info.plist +++ b/apple/Plugins/ElasticsearchDriverPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + Elasticsearch Driver TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesDatabaseTypeIds diff --git a/apple/Plugins/EtcdDriverPlugin/Info.plist b/apple/Plugins/EtcdDriverPlugin/Info.plist index c79338b3ea..84124ee9fe 100644 --- a/apple/Plugins/EtcdDriverPlugin/Info.plist +++ b/apple/Plugins/EtcdDriverPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + etcd Driver TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesDatabaseTypeIds diff --git a/apple/Plugins/FirebaseDriverPlugin/Info.plist b/apple/Plugins/FirebaseDriverPlugin/Info.plist index 0a260443b2..60db2f8766 100644 --- a/apple/Plugins/FirebaseDriverPlugin/Info.plist +++ b/apple/Plugins/FirebaseDriverPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + Firebase Driver TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesDatabaseTypeIds diff --git a/apple/Plugins/HanaDriverPlugin/Info.plist b/apple/Plugins/HanaDriverPlugin/Info.plist index 37b21f2e8d..38d2fdf689 100644 --- a/apple/Plugins/HanaDriverPlugin/Info.plist +++ b/apple/Plugins/HanaDriverPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + SAP HANA Driver TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesDatabaseTypeIds diff --git a/apple/Plugins/InfluxDBDriverPlugin/Info.plist b/apple/Plugins/InfluxDBDriverPlugin/Info.plist index a472fa3961..6193d36df8 100644 --- a/apple/Plugins/InfluxDBDriverPlugin/Info.plist +++ b/apple/Plugins/InfluxDBDriverPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + InfluxDB Driver TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesDatabaseTypeIds diff --git a/apple/Plugins/JSONExportPlugin/Info.plist b/apple/Plugins/JSONExportPlugin/Info.plist index 4077dfde3a..cd3c2a00e7 100644 --- a/apple/Plugins/JSONExportPlugin/Info.plist +++ b/apple/Plugins/JSONExportPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + JSON Export TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesExportFormatIds diff --git a/apple/Plugins/JSONImportPlugin/Info.plist b/apple/Plugins/JSONImportPlugin/Info.plist index d0beb83840..7cd3012c3e 100644 --- a/apple/Plugins/JSONImportPlugin/Info.plist +++ b/apple/Plugins/JSONImportPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + JSON Import TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesImportFormatIds diff --git a/apple/Plugins/KafkaDriverPlugin/Info.plist b/apple/Plugins/KafkaDriverPlugin/Info.plist index 2f105003d2..dac3c735c0 100644 --- a/apple/Plugins/KafkaDriverPlugin/Info.plist +++ b/apple/Plugins/KafkaDriverPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + Kafka Driver TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesDatabaseTypeIds diff --git a/apple/Plugins/KingbaseESDriverPlugin/Info.plist b/apple/Plugins/KingbaseESDriverPlugin/Info.plist index 2a09d82f10..60b4b87ea8 100644 --- a/apple/Plugins/KingbaseESDriverPlugin/Info.plist +++ b/apple/Plugins/KingbaseESDriverPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + KingbaseES Driver TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesDatabaseTypeIds diff --git a/apple/Plugins/LibSQLDriverPlugin/Info.plist b/apple/Plugins/LibSQLDriverPlugin/Info.plist index 64fe9da34f..8bf48d7389 100644 --- a/apple/Plugins/LibSQLDriverPlugin/Info.plist +++ b/apple/Plugins/LibSQLDriverPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + libSQL / Turso Driver TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesDatabaseTypeIds diff --git a/apple/Plugins/MQLExportPlugin/Info.plist b/apple/Plugins/MQLExportPlugin/Info.plist index 7cc82fecc2..1111bf8a60 100644 --- a/apple/Plugins/MQLExportPlugin/Info.plist +++ b/apple/Plugins/MQLExportPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + MQL Export TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesExportFormatIds diff --git a/apple/Plugins/MSSQLDriverPlugin/Info.plist b/apple/Plugins/MSSQLDriverPlugin/Info.plist index 11d93c8982..da796d02a2 100644 --- a/apple/Plugins/MSSQLDriverPlugin/Info.plist +++ b/apple/Plugins/MSSQLDriverPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + MSSQL Driver TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesDatabaseTypeIds diff --git a/apple/Plugins/MarkdownExportPlugin/Info.plist b/apple/Plugins/MarkdownExportPlugin/Info.plist index 9d9b33d127..020f6ad472 100644 --- a/apple/Plugins/MarkdownExportPlugin/Info.plist +++ b/apple/Plugins/MarkdownExportPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + Markdown Export TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesExportFormatIds diff --git a/apple/Plugins/MemcachedDriverPlugin/Info.plist b/apple/Plugins/MemcachedDriverPlugin/Info.plist index a9240bbf3f..4508b3c172 100644 --- a/apple/Plugins/MemcachedDriverPlugin/Info.plist +++ b/apple/Plugins/MemcachedDriverPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + Memcached Driver TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesDatabaseTypeIds diff --git a/apple/Plugins/MongoDBDriverPlugin/Info.plist b/apple/Plugins/MongoDBDriverPlugin/Info.plist index ad462443d3..a4ecc68ffa 100644 --- a/apple/Plugins/MongoDBDriverPlugin/Info.plist +++ b/apple/Plugins/MongoDBDriverPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + MongoDB Driver TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesDatabaseTypeIds diff --git a/apple/Plugins/MySQLDriverPlugin/Info.plist b/apple/Plugins/MySQLDriverPlugin/Info.plist index e736a2c92e..557f35f946 100644 --- a/apple/Plugins/MySQLDriverPlugin/Info.plist +++ b/apple/Plugins/MySQLDriverPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + MySQL Driver TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesDatabaseTypeIds diff --git a/apple/Plugins/Neo4jDriverPlugin/Info.plist b/apple/Plugins/Neo4jDriverPlugin/Info.plist index 7293e94d0b..d2630185ac 100644 --- a/apple/Plugins/Neo4jDriverPlugin/Info.plist +++ b/apple/Plugins/Neo4jDriverPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + Neo4j Driver TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesDatabaseTypeIds diff --git a/apple/Plugins/OracleDriverPlugin/Info.plist b/apple/Plugins/OracleDriverPlugin/Info.plist index bb2478ab96..a0b6894a6b 100644 --- a/apple/Plugins/OracleDriverPlugin/Info.plist +++ b/apple/Plugins/OracleDriverPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + Oracle Driver TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesDatabaseTypeIds diff --git a/apple/Plugins/ParquetExportPlugin/Info.plist b/apple/Plugins/ParquetExportPlugin/Info.plist index 758650d5c3..a6000c7d0f 100644 --- a/apple/Plugins/ParquetExportPlugin/Info.plist +++ b/apple/Plugins/ParquetExportPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + Parquet Export TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesExportFormatIds diff --git a/apple/Plugins/PostgreSQLDriverPlugin/Info.plist b/apple/Plugins/PostgreSQLDriverPlugin/Info.plist index 4c5c2710c6..b25cf5ebe0 100644 --- a/apple/Plugins/PostgreSQLDriverPlugin/Info.plist +++ b/apple/Plugins/PostgreSQLDriverPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + PostgreSQL Driver TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesDatabaseTypeIds diff --git a/apple/Plugins/QdrantDriverPlugin/Info.plist b/apple/Plugins/QdrantDriverPlugin/Info.plist index a9c5f4eb04..1586112f04 100644 --- a/apple/Plugins/QdrantDriverPlugin/Info.plist +++ b/apple/Plugins/QdrantDriverPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + Qdrant Driver TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesDatabaseTypeIds diff --git a/apple/Plugins/RedisDriverPlugin/Info.plist b/apple/Plugins/RedisDriverPlugin/Info.plist index 3bb3e5f4b7..5e6c28724d 100644 --- a/apple/Plugins/RedisDriverPlugin/Info.plist +++ b/apple/Plugins/RedisDriverPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + Redis Driver TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesDatabaseTypeIds diff --git a/apple/Plugins/SQLExportPlugin/Info.plist b/apple/Plugins/SQLExportPlugin/Info.plist index fd6dcc5ec1..d70d6a1dee 100644 --- a/apple/Plugins/SQLExportPlugin/Info.plist +++ b/apple/Plugins/SQLExportPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + SQL Export TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesExportFormatIds diff --git a/apple/Plugins/SQLImportPlugin/Info.plist b/apple/Plugins/SQLImportPlugin/Info.plist index 262e0c28d1..b57054834a 100644 --- a/apple/Plugins/SQLImportPlugin/Info.plist +++ b/apple/Plugins/SQLImportPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + SQL Import TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesImportFormatIds diff --git a/apple/Plugins/SQLiteDriverPlugin/Info.plist b/apple/Plugins/SQLiteDriverPlugin/Info.plist index 5354fb9599..e44c913842 100644 --- a/apple/Plugins/SQLiteDriverPlugin/Info.plist +++ b/apple/Plugins/SQLiteDriverPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + SQLite Driver TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesDatabaseTypeIds diff --git a/apple/Plugins/SnowflakeDriverPlugin/Info.plist b/apple/Plugins/SnowflakeDriverPlugin/Info.plist index 8f3283d511..1bc2cbb831 100644 --- a/apple/Plugins/SnowflakeDriverPlugin/Info.plist +++ b/apple/Plugins/SnowflakeDriverPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + Snowflake Driver TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesDatabaseTypeIds diff --git a/apple/Plugins/SpannerDriverPlugin/Info.plist b/apple/Plugins/SpannerDriverPlugin/Info.plist index 36fa241b70..a47438724b 100644 --- a/apple/Plugins/SpannerDriverPlugin/Info.plist +++ b/apple/Plugins/SpannerDriverPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + Spanner Driver TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesDatabaseTypeIds diff --git a/apple/Plugins/StarRocksDriverPlugin/Info.plist b/apple/Plugins/StarRocksDriverPlugin/Info.plist index 259ec20952..18f66f9ec1 100644 --- a/apple/Plugins/StarRocksDriverPlugin/Info.plist +++ b/apple/Plugins/StarRocksDriverPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + StarRocks Driver TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesDatabaseTypeIds diff --git a/apple/Plugins/SurrealDBDriverPlugin/Info.plist b/apple/Plugins/SurrealDBDriverPlugin/Info.plist index 34c7f92701..099bb24ee9 100644 --- a/apple/Plugins/SurrealDBDriverPlugin/Info.plist +++ b/apple/Plugins/SurrealDBDriverPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + SurrealDB Driver TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesDatabaseTypeIds diff --git a/apple/Plugins/TeradataDriverPlugin/Info.plist b/apple/Plugins/TeradataDriverPlugin/Info.plist index 5bb701622c..a8e9f352f3 100644 --- a/apple/Plugins/TeradataDriverPlugin/Info.plist +++ b/apple/Plugins/TeradataDriverPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + Teradata Driver TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesDatabaseTypeIds diff --git a/apple/Plugins/TrinoDriverPlugin/Info.plist b/apple/Plugins/TrinoDriverPlugin/Info.plist index 79b7acc065..8dccae6cce 100644 --- a/apple/Plugins/TrinoDriverPlugin/Info.plist +++ b/apple/Plugins/TrinoDriverPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + Trino Driver TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesDatabaseTypeIds diff --git a/apple/Plugins/TypesenseDriverPlugin/Info.plist b/apple/Plugins/TypesenseDriverPlugin/Info.plist index 0e0d2c4e6c..b6ec48e62a 100644 --- a/apple/Plugins/TypesenseDriverPlugin/Info.plist +++ b/apple/Plugins/TypesenseDriverPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + Typesense Driver TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesDatabaseTypeIds diff --git a/apple/Plugins/WeaviateDriverPlugin/Info.plist b/apple/Plugins/WeaviateDriverPlugin/Info.plist index 153b6de197..c27dcfc388 100644 --- a/apple/Plugins/WeaviateDriverPlugin/Info.plist +++ b/apple/Plugins/WeaviateDriverPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + Weaviate Driver TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesDatabaseTypeIds diff --git a/apple/Plugins/XLSXExportPlugin/Info.plist b/apple/Plugins/XLSXExportPlugin/Info.plist index 661aa2ce9e..e44a235083 100644 --- a/apple/Plugins/XLSXExportPlugin/Info.plist +++ b/apple/Plugins/XLSXExportPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + XLSX Export TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesExportFormatIds diff --git a/apple/Plugins/XLSXImportPlugin/Info.plist b/apple/Plugins/XLSXImportPlugin/Info.plist index a87e8e8ac3..6a7bf57fd2 100644 --- a/apple/Plugins/XLSXImportPlugin/Info.plist +++ b/apple/Plugins/XLSXImportPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + XLSX Import TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesImportFormatIds diff --git a/apple/TablePro/AppDelegate.swift b/apple/TablePro/AppDelegate.swift index 5e76ec815b..30de3144d1 100644 --- a/apple/TablePro/AppDelegate.swift +++ b/apple/TablePro/AppDelegate.swift @@ -1,8 +1,3 @@ -// -// AppDelegate.swift -// TablePro -// - import AppKit import Combine import os @@ -16,8 +11,6 @@ class AppDelegate: NSObject, NSApplicationDelegate { private var hasRunPostLaunchActivation = false - // MARK: - URL & File Open - func applicationWillFinishLaunching(_ notification: Notification) { LaunchTracer.shared.mark(.willFinishLaunchingBegan) // First: the migration below writes the flag that tells an existing install from a new one. @@ -28,6 +21,8 @@ class AppDelegate: NSObject, NSApplicationDelegate { AppSettingsStorage.shared.migrateStartupBehaviorToReopenLastIfNeeded() AppSettingsStorage.shared.removeRetiredFieldHeightKeys() AIProviderRegistration.registerAll() + // Before sync can pull a language change, and not earlier: settings built before the migrations above would miss them. + LanguageLaunchState.record() // Before any window exists, so the bar is right from the first frame. MainMenuBuilder.install(keyboard: AppSettingsManager.shared.keyboard) @@ -60,8 +55,6 @@ class AppDelegate: NSObject, NSApplicationDelegate { AppLaunchCoordinator.shared.handleReopen(hasVisibleWindows: flag) } - // MARK: - Lifecycle - func applicationDidFinishLaunching(_ notification: Notification) { LaunchTracer.shared.mark(.didFinishLaunchingBegan) if ProcessInfo.processInfo.environment["XCTestConfigurationFilePath"] != nil { @@ -69,8 +62,7 @@ class AppDelegate: NSObject, NSApplicationDelegate { return } - /// `AppSettingsManager.init` has already resolved the theme from these same three values. - /// Only a screenshot run overrides the mode, so only a screenshot run resolves it twice. + // AppSettingsManager.init already resolved the theme; only a screenshot run overrides the mode and resolves again. if let screenshotMode = ScreenshotEnvironment.appearanceMode { let appearanceSettings = AppSettingsManager.shared.appearance ThemeEngine.shared.apply( @@ -84,7 +76,7 @@ class AppDelegate: NSObject, NSApplicationDelegate { WindowOpener.shared.setWelcomePresenter { WelcomeWindowController.present() } WindowOpener.shared.setConnectionFormPresenter { ConnectionFormWindowController.present($0) } WindowOpener.shared.setIntegrationsActivityPresenter { IntegrationsActivityWindowController.present() } - WindowOpener.shared.setSettingsPresenter { SettingsWindowController.present(pane: $0) } + WindowOpener.shared.setSettingsPresenter { SettingsWindowController.present($0) } KeyRepeatFilter.shared.install() TableClickFocus.shared.install() RecentTabSwitcherController.installEditorKeyClaim() @@ -95,20 +87,14 @@ class AppDelegate: NSObject, NSApplicationDelegate { DatabaseManager.shared.startObservingSystemEvents() DatabaseManager.shared.tabStatePersister = SessionTabStatePersister() - /// A notification the person acted on to launch the app is delivered as soon as - /// `applicationDidFinishLaunching` returns, before any window has a frame. Apple documents - /// the delegate assignment for that reason, and the two services below own the categories - /// `NotificationRouter` looks the action up in, so deferring either drops the action. + // Not deferred: a launching notification's action arrives as soon as this returns, and these services own its categories. UNUserNotificationCenter.current().delegate = self PluginNotificationService.shared.setUp() OperationCompletionReporter.shared.setUp() AgentAttentionNotifier.shared.setUp() ChatToolBootstrap.register() - /// Prerequisites for a connection, not post-launch work: a `cloudflared` or - /// `cloud-sql-proxy` left behind by a crash still holds its local port, and a restored - /// connection reaches `ensureConnected` while intents are routing. Both hop straight off - /// the main actor, so starting them here costs the first frame nothing. + // Not post-launch work: a crashed run's tunnel still holds its port when a restored connection reconnects. Task { await CloudflareTunnelManager.shared.sweepStalePidsIfNeeded() } Task { await CloudSQLProxyManager.shared.sweepStalePidsIfNeeded() } Task { await TunnelCommandManager.shared.sweepStalePidsIfNeeded() } @@ -159,7 +145,7 @@ class AppDelegate: NSObject, NSApplicationDelegate { SoftwareUpdater.shared.start() // Before the account starts, so a stored key's migration reaches it as a sign-in. Telemetry.shared.start( - sharesUsageData: AppSettingsManager.shared.$general.map(\.shareAnalytics).eraseToAnyPublisher(), + sharesUsageData: AppSettingsManager.shared.generalSlice.publisher.map(\.shareAnalytics).eraseToAnyPublisher(), account: AccountServices.shared ) AccountServices.shared.start() @@ -173,8 +159,6 @@ class AppDelegate: NSObject, NSApplicationDelegate { true } - // MARK: - Remote Notifications - func application(_ application: NSApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { SyncCoordinator.shared.pushRegistrationDidFinish(registered: true) } @@ -188,8 +172,7 @@ class AppDelegate: NSObject, NSApplicationDelegate { SyncCoordinator.shared.handleRemoteNotification(userInfo) } - /// Unhiding is the one way a window comes back without any window notification firing, and the - /// app reports every window it owns as invisible while it is hidden. + // Unhiding brings windows back with no window notification, and while hidden every window reports invisible. func applicationDidUnhide(_ notification: Notification) { AppActivationPolicyController.shared.reevaluate() } @@ -221,8 +204,7 @@ class AppDelegate: NSObject, NSApplicationDelegate { func applicationWillTerminate(_ notification: Notification) { SessionRecoveryTracker.saveOnQuit() - /// Synchronously, because an actor hop at terminate may never be scheduled: a session killed - /// mid-reply used to come back with its last turn missing. + // Synchronously: an actor hop at terminate may never run, which lost a killed session's last turn. AgentSessionRegistry.shared.persistSynchronouslyForTermination() LinkedFolderWatcher.shared.stop() SQLFolderWatcher.shared.stop() @@ -238,9 +220,6 @@ class AppDelegate: NSObject, NSApplicationDelegate { SQLFolderWatcher.shared.reload() } - - // MARK: - Window Notifications - @objc func windowWillClose(_ notification: Notification) { guard let window = notification.object as? NSWindow else { return } @@ -262,13 +241,10 @@ class AppDelegate: NSObject, NSApplicationDelegate { } else { csvLogger.debug("AppDelegate.windowWillClose - non-main window '\(window.identifier?.rawValue ?? "nil", privacy: .public)' closing") } - /// Any window, not only a primary one: a machine-started session can have nothing on screen - /// but a settings window, and closing it leaves the process with no user interface again. + // Any window: a machine-started session may show only a settings window, and closing it leaves no UI. AppActivationPolicyController.shared.reevaluate(excluding: window) } - // MARK: - Dock Menu - func applicationDockMenu(_ sender: NSApplication) -> NSMenu? { let menu = NSMenu() @@ -331,8 +307,7 @@ class AppDelegate: NSObject, NSApplicationDelegate { } } -/// Carries a UserNotifications callback from the delegate thread to the main actor. -/// UNUserNotificationCenter hands each one over exactly once and keeps no reference. +// The center hands each callback over exactly once and keeps no reference, so carrying it to the main actor is safe. private struct NotificationDelivery: @unchecked Sendable { let payload: Payload let complete: () -> Void diff --git a/apple/TablePro/Core/AI/AISchemaContext.swift b/apple/TablePro/Core/AI/AISchemaContext.swift index 1a495ae7a8..fb45df3550 100644 --- a/apple/TablePro/Core/AI/AISchemaContext.swift +++ b/apple/TablePro/Core/AI/AISchemaContext.swift @@ -1,17 +1,9 @@ -// -// AISchemaContext.swift -// TablePro -// -// Builds AI system prompt context from current database connection schema. -// - import Foundation import TableProAutocomplete import TableProPluginKit import TableProSQLGrammar -/// One table as the schema context describes it. The producer joins each table to its own columns -/// and foreign keys, because a lookup by name cannot tell two schemas' tables of the same name apart. +// Each table carries its own columns and foreign keys: a lookup by name cannot tell two schemas' tables apart. struct AISchemaTable: Sendable { let table: TableInfo let columns: [ColumnInfo] @@ -36,8 +28,6 @@ struct AISchemaRankingInput: Sendable { struct AISchemaContext { static let maxQueryLength = 2_000 - // MARK: - Public - static func buildSystemPrompt( databaseType: DatabaseType, databaseName: String, @@ -65,7 +55,7 @@ struct AISchemaContext { let schemaContext = buildSchemaSection( tables: tables, defaultSchema: defaultSchema, - maxTables: settings.maxSchemaTables, + maxTables: settings.clampedMaxSchemaTables, identifierQuote: identifierQuote ) if !schemaContext.isEmpty { @@ -117,10 +107,7 @@ struct AISchemaContext { return parts.joined(separator: "\n") } - // MARK: - Private - - /// A table outside `defaultSchema` is named with its schema, so two tables that share a name - /// read as two tables rather than one listed twice. + // A table outside defaultSchema is named with its schema, so two tables sharing a name read as two. static func buildSchemaSection( tables: [AISchemaTable], defaultSchema: String?, diff --git a/apple/TablePro/Core/AI/Chat/SlashCommand.swift b/apple/TablePro/Core/AI/Chat/SlashCommand.swift index c05ba82af2..e905814447 100644 --- a/apple/TablePro/Core/AI/Chat/SlashCommand.swift +++ b/apple/TablePro/Core/AI/Chat/SlashCommand.swift @@ -46,24 +46,23 @@ enum SlashCommand: String, CaseIterable, Identifiable, Sendable { SlashCommand(rawValue: name.trimmingCharacters(in: .whitespaces).lowercased()) != nil } - /// Parses a typed input. Returns the command and any body text after it, - /// or nil if the text doesn't start with a known slash command. - /// Examples: - /// "/explain" -> (.explain, "") - /// "/explain SELECT 1" -> (.explain, "SELECT 1") - /// "/Notacommand" -> nil - /// "hello" -> nil static func parse(_ text: String) -> (command: SlashCommand, body: String)? { + guard let invocation = invocation(in: text), + let command = SlashCommand(rawValue: invocation.name.lowercased()) + else { return nil } + return (command, invocation.body) + } + + static func invocation(in text: String) -> (name: String, body: String)? { let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines) guard trimmed.hasPrefix("/") else { return nil } let afterSlash = trimmed.dropFirst() - let nameSubstring = afterSlash.prefix(while: { !$0.isWhitespace }) - let name = String(nameSubstring).lowercased() - guard let command = SlashCommand(rawValue: name) else { return nil } + let name = afterSlash.prefix(while: { !$0.isWhitespace }) + guard !name.isEmpty else { return nil } let body = afterSlash - .dropFirst(nameSubstring.count) - .trimmingCharacters(in: .whitespaces) - return (command, body) + .dropFirst(name.count) + .trimmingCharacters(in: .whitespacesAndNewlines) + return (String(name), body) } static func match(prefix: String) -> [SlashCommand] { diff --git a/apple/TablePro/Core/AI/Copilot/CopilotPreambleBuilder.swift b/apple/TablePro/Core/AI/Copilot/CopilotPreambleBuilder.swift index 514cc3a350..9774db7567 100644 --- a/apple/TablePro/Core/AI/Copilot/CopilotPreambleBuilder.swift +++ b/apple/TablePro/Core/AI/Copilot/CopilotPreambleBuilder.swift @@ -1,8 +1,3 @@ -// -// CopilotPreambleBuilder.swift -// TablePro -// - import Foundation import os import TableProPluginKit @@ -58,7 +53,7 @@ final class CopilotPreambleBuilder { databaseType: DatabaseType, referencing documentText: String? = nil, grammar: SQLLexicalGrammar? = nil, - maxTables: Int = AppSettingsManager.shared.ai.maxSchemaTables + maxTables: Int = AppSettingsManager.shared.ai.clampedMaxSchemaTables ) async { try? FileManager.default.createDirectory(at: Self.contextDirectory, withIntermediateDirectories: true) diff --git a/apple/TablePro/Core/AI/Copilot/CopilotService.swift b/apple/TablePro/Core/AI/Copilot/CopilotService.swift index a1ea975ab0..663db1acdd 100644 --- a/apple/TablePro/Core/AI/Copilot/CopilotService.swift +++ b/apple/TablePro/Core/AI/Copilot/CopilotService.swift @@ -29,6 +29,8 @@ final class CopilotService: ObservableObject { @Published private(set) var status: Status = .stopped @Published private(set) var authState: AuthState = .signedOut @Published private(set) var statusMessage: String? + // Until the server answers, authState reads signedOut whether or not the user is signed in. + @Published private(set) var hasReportedAuthState = false private var lspClient: LSPClient? private var transport: LSPTransport? @@ -47,8 +49,7 @@ final class CopilotService: ObservableObject { } ) - /// Stops the LSP server if the user hasn't signed in within this window after start. - /// Avoids leaving a Node process idle for users who add a Copilot config but never authorise. + // Leaves no Node process idle for someone who adds Copilot and never signs in. private static let unauthenticatedTimeout: Duration = .seconds(5 * 60) private init() {} @@ -58,10 +59,7 @@ final class CopilotService: ObservableObject { var isAuthenticated: Bool { authState.isSignedIn } var generation: Int { serverGeneration } - // MARK: - Lifecycle - - /// Concurrent callers share one launch, so a caller that arrives mid-start waits for it rather - /// than finding no client. `stop()` drops the shared launch, so a caller after it starts afresh. + // Concurrent callers share one launch; stop() drops it, so a later caller starts afresh. func start() async { if let startTask { await startTask.value @@ -76,8 +74,7 @@ final class CopilotService: ObservableObject { } } - /// The client, starting the language server first when this is its first use. A turn that was - /// queued before AI was turned off or Copilot removed must not bring the server back. + // A turn queued before AI was turned off or Copilot removed must not bring the server back. func runningClient() async throws -> LSPClient { guard CopilotLifecycle.allowsRunning(AppSettingsManager.shared.ai) else { throw CopilotError.serverNotRunning @@ -187,8 +184,6 @@ final class CopilotService: ObservableObject { Self.logger.info("Copilot language server stopped") } - // MARK: - Authentication - func signIn() async throws { await start() guard let transport else { @@ -196,6 +191,7 @@ final class CopilotService: ObservableObject { } let result = try await authManager.initiateSignIn(transport: transport) authState = .signingIn(userCode: result.userCode, verificationURI: result.verificationURI) + hasReportedAuthState = true } func completeSignIn() async throws { @@ -204,6 +200,7 @@ final class CopilotService: ObservableObject { } let username = try await authManager.completeSignIn(transport: transport) authState = .signedIn(username: username) + hasReportedAuthState = true unauthenticatedStop.cancel() } @@ -211,11 +208,10 @@ final class CopilotService: ObservableObject { guard let transport else { return } await authManager.signOut(transport: transport) authState = .signedOut + hasReportedAuthState = true scheduleUnauthenticatedStopIfNeeded() } - // MARK: - Private - private func scheduleRestart() { restartAttempt += 1 let delay = min(Double(1 << min(restartAttempt, 6)), 60.0) @@ -248,6 +244,7 @@ final class CopilotService: ObservableObject { } catch { Self.logger.debug("Auth status check failed: \(error.localizedDescription)") } + hasReportedAuthState = true } private func scheduleUnauthenticatedStopIfNeeded() { @@ -266,6 +263,7 @@ final class CopilotService: ObservableObject { statusMessage = message if let message, message.lowercased().contains("sign") || message.lowercased().contains("expired") { authState = .signedOut + hasReportedAuthState = true scheduleUnauthenticatedStopIfNeeded() } case "Warning": diff --git a/apple/TablePro/Core/Autocomplete/SQLSchemaProvider.swift b/apple/TablePro/Core/Autocomplete/SQLSchemaProvider.swift index c709c3315e..d406f8f48d 100644 --- a/apple/TablePro/Core/Autocomplete/SQLSchemaProvider.swift +++ b/apple/TablePro/Core/Autocomplete/SQLSchemaProvider.swift @@ -7,8 +7,7 @@ import TableProSQLGrammar actor SQLSchemaProvider { private static let logger = Logger(subsystem: "com.TablePro", category: "SQLSchemaProvider") - /// The cache's capacity in tables, and the largest schema one bulk column read fills: reading - /// every column and keeping a fraction is the waste the preload exists to avoid. + // Also the largest schema one bulk column read fills: reading every column to keep a fraction is waste. static let maxCachedTables = 300 // A column list belongs to a table, spelled as the catalog spells its schema and name: an engine can keep apart @@ -59,10 +58,10 @@ actor SQLSchemaProvider { enum Outcome { case loaded, skipped, failed } } - /// Each state keeps the table-list generation it answered, so a later list reads it as stale. + // Each state keeps the table-list generation it answered, so a later list reads it as stale. private var columnPreload: ColumnPreload = .idle private var tableListGeneration = 0 - /// Until a query editor asks, a no-reference completion never starts a bulk read. + // Until a query editor asks, a no-reference completion never starts a bulk read. private var hasEditorDemand = false struct ColumnMetadataSource: Sendable { @@ -94,9 +93,7 @@ actor SQLSchemaProvider { private var fieldPathCache: [ColumnCacheKey: [PluginFieldPath]] = [:] private var fieldPathTasks: [ColumnCacheKey: Task<[PluginFieldPath], Never>] = [:] - /// Another schema's tables, fetched when a statement names that schema and a dot. They are - /// held apart from `tables`, which the scope's owner writes and every unqualified reader - /// trusts, so completing `attendance.` cannot make `timesheet` an answer for a bare name. + // Kept apart from tables, so completing attendance. cannot make timesheet an answer for a bare name. private var onDemandSchemaTables: [CatalogName: [TableInfo]] = [:] private var onDemandSchemaTableTasks: [CatalogName: Task<[TableInfo]?, Never>] = [:] @@ -124,24 +121,21 @@ actor SQLSchemaProvider { private let metadataSource: ColumnMetadataSource? private var connectionInfo: DatabaseConnection? - /// The database this provider describes. A provider is per scope, so it can be a database the - /// sidebar is not browsing, and the AI schema context must name the one the tables came from. + // A provider is per scope, so this can be a database the sidebar is not browsing. private var scopeDatabase: String? init(metadataSource: ColumnMetadataSource? = nil) { self.metadataSource = metadataSource } - // MARK: - Public API - - /// Concurrent callers await the same in-flight Task instead of firing duplicate queries. + // Concurrent callers await the same in-flight Task instead of firing duplicate queries. func loadSchema(using driver: DatabaseDriver, connection: DatabaseConnection? = nil) async { if let existing = loadTask { Self.logger.debug("[schema] loadSchema awaiting existing in-flight task") let t0 = Date() if let connection { self.connectionInfo = connection } await existing.value - Self.logger.debug("[schema] loadSchema coalesced — awaited existing task ms=\(Int(Date().timeIntervalSince(t0) * 1_000)) tableCount=\(self.tables.count)") + Self.logger.debug("[schema] loadSchema coalesced, awaited existing task ms=\(Int(Date().timeIntervalSince(t0) * 1_000)) tableCount=\(self.tables.count)") return } @@ -312,8 +306,7 @@ actor SQLSchemaProvider { }) } - /// A lookup that names no schema reads the schema an unqualified fetch targets, which is the one - /// the column preload fills, so `orders` and `public.orders` on PostgreSQL share one entry. + // An unqualified lookup reads the schema the preload fills, so orders and public.orders share one entry. private func cacheKey(table: String, schema: String?) -> ColumnCacheKey { if let listed = listedSpelling(ofTable: table, schema: schema) { return cacheKey(listed) } return ColumnCacheKey( @@ -333,8 +326,7 @@ actor SQLSchemaProvider { return schema == CatalogName(key.isTyped ? Self.folded(defaultSchema) : schemaSpelling(defaultSchema) ?? defaultSchema) } - /// A table outside the default schema keeps its schema, so two cached tables of one name never - /// offer the same `orders.id` for columns of two different tables. + // A table outside the default schema keeps its schema, so two tables of one name never share orders.id. private func fallbackTableLabel(for key: ColumnCacheKey, listed: ListedName?) -> String { let name = listed?.name ?? key.name.text guard let schema = key.schema, !isDefaultSchema(key) else { return name } @@ -348,8 +340,7 @@ actor SQLSchemaProvider { return [.statement(schema.text, quoted: false), table] } - /// The schema a table can be named in without its schema: the engine's implicit schema when it - /// has one, otherwise the schema the driver was on when this scope loaded. + // The engine's implicit schema when it has one, otherwise the schema the driver was on when this scope loaded. func getDefaultSchema() -> String? { connectionInfo?.type.implicitSchemaName ?? eagerLoadSchema } @@ -416,7 +407,7 @@ actor SQLSchemaProvider { staleRereadsStarted.subtract(keys) } - /// Reads nothing. The next editor request or no-reference completion refills it. + // Reads nothing: the next editor request or no-reference completion refills it. func clearColumnCache() { if case .running(_, let task) = columnPreload { task.cancel() } columnPreload = .idle @@ -432,23 +423,19 @@ actor SQLSchemaProvider { fieldPathTasks.removeAll() } - // MARK: - Column Preload - - /// Only a query editor's `prepare` calls this. It joins a read in flight and retries a failed one. + // Only a query editor's prepare calls this. It joins a read in flight and retries a failed one. func requestColumnPreload() { hasEditorDemand = true startColumnPreloadIfStale(retryingFailure: true) } - /// Reads again for a table list written after a preload had served the previous one. func renewColumnPreload() { guard case .settled(let generation, .loaded) = columnPreload, generation != tableListGeneration else { return } startColumnPreloadIfStale(retryingFailure: false) } - /// The bulk read covers one schema while `tables` holds every expanded one. Zero means the list - /// names other schemas only, so a read sized by it would be a guess. + // The bulk read covers one schema; zero means the list names other schemas only, so its size is unknown. private var eagerLoadTableCount: Int { tables.filter { isInEagerLoadSchema($0) }.count } @@ -510,7 +497,7 @@ actor SQLSchemaProvider { columnPreload = .running(generation: generation, task: task) } - /// The pooled lease ignores cancellation, so a superseded read still completes and is stopped here. + // The pooled lease ignores cancellation, so a superseded read still completes and is stopped here. private func commitColumnPreload(_ result: Result<[CatalogName: [ColumnInfo]], any Error>, generation: Int) { guard case .running(let running, _) = columnPreload, running == generation else { return } switch result { @@ -526,8 +513,7 @@ actor SQLSchemaProvider { } } - /// A request the previous list had not served yet is served against this one. A settled preload - /// waits for the next request. + // A request the previous list had not served is served against this one; a settled preload waits. private func noteTableListWritten() { tableListGeneration &+= 1 unqualifiedTableItems = nil @@ -546,8 +532,7 @@ actor SQLSchemaProvider { } } - /// In the schema's own table order, so the tables kept under the cache limit are the same every - /// run. Only a table listed in the preload schema takes an entry from the read. + // In the schema's own order, so the tables kept under the cache limit are the same every run. private func populateColumnCache(_ allColumns: [CatalogName: [ColumnInfo]]) { var pending = allColumns // A read that spells a listed table otherwise, by case alone, still fills it when neither side has another @@ -589,8 +574,6 @@ actor SQLSchemaProvider { columnAccessOrder.append(key) } - // MARK: - Column Catalog - // Compared by bytes, like the catalog it names. private struct ListedName: Hashable { let schema: String? @@ -724,9 +707,7 @@ actor SQLSchemaProvider { return nil } - /// `tables` is every table the scope's owner loaded, which for the browse scope includes each - /// schema the sidebar has expanded. A bare name only reaches the schema unqualified names - /// resolve in, so only its tables may be offered or matched without their schema. + // tables includes every schema the sidebar expanded, but a bare name only reaches the unqualified one. private var tablesResolvableUnqualified: [TableInfo] { guard let defaultSchema = getDefaultSchema(), !defaultSchema.isEmpty else { return tables } let spelling = schemaSpelling(defaultSchema) @@ -736,8 +717,6 @@ actor SQLSchemaProvider { } } - // MARK: - AI Schema Context - // The tables the statement at the cursor reads take the column budget first. func buildSchemaContextForAI(settings: AISettings, editorText: String? = nil, cursorOffset: Int = 0) async -> String? { guard !tables.isEmpty, let connection = connectionInfo else { return nil } @@ -756,8 +735,9 @@ actor SQLSchemaProvider { return (resolvedName, quote, lang, langName, sessionGrammar) } + let budget = settings.clampedMaxSchemaTables var listedTables = tables - if let editorText, editorLanguage == .sql, listedTables.count > settings.maxSchemaTables { + if let editorText, editorLanguage == .sql, listedTables.count > budget { let statement = SQLStatementScanner.statementAtCursor( in: editorText, cursorPosition: cursorOffset, @@ -775,11 +755,11 @@ actor SQLSchemaProvider { var schemaTables: [AISchemaTable] = [] schemaTables.reserveCapacity(listedTables.count) - for table in listedTables.prefix(settings.maxSchemaTables) { + for table in listedTables.prefix(budget) { let columns = await getColumns(for: table.name, schema: table.schema) schemaTables.append(AISchemaTable(table: table, columns: columns)) } - schemaTables += listedTables.dropFirst(settings.maxSchemaTables).map { AISchemaTable(table: $0) } + schemaTables += listedTables.dropFirst(budget).map { AISchemaTable(table: $0) } return AISchemaContext.buildSystemPrompt( databaseType: dbType, @@ -795,8 +775,6 @@ actor SQLSchemaProvider { ) } - // MARK: - Completion Items - func tableCompletionItems() async -> [SQLCompletionItem] { let defaultSchema = getDefaultSchema() if let cached = unqualifiedTableItems, cached.defaultSchema == defaultSchema { return cached.items } @@ -916,8 +894,7 @@ actor SQLSchemaProvider { } } - /// Dotted field paths for a document-store collection, cached per collection. - /// Concurrent callers await the same sample instead of firing duplicate queries. + // Concurrent callers await the same sample instead of firing duplicate queries. func fieldPaths(for tableName: String, sampleSize: Int = 50) async -> [PluginFieldPath] { let key = cacheKey(table: tableName, schema: nil) if let cached = fieldPathCache[key] { return cached } @@ -940,8 +917,7 @@ actor SQLSchemaProvider { return paths } - /// Reads only the column cache, because completion runs per keystroke and must not add a fetch. - /// Until the preload or this statement's column completion has read the table, it offers nothing. + // Reads only the column cache: completion runs per keystroke and must not add a fetch. func allowedValues(forColumn column: String, in references: [TableReference]) -> [String] { let name = column.lowercased() let candidates = references.isEmpty diff --git a/apple/TablePro/Core/MCP/Clients/MCPClientRowPresentation.swift b/apple/TablePro/Core/MCP/Clients/MCPClientRowPresentation.swift index 21a1f29426..af963ec3c9 100644 --- a/apple/TablePro/Core/MCP/Clients/MCPClientRowPresentation.swift +++ b/apple/TablePro/Core/MCP/Clients/MCPClientRowPresentation.swift @@ -232,7 +232,7 @@ enum MCPClientDetailText { String(format: String(localized: "TablePro is turned off in %1$@. Turn it on in %1$@'s MCP settings to use it."), name) case .usesToken: String( - format: String(localized: "%@ connects with a token from Settings > MCP > Authentication, which can limit what it reaches. TablePro leaves it as is."), + format: String(localized: "%@ connects with a token from Settings > MCP > Tokens, which can limit what it reaches. TablePro leaves it as is."), name ) case .unreadable: diff --git a/apple/TablePro/Core/MCP/Lifecycle/MCPServerManager.swift b/apple/TablePro/Core/MCP/Lifecycle/MCPServerManager.swift index ea8ab78310..e6bd5f0e71 100644 --- a/apple/TablePro/Core/MCP/Lifecycle/MCPServerManager.swift +++ b/apple/TablePro/Core/MCP/Lifecycle/MCPServerManager.swift @@ -68,18 +68,21 @@ internal final class MCPServerManager: ObservableObject { @Published internal private(set) var connectedClients: [SessionSnapshot] = [] @Published internal private(set) var tokenStore: MCPTokenStore? + // Fires when Settings forgets an approval or a revocation withdraws one; a new approval waits for the next visit. + internal let grantChanges = MCPChangeSignal() + private let lifecycle = MCPServerLifecycleQueue() private let handshake: MCPHandshakeFile private let isEnabled: @MainActor () -> Bool - @Published private(set) var composition: MCPServerComposition? - @Published private var bridgeCredential: BridgeCredential? - @Published private var instanceId = "" - @Published private var generation = 0 - @Published private var revocationObserverId: UUID? - @Published private var dispatchTask: Task? - @Published private var stateTask: Task? - @Published private var tokenRenewalTask: Task? + private(set) var composition: MCPServerComposition? + private var bridgeCredential: BridgeCredential? + private var instanceId = "" + private var generation = 0 + private var revocationObserverId: UUID? + private var dispatchTask: Task? + private var stateTask: Task? + private var tokenRenewalTask: Task? internal var isRunning: Bool { if case .running = state { return true } @@ -149,10 +152,12 @@ internal final class MCPServerManager: ObservableObject { internal func forgetGrant(subject: String, connectionId: UUID) async { await approvalPolicy().revokeGrant(subject: subject, connectionId: connectionId) + grantChanges.send() } internal func forgetEveryGrant() async { await approvalPolicy().forgetEveryGrant() + grantChanges.send() } private func approvalPolicy() -> MCPAuthPolicy { @@ -193,6 +198,7 @@ internal final class MCPServerManager: ObservableObject { let withdrawn = stored?.subjectWithdrawnWhenEnded ?? .token(tokenId) let persisted = await revokeToken(id: tokenId) await composition.authPolicy.clearApprovals(subject: withdrawn) + grantChanges.send() await composition.activityLedger.forget(tokenId: tokenId) await refreshClients() return persisted @@ -468,6 +474,7 @@ internal final class MCPServerManager: ObservableObject { let cancelled = await dispatcher.cancelInflight(matchingTokenId: tokenId) if let subject { await composition?.authPolicy.clearApprovals(subject: subject) + grantChanges.send() } guard cancelled > 0 else { return } Self.logger.info( diff --git a/apple/TablePro/Core/MCP/MCPTokenStore.swift b/apple/TablePro/Core/MCP/MCPTokenStore.swift index f0e1da94c2..69a6a7cf7d 100644 --- a/apple/TablePro/Core/MCP/MCPTokenStore.swift +++ b/apple/TablePro/Core/MCP/MCPTokenStore.swift @@ -62,6 +62,9 @@ struct MCPAuthToken: Codable, Identifiable, Sendable { var isEffectivelyActive: Bool { isActive && !isExpired } + // TablePro mints the bridge and Claude Agent tokens itself, so Settings and the activity window leave them out. + var isUserManaged: Bool { !isBridgeCredential && !isClaudeAgentCredential } + func renamed(_ name: String) -> MCPAuthToken { MCPAuthToken( id: id, @@ -238,6 +241,17 @@ enum TokenPermissions: String, Codable, Sendable, CaseIterable, Identifiable { } } + var summary: String { + switch self { + case .readOnly: + String(localized: "Read schema and run SELECT queries.") + case .readWrite: + String(localized: "Read schema and run any non-destructive query, including INSERT, UPDATE, and DELETE.") + case .fullAccess: + String(localized: "Full access including destructive DDL after explicit confirmation.") + } + } + var scopes: Set { switch self { case .readOnly: @@ -258,6 +272,9 @@ actor MCPTokenStore { private static let logger = Logger(subsystem: "com.TablePro", category: "MCPTokenStore") + // Fires when a user-managed token is added, revoked or removed; never for a last-used stamp. + nonisolated let membershipChanges = MCPChangeSignal() + private var tokens: [MCPAuthToken] = [] // Stored entries this build cannot decode, kept as JSON so a save writes them back. private var undecodedEntries: [Data] = [] @@ -363,6 +380,9 @@ actor MCPTokenStore { Self.logger.info("Generated MCP token '\(name, privacy: .private(mask: .hash))'") MCPAuditLogger.logTokenCreated(tokenId: token.id, tokenName: name) + if token.isUserManaged { + membershipChanges.send() + } return (token, plaintext) } @@ -391,8 +411,12 @@ actor MCPTokenStore { tokens[index].isActive = false let revokedName = tokens[index].name let withdrawn = tokens[index].subjectWithdrawnWhenEnded + let isUserManaged = tokens[index].isUserManaged let persisted = save() notifyRevocationObservers(tokenId: tokenId, withdrawing: withdrawn) + if isUserManaged { + membershipChanges.send() + } Self.logger.info("Revoked MCP token '\(revokedName, privacy: .private(mask: .hash))'") MCPAuditLogger.logTokenRevoked(tokenId: tokenId, tokenName: revokedName) @@ -444,9 +468,13 @@ actor MCPTokenStore { let name = tokens[index].name let withdrawn = withdrawsApprovals ? tokens[index].subjectWithdrawnWhenEnded : nil + let isUserManaged = tokens[index].isUserManaged tokens.remove(at: index) let persisted = save() notifyRevocationObservers(tokenId: tokenId, withdrawing: withdrawn) + if isUserManaged { + membershipChanges.send() + } Self.logger.info("Deleted MCP token '\(name, privacy: .private(mask: .hash))'") return persisted @@ -500,17 +528,26 @@ actor MCPTokenStore { let staleCount = tokens.filter(Self.isStaleBridge).count tokens.removeAll(where: Self.isStaleBridge) + let expiredAgentCount = tokens.filter(Self.isExpiredAgentToken).count + tokens.removeAll(where: Self.isExpiredAgentToken) let renamedCount = tokens.filter(Self.claimsAgentName).count tokens = tokens.map(Self.releasingAgentName) - guard staleCount > 0 || renamedCount > 0 else { return } + guard staleCount > 0 || expiredAgentCount > 0 || renamedCount > 0 else { return } save() - Self.logger.info("Cleaned up \(staleCount) stale bridge token(s), renamed \(renamedCount) client token(s)") + Self.logger.info( + "Cleaned up \(staleCount) stale bridge and \(expiredAgentCount) expired agent token(s), renamed \(renamedCount) client token(s)" + ) } private static func isStaleBridge(_ token: MCPAuthToken) -> Bool { token.isBridgeCredential || token.name == stdioBridgeTokenName } + // A turn that crashed never retired its token; once expired it opens nothing and only clutters the list. + private static func isExpiredAgentToken(_ token: MCPAuthToken) -> Bool { + token.isClaudeAgentCredential && token.isExpired + } + // Builds before the agent's name was reserved let a pairing client take it. private static func claimsAgentName(_ token: MCPAuthToken) -> Bool { token.name == claudeAgentTokenName && !token.isClaudeAgentCredential @@ -575,7 +612,7 @@ actor MCPTokenStore { storedTokensUnread = false let minted = Set(tokens.map(\.id)) tokens = stored.tokens - .filter { !minted.contains($0.id) && !Self.isStaleBridge($0) } + .filter { !minted.contains($0.id) && !Self.isStaleBridge($0) && !Self.isExpiredAgentToken($0) } .map(Self.releasingAgentName) + tokens undecodedEntries = stored.undecoded Self.logger.info("Read the stored MCP tokens after an earlier failure") @@ -677,6 +714,28 @@ actor MCPTokenStore { } } +// Fans one change out to every listener; a listener that falls behind holds one pending change, not each. +final class MCPChangeSignal: Sendable { + private let listeners = OSAllocatedUnfairLock<[UUID: AsyncStream.Continuation]>(initialState: [:]) + + func changes() -> AsyncStream { + let (stream, continuation) = AsyncStream.makeStream(bufferingPolicy: .bufferingNewest(1)) + let id = UUID() + listeners.withLock { $0[id] = continuation } + continuation.onTermination = { [weak self] _ in + self?.listeners.withLock { _ = $0.removeValue(forKey: id) } + } + return stream + } + + func send() { + let current = listeners.withLock { Array($0.values) } + for continuation in current { + continuation.yield() + } + } +} + enum MCPTokenBlob: Sendable, Equatable { case found(Data) case missing diff --git a/apple/TablePro/Core/MCP/Outside/MCPServerStore.swift b/apple/TablePro/Core/MCP/Outside/MCPServerStore.swift index cc1534bc6f..205c81e4f9 100644 --- a/apple/TablePro/Core/MCP/Outside/MCPServerStore.swift +++ b/apple/TablePro/Core/MCP/Outside/MCPServerStore.swift @@ -1,12 +1,14 @@ -// -// MCPServerStore.swift -// TablePro -// - import Combine import Foundation import TableProMCP +internal enum MCPServerSaveError: Error, Equatable, Sendable { + case invalid(MCPServerConfigurationError) + // A new server, or a saved one pointed at another scheme, host or port, must bring its own token. + case tokenRequired + case tokenNotSaved +} + // Device-local and never synced: a server this Mac reaches may not be reachable from another. @MainActor internal final class MCPServerStore: ObservableObject { @@ -30,8 +32,6 @@ internal final class MCPServerStore: ObservableObject { servers = defaults.read(Self.serversKey).value ?? [] } - // MARK: - Reads - internal func server(id: UUID) -> MCPServerConfiguration? { servers.first { $0.id == id } } @@ -51,27 +51,33 @@ internal final class MCPServerStore: ObservableObject { servers.first { toolName.hasPrefix($0.toolNamespace) } } - // MARK: - Writes - + // The token is written first, so a Keychain refusal leaves the list and the saved token as they were. @discardableResult internal func upsert( _ configuration: MCPServerConfiguration, token: String? - ) -> MCPServerConfigurationError? { + ) -> MCPServerSaveError? { if let error = MCPServerConfigurationValidator.validate( name: configuration.name, endpoint: configuration.endpoint ) { - return error + return .invalid(error) } - if let index = servers.firstIndex(where: { $0.id == configuration.id }) { - servers[index] = configuration - } else { - servers.append(configuration) + let newToken = token.flatMap { $0.isEmpty ? nil : $0 } + if newToken == nil { + guard let saved = server(id: configuration.id), + Self.sharesOrigin(saved.endpoint, configuration.endpoint) else { return .tokenRequired } + } + if let newToken, !keychain.writeString(newToken, forKey: Self.tokenKey(configuration.id)) { + return .tokenNotSaved } - if let token, !token.isEmpty { - _ = keychain.writeString(token, forKey: Self.tokenKey(configuration.id)) + var next = servers + if let index = next.firstIndex(where: { $0.id == configuration.id }) { + next[index] = configuration + } else { + next.append(configuration) } + servers = next persist() return nil } @@ -115,7 +121,23 @@ internal final class MCPServerStore: ObservableObject { return token } - // MARK: - Storage + // A saved token may follow a path change, never a move to another scheme, host or port. + nonisolated internal static func sharesOrigin(_ lhs: URL, _ rhs: URL) -> Bool { + guard let lhsScheme = lhs.scheme?.lowercased(), let rhsScheme = rhs.scheme?.lowercased(), + let lhsHost = lhs.host?.lowercased(), let rhsHost = rhs.host?.lowercased() else { return false } + return lhsScheme == rhsScheme + && lhsHost == rhsHost + && effectivePort(lhs, scheme: lhsScheme) == effectivePort(rhs, scheme: rhsScheme) + } + + nonisolated private static func effectivePort(_ url: URL, scheme: String) -> Int? { + if let port = url.port { return port } + switch scheme { + case "https": return 443 + case "http": return 80 + default: return nil + } + } private static func tokenKey(_ serverId: UUID) -> String { "mcp.outsideServer.\(serverId.uuidString)" diff --git a/apple/TablePro/Core/Plugins/PluginManager+AutoUpdate.swift b/apple/TablePro/Core/Plugins/PluginManager+AutoUpdate.swift index 9d224a2a4a..2a8fbda7db 100644 --- a/apple/TablePro/Core/Plugins/PluginManager+AutoUpdate.swift +++ b/apple/TablePro/Core/Plugins/PluginManager+AutoUpdate.swift @@ -278,6 +278,10 @@ extension PluginManager { } func resolveRegistryId(for rejected: RejectedPlugin, manifest: RegistryManifest) -> String? { + Self.resolveRegistryId(for: rejected, in: manifest) + } + + nonisolated static func resolveRegistryId(for rejected: RejectedPlugin, in manifest: RegistryManifest) -> String? { if let id = rejected.registryId { return id } if let bundleId = rejected.bundleId, manifest.plugins.contains(where: { $0.id == bundleId }) { @@ -291,15 +295,23 @@ extension PluginManager { } func registryPlugin(for rejected: RejectedPlugin) -> RegistryPlugin? { - guard let manifest = RegistryClient.shared.manifest else { return nil } - guard let id = resolveRegistryId(for: rejected, manifest: manifest) else { return nil } + Self.registryPlugin(for: rejected, in: RegistryClient.shared.manifest) + } + + nonisolated static func registryPlugin(for rejected: RejectedPlugin, in manifest: RegistryManifest?) -> RegistryPlugin? { + guard let manifest, let id = resolveRegistryId(for: rejected, in: manifest) else { return nil } return manifest.plugins.first(where: { $0.id == id }) } func rejectedAction(for rejected: RejectedPlugin) -> RejectedPluginAction { + rejectedAction(for: rejected, manifest: RegistryClient.shared.manifest) + } + + // A surface that holds its own registry client passes that client's manifest, so its captions follow it. + func rejectedAction(for rejected: RejectedPlugin, manifest: RegistryManifest?) -> RejectedPluginAction { Self.rejectedAction( - registryPlugin: registryPlugin(for: rejected), - manifestLoaded: RegistryClient.shared.manifest != nil, + registryPlugin: Self.registryPlugin(for: rejected, in: manifest), + manifestLoaded: manifest != nil, kits: Self.compatibleKits ) } diff --git a/apple/TablePro/Core/Plugins/PluginManager+Install.swift b/apple/TablePro/Core/Plugins/PluginManager+Install.swift index 0fb022b0c6..f26d7767cb 100644 --- a/apple/TablePro/Core/Plugins/PluginManager+Install.swift +++ b/apple/TablePro/Core/Plugins/PluginManager+Install.swift @@ -154,8 +154,6 @@ extension PluginManager { ) } - // MARK: - Local bundle / zip install - // A file never puts back an older build than the one installed or staged. It drops the registry sidecar only at // or above the app's build, which the update pass never targets; below it the pass keeps the plugin current. nonisolated static func refuseOlderFile(build: Int, installedBuild: Int?) throws { @@ -183,8 +181,24 @@ extension PluginManager { .max() } + // Staging and replacing move the bundle they are given, so a file from elsewhere is copied first and stays put. + // The copy is what gets verified, so the file cannot change between the check and the install. + nonisolated static func copyLooseBundle(at url: URL, into workingDir: URL) throws -> URL { + try FileManager.default.createDirectory(at: workingDir, withIntermediateDirectories: true) + let copyURL = workingDir.appendingPathComponent(url.lastPathComponent, isDirectory: true) + try FileManager.default.copyItem(at: url, to: copyURL) + return copyURL + } + private func installLooseBundle(from url: URL) async throws -> PluginEntry { - guard let sourceBundle = Bundle(url: url) else { + let destURL = userPluginsDir.appendingPathComponent(url.lastPathComponent) + let isInPlace = url.standardizedFileURL == destURL.standardizedFileURL + let workingDir = PluginInstaller.stagingRoot(for: userPluginsDir) + .appendingPathComponent(UUID().uuidString, isDirectory: true) + defer { try? FileManager.default.removeItem(at: workingDir) } + let bundleURL = try isInPlace ? url : Self.copyLooseBundle(at: url, into: workingDir) + + guard let sourceBundle = Bundle(url: bundleURL) else { throw PluginError.invalidBundle("Cannot create bundle from \(url.lastPathComponent)") } try PluginCodeSignatureVerifier.verify(bundle: sourceBundle) @@ -195,22 +209,16 @@ extension PluginManager { if let existing = plugins.first(where: { $0.id == bundleId }) { guard url.standardizedFileURL != existing.url.standardizedFileURL else { return existing } - try Self.refuseOlderFile(build: Self.bundleBuild(at: url), installedBuild: installedBuild(of: existing)) - PluginInstaller.stripQuarantine(at: url) - return try stageForNextLaunch(bundleAt: url, replacing: existing) + try Self.refuseOlderFile(build: Self.bundleBuild(at: bundleURL), installedBuild: installedBuild(of: existing)) + PluginInstaller.stripQuarantine(at: bundleURL) + return try stageForNextLaunch(bundleAt: bundleURL, replacing: existing) } - let fileBuild = Self.bundleBuild(at: url) + let fileBuild = Self.bundleBuild(at: bundleURL) let rejected = rejectedBuild(of: bundleId) try Self.refuseOlderFile(build: fileBuild, installedBuild: rejected) try FileManager.default.createDirectory(at: userPluginsDir, withIntermediateDirectories: true) - let destURL = userPluginsDir.appendingPathComponent(url.lastPathComponent) - let loadURL: URL - if url.standardizedFileURL != destURL.standardizedFileURL { - loadURL = try PluginInstaller.atomicReplace(stagedBundleURL: url, destURL: destURL) - } else { - loadURL = destURL - } + let loadURL = try isInPlace ? destURL : PluginInstaller.atomicReplace(stagedBundleURL: bundleURL, destURL: destURL) PluginInstaller.stripQuarantine(at: loadURL) if rejected == nil || fileBuild >= Bundle.main.buildNumber { removeRegistryMetadata(for: loadURL) diff --git a/apple/TablePro/Core/Plugins/PluginManager+Lifecycle.swift b/apple/TablePro/Core/Plugins/PluginManager+Lifecycle.swift index b5067794fa..81c2e97c3b 100644 --- a/apple/TablePro/Core/Plugins/PluginManager+Lifecycle.swift +++ b/apple/TablePro/Core/Plugins/PluginManager+Lifecycle.swift @@ -5,28 +5,29 @@ import SwiftUI import TableProPluginKit extension PluginManager { - func uninstallPlugin(id: String) async throws { - guard let index = plugins.firstIndex(where: { $0.id == id }) else { + // The bundle goes first, so a refused removal leaves the plugin listed and working. + func uninstallPlugin( + id: String, + removeBundle: (URL) throws -> Void = { try FileManager.default.removeItem(at: $0) } + ) async throws { + guard let entry = plugins.first(where: { $0.id == id }) else { throw PluginError.notFound } - let entry = plugins[index] - guard entry.source == .userInstalled else { throw PluginError.cannotUninstallBuiltIn } + if FileManager.default.fileExists(atPath: entry.url.path) { + try removeBundle(entry.url) + } + unregisterCapabilities(pluginId: id) entry.bundle.unload() - plugins.remove(at: index) + plugins.removeAll { $0.id == id } + rebuildLazyRegistrations() removeRegistryMetadata(for: entry.url) - - let fm = FileManager.default - if fm.fileExists(atPath: entry.url.path) { - try fm.removeItem(at: entry.url) - } - PluginSettingsStorage(pluginId: id).removeAll() removeStagedUpdate(pluginId: id) @@ -46,7 +47,8 @@ extension PluginManager { return folder == userPluginsDir.standardizedFileURL.resolvingSymlinksInPath().path } - // To the Trash rather than deleted, so a mistaken removal can be put back. + // To the Trash rather than deleted, so a mistaken removal can be put back. A lazily registered copy of the + // same bundle goes with it, or the plugin would stay listed after its file is gone. func removeRejectedPlugin( _ plugin: RejectedPlugin, moveToTrash: (URL) throws -> Void = { try FileManager.default.trashItem(at: $0, resultingItemURL: nil) } @@ -58,6 +60,10 @@ extension PluginManager { } catch CocoaError.fileNoSuchFile {} } removeFromRejected(url: plugin.url) + if plugins.contains(where: { $0.url == plugin.url }) { + plugins.removeAll { $0.url == plugin.url } + rebuildLazyRegistrations() + } Self.logger.info("Moved rejected plugin '\(plugin.name, privacy: .public)' to the Trash") } } diff --git a/apple/TablePro/Core/Plugins/PluginManager.swift b/apple/TablePro/Core/Plugins/PluginManager.swift index c4095f3e55..abe1c4e491 100644 --- a/apple/TablePro/Core/Plugins/PluginManager.swift +++ b/apple/TablePro/Core/Plugins/PluginManager.swift @@ -105,7 +105,7 @@ final class PluginManager: ObservableObject { private var lazyExportURLs: [String: URL] = [:] private var lazyImportURLs: [String: URL] = [:] private var activatedBundleIds: Set = [] - /// Bundles a connect already took through the load gate and loaded off the main actor. + // Bundles already taken through the load gate off the main actor, so activation skips a second check. private var gatedBundleURLs: Set = [] internal var registryUpdateTask: Task? @@ -151,8 +151,6 @@ final class PluginManager: ObservableObject { .appendingPathComponent("TablePro/Plugins", isDirectory: true) } - // MARK: - Registry Metadata - struct RegistryMetadata: Codable { let pluginId: String } @@ -190,8 +188,6 @@ final class PluginManager: ObservableObject { } } - // MARK: - Loading - func loadPlugins() { hasStartedInitialLoad = true Self.applyStagedUpdates(in: userPluginsDir) @@ -259,8 +255,6 @@ final class PluginManager: ObservableObject { } } - // MARK: - Lazy Plugin Activation - private func registerLazyManifest(at url: URL, source: PluginSource, manifest: PluginManifest) { guard let bundle = Bundle(url: url) else { return } let bundleId = manifest.bundleId @@ -278,6 +272,8 @@ final class PluginManager: ObservableObject { let info = bundle.infoDictionary ?? [:] let version = (info["CFBundleShortVersionString"] as? String) ?? "0.0.0" let displayName = registrySnapshot?.displayName + ?? Self.declaredDisplayName(in: info) + ?? Self.formatDisplayName(manifest: manifest) ?? bundleId.split(separator: ".").last.map(String.init) ?? bundleId let pluginIconName = Self.iconName(forPrimaryTypeId: primaryTypeId) @@ -319,8 +315,28 @@ final class PluginManager: ObservableObject { typeId.flatMap { PluginMetadataRegistry.shared.snapshot(forRegisteredTypeId: $0)?.iconName } ?? "puzzlepiece" } - /// Takes back everything `registerLazyManifest` published for this bundle, so a plugin the app - /// would refuse to activate stops being offered as an installed one. + // check-plugin-provides.py stamps pluginName here, so a plugin is named before its code loads. + nonisolated static func declaredDisplayName(in info: [String: Any]) -> String? { + guard let name = info["CFBundleDisplayName"] as? String else { return nil } + let trimmed = name.trimmingCharacters(in: .whitespacesAndNewlines) + return trimmed.isEmpty ? nil : trimmed + } + + nonisolated static func formatDisplayName(manifest: PluginManifest) -> String? { + if let formatId = manifest.providedExportFormatIds.first { + return String(format: String(localized: "%@ Export"), formatId.uppercased()) + } + if let formatId = manifest.providedImportFormatIds.first { + return String(format: String(localized: "%@ Import"), formatId.uppercased()) + } + return nil + } + + nonisolated static func rejectedDisplayName(at url: URL) -> String { + declaredDisplayName(in: infoPlist(at: url)) ?? url.deletingPathExtension().lastPathComponent + } + + // A plugin the app would refuse to activate stops being offered as an installed one. internal func withdrawPlugin(at url: URL, reason: Error) { let manifest = Bundle(url: url).flatMap { PluginManifest(bundle: $0) } @@ -328,7 +344,7 @@ final class PluginManager: ObservableObject { rebuildLazyRegistrations() guard !rejectedPlugins.contains(where: { $0.url == url }) else { return } - let name = manifest?.bundleId ?? url.deletingPathExtension().lastPathComponent + let name = Self.declaredDisplayName(in: Self.infoPlist(at: url)) ?? manifest?.bundleId ?? url.deletingPathExtension().lastPathComponent let registryId = Self.readRegistryMetadata(for: url)?.pluginId rejectedPlugins.append(RejectedPlugin( url: url, @@ -341,12 +357,9 @@ final class PluginManager: ObservableObject { )) } - /// Rebuilt from the surviving manifests rather than filtered by URL. - /// - /// Two bundles may declare the same driver or format key, and the one registered - /// last owns it. Deleting the withdrawn bundle's keys would take the shared key with it and - /// leave the valid plugin listed but unreachable for the rest of the process. - private func rebuildLazyRegistrations() { + // Rebuilt rather than filtered by URL: two bundles may declare one key, and dropping the removed one's + // keys would leave the other listed but unreachable for the rest of the process. + internal func rebuildLazyRegistrations() { lazyDriverURLs = [:] gatedBundleURLs = [] lazyExportURLs = [:] @@ -394,17 +407,36 @@ final class PluginManager: ObservableObject { Array(lazyImportURLs.keys) } - // The signature check and dlopen of a driver plugin hold the thread for hundreds of milliseconds the - // first time a launch reads its file, so a connect does both here and leaves only registration to main. + // The signature check and dlopen of a plugin hold the thread for hundreds of milliseconds the first time + // a launch reads its file, so a connect or a Settings page does both here and leaves only registration to main. func loadLazyDriverExecutable(typeId: String) async { guard driverPlugins[typeId] == nil, let url = lazyDriverURLs[typeId], !gatedBundleURLs.contains(url) else { return } + guard await loadLazyBundleExecutable(at: url) else { return } + gatedBundleURLs.insert(url) + } + + // Only a driver load records the gate (plugin_gated_bundle_insert), so activation checks a format again, + // but the dlopen has already happened here. + func loadLazyExportExecutable(formatId: String) async { + guard exportPlugins[formatId] == nil, let url = lazyExportURLs[formatId] else { return } + await loadLazyBundleExecutable(at: url) + } + + func loadLazyImportExecutable(formatId: String) async { + guard importPlugins[formatId] == nil, let url = lazyImportURLs[formatId] else { return } + await loadLazyBundleExecutable(at: url) + } + + @discardableResult + private func loadLazyBundleExecutable(at url: URL) async -> Bool { let source = plugins.first(where: { $0.url == url })?.source ?? .userInstalled do { _ = try await Self.validateAndLoadBundleAsync(at: url, source: source) - gatedBundleURLs.insert(url) + return true } catch { // Activation runs the gate again on the main actor and records the rejection there. - Self.logger.error("Loading driver plugin '\(url.lastPathComponent)' ahead of activation failed: \(error.localizedDescription)") + Self.logger.error("Loading plugin '\(url.lastPathComponent)' ahead of activation failed: \(error.localizedDescription)") + return false } } @@ -569,7 +601,7 @@ final class PluginManager: ObservableObject { url: failure.url, bundleId: bundle?.bundleIdentifier, registryId: registryId, - name: failure.url.deletingPathExtension().lastPathComponent, + name: Self.rejectedDisplayName(at: failure.url), reason: failure.reason, isOutdated: false, providedDatabaseTypeIds: Self.databaseTypeIds(of: bundle, registryId: registryId) @@ -670,7 +702,7 @@ final class PluginManager: ObservableObject { url: winner.url, bundleId: bundle?.bundleIdentifier, registryId: registryId, - name: winner.url.deletingPathExtension().lastPathComponent, + name: Self.rejectedDisplayName(at: winner.url), reason: error.localizedDescription, isOutdated: (error as? PluginError)?.isOutdated ?? false, providedDatabaseTypeIds: Self.databaseTypeIds(of: bundle, registryId: registryId) diff --git a/apple/TablePro/Core/Services/Infrastructure/ConnectionRecoveryPerformer.swift b/apple/TablePro/Core/Services/Infrastructure/ConnectionRecoveryPerformer.swift index 11be701b3c..6a4eaffc30 100644 --- a/apple/TablePro/Core/Services/Infrastructure/ConnectionRecoveryPerformer.swift +++ b/apple/TablePro/Core/Services/Infrastructure/ConnectionRecoveryPerformer.swift @@ -1,8 +1,3 @@ -// -// ConnectionRecoveryPerformer.swift -// TablePro -// - import AppKit internal struct PendingConnectionRecovery { @@ -23,16 +18,16 @@ internal enum ConnectionRecoveryPerformer { internal static func perform( _ action: ConnectionRecoveryAction, - for connection: DatabaseConnection + for connection: DatabaseConnection, + opener: WindowOpener = .shared ) { switch action { case .installPlugin: WelcomeRouter.shared.routePluginInstall(connection) case .openPluginSettings(let pluginId): - PluginsSettingsNavigation.shared.reveal(pluginId: pluginId) - WindowOpener.shared.openSettings(tab: .plugins) + opener.openSettings(revealingPlugin: pluginId) case .editConnection: - WindowOpener.shared.openConnectionForm(editing: connection.id) + opener.openConnectionForm(editing: connection.id) case .openLocalNetworkSettings: guard let url = localNetworkSettingsURL else { return } NSWorkspace.shared.open(url) diff --git a/apple/TablePro/Core/Services/Infrastructure/DeeplinkParser.swift b/apple/TablePro/Core/Services/Infrastructure/DeeplinkParser.swift index 9b8723395b..61612e68e7 100644 --- a/apple/TablePro/Core/Services/Infrastructure/DeeplinkParser.swift +++ b/apple/TablePro/Core/Services/Infrastructure/DeeplinkParser.swift @@ -1,8 +1,3 @@ -// -// DeeplinkParser.swift -// TablePro -// - import Foundation import os import TableProImport @@ -83,17 +78,15 @@ internal enum DeeplinkParser { return .success(.openSharedLink(token: token)) } - /// Never fails: an unknown id or extra segments open the last-used pane, so a link to a pane - /// or section added later still opens Settings on an older app. + // Never fails, so a link to a pane or page added later still opens Settings on an older app. + // It only navigates: opening a page performs nothing and grants nothing. private static func parseSettings(_ url: URL) -> Result { - guard let identifier = pathSegments(url).first else { - return .success(.openSettings(nil)) - } - guard let pane = SettingsPane(urlIdentifier: identifier) else { + let segments = pathSegments(url) + let location = SettingsLocation(urlPathSegments: segments) + if location == nil, let identifier = segments.first { logger.notice("Unknown settings pane id \(identifier, privacy: .public), opening the last-used pane") - return .success(.openSettings(nil)) } - return .success(.openSettings(pane)) + return .success(.openSettings(location)) } private static func parseConnect(_ url: URL) -> Result { @@ -256,11 +249,7 @@ internal enum DeeplinkParser { responseMode = .legacy } - /// Only an absent parameter means every connection. Naming the parameter and then handing - /// over something unreadable used to fall back to absent, which turned a request scoped to - /// one connection into a request for all of them with the sheet pre-ticked to All - /// Connections. So presence is the test, not a non-empty value, and an empty field is kept - /// rather than dropped so it has to answer the same guard. (#2930) + // Only an absent parameter means every connection; an empty or unreadable one must not widen to all (#2930). let connectionIds: Set? if queryItems.contains(where: { $0.name == "connection-ids" }) { let csv = value("connection-ids") ?? "" diff --git a/apple/TablePro/Core/Services/Infrastructure/LaunchIntent.swift b/apple/TablePro/Core/Services/Infrastructure/LaunchIntent.swift index 37ba828a0c..0ef70be726 100644 --- a/apple/TablePro/Core/Services/Infrastructure/LaunchIntent.swift +++ b/apple/TablePro/Core/Services/Infrastructure/LaunchIntent.swift @@ -1,8 +1,3 @@ -// -// LaunchIntent.swift -// TablePro -// - import Foundation import TableProImport @@ -26,8 +21,8 @@ internal enum LaunchIntent: @unchecked Sendable { case openSharedLink(token: String) case pairIntegration(PairingRequest) case startMCPServer - /// nil opens the last-used pane. - case openSettings(SettingsPane?) + // nil opens the last-used pane. + case openSettings(SettingsLocation?) case openDatabaseURL(URL) case installPlugin(URL) case reopenClosedTab(RecentlyClosedTabEntry) diff --git a/apple/TablePro/Core/Services/Infrastructure/LaunchIntentRouter.swift b/apple/TablePro/Core/Services/Infrastructure/LaunchIntentRouter.swift index 0e7f89087a..595b43d497 100644 --- a/apple/TablePro/Core/Services/Infrastructure/LaunchIntentRouter.swift +++ b/apple/TablePro/Core/Services/Infrastructure/LaunchIntentRouter.swift @@ -42,8 +42,8 @@ internal final class LaunchIntentRouter { case .startMCPServer: await startMCPServer() - case .openSettings(let pane): - WindowOpener.shared.openSettings(tab: pane) + case .openSettings(let location): + WindowOpener.shared.openSettings(location) case .installPlugin(let url): try await installPlugin(url) @@ -106,7 +106,7 @@ internal final class LaunchIntentRouter { private func installPlugin(_ url: URL) async throws { let entry = try await PluginManager.shared.installPlugin(from: url) Self.logger.info("Installed plugin '\(entry.name, privacy: .public)' from Finder") - WindowOpener.shared.openSettings(tab: .plugins) + WindowOpener.shared.openSettings(revealingPlugin: entry.id) } private func presentRecoverableError(_ error: Error, for intent: LaunchIntent, title: String) -> Bool { diff --git a/apple/TablePro/Core/Services/Infrastructure/WindowOpener.swift b/apple/TablePro/Core/Services/Infrastructure/WindowOpener.swift index 366c740e00..2ebc42a0da 100644 --- a/apple/TablePro/Core/Services/Infrastructure/WindowOpener.swift +++ b/apple/TablePro/Core/Services/Infrastructure/WindowOpener.swift @@ -1,12 +1,14 @@ -// -// WindowOpener.swift -// TablePro -// - import AppKit import Combine import os +internal enum SettingsRequest: Equatable, Sendable { + // nil opens the last-used pane. + case open(SettingsLocation?) + // A nil id asks for the first plugin that needs an update. + case revealPlugin(String?) +} + @MainActor internal final class WindowOpener: ObservableObject { internal static let shared = WindowOpener() @@ -16,12 +18,11 @@ internal final class WindowOpener: ObservableObject { private var openWelcomeAction: (() -> Void)? private var openConnectionFormAction: ((ConnectionFormRequest) -> Void)? private var openIntegrationsActivityAction: (() -> Void)? - private var openSettingsAction: ((SettingsPane?) -> Void)? + private var openSettingsAction: ((SettingsRequest) -> Void)? private var stagedDraftId: UUID? private var pendingCalls: [() -> Void] = [] - /// Not private so a test can exercise the queue on an instance with no presenters - /// registered. Production code uses `shared`. + // Not private so a test can exercise the queue on an instance with no presenters registered. internal init() {} internal func openWelcome() { @@ -33,10 +34,22 @@ internal final class WindowOpener: ObservableObject { } } - internal func openSettings(tab: SettingsPane? = nil) { + internal func openSettings(_ location: SettingsLocation? = nil) { + requestSettings(.open(location)) + } + + internal func openSettings(tab pane: SettingsPane?) { + openSettings(pane.map { SettingsLocation.root($0) }) + } + + internal func openSettings(revealingPlugin pluginId: String?) { + requestSettings(.revealPlugin(pluginId)) + } + + private func requestSettings(_ request: SettingsRequest) { perform { opener in guard let present = opener.openSettingsAction else { return false } - present(tab) + present(request) return true } } @@ -115,14 +128,12 @@ internal final class WindowOpener: ObservableObject { drainPendingCalls() } - internal func setSettingsPresenter(_ present: @escaping (SettingsPane?) -> Void) { + internal func setSettingsPresenter(_ present: @escaping (SettingsRequest) -> Void) { openSettingsAction = 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. + // A block returns false while its window has no presenter yet, which queues the call. private func perform(_ block: @escaping (WindowOpener) -> Bool) { AppActivationPolicyController.shared.enterForeground() guard !block(self) else { return } diff --git a/apple/TablePro/Core/Services/Infrastructure/WorkspaceRailViewController.swift b/apple/TablePro/Core/Services/Infrastructure/WorkspaceRailViewController.swift index d9fc7ad0cd..b952021515 100644 --- a/apple/TablePro/Core/Services/Infrastructure/WorkspaceRailViewController.swift +++ b/apple/TablePro/Core/Services/Infrastructure/WorkspaceRailViewController.swift @@ -1,8 +1,3 @@ -// -// WorkspaceRailViewController.swift -// TablePro -// - import AppKit import Combine import Observation @@ -10,11 +5,7 @@ import os import OSLog import TableProConnectionLibrary -/// The window a rail belongs to. A window hosts several connections and shows one at a time, so -/// which row the rail highlights is a question only the window can answer, and the answer changes. -/// The rail used to capture the connection its window was created for, which could name the right -/// row exactly once: after the window switched to a second connection the rail kept highlighting -/// the first, and clicking the row it was already standing on did nothing. +// Only the window knows which of its connections is on screen, so the rail asks rather than capturing one. @MainActor internal protocol WorkspaceRailHost: AnyObject { var hostedConnectionIds: [UUID] { get } @@ -22,20 +13,12 @@ internal protocol WorkspaceRailHost: AnyObject { func selectHostedConnection(_ connectionId: UUID) } -/// Middle-click closes the row under the pointer, which is what a list of open things does -/// everywhere it exists: browser tabs, and every database client surveyed. `NSTableView` routes no -/// action for the tertiary button, so the row is resolved from the click point the same way -/// `menu(for:)` resolves one. -/// -/// The table owns its own look, so a test hosting it gets the configuration the strip really ships -/// with: a source list rewrites cells and pads rows in ways a free-standing cell never shows. +// AppKit table on purpose: `NSTableView` routes no middle-click, and a source list pads rows a free cell never shows. @MainActor internal final class WorkspaceRailTableView: NSTableView { internal var onMiddleClick: ((Int) -> Void)? - /// Set by the window's rule the moment the strip is told to hide. AppKit hides a collapsing split - /// item only once its animation ends, and until then the list kept its full frame, so a window - /// first shown during that animation picked it as its first key view. + // Set the moment the strip hides: AppKit hides a collapsing item only after its animation, so the list could take first key view. internal var isStripShown = true override internal var canBecomeKeyView: Bool { @@ -53,8 +36,7 @@ internal final class WorkspaceRailTableView: NSTableView { backgroundColor = .clear allowsMultipleSelection = false allowsEmptySelection = true - /// A source list draws the selection over the spacing too, so spacing would only pad the - /// inside of the fill. The tile's own padding is what separates one entry from the next. + // A source list draws the selection over the spacing, so the tile's own padding separates entries. intercellSpacing = NSSize(width: 0, height: 0) } @@ -63,9 +45,7 @@ internal final class WorkspaceRailTableView: NSTableView { fatalError("WorkspaceRailTableView does not support NSCoder init") } - /// Read from the rows themselves, because where they start is the source list's to decide: it - /// pads the first one down from the document's top, and a model that assumed otherwise is what - /// left a slice of the previous tile showing. + // Read from the rows: the source list pads the first one down from the document's top. internal func scrollGeometry(viewportHeight: CGFloat) -> WorkspaceRailScrollGeometry { let first = numberOfRows > 0 ? rect(ofRow: 0) : .zero return WorkspaceRailScrollGeometry( @@ -113,10 +93,7 @@ internal final class WorkspaceRailViewController: NSViewController { private let scrollView = NSScrollView() private let tableView = WorkspaceRailTableView() - /// `rowSizeStyle` is the only route to the sidebar icon size preference, but any value - /// other than `.custom` makes the table impose the system row height and ignore - /// `heightOfRow`, which the rail's stacked cell needs. This unattached table lets AppKit - /// resolve the preference so the rail itself can stay `.custom`. + // Resolves the sidebar icon size; anything but `.custom` on the rail itself would ignore `heightOfRow`. private let rowSizeProbe = NSTableView() private var entries: [WorkspaceRailEntry] = [] @@ -131,22 +108,15 @@ internal final class WorkspaceRailViewController: NSViewController { private let scrollObserver = OSAllocatedUnfairLock<(any NSObjectProtocol)?>(uncheckedState: nil) private var contentTopConstraint: NSLayoutConstraint? - /// A scroll is settled once it has stopped changing, which is the only signal every input - /// device gives. `NSScrollViewWillStartLiveScroll`/`DidEndLiveScroll` would be the obvious pair, - /// and `NSScrollView.h` says outright that a legacy mouse is not bracketed by them, which is the - /// device most likely to leave the strip resting mid-tile. + // Settled once the scroll stops changing: a legacy mouse never posts the live-scroll pair. private var scrollSettle: DispatchWorkItem? - /// A reorder scrolls the strip itself as the pointer nears an edge, so settling during one would - /// fight the drag it is reacting to. + // A reorder autoscrolls the strip, so settling during one would fight the drag. private var isReordering = false private var needsSelectionReveal = false - /// What the rail last put on screen as selected, which after every `applySelection` is the - /// workspace the host is really showing. A commit for that same workspace has nothing to do, - /// and is the case the arrow keys hit constantly as they move the highlight across a row the - /// window is already on. + // A commit for the workspace already applied has nothing to do, which is what the arrow keys hit constantly. private var appliedSelection: WorkspaceID? internal init() { @@ -187,10 +157,7 @@ internal final class WorkspaceRailViewController: NSViewController { scrollView.autohidesScrollers = true scrollView.hasHorizontalScroller = false scrollView.drawsBackground = false - /// The bottom inset is the rail's own, and `contentInsets` and the automatic flag are one - /// property: writing the inset clears the flag anyway, so it is cleared here where it can be - /// read. Nothing is given up, because the automatic inset reads the scroll view's own safe - /// area, which `pinContentBelowTitleBar` has already reduced to nothing. + // Writing `contentInsets` clears the automatic flag anyway, and the safe area here is already zero. scrollView.automaticallyAdjustsContentInsets = false scrollView.contentView.postsBoundsChangedNotifications = true scrollView.translatesAutoresizingMaskIntoConstraints = false @@ -204,10 +171,7 @@ internal final class WorkspaceRailViewController: NSViewController { pinContentBelowTitleBar() } - /// The rail is a full-height sidebar, so AppKit gives it a top safe-area inset that - /// clears the window buttons and does not move when the native tab bar appears. - /// Anchoring to `NSWindow.contentLayoutGuide` instead tracked the tab bar and made the - /// rail jump between workspaces with different tab counts. + // The safe-area inset clears the window buttons and stays put when the native tab bar appears; the content layout guide did not. private func pinContentBelowTitleBar() { contentTopConstraint?.isActive = false let constraint = scrollView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor) @@ -227,9 +191,7 @@ internal final class WorkspaceRailViewController: NSViewController { .sink { [weak self] _ in self?.reload() } - /// Changing the Appearance setting means leaving TablePro and coming back, and AppKit - /// publishes that. `effectiveRowSizeStyle` is then re-read, which is the documented way to - /// ask what the system resolved. The undocumented defaults key this used to observe is gone. + // An Appearance change happens outside the app, so the system row size is re-read on return. let observer = NotificationCenter.default.addObserver( forName: NSApplication.didBecomeActiveNotification, object: nil, queue: .main ) { [weak self] _ in @@ -252,9 +214,7 @@ internal final class WorkspaceRailViewController: NSViewController { scrollObserver.withLockUnchecked { $0 = observer } } - /// Re-armed on every bounds change, so the strip settles once the scrolling stops rather than - /// once per frame of it. Settling itself changes the bounds, which comes back through here and - /// finds nothing left to do. + // Re-armed on every bounds change, so the strip settles once scrolling stops, not once per frame. private func scheduleScrollSettle() { scrollSettle?.cancel() let work = DispatchWorkItem { [weak self] in @@ -283,8 +243,7 @@ internal final class WorkspaceRailViewController: NSViewController { } } - /// Recomputed rather than set once, because the row count, the row height and the viewport all - /// move: an entry opens or closes, the sidebar icon size changes, the window resizes. + // Recomputed: the row count, the row height and the viewport all move. private var scrollGeometry: WorkspaceRailScrollGeometry { tableView.scrollGeometry(viewportHeight: scrollView.contentView.bounds.height) } @@ -295,12 +254,7 @@ internal final class WorkspaceRailViewController: NSViewController { scrollView.contentInsets = NSEdgeInsets(top: 0, left: 0, bottom: inset, right: 0) } - /// Asked for when the highlight moves, and held until the strip has a viewport to move inside. - /// - /// The rail is laid out after `viewDidLoad` has already applied the first selection, so the - /// clip view can still be zero high when the entry to show is below the fold. Nothing arrives - /// later to say so: `NSView.boundsDidChangeNotification` is not posted for a bounds change that - /// came from the frame resizing, and `NSTableView` does not reveal a selection it already holds. + // Held until the clip view has a height: no bounds notification follows a frame resize, and `NSTableView` never reveals a selection it already holds. private func requestSelectionReveal() { needsSelectionReveal = true revealSelectedRowIfNeeded() @@ -312,9 +266,7 @@ internal final class WorkspaceRailViewController: NSViewController { revealSelectedRow() } - /// Silent while the entry is already whole and on screen. Every rail lists every workspace, so - /// one window's change reloads all of them; the callers are the paths where the highlight - /// actually moved, so a strip whose own entry did not change stays where its window left it. + // Silent while the entry is whole on screen: every rail reloads on any window's change. private func revealSelectedRow() { let clipView = scrollView.contentView guard let origin = scrollGeometry.revealOrigin( @@ -340,8 +292,7 @@ internal final class WorkspaceRailViewController: NSViewController { } } - /// Reported from here rather than from the split view's resize callback, which runs before the - /// strip inside the item has taken its new width. + // Not the split view's resize callback, which runs before the strip has its new width. override func viewDidLayout() { super.viewDidLayout() tableView.sizeLastColumnToFit() @@ -352,8 +303,6 @@ internal final class WorkspaceRailViewController: NSViewController { onWidthChange?() } - // MARK: - Data - private func reload() { entries = WorkspaceRailStore.entries Self.logger.debug( @@ -386,19 +335,15 @@ internal final class WorkspaceRailViewController: NSViewController { "\(workspace.connectionId.uuidString.prefix(8)):\(workspace.container.isEmpty ? "-" : workspace.container)" } - /// Which window's rail a line came from. Every rail lists every workspace, so without this - /// a log of two connections switching back and forth cannot be attributed. + // Every rail lists every workspace, so a log line names which window's rail wrote it. private var railName: String { guard let connectionId = host?.selectedConnectionId else { return "none" } return String(connectionId.uuidString.prefix(8)) } - /// Re-arms itself, because `withObservationTracking` fires once per registration. private func observeRowSizePreference() { - /// `objectWillChange` covers every settings group, so the row size is compared here - /// to keep the rebuild as rare as the per-property tracking made it. var lastRowSize = AppSettingsManager.shared.general.sidebarRowSize - rowSizeObservation = AppSettingsManager.shared.onMainActorChange { [weak self] in + rowSizeObservation = AppSettingsManager.shared.generalSlice.onMainActorChange { [weak self] in let current = AppSettingsManager.shared.general.sidebarRowSize guard current != lastRowSize else { return } lastRowSize = current @@ -406,8 +351,7 @@ internal final class WorkspaceRailViewController: NSViewController { } } - /// The rail sits directly beside the object list, so it takes the same size. Following only the - /// system preference left the two disagreeing the moment the user set a size of their own. + // Same size as the object list beside it, including a size the user set. private var resolvedRowSizeStyle: NSTableView.RowSizeStyle { let preference = AppSettingsManager.shared.general.sidebarRowSize guard preference == .matchSystem else { @@ -424,19 +368,13 @@ internal final class WorkspaceRailViewController: NSViewController { tableView.reloadData() applyBottomInset() applySelection() - /// Every tile edge moved, and a scroll offset that moves nothing posts no bounds change, so - /// neither the settle nor the reveal would run on its own: the strip stayed mid-tile. + // A scroll offset that moves nothing posts no bounds change, so neither the settle nor the reveal would run on its own. requestSelectionReveal() scheduleScrollSettle() onLayoutChange?(resolved) } - /// Both halves move: the window switches which connection it shows, and that connection's tabs - /// switch which entry is in front. Neither can be captured at init. - /// - /// The entry this window shows, not the one the connection browses: a window a tab was torn off - /// into shares its connection's cursor with the window it came from, and highlighting the cursor - /// named an entry whose tabs that window was not showing. + // The entry this window shows, not the connection's browse cursor, which a torn-off window shares. private var activeWorkspace: WorkspaceID? { guard let connectionId = host?.selectedConnectionId else { return nil } if let shown = WindowManager.shared.coordinator(for: connectionId, in: view.window)? @@ -446,8 +384,7 @@ internal final class WorkspaceRailViewController: NSViewController { return WorkspaceRailStore.browsedWorkspace(for: connectionId) } - /// Called when the window changes which connection it is showing. The entry list is unchanged - /// by that, only which row is current, so this moves the highlight instead of reloading. + // The entry list is unchanged by a connection switch, so only the highlight moves. internal func refreshSelection() { applySelection() } @@ -483,32 +420,20 @@ internal final class WorkspaceRailViewController: NSViewController { requestSelectionReveal() } - // MARK: - Activation - @objc private func handleRowClick() { commit(row: tableView.clickedRow) } - /// Return opens the highlighted row, the same contract every AppKit list keeps. override func insertNewline(_ sender: Any?) { commit(row: tableView.selectedRow) } - /// Close means the entry highlighted here while the strip holds the keyboard, and the - /// connection when that entry is the only one it has. - /// - /// The selector is the window's, deliberately: `performClose:` reaching the responder chain - /// finds this implementation before the window's whenever the strip is focused, which is the - /// same mechanism that gives Cut and Copy a different meaning in each view. The window used to - /// ask whether the strip had focus and branch on the answer, which is this rule written out by - /// hand. + // Found before the window's `performClose:` whenever the strip is focused; closes the connection when the entry is its only one. @objc internal func performClose(_ sender: Any?) { guard let workspace = appliedSelection else { - /// Nothing highlighted means the strip has no entry to close, not that Close does - /// nothing: swallowing it here would leave the command dead in a window that has tabs, - /// which is the failure this whole route exists to prevent. + // Swallowing Close here would leave the command dead in a window that has tabs. view.window?.performClose(sender) return } @@ -518,8 +443,7 @@ internal final class WorkspaceRailViewController: NSViewController { private func commit(row: Int) { guard entries.indices.contains(row) else { return } let workspace = entries[row].workspace - /// The highlighted entry is clicked again to retry a switch that failed: its tabs are on - /// screen, but the object browser stayed where it was. + // Clicking the highlighted entry again retries a switch whose object browser stayed behind. guard workspace != appliedSelection || WorkspaceRailStore.browsedWorkspace(for: workspace.connectionId) != workspace else { @@ -581,19 +505,13 @@ internal final class WorkspaceRailViewController: NSViewController { return (window, host) } - /// Going to an entry of a connection: its tabs come forward, and the object tree follows to its - /// container once the switch lands. `BrowseCursorCoordinator.goToEntry` holds both halves, so the order cannot be got - /// wrong here. + // `BrowseCursorCoordinator.goToEntry` brings the tabs forward and moves the tree, in that order. private func moveBrowseCursor(of window: NSWindow, to workspace: WorkspaceID) { guard !workspace.container.isEmpty else { Self.logger.debug("moveBrowseCursor skipped: unnamed container") return } - /// Resolved by connection through the window that hosts it, never by window alone. - /// `coordinator(forWindow:)` answers with the window's selected workspace, so a row for any - /// other connection moved the browse cursor of the one on screen instead: it switched the - /// visible connection to a database named after a different one, or failed against a - /// database that connection does not have. + // By connection, never by window alone, which answers with the window's selected workspace. guard let coordinator = WindowManager.shared.coordinator(for: workspace.connectionId, in: window) else { Self.logger.error( """ @@ -607,8 +525,7 @@ internal final class WorkspaceRailViewController: NSViewController { coordinator.browseCursorCoordinator.goToEntry(workspace.container) } - /// The menu command is a commit, not a highlight: it names the workspace it goes to, so it - /// has to get there without a second keystroke. + // A commit, not a highlight: the command names where it goes. internal func activateWorkspace(offsetBy offset: Int) { guard let next = WorkspaceRailOrdering.cycled( in: entries.map(\.id), @@ -621,8 +538,6 @@ internal final class WorkspaceRailViewController: NSViewController { commit(row: row) } - // MARK: - Context Menu - private func contextMenu() -> NSMenu { let menu = NSMenu() menu.delegate = self @@ -683,12 +598,7 @@ internal final class WorkspaceRailViewController: NSViewController { close(workspace) } - /// Named for the rail rather than for the command, because `closeConnection(_:)` is the File - /// menu's own nil-target action on `MainSplitViewController`. `@objc` puts this in the - /// responder chain whatever its access level, and the rail sits ahead of the controller there, - /// so sharing the name meant the menu bar's Close Connection resolved here instead, found a - /// sender carrying no `representedObject`, and returned having done nothing at all. The rail's - /// own items set `target` explicitly, so nothing here depends on the selector's spelling. + // Not `closeConnection(_:)`: that is the File menu's nil-target action, and the rail sits ahead of its owner in the responder chain. @objc private func closeWorkspaceConnection(_ sender: NSMenuItem) { guard let workspace = sender.representedObject as? WorkspaceID else { return } @@ -704,9 +614,7 @@ internal final class WorkspaceRailViewController: NSViewController { Task { await WorkspaceCloseAction.close(workspace) } } - /// Named after what the engine calls a container, not after the row. "Close “logs”" would read - /// as the connection on the one key the app already uses for exactly that, and its translations - /// say so: the Turkish for `Close “%@”` is "close %@'s connection". + // Named after the container: "Close %@" reads as closing the connection in some languages. internal static func containerCloseTitle(for entry: WorkspaceRailEntry) -> String { let format = entry.containerTarget == .schema ? String(localized: "Close Schema “%@”") @@ -714,7 +622,6 @@ internal final class WorkspaceRailViewController: NSViewController { return String(format: format, entry.container) } - /// Read from the entries this rail is showing, which is the list the user is looking at. private func closeScope(for workspace: WorkspaceID) -> WorkspaceCloseAction.Scope { guard !workspace.container.isEmpty else { return .connection } let count = entries.count { $0.workspace.connectionId == workspace.connectionId } @@ -725,9 +632,7 @@ internal final class WorkspaceRailViewController: NSViewController { Task { await ConnectionCloseAction.close(connectionId: connectionId) } } - /// Hands the connection's database file back to the rest of the machine and keeps the session, - /// so the tabs, the schema cache and the row the user was on all stay where they are. The next - /// query takes the file again. + // Releases the database file and keeps the session, so tabs, schema cache and position stay; the next query takes it again. @objc private func releaseWorkspaceFileLock(_ sender: NSMenuItem) { guard let workspace = sender.representedObject as? WorkspaceID, @@ -756,16 +661,13 @@ internal final class WorkspaceRailViewController: NSViewController { shown.host.performConnectionAction(action, for: workspace.connectionId) } - /// Ends the session, which every workspace of the connection shares, so the other rows for it - /// go quiet too. No window closes: each one repaints from its own phase. + // Every workspace of the connection shares the session, so its other rows go quiet too; no window closes. @objc private func disconnectWorkspace(_ sender: NSMenuItem) { guard let workspace = sender.representedObject as? WorkspaceID, let entry = entries.first(where: { $0.workspace.connectionId == workspace.connectionId }) else { return } - /// The rail's own window, not the connection's most recent one: the user is looking at this - /// window, and the connection's most recent window can be behind it or miniaturized, which - /// would put the confirmation sheet somewhere they cannot see and read as a dead menu item. + // This window, not the connection's most recent one, which can be behind it or miniaturized. let presentingWindow = view.window Task { await ConnectionDisconnectAction.disconnect( @@ -777,14 +679,8 @@ internal final class WorkspaceRailViewController: NSViewController { } } -// MARK: - CloseCommandNaming - extension WorkspaceRailViewController: CloseCommandNaming { - /// The strip's own contextual menu names what it would close, and the menu bar has to agree with - /// it word for word: the command is the same one, so an entry that is its connection's only one - /// reads "Close Connection" in both, because that is what closing it takes. - /// nil while nothing is highlighted, so the resolver falls back to the window, which is where - /// the command goes in that state too. + // Matches the strip's own menu word for word; nil while nothing is highlighted, so the window's title applies. internal var closeCommandTitle: String? { guard let workspace = appliedSelection, let entry = entries.first(where: { $0.workspace == workspace }) @@ -796,8 +692,6 @@ extension WorkspaceRailViewController: CloseCommandNaming { } } -// MARK: - NSMenuDelegate - extension WorkspaceRailViewController: NSMenuDelegate { internal func menuNeedsUpdate(_ menu: NSMenu) { menu.removeAllItems() @@ -883,8 +777,6 @@ extension WorkspaceRailViewController: NSMenuDelegate { } } -// MARK: - NSTableViewDataSource - extension WorkspaceRailViewController: NSTableViewDataSource { internal func numberOfRows(in tableView: NSTableView) -> Int { entries.count @@ -948,8 +840,6 @@ extension WorkspaceRailViewController: NSTableViewDataSource { } } -// MARK: - NSTableViewDelegate - extension WorkspaceRailViewController: NSTableViewDelegate { internal func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat { rowHeight @@ -985,20 +875,11 @@ extension WorkspaceRailViewController: NSTableViewDelegate { ) } - /// Selection is the highlight, not the commit. - /// - /// `NSTableView` selects on mouse-down, before the drag threshold, so committing here meant - /// grabbing an icon to reorder first switched to it and the rest of the drag happened in a - /// window that was no longer key. Arrow keys were worse: one press onto another connection's - /// row raised that window, so the rail lost key status and the next press went somewhere else - /// entirely. Commit belongs on the table's action, which fires after tracking ends, and on - /// Return, which is how every AppKit list opens the row the user arrowed to. + // Selection is the highlight, not the commit: `NSTableView` selects on mouse-down, before a reorder drag starts. internal func tableViewSelectionDidChange(_ notification: Notification) { let row = tableView.selectedRow guard entries.indices.contains(row) else { return } - /// The arrow keys move the highlight through `NSTableView` itself, which reveals the row it - /// lands on by scrolling the least it can and so stops between entries. Landing on the - /// boundary here keeps the strip from having to slide again once the scroll settles. + // `NSTableView` scrolls the least it can and stops between entries, so the reveal lands on a boundary. requestSelectionReveal() Self.logger.debug( """ diff --git a/apple/TablePro/Core/Services/Notifications/AgentAttentionNotifier.swift b/apple/TablePro/Core/Services/Notifications/AgentAttentionNotifier.swift index 065a13b1df..c5f353e3db 100644 --- a/apple/TablePro/Core/Services/Notifications/AgentAttentionNotifier.swift +++ b/apple/TablePro/Core/Services/Notifications/AgentAttentionNotifier.swift @@ -114,6 +114,7 @@ internal final class AgentAttentionNotifier { content.subtitle = subtitle } content.body = body + content.sound = .default content.categoryIdentifier = Self.categoryId content.threadIdentifier = session.connectionId.uuidString content.userInfo = [ @@ -149,8 +150,8 @@ internal final class AgentAttentionNotifier { extension AgentAttentionNotifier: NotificationHandling { internal func presentationOptions(for notification: UNNotification) -> UNNotificationPresentationOptions { - guard let session = session(from: notification.request.content.userInfo) else { return [.banner, .list] } - return isOnScreen(session) ? [] : [.banner, .list] + guard let session = session(from: notification.request.content.userInfo) else { return [.banner, .list, .sound] } + return isOnScreen(session) ? [] : [.banner, .list, .sound] } internal func handle(_ response: UNNotificationResponse) { diff --git a/apple/TablePro/Core/Services/Notifications/NotificationPermissionMonitor.swift b/apple/TablePro/Core/Services/Notifications/NotificationPermissionMonitor.swift index 87721602aa..d4c18a7244 100644 --- a/apple/TablePro/Core/Services/Notifications/NotificationPermissionMonitor.swift +++ b/apple/TablePro/Core/Services/Notifications/NotificationPermissionMonitor.swift @@ -1,18 +1,11 @@ -// -// NotificationPermissionMonitor.swift -// TablePro -// - import AppKit import Combine import UserNotifications -// The permission changes in System Settings while TablePro is in the background, so the pane reads -// it again each time the app comes back. It never asks for permission: NotificationAuthorization -// is the one requester. +// Reads only, again on each activation since System Settings can change it meanwhile; NotificationAuthorization is the one requester. @MainActor internal final class NotificationPermissionMonitor: ObservableObject { - @Published internal private(set) var status: UNAuthorizationStatus = .notDetermined + @Published internal private(set) var status: UNAuthorizationStatus private let authorization: NotificationAuthorization private var activation: AnyCancellable? @@ -23,6 +16,7 @@ internal final class NotificationPermissionMonitor: ObservableObject { center: NotificationCenter = .default ) { self.authorization = authorization + status = authorization.status activation = center.publisher(for: NSApplication.didBecomeActiveNotification) .sink { [weak self] _ in Task { @MainActor in await self?.refresh() } diff --git a/apple/TablePro/Core/Services/Notifications/PluginNotificationService.swift b/apple/TablePro/Core/Services/Notifications/PluginNotificationService.swift index aef854ffc1..9fb08f85f1 100644 --- a/apple/TablePro/Core/Services/Notifications/PluginNotificationService.swift +++ b/apple/TablePro/Core/Services/Notifications/PluginNotificationService.swift @@ -132,6 +132,7 @@ final class PluginNotificationService { let content = UNMutableNotificationContent() content.title = title content.body = body + content.sound = .default content.categoryIdentifier = Self.updateFailedCategoryId if let pluginId { content.userInfo = [Self.pluginIdKey: pluginId] @@ -165,7 +166,7 @@ final class PluginNotificationService { extension PluginNotificationService: NotificationHandling { func presentationOptions(for notification: UNNotification) -> UNNotificationPresentationOptions { - [.banner, .list] + [.banner, .list, .sound] } func handle(_ response: UNNotificationResponse) { @@ -173,7 +174,6 @@ extension PluginNotificationService: NotificationHandling { guard action == Self.openPluginSettingsActionId || action == UNNotificationDefaultActionIdentifier else { return } let pluginId = response.notification.request.content.userInfo[Self.pluginIdKey] as? String - PluginsSettingsNavigation.shared.reveal(pluginId: pluginId) - WindowOpener.shared.openSettings(tab: .plugins) + WindowOpener.shared.openSettings(revealingPlugin: pluginId) } } diff --git a/apple/TablePro/Core/Services/Operations/OperationCompletionReporter+Handling.swift b/apple/TablePro/Core/Services/Operations/OperationCompletionReporter+Handling.swift index f5b72ebdd0..de8de9cd12 100644 --- a/apple/TablePro/Core/Services/Operations/OperationCompletionReporter+Handling.swift +++ b/apple/TablePro/Core/Services/Operations/OperationCompletionReporter+Handling.swift @@ -12,14 +12,14 @@ extension OperationCompletionReporter: NotificationHandling { internal func presentationOptions(for notification: UNNotification) -> UNNotificationPresentationOptions { guard let payload = OperationNotificationPayload(userInfo: notification.request.content.userInfo), let connectionId = payload.connectionId - else { return [.banner, .list] } + else { return [.banner, .list, .sound] } let owner: OperationOwner = payload.compareWindowId.map { .compareWindow($0) } ?? payload.tabId.map { .tab(windowId: payload.windowId, tabId: $0) } ?? .connection(connectionId) let visibility = ResultVisibilityResolver.resolve(owner: owner, connectionId: connectionId) - return visibility.resultIsOnScreen ? [] : [.banner, .list] + return visibility.resultIsOnScreen ? [] : [.banner, .list, .sound] } internal func handle(_ response: UNNotificationResponse) { diff --git a/apple/TablePro/Core/Services/Operations/OperationCompletionReporter.swift b/apple/TablePro/Core/Services/Operations/OperationCompletionReporter.swift index de33e57ffc..35b41eb5d8 100644 --- a/apple/TablePro/Core/Services/Operations/OperationCompletionReporter.swift +++ b/apple/TablePro/Core/Services/Operations/OperationCompletionReporter.swift @@ -119,6 +119,7 @@ internal final class OperationCompletionReporter { content.subtitle = subtitle } content.body = plan.body + content.sound = .default content.categoryIdentifier = plan.categoryIdentifier content.threadIdentifier = plan.threadIdentifier content.userInfo = OperationNotificationPayload(plan: plan).userInfo diff --git a/apple/TablePro/Core/Services/TeamLibrary/TeamLibrarySync.swift b/apple/TablePro/Core/Services/TeamLibrary/TeamLibrarySync.swift index ef259ef854..f9f06ec53b 100644 --- a/apple/TablePro/Core/Services/TeamLibrary/TeamLibrarySync.swift +++ b/apple/TablePro/Core/Services/TeamLibrary/TeamLibrarySync.swift @@ -1,8 +1,3 @@ -// -// TeamLibrarySync.swift -// TablePro -// - import Combine import Foundation import os @@ -91,6 +86,11 @@ internal final class TeamLibrarySync: ObservableObject { !writableTeams.isEmpty } + // What a sign-out drops with the rest of the library: edits not pushed yet and conflicts not resolved. + var hasUnsentChanges: Bool { + teams.values.contains { !$0.pending.isEmpty || !$0.conflicts.isEmpty } + } + func start() { guard scheduleTask == nil else { return } loadIfNeeded() @@ -209,8 +209,6 @@ internal final class TeamLibrarySync: ObservableObject { publishContent() } - // MARK: - Sync - private func performSync() async -> TeamLibrarySyncOutcome { guard account.session.isSignedIn else { return .skipped } guard account.access.isAvailable(.teamLibrary) else { @@ -501,8 +499,6 @@ internal final class TeamLibrarySync: ObservableObject { commit(state) } - // MARK: - Publish - // `owns` tells this Mac's own items from someone else's that a publish only moves. private func publish( to teamID: String, @@ -572,8 +568,6 @@ internal final class TeamLibrarySync: ObservableObject { return .success(conflicted > 0 ? .conflicts(conflicted) : .published(edits.count)) } - // MARK: - Helpers - private func serially(_ work: @escaping @MainActor () async -> Value) -> Task { let previous = tail let task = Task { @MainActor in diff --git a/apple/TablePro/Core/Storage/AIKeyStorage.swift b/apple/TablePro/Core/Storage/AIKeyStorage.swift index 22f302b535..09a4be3d9e 100644 --- a/apple/TablePro/Core/Storage/AIKeyStorage.swift +++ b/apple/TablePro/Core/Storage/AIKeyStorage.swift @@ -1,11 +1,3 @@ -// -// AIKeyStorage.swift -// TablePro -// -// Keychain storage for AI provider API keys. -// Follows ConnectionStorage.swift Keychain pattern. -// - import Foundation import os @@ -20,9 +12,10 @@ final class AIKeyStorage: Sendable { self.keychain = keychain } - func saveAPIKey(_ apiKey: String, for providerID: UUID) { + @discardableResult + func saveAPIKey(_ apiKey: String, for providerID: UUID) -> Bool { let key = "com.TablePro.aikey.\(providerID.uuidString)" - keychain.writeString(apiKey, forKey: key) + return keychain.writeString(apiKey, forKey: key) } func loadAPIKey(for providerID: UUID) -> String? { diff --git a/apple/TablePro/Core/Storage/AppSettingsManager.swift b/apple/TablePro/Core/Storage/AppSettingsManager.swift index f444064e16..099dd9e848 100644 --- a/apple/TablePro/Core/Storage/AppSettingsManager.swift +++ b/apple/TablePro/Core/Storage/AppSettingsManager.swift @@ -1,200 +1,107 @@ import AppKit import Combine import Foundation -import os import TableProSyncTransport @MainActor -final class AppSettingsManager: ObservableObject { +final class AppSettingsManager { static let shared = AppSettingsManager() - @Published var general: GeneralSettings { - didSet { - general.language.apply() - storage.saveGeneral(general) - if oldValue.showWorkspaceRail != general.showWorkspaceRail { - appEvents.workspaceRailVisibilityChanged.send(()) - } - if oldValue.connectionHealthCheck != general.connectionHealthCheck { - appEvents.connectionHealthCheckChanged.send(()) - } - syncTracker.markDirty(.settings, id: AppSettingsCategory.general) - } + let generalSlice: SettingsSlice + let appearanceSlice: SettingsSlice + // Device-local, like typography: each Mac picks Auto, Light or Dark for itself. + let appearanceModeSlice: SettingsSlice + let editorSlice: SettingsSlice + let formatterSlice: SettingsSlice + // Device-local, absent from `AppSettingsCategory.synced`: a zoom press never pushes a record an older build could reset. + let typographySlice: SettingsSlice + let notificationsSlice: SettingsSlice + let dataGridSlice: SettingsSlice + let valueColorsSlice: SettingsSlice + let historySlice: SettingsSlice + let tabsSlice: SettingsSlice + let keyboardSlice: SettingsSlice + let aiSlice: SettingsSlice + let syncSlice: SettingsSlice + let mcpSlice: SettingsSlice + + var general: GeneralSettings { + get { generalSlice.value } + set { generalSlice.value = newValue } } - @Published var appearance: AppearanceSettings { - didSet { - storage.saveAppearance(appearance) - themeEngine.select( - lightThemeId: appearance.preferredLightThemeId, - darkThemeId: appearance.preferredDarkThemeId - ) - syncTracker.markDirty(.settings, id: AppSettingsCategory.appearance) - } + var appearance: AppearanceSettings { + get { appearanceSlice.value } + set { appearanceSlice.value = newValue } } - // Device-local, like typography: each Mac picks Auto, Light or Dark for itself. - @Published var appearanceMode: AppAppearanceMode { - didSet { - guard appearanceMode != oldValue else { return } - storage.saveAppearanceMode(appearanceMode) - themeEngine.apply(mode: appearanceMode) - } + var appearanceMode: AppAppearanceMode { + get { appearanceModeSlice.value } + set { appearanceModeSlice.value = newValue } } - @Published var editor: EditorSettings { - didSet { - storage.saveEditor(editor) - appEvents.editorSettingsChanged.send(()) - syncTracker.markDirty(.settings, id: AppSettingsCategory.editor) - } + var editor: EditorSettings { + get { editorSlice.value } + set { editorSlice.value = newValue } } - @Published var formatter: SQLFormatterSettings { - didSet { - guard formatter != oldValue else { return } - storage.saveFormatter(formatter) - syncTracker.markDirty(.settings, id: AppSettingsCategory.formatter) - } + var formatter: SQLFormatterSettings { + get { formatterSlice.value } + set { formatterSlice.value = newValue } } var formatterOptions: SQLFormatterOptions { formatter.options(for: editor) } - // Device-local, absent from `AppSettingsCategory.synced`: a zoom press never pushes a record an older build could reset. - @Published var typography: TypographySettings { - didSet { - guard typography != oldValue else { return } - storage.saveTypography(typography) - themeEngine.apply(typography: typography) - } + var typography: TypographySettings { + get { typographySlice.value } + set { typographySlice.value = newValue } } - @Published var notifications: NotificationSettings { - didSet { - guard !isValidating else { return } - var validated = notifications - validated.thresholdSeconds = notifications.validatedThresholdSeconds - if validated != notifications { - isValidating = true - notifications = validated - isValidating = false - } - storage.saveNotifications(notifications) - syncTracker.markDirty(.settings, id: AppSettingsCategory.notifications) - } + var notifications: NotificationSettings { + get { notificationsSlice.value } + set { notificationsSlice.value = newValue } } - @Published var dataGrid: DataGridSettings { - didSet { - guard !isValidating else { return } - var validated = dataGrid - validated.nullDisplay = dataGrid.validatedNullDisplay - validated.defaultPageSize = dataGrid.validatedDefaultPageSize - - if validated != dataGrid { - isValidating = true - dataGrid = validated - isValidating = false - } - - storage.saveDataGrid(validated) - dateFormattingService.updateFormat(validated.dateFormat) - appEvents.dataGridSettingsChanged.send(()) - syncTracker.markDirty(.settings, id: AppSettingsCategory.dataGrid) - } + var dataGrid: DataGridSettings { + get { dataGridSlice.value } + set { dataGridSlice.value = newValue } } - @Published var valueColors: ValueColorSettings { - didSet { - guard valueColors != oldValue else { return } - storage.saveValueColors(valueColors) - appEvents.valueColorSettingsChanged.send(()) - syncTracker.markDirty(.settings, id: AppSettingsCategory.valueColors) - } + var valueColors: ValueColorSettings { + get { valueColorsSlice.value } + set { valueColorsSlice.value = newValue } } - @Published var history: HistorySettings { - didSet { - guard !isValidating else { return } - var validated = history - validated.maxEntries = history.validatedMaxEntries - validated.maxDays = history.validatedMaxDays - - if validated != history { - isValidating = true - history = validated - isValidating = false - } - - storage.saveHistory(validated) - Task { await applyHistorySettingsImmediately() } - syncTracker.markDirty(.settings, id: AppSettingsCategory.history) - } + var history: HistorySettings { + get { historySlice.value } + set { historySlice.value = newValue } } - @Published var tabs: TabSettings { - didSet { - storage.saveTabs(tabs) - syncTracker.markDirty(.settings, id: AppSettingsCategory.tabs) - } + var tabs: TabSettings { + get { tabsSlice.value } + set { tabsSlice.value = newValue } } - @Published var keyboard: KeyboardSettings { - didSet { - storage.saveKeyboard(keyboard) - syncTracker.markDirty(.settings, id: AppSettingsCategory.keyboard) - MainMenuBuilder.syncKeyEquivalents(keyboard: keyboard) - appEvents.keyboardSettingsChanged.send(()) - } + var keyboard: KeyboardSettings { + get { keyboardSlice.value } + set { keyboardSlice.value = newValue } } - @Published var ai: AISettings { - didSet { - storage.saveAI(ai) - syncTracker.markDirty(.settings, id: AppSettingsCategory.ai) - appEvents.aiSettingsChanged.send(()) - copilotService.stopIfDisallowed(by: ai) - } + var ai: AISettings { + get { aiSlice.value } + set { aiSlice.value = newValue } } - // Every writer, a reset from another pane included, has to reach the Keychain flag and the coordinator. - @Published var sync: SyncSettings { - didSet { - storage.saveSync(sync) - passwordSyncDefaults.set(sync.syncsPasswords, forKey: KeychainHelper.passwordSyncEnabledKey) - if oldValue.enabled != sync.enabled { - switchSync(sync.enabled) - } - } + var sync: SyncSettings { + get { syncSlice.value } + set { syncSlice.value = newValue } } - @Published var mcp: MCPSettings { - didSet { - guard !isValidating else { return } - var validated = mcp - validated.port = mcp.validatedPort - validated.maxRowLimit = mcp.validatedMaxRowLimit - validated.defaultRowLimit = mcp.validatedDefaultRowLimit - validated.queryTimeoutSeconds = mcp.validatedQueryTimeoutSeconds - if validated != mcp { - isValidating = true - mcp = validated - isValidating = false - } - - storage.saveMCP(validated) - let enabledChanged = mcp.enabled != oldValue.enabled - let portChanged = mcp.port != oldValue.port - if enabledChanged || portChanged { - if mcp.enabled { - mcpServerManager.scheduleRestart(port: UInt16(clamping: mcp.port)) - } else { - mcpServerManager.scheduleStop() - } - } - } + var mcp: MCPSettings { + get { mcpSlice.value } + set { mcpSlice.value = newValue } } private let storage: AppSettingsStorage @@ -202,13 +109,14 @@ final class AppSettingsManager: ObservableObject { private let syncTracker: SyncChangeTracker private let appEvents: AppEvents private let dateFormattingService: DateFormattingService - private let queryHistoryManager: QueryHistoryManager private let mcpServerManager: MCPServerManager private let copilotService: CopilotService private let connectionListPreferences: ConnectionListPreferences private let passwordSyncDefaults: UserDefaults private let switchSync: @MainActor (Bool) -> Void - private var isValidating = false + private let applyHistoryRetention: @MainActor () -> Void + private let resetOutsideSettings: @MainActor () -> Void + private var deferredDirtyCategories: [String]? init( storage: AppSettingsStorage = .shared, @@ -216,7 +124,6 @@ final class AppSettingsManager: ObservableObject { syncTracker: SyncChangeTracker = .shared, appEvents: AppEvents = .shared, dateFormattingService: DateFormattingService = .shared, - queryHistoryManager: QueryHistoryManager = .shared, mcpServerManager: MCPServerManager = .shared, copilotService: CopilotService = .shared, connectionListPreferences: ConnectionListPreferences = .shared, @@ -228,6 +135,15 @@ final class AppSettingsManager: ObservableObject { } else { SyncCoordinator.shared.disableSync() } + }, + applyHistoryRetention: @escaping @MainActor () -> Void = { + Task { await QueryHistoryManager.shared.applySettingsChange() } + }, + resetOutsideSettings: @escaping @MainActor () -> Void = { + InspectorFieldHeightStore.shared.reload() + // The reset alert promises every section, so Sparkle's update preferences go too. + SoftwareUpdater.shared.resetUpdatePreferences() + AppModuleActivation.resetToDefaults() } ) { self.storage = storage @@ -235,39 +151,44 @@ final class AppSettingsManager: ObservableObject { self.syncTracker = syncTracker self.appEvents = appEvents self.dateFormattingService = dateFormattingService - self.queryHistoryManager = queryHistoryManager self.mcpServerManager = mcpServerManager self.copilotService = copilotService self.connectionListPreferences = connectionListPreferences self.passwordSyncDefaults = passwordSyncDefaults self.switchSync = switchSync + self.applyHistoryRetention = applyHistoryRetention + self.resetOutsideSettings = resetOutsideSettings + + generalSlice = SettingsSlice(storage.loadGeneral()) + appearanceSlice = SettingsSlice(storage.loadAppearance()) + appearanceModeSlice = SettingsSlice(storage.loadAppearanceMode()) + editorSlice = SettingsSlice(storage.loadEditor()) + formatterSlice = SettingsSlice(storage.loadFormatter()) + dataGridSlice = SettingsSlice(storage.loadDataGrid(), normalize: { $0.normalized }) + valueColorsSlice = SettingsSlice(storage.loadValueColors()) + historySlice = SettingsSlice(storage.loadHistory(), normalize: { $0.normalized }) + tabsSlice = SettingsSlice(storage.loadTabs()) + keyboardSlice = SettingsSlice(storage.loadKeyboard()) + aiSlice = SettingsSlice(Self.migrateAI(storage.loadAI())) + syncSlice = SettingsSlice(storage.loadSync()) + mcpSlice = SettingsSlice(storage.loadMCP(), normalize: { $0.normalized }) + notificationsSlice = SettingsSlice(storage.loadNotifications(), normalize: { $0.normalized }) + typographySlice = SettingsSlice( + storage.loadTypography(systemIsDark: NSApp?.effectiveAppearance.isDarkTheme ?? false) + ) + + generalSlice.value.language.apply() - self.general = storage.loadGeneral() - self.appearance = storage.loadAppearance() - self.appearanceMode = storage.loadAppearanceMode() - self.editor = storage.loadEditor() - self.formatter = storage.loadFormatter() - self.dataGrid = storage.loadDataGrid() - self.valueColors = storage.loadValueColors() - self.history = storage.loadHistory() - self.tabs = storage.loadTabs() - self.keyboard = storage.loadKeyboard() - self.ai = Self.migrateAI(storage.loadAI()) - self.sync = storage.loadSync() - self.mcp = storage.loadMCP() - self.notifications = storage.loadNotifications() - self.typography = storage.loadTypography(systemIsDark: NSApp?.effectiveAppearance.isDarkTheme ?? false) - - general.language.apply() - - themeEngine.apply(typography: typography) + themeEngine.apply(typography: typographySlice.value) themeEngine.apply( - mode: appearanceMode, - lightThemeId: appearance.preferredLightThemeId, - darkThemeId: appearance.preferredDarkThemeId + mode: appearanceModeSlice.value, + lightThemeId: appearanceSlice.value.preferredLightThemeId, + darkThemeId: appearanceSlice.value.preferredDarkThemeId ) - dateFormattingService.updateFormat(dataGrid.dateFormat) + dateFormattingService.updateFormat(dataGridSlice.value.dateFormat) + + attachCommits() } // Settings saved before there was an active provider would otherwise read as AI turned off. @@ -280,19 +201,18 @@ final class AppSettingsManager: ObservableObject { return migrated } - nonisolated private static let logger = Logger(subsystem: "com.TablePro", category: "AppSettingsManager") - - private func applyHistorySettingsImmediately() async { - await queryHistoryManager.applySettingsChange() - } - - // Resets Sparkle's update preferences too: the reset alert promises every section. func resetToDefaults() { - general = .default + var resetGeneral = GeneralSettings.default + // Share usage data is a consent choice, so a reset keeps it. + resetGeneral.shareAnalytics = general.shareAnalytics + + deferredDirtyCategories = [] + general = resetGeneral appearance = .default appearanceMode = .auto editor = .default formatter = .default + notifications = .default dataGrid = .default valueColors = .default history = .default @@ -303,9 +223,189 @@ final class AppSettingsManager: ObservableObject { mcp = .default typography = .default storage.resetToDefaults() - InspectorFieldHeightStore.shared.reload() + let changedCategories = deferredDirtyCategories ?? [] + deferredDirtyCategories = nil + syncTracker.markDirty(.settings, ids: changedCategories) + connectionListPreferences.resetShowsRecent() - SoftwareUpdater.shared.resetUpdatePreferences() - AppModuleActivation.resetToDefaults() + resetOutsideSettings() + } + + private func attachCommits() { + generalSlice.attach { [weak self] old, new in self?.commitGeneral(from: old, to: new) } + appearanceSlice.attach { [weak self] _, new in self?.commitAppearance(new) } + appearanceModeSlice.attach { [weak self] _, new in self?.commitAppearanceMode(new) } + editorSlice.attach { [weak self] _, new in self?.commitEditor(new) } + formatterSlice.attach { [weak self] _, new in self?.commitFormatter(new) } + typographySlice.attach { [weak self] _, new in self?.commitTypography(new) } + notificationsSlice.attach { [weak self] _, new in self?.commitNotifications(new) } + dataGridSlice.attach { [weak self] old, new in self?.commitDataGrid(from: old, to: new) } + valueColorsSlice.attach { [weak self] _, new in self?.commitValueColors(new) } + historySlice.attach { [weak self] old, new in self?.commitHistory(from: old, to: new) } + tabsSlice.attach { [weak self] _, new in self?.commitTabs(new) } + keyboardSlice.attach { [weak self] _, new in self?.commitKeyboard(new) } + aiSlice.attach { [weak self] _, new in self?.commitAI(new) } + syncSlice.attach { [weak self] old, new in self?.commitSync(from: old, to: new) } + mcpSlice.attach { [weak self] old, new in self?.commitMCP(from: old, to: new) } + } + + // A reset collects its categories and marks them once, after the whole reset is saved. + private func markDirty(_ category: String) { + if deferredDirtyCategories != nil { + deferredDirtyCategories?.append(category) + } else { + syncTracker.markDirty(.settings, id: category) + } + } + + private func commitGeneral(from old: GeneralSettings, to new: GeneralSettings) { + storage.saveGeneral(new) + if old.language != new.language { + new.language.apply() + } + if old.showWorkspaceRail != new.showWorkspaceRail { + appEvents.workspaceRailVisibilityChanged.send(()) + } + if old.connectionHealthCheck != new.connectionHealthCheck { + appEvents.connectionHealthCheckChanged.send(()) + } + markDirty(AppSettingsCategory.general) + } + + private func commitAppearance(_ new: AppearanceSettings) { + storage.saveAppearance(new) + themeEngine.select(lightThemeId: new.preferredLightThemeId, darkThemeId: new.preferredDarkThemeId) + markDirty(AppSettingsCategory.appearance) + } + + private func commitAppearanceMode(_ new: AppAppearanceMode) { + storage.saveAppearanceMode(new) + themeEngine.apply(mode: new) + } + + private func commitEditor(_ new: EditorSettings) { + storage.saveEditor(new) + appEvents.editorSettingsChanged.send(()) + markDirty(AppSettingsCategory.editor) + } + + private func commitFormatter(_ new: SQLFormatterSettings) { + storage.saveFormatter(new) + markDirty(AppSettingsCategory.formatter) + } + + private func commitTypography(_ new: TypographySettings) { + storage.saveTypography(new) + themeEngine.apply(typography: new) + } + + private func commitNotifications(_ new: NotificationSettings) { + storage.saveNotifications(new) + markDirty(AppSettingsCategory.notifications) + } + + private func commitDataGrid(from old: DataGridSettings, to new: DataGridSettings) { + storage.saveDataGrid(new) + if old.dateFormat != new.dateFormat { + dateFormattingService.updateFormat(new.dateFormat) + } + appEvents.dataGridSettingsChanged.send(()) + markDirty(AppSettingsCategory.dataGrid) + } + + private func commitValueColors(_ new: ValueColorSettings) { + storage.saveValueColors(new) + appEvents.valueColorSettingsChanged.send(()) + markDirty(AppSettingsCategory.valueColors) + } + + private func commitHistory(from old: HistorySettings, to new: HistorySettings) { + storage.saveHistory(new) + if !new.hasSameRetention(as: old) { + applyHistoryRetention() + } + markDirty(AppSettingsCategory.history) + } + + private func commitTabs(_ new: TabSettings) { + storage.saveTabs(new) + markDirty(AppSettingsCategory.tabs) + } + + private func commitKeyboard(_ new: KeyboardSettings) { + storage.saveKeyboard(new) + markDirty(AppSettingsCategory.keyboard) + MainMenuBuilder.syncKeyEquivalents(keyboard: new) + appEvents.keyboardSettingsChanged.send(()) + } + + private func commitAI(_ new: AISettings) { + storage.saveAI(new) + markDirty(AppSettingsCategory.ai) + appEvents.aiSettingsChanged.send(()) + copilotService.stopIfDisallowed(by: new) + } + + // Every writer, a reset from another pane included, has to reach the Keychain flag and the coordinator. + private func commitSync(from old: SyncSettings, to new: SyncSettings) { + storage.saveSync(new) + passwordSyncDefaults.set(new.syncsPasswords, forKey: KeychainHelper.passwordSyncEnabledKey) + if old.enabled != new.enabled { + switchSync(new.enabled) + } + } + + private func commitMCP(from old: MCPSettings, to new: MCPSettings) { + storage.saveMCP(new) + guard old.enabled != new.enabled || old.port != new.port else { return } + if new.enabled { + mcpServerManager.scheduleRestart(port: UInt16(clamping: new.port)) + } else { + mcpServerManager.scheduleStop() + } + } +} + +extension HistorySettings { + // Data Rewind's switch is not retention, so turning it never starts a cleanup. + func hasSameRetention(as other: HistorySettings) -> Bool { + maxEntries == other.maxEntries && maxDays == other.maxDays && autoCleanup == other.autoCleanup + } +} + +private extension NotificationSettings { + var normalized: NotificationSettings { + var settings = self + settings.thresholdSeconds = validatedThresholdSeconds + return settings + } +} + +private extension DataGridSettings { + var normalized: DataGridSettings { + var settings = self + settings.nullDisplay = validatedNullDisplay + settings.defaultPageSize = validatedDefaultPageSize + return settings + } +} + +private extension HistorySettings { + var normalized: HistorySettings { + var settings = self + settings.maxEntries = validatedMaxEntries + settings.maxDays = validatedMaxDays + return settings + } +} + +private extension MCPSettings { + var normalized: MCPSettings { + var settings = self + settings.port = validatedPort + settings.maxRowLimit = validatedMaxRowLimit + settings.defaultRowLimit = validatedDefaultRowLimit + settings.queryTimeoutSeconds = validatedQueryTimeoutSeconds + return settings } } diff --git a/apple/TablePro/Core/Storage/AppSettingsStorage.swift b/apple/TablePro/Core/Storage/AppSettingsStorage.swift index 742bdfb3b6..f1d1d2ab2b 100644 --- a/apple/TablePro/Core/Storage/AppSettingsStorage.swift +++ b/apple/TablePro/Core/Storage/AppSettingsStorage.swift @@ -1,11 +1,3 @@ -// -// AppSettingsStorage.swift -// TablePro -// -// Persistent storage for application settings using UserDefaults. -// Follows FilterSettingsStorage pattern - singleton with JSON encoding. -// - import Foundation import os @@ -17,8 +9,6 @@ final class AppSettingsStorage: Sendable { private let decoder = JSONDecoder() private let encoder = JSONEncoder() - // MARK: - UserDefaults Keys - private enum Keys { static let general = "com.TablePro.settings.general" static let appearance = "com.TablePro.settings.appearance" @@ -52,8 +42,6 @@ final class AppSettingsStorage: Sendable { self.defaults = userDefaults } - // MARK: - General Settings - func loadGeneral() -> GeneralSettings { load(key: Keys.general, default: .default) } @@ -84,8 +72,6 @@ final class AppSettingsStorage: Sendable { } } - // MARK: - Appearance Settings - func loadAppearance() -> AppearanceSettings { load(key: Keys.appearance, default: .default) } @@ -94,8 +80,7 @@ final class AppSettingsStorage: Sendable { save(settings, key: Keys.appearance) } - // Older builds kept the mode inside the synced appearance blob. The first load carries it to its - // own key and writes it there, because the next save of the blob drops the field. + // Older builds kept the mode in the synced appearance blob; the first load moves it, since the blob's next save drops it. func loadAppearanceMode() -> AppAppearanceMode { if let stored = defaults.string(forKey: Keys.appearanceMode) { guard let mode = AppAppearanceMode(rawValue: stored) else { @@ -156,8 +141,6 @@ final class AppSettingsStorage: Sendable { save(settings, key: Keys.typography) } - // MARK: - Editor Settings - func loadEditor() -> EditorSettings { load(key: Keys.editor, default: .default) } @@ -166,8 +149,6 @@ final class AppSettingsStorage: Sendable { save(settings, key: Keys.editor) } - // MARK: - Formatter Settings - func loadFormatter() -> SQLFormatterSettings { load(key: Keys.formatter, default: .default) } @@ -176,8 +157,6 @@ final class AppSettingsStorage: Sendable { save(settings, key: Keys.formatter) } - // MARK: - Data Grid Settings - func loadDataGrid() -> DataGridSettings { load(key: Keys.dataGrid, default: .default) } @@ -186,8 +165,6 @@ final class AppSettingsStorage: Sendable { save(settings, key: Keys.dataGrid) } - // MARK: - Value Color Settings - func loadValueColors() -> ValueColorSettings { load(key: Keys.valueColors, default: .default) } @@ -196,8 +173,6 @@ final class AppSettingsStorage: Sendable { save(settings, key: Keys.valueColors) } - // MARK: - History Settings - func loadHistory() -> HistorySettings { load(key: Keys.history, default: .default) } @@ -206,9 +181,6 @@ final class AppSettingsStorage: Sendable { save(settings, key: Keys.history) } - - // MARK: - Tab Settings - func loadTabs() -> TabSettings { load(key: Keys.tabs, default: .default) } @@ -217,8 +189,6 @@ final class AppSettingsStorage: Sendable { save(settings, key: Keys.tabs) } - // MARK: - Keyboard Settings - func loadKeyboard() -> KeyboardSettings { load(key: Keys.keyboard, default: KeyboardSettings.default).sanitized() } @@ -227,8 +197,6 @@ final class AppSettingsStorage: Sendable { save(settings, key: Keys.keyboard) } - // MARK: - AI Settings - func loadAI() -> AISettings { load(key: Keys.ai, default: .default) } @@ -237,8 +205,6 @@ final class AppSettingsStorage: Sendable { save(settings, key: Keys.ai) } - // MARK: - Sync Settings - func loadSync() -> SyncSettings { load(key: Keys.sync, default: .default) } @@ -247,8 +213,6 @@ final class AppSettingsStorage: Sendable { save(settings, key: Keys.sync) } - // MARK: - MCP Settings - func loadNotifications() -> NotificationSettings { load(key: Keys.notifications, default: .default) } @@ -265,8 +229,6 @@ final class AppSettingsStorage: Sendable { save(settings, key: Keys.mcp) } - // MARK: - Last Selected Database (per connection) - func saveLastDatabase(_ database: String?, for connectionId: UUID) { if let database { defaults.set(database, forKey: "com.TablePro.lastSelectedDatabase.\(connectionId)") @@ -279,8 +241,6 @@ final class AppSettingsStorage: Sendable { defaults.string(forKey: "com.TablePro.lastSelectedDatabase.\(connectionId)") } - // MARK: - Last Selected Schema (per connection) - func saveLastSchema(_ schema: String?, for connectionId: UUID) { if let schema { defaults.set(schema, forKey: "com.TablePro.lastSelectedSchema.\(connectionId)") @@ -293,8 +253,6 @@ final class AppSettingsStorage: Sendable { defaults.string(forKey: "com.TablePro.lastSelectedSchema.\(connectionId)") } - // MARK: - Welcome Sheet - func hasSeenWelcomeSheet() -> Bool { defaults.bool(forKey: Keys.hasSeenWelcomeSheet) } @@ -303,10 +261,11 @@ final class AppSettingsStorage: Sendable { defaults.set(true, forKey: Keys.hasSeenWelcomeSheet) } - // MARK: - Reset - func resetToDefaults() { - saveGeneral(.default) + var general = GeneralSettings.default + // Share usage data is a consent choice, so a reset keeps it. + general.shareAnalytics = loadGeneral().shareAnalytics + saveGeneral(general) saveAppearance(.default) saveAppearanceMode(.auto) saveEditor(.default) @@ -319,6 +278,7 @@ final class AppSettingsStorage: Sendable { saveAI(loadAI().resetKeepingProviders) saveSync(.default) saveMCP(.default) + saveNotifications(.default) saveTypography(.default) defaults.removeObject(forKey: PreferenceKeys.selectedSettingsPane.name) defaults.removeObject(forKey: PreferenceKeys.rowInspectorFieldHeights.name) @@ -327,8 +287,6 @@ final class AppSettingsStorage: Sendable { RoutineDebugOptionStore(defaults: { [defaults] in defaults }).removeAll() } - // MARK: - Helpers - private func load(key: String, default defaultValue: T) -> T { guard let data = defaults.data(forKey: key) else { return defaultValue diff --git a/apple/TablePro/Core/Storage/CredentialProfileStorage.swift b/apple/TablePro/Core/Storage/CredentialProfileStorage.swift index 829cac0e6e..adad2a60d6 100644 --- a/apple/TablePro/Core/Storage/CredentialProfileStorage.swift +++ b/apple/TablePro/Core/Storage/CredentialProfileStorage.swift @@ -1,8 +1,3 @@ -// -// CredentialProfileStorage.swift -// TablePro -// - import Foundation import os import TableProImport @@ -12,20 +7,49 @@ extension Notification.Name { static let credentialProfilesDidChange = Notification.Name("CredentialProfilesDidChange") } -/// The named credential profiles, in a file beside `connections.json` and stamped the same way. -/// -/// Not `UserDefaults`, which is where SSH profiles live. A credential profile can declare a -/// `PasswordSource.command(shell:)`, and the trust tag is the only thing standing between an -/// attacker-writable file and a command this Mac never agreed to run. `ConnectionStorage` has that -/// tag; the defaults domain has nothing of the kind. +enum ProfileSecretRead: Equatable, Sendable { + case found(String) + case absent + case unreadable + + init(_ result: KeychainStringResult) { + switch result { + case .found(let value): + self = value.isEmpty ? .absent : .found(value) + case .notFound: + self = .absent + case .locked, .userCancelled, .authFailed, .error: + self = .unreadable + } + } + + var value: String? { + guard case .found(let value) = self else { return nil } + return value + } +} + +enum ProfileSecretChange: Equatable, Sendable { + case write(String) + case keep + case delete + + // An empty field over a secret that could not be read means "not shown", never "cleared". + static func decide(applies: Bool, value: String, read: ProfileSecretRead) -> ProfileSecretChange { + if applies, !value.isEmpty { + return read == .found(value) ? .keep : .write(value) + } + return read == .unreadable ? .keep : .delete + } +} + +// A file and not UserDefaults: a profile can name a shell command, and only the file's trust tag stops one this Mac never agreed to run. @MainActor final class CredentialProfileStorage { static let shared = CredentialProfileStorage() nonisolated private static let logger = Logger(subsystem: "com.TablePro", category: "CredentialProfileStorage") - /// The prefix is load-bearing. `TableProMobile`'s `KeychainSecureStore.cleanOrphanedCredentials` - /// sweeps `com.TablePro.password.` and deletes any item whose trailing UUID is not a saved - /// connection, and a profile id is never a connection id. + // TableProMobile sweeps `com.TablePro.password.` items whose UUID is not a connection, so profile secrets must not share that prefix. static let secretKeyPrefix = "com.TablePro.credprofile." private static let secretPrefix = secretKeyPrefix @@ -34,13 +58,9 @@ final class CredentialProfileStorage { private let syncTracker: SyncChangeTracker private let connectionStorageProvider: () -> ConnectionStorage - /// True when the file exists and would not decode. Saving then would write an empty list over - /// whatever it holds, so every mutation refuses until a load succeeds. + // Every mutation refuses while this is true, or a save would write an empty list over the file. private(set) var lastLoadFailed = false - /// Whether the profiles file is the one TablePro last wrote. `resolvePassword` reads it before - /// running a profile's password source, exactly as it reads `ConnectionStorage.storeIsTrusted` - /// before running a connection's. var storeIsTrusted: Bool { file.isTrusted } init( @@ -68,8 +88,6 @@ final class CredentialProfileStorage { return directory.appendingPathComponent("credentialProfiles.json") } - // MARK: - Profile CRUD - func loadProfiles() -> [CredentialProfile] { guard let profiles = file.load() else { lastLoadFailed = true @@ -108,8 +126,6 @@ final class CredentialProfileStorage { return false } guard file.save(profiles) else { return false } - /// The Settings window is kept alive between openings, so a profile created from a - /// connection window has to reach a Profiles pane that is already on screen. NotificationCenter.default.post(name: .credentialProfilesDidChange, object: nil) return true } @@ -118,15 +134,18 @@ final class CredentialProfileStorage { func addProfile(_ profile: CredentialProfile) -> Bool { var profiles = loadProfiles() guard !lastLoadFailed else { return false } + // A record this build cannot read still owns its id, so a second record under it would replace it on save. + guard !profiles.contains(where: { $0.id == profile.id }), !file.unreadableIds.contains(profile.id) else { + Self.logger.error("Refusing to add credential profile \(profile.id.uuidString, privacy: .public): the id is taken") + return false + } var placed = profile placed.sortOrder = (profiles.map { $0.sortOrder }.max() ?? -1) + 1 profiles.append(placed) return saveProfiles(profiles) } - /// Returns only the profiles this call created. A name already here is skipped, so a file can - /// never select one of this Mac's credentials by naming it. Nil when the store is unreadable - /// or the save failed. + // A name already here is skipped, so a file can never select one of this Mac's credentials by naming it. func addImportedProfiles(_ imported: [PlannedCredentialProfile]) -> [BundleRef: UUID]? { guard !imported.isEmpty else { return [:] } var profiles = loadProfiles() @@ -163,9 +182,7 @@ final class CredentialProfileStorage { guard let index = profiles.firstIndex(where: { $0.id == profile.id }) else { return false } profiles[index] = profile guard saveProfiles(profiles) else { return false } - /// Best effort, and deliberately not part of the result. The profile is saved and the - /// connect path resolves the username from it either way; this is what keeps the copy on - /// each connection, which every other reader of `username` uses, in step. + // Best effort: the connect path resolves the username from the profile either way. if !writeUsernameThrough(profile) { Self.logger.error( "Saved credential profile \(profile.id.uuidString, privacy: .public) but could not update the connections linked to it" @@ -174,30 +191,24 @@ final class CredentialProfileStorage { return true } - /// Deleting hands each linked connection the profile's username and its stored password, as - /// that connection's own inline credentials, so nothing stops connecting. Returns false without - /// deleting anything when that hand-over cannot be completed. + // Linked connections take the profile's credentials as their own first; nothing is deleted if that hand-over fails. @discardableResult func deleteProfile(_ profile: CredentialProfile) -> Bool { var profiles = loadProfiles() guard !lastLoadFailed else { return false } + // The stored record, not the caller's copy, which can predate a sync or another window's edit. + var current = profiles.first { $0.id == profile.id } ?? profile + current.secureFieldIds = Array(Set(current.secureFieldIds).union(profile.secureFieldIds)).sorted() profiles.removeAll { $0.id == profile.id } - guard unlinkConnections(from: profile) else { return false } + guard unlinkConnections(from: current) else { return false } guard saveProfiles(profiles) else { return false } syncTracker.markDeleted(.credentialProfile, id: profile.id.uuidString) - deleteSecrets(for: profile) + deleteSecrets(for: current) return true } - // MARK: - Linked Connections - - /// Copies the profile's username onto every connection that links to it. - /// - /// `connection.username` stays populated for a linked connection on purpose. It is read raw by - /// the AWS IAM signer, the `~/.pgpass` lookup, `NativeDumpRegistry`'s `-U` flags, - /// `ExternalConnectionTrustKey` and the connection record pushed to iCloud, and blanking it - /// would have pushed an empty username over the good value on a second Mac. + // connection.username stays filled for a linked connection: the IAM signer, ~/.pgpass, dump flags and sync read it raw. @discardableResult func writeUsernameThrough(_ profile: CredentialProfile, byUser: Bool = true) -> Bool { let storage = connectionStorageProvider() @@ -214,6 +225,13 @@ final class CredentialProfileStorage { @discardableResult func unlinkConnections(from profile: CredentialProfile) -> Bool { let storage = connectionStorageProvider() + // An unreadable library may hold connections that use this profile, and they would be left pointing at nothing. + guard !storage.isLibraryUnreadable else { + Self.logger.error( + "Refusing to unlink from credential profile \(profile.id.uuidString, privacy: .public): the connections could not be read" + ) + return false + } let linked = storage.loadConnections().filter { $0.credentialMode == .profile(id: profile.id) } guard !linked.isEmpty else { return true } @@ -234,16 +252,10 @@ final class CredentialProfileStorage { let converted = storage.mutateConnections(ids: Set(linked.map { $0.id })) { connection in connection.credentialMode = .inline connection.username = profile.username - /// Every inline password field is written, not only the one this profile used. A - /// connection that carried a prompt flag or a pgpass flag from before it was linked - /// would otherwise keep it and override the password just copied in. + // Every inline password flag is written, or a stale prompt or pgpass flag overrides the password just copied in. connection.promptForPassword = profile.passwordMode == .prompt connection.usePgpass = profile.passwordMode == .pgpass - /// A password source can name a shell command, and `connections.json` re-stamps itself - /// as trusted whenever the user saves it. Carrying one out of a profiles file that - /// something else wrote would move a command from a store that refuses to run it into - /// one that will, with a profile delete standing in for the user's consent. So it is - /// carried only from a file TablePro itself last wrote; otherwise the connection asks. + // connections.json re-stamps itself on a user save, so a source from an untrusted profiles file would become runnable. if case .source(let source) = profile.passwordMode, carriesSource { connection.passwordSource = source } else { @@ -261,8 +273,7 @@ final class CredentialProfileStorage { return converted } - // MARK: - Secrets - + @discardableResult func savePassword(_ password: String, for profileId: UUID) -> Bool { keychain.writeString(password, forKey: Self.passwordKey(profileId)) } @@ -272,6 +283,10 @@ final class CredentialProfileStorage { .value(label: "Credential profile password (profileId=\(profileId.uuidString))", logger: Self.logger) } + func readPassword(for profileId: UUID) -> ProfileSecretRead { + ProfileSecretRead(keychain.readStringResult(forKey: Self.passwordKey(profileId))) + } + func deletePassword(for profileId: UUID) { keychain.delete(forKey: Self.passwordKey(profileId)) } @@ -289,12 +304,15 @@ final class CredentialProfileStorage { ) } + func readSecureField(fieldId: String, for profileId: UUID) -> ProfileSecretRead { + ProfileSecretRead(keychain.readStringResult(forKey: Self.fieldKey(fieldId, profileId))) + } + func deleteSecureField(fieldId: String, for profileId: UUID) { keychain.delete(forKey: Self.fieldKey(fieldId, profileId)) } - /// Every keychain item this type writes, removed together. A key written here and missing from - /// this list is a secret that outlives its owner with nothing left that can name it. + // Every Keychain item this type writes. A key missing here outlives its profile with nothing left to name it. func deleteSecrets(for profile: CredentialProfile) { deletePassword(for: profile.id) for fieldId in profile.secureFieldIds { @@ -339,35 +357,24 @@ final class CredentialProfileStorage { } } - private enum SecretRead { - case readable(String?) - case unreadable - } - - /// Nil when anything the profile owns exists but could not be read. A profile with no stored - /// secret reads as an empty set, which is correct for prompt, pgpass and source modes. + // Nil when anything the profile owns exists but could not be read; prompt, pgpass and source modes own no password. private func readSecrets(for profile: CredentialProfile) -> ProfileSecrets? { var password: String? if profile.passwordMode.usesStoredSecret { - guard case .readable(let value) = readSecret(Self.passwordKey(profile.id)) else { return nil } - password = value + switch readPassword(for: profile.id) { + case .found(let value): password = value + case .absent: break + case .unreadable: return nil + } } var fields: [String: String] = [:] for fieldId in profile.secureFieldIds { - guard case .readable(let value) = readSecret(Self.fieldKey(fieldId, profile.id)) else { return nil } - if let value { fields[fieldId] = value } + switch readSecureField(fieldId: fieldId, for: profile.id) { + case .found(let value): fields[fieldId] = value + case .absent: break + case .unreadable: return nil + } } return ProfileSecrets(password: password, fields: fields) } - - private func readSecret(_ key: String) -> SecretRead { - switch keychain.readStringResult(forKey: key) { - case .found(let value): - return .readable(value.isEmpty ? nil : value) - case .notFound: - return .readable(nil) - case .locked, .userCancelled, .authFailed, .error: - return .unreadable - } - } } diff --git a/apple/TablePro/Core/Storage/ExternalConnectionTrustStore.swift b/apple/TablePro/Core/Storage/ExternalConnectionTrustStore.swift index f5d6e5cc99..74f7c23ddf 100644 --- a/apple/TablePro/Core/Storage/ExternalConnectionTrustStore.swift +++ b/apple/TablePro/Core/Storage/ExternalConnectionTrustStore.swift @@ -1,8 +1,4 @@ -// -// ExternalConnectionTrustStore.swift -// TablePro -// - +import Combine import Foundation import os @@ -29,11 +25,17 @@ internal final class ExternalConnectionTrustStore: ExternalConnectionTrustChecki ) private let defaults: UserDefaults + private let changeSubject = PassthroughSubject() internal init(defaults: UserDefaults = AppStorageEnvironment.shared.defaults) { self.defaults = defaults } + // Sent after the write, so a subscriber that reads entries() sees the change. + internal var changes: AnyPublisher { + changeSubject.eraseToAnyPublisher() + } + internal func isTrusted(_ key: ExternalConnectionTrustKey) -> Bool { guard key.isLoopbackHost else { return false } return entries().contains { $0.key == key } @@ -48,14 +50,17 @@ internal final class ExternalConnectionTrustStore: ExternalConnectionTrustChecki updated.append(TrustedExternalConnection(key: key, trustedAt: Date())) save(updated) Self.logger.info("Trusted external connection \(key.displayDescription, privacy: .private(mask: .hash))") + changeSubject.send(()) } internal func revoke(_ key: ExternalConnectionTrustKey) { save(entries().filter { $0.key != key }) + changeSubject.send(()) } internal func revokeAll() { defaults.removeValue(for: Self.storageKey) + changeSubject.send(()) } internal func entries() -> [TrustedExternalConnection] { diff --git a/apple/TablePro/Core/Storage/SSHProfileStorage.swift b/apple/TablePro/Core/Storage/SSHProfileStorage.swift index 455d73840f..4c77829cba 100644 --- a/apple/TablePro/Core/Storage/SSHProfileStorage.swift +++ b/apple/TablePro/Core/Storage/SSHProfileStorage.swift @@ -1,8 +1,3 @@ -// -// SSHProfileStorage.swift -// TablePro -// - import Foundation import os import TableProSyncTransport @@ -25,9 +20,7 @@ final class SSHProfileStorage { private let syncTracker: SyncChangeTracker private(set) var lastLoadFailed = false - /// The keychain arrives through `AppStorageEnvironment` rather than as `KeychainHelper.shared`, - /// so a sandboxed run keeps its profile secrets inside the sandbox instead of writing them to - /// the real login keychain, exactly as `ConnectionStorage` already does. + // The Keychain comes from AppStorageEnvironment, so a sandboxed run keeps profile secrets inside the sandbox. init( userDefaults: UserDefaults = AppStorageEnvironment.shared.defaults, keychain: any KeychainStoring = AppStorageEnvironment.shared.keychain, @@ -40,8 +33,6 @@ final class SSHProfileStorage { self.connectionStorageProvider = connectionStorage } - // MARK: - Profile CRUD - func loadProfiles() -> [SSHProfile] { guard let data = defaults.data(forKey: profilesKey) else { lastLoadFailed = false @@ -59,8 +50,7 @@ final class SSHProfileStorage { } } - /// Returns `false` when nothing reached disk, so a caller that also writes keychain items or - /// tombstones can abort instead of stranding them against a profile that was never persisted. + // False when nothing reached disk, so a caller that also writes Keychain items or tombstones can stop. @discardableResult func saveProfiles(_ profiles: [SSHProfile]) -> Bool { let previous = loadProfiles() @@ -90,6 +80,10 @@ final class SSHProfileStorage { func addProfile(_ profile: SSHProfile) -> Bool { var profiles = loadProfiles() guard !lastLoadFailed else { return false } + guard !profiles.contains(where: { $0.id == profile.id }) else { + Self.logger.error("Refusing to add SSH profile \(profile.id.uuidString, privacy: .public): the id is taken") + return false + } profiles.append(profile) return saveProfiles(profiles) } @@ -101,9 +95,7 @@ final class SSHProfileStorage { guard let index = profiles.firstIndex(where: { $0.id == profile.id }) else { return false } profiles[index] = profile guard saveProfiles(profiles) else { return false } - /// Best effort, and deliberately not part of the result. The profile is the source of - /// truth and it is saved; a connection whose snapshot could not be rewritten is still - /// resolved against the profile by `refreshingLinkedProfile` at connect time. + // Best effort: a connection whose snapshot was not rewritten is resolved against the profile at connect time. if !refreshLinkedConnections(with: profile) { Self.logger.error("Saved SSH profile \(profile.id.uuidString, privacy: .public) but could not update the connections linked to it") } @@ -114,8 +106,10 @@ final class SSHProfileStorage { func deleteProfile(_ profile: SSHProfile) -> Bool { var profiles = loadProfiles() guard !lastLoadFailed else { return false } + // The stored record, not the caller's copy: unlinking writes its configuration into every linked connection. + let current = profiles.first { $0.id == profile.id } ?? profile profiles.removeAll { $0.id == profile.id } - guard unlinkConnections(fromProfile: profile) else { return false } + guard unlinkConnections(fromProfile: current) else { return false } guard saveProfiles(profiles) else { return false } syncTracker.markDeleted(.sshProfile, id: profile.id.uuidString) @@ -127,14 +121,7 @@ final class SSHProfileStorage { loadProfiles().first { $0.id == id } } - // MARK: - Linked Connections - - /// Writes an edited profile's configuration into every connection that links to it. - /// - /// A linked connection stores `.profile(id:snapshot:)`, and that snapshot is what - /// `resolvedSSHConfig` hands to the tunnel, the URL formatter, the display strings and the - /// stage labels. Only the secrets were ever resolved live, so changing a profile's host left - /// every already-linked connection tunnelling to the old one while sending the new password. + // A linked connection tunnels through its stored snapshot, so an edited profile has to be written into each one. @discardableResult func refreshLinkedConnections(with profile: SSHProfile, byUser: Bool = true) -> Bool { let storage = connectionStorageProvider() @@ -148,11 +135,7 @@ final class SSHProfileStorage { } } - /// The connection as it would be if the fan-out above had already run for it. - /// - /// The fan-out covers an edit made here. This covers the window before one has run: a profile - /// edited on another Mac and synced down, or a connection whose store could not be written. - /// Connecting is the moment the answer has to be right, so it asks the profile directly. + // Covers a profile edited on another Mac, or a fan-out that could not be written, at the moment it matters. func refreshingLinkedProfile(_ connection: DatabaseConnection) -> DatabaseConnection { guard case .profile(let profileId, _) = connection.sshTunnelMode, let profile = profile(for: profileId) @@ -160,19 +143,15 @@ final class SSHProfileStorage { return profile.applied(to: connection) } - /// Turns every connection pointing at a profile that is going away into an inline tunnel - /// carrying the same configuration, so a delete never leaves a connection addressing a profile - /// id that no longer resolves. - /// - /// The configuration comes from the profile as it stands now, never from the connection's - /// stored snapshot: a snapshot the fan-out never reached is stale, and converting that one - /// while handing over the profile's current password would send new credentials to the old - /// server. Returns false without changing anything when the secrets cannot be moved, because a - /// connection converted without them cannot authenticate and there is nothing left to recover - /// them from once the profile is deleted. + // The tunnel comes from the profile as it stands, never a stale snapshot, or new credentials reach the old server. @discardableResult func unlinkConnections(fromProfile profile: SSHProfile) -> Bool { let storage = connectionStorageProvider() + // An unreadable library may hold connections that use this profile, and they would be left pointing at nothing. + guard !storage.isLibraryUnreadable else { + Self.logger.error("Refusing to unlink from SSH profile \(profile.id.uuidString, privacy: .public): the connections could not be read") + return false + } let linked = storage.loadConnections().filter { $0.isLinked(toSSHProfile: profile.id) } guard !linked.isEmpty else { return true } @@ -194,10 +173,7 @@ final class SSHProfileStorage { connection.sshProfileId = nil } - /// The copies go back if the conversion did not land. A connection still in profile mode - /// reads its secrets from the profile, so the copy would sit in its inline namespace with - /// nothing reading it. Deleting is safe there because the form already clears that - /// namespace on every save a profile-linked connection makes. + // A connection still in profile mode never reads its inline namespace, so the copies go back. if !converted { for connection in linked { storage.deleteSSHPassword(for: connection.id) @@ -208,8 +184,6 @@ final class SSHProfileStorage { return converted } - /// A profile's secrets on their way into a connection's own keychain namespace, which is where - /// an inline tunnel reads them from. private struct ProfileSecrets { let password: String? let keyPassphrase: String? @@ -224,100 +198,92 @@ final class SSHProfileStorage { } } - private enum SecretRead { - case readable(String?) - case unreadable - } - - /// Nil when any of the three could not be read. A profile that simply has none reads as three - /// nils, which is correct for agent and keyless authentication. + // Nil when any of the three could not be read; agent and keyless profiles read as three nils. private func readSecrets(for profileId: UUID) -> ProfileSecrets? { - guard case .readable(let password) = readSecret(Self.passwordKey(profileId)), - case .readable(let keyPassphrase) = readSecret(Self.passphraseKey(profileId)), - case .readable(let totpSecret) = readSecret(Self.totpKey(profileId)) - else { return nil } - return ProfileSecrets(password: password, keyPassphrase: keyPassphrase, totpSecret: totpSecret) + var values: [SSHSecret: String] = [:] + for secret in SSHSecret.allCases { + switch readSecret(secret, for: profileId) { + case .found(let value): values[secret] = value + case .absent: break + case .unreadable: return nil + } + } + return ProfileSecrets( + password: values[.password], + keyPassphrase: values[.keyPassphrase], + totpSecret: values[.totpSecret] + ) } - private func readSecret(_ key: String) -> SecretRead { - switch keychain.readStringResult(forKey: key) { - case .found(let value): - return .readable(value.isEmpty ? nil : value) - case .notFound: - return .readable(nil) - case .locked, .userCancelled, .authFailed, .error: - return .unreadable + // Every Keychain item this type writes. A key missing here outlives its profile with nothing left to name it. + func deleteSecrets(for profileId: UUID) { + for secret in SSHSecret.allCases { + deleteSecret(secret, for: profileId) } } - /// Every keychain item this type writes, removed together. A key written here and missing from - /// this list is a secret that outlives its owner with nothing left that can name it. - func deleteSecrets(for profileId: UUID) { - deleteSSHPassword(for: profileId) - deleteKeyPassphrase(for: profileId) - deleteTOTPSecret(for: profileId) + func readSecret(_ secret: SSHSecret, for profileId: UUID) -> ProfileSecretRead { + ProfileSecretRead(keychain.readStringResult(forKey: Self.key(secret, profileId))) } - // MARK: - SSH Password Storage + @discardableResult + func saveSecret(_ value: String, _ secret: SSHSecret, for profileId: UUID) -> Bool { + keychain.writeString(value, forKey: Self.key(secret, profileId)) + } + + func deleteSecret(_ secret: SSHSecret, for profileId: UUID) { + keychain.delete(forKey: Self.key(secret, profileId)) + } - func saveSSHPassword(_ password: String, for profileId: UUID) { - keychain.writeString(password, forKey: Self.passwordKey(profileId)) + @discardableResult + func saveSSHPassword(_ password: String, for profileId: UUID) -> Bool { + saveSecret(password, .password, for: profileId) } func loadSSHPassword(for profileId: UUID) -> String? { - resolveString(label: "SSH profile password", profileId: profileId, forKey: Self.passwordKey(profileId)) + resolveString(label: "SSH profile password", profileId: profileId, secret: .password) } func deleteSSHPassword(for profileId: UUID) { - keychain.delete(forKey: Self.passwordKey(profileId)) + deleteSecret(.password, for: profileId) } - // MARK: - Key Passphrase Storage - - func saveKeyPassphrase(_ passphrase: String, for profileId: UUID) { - keychain.writeString(passphrase, forKey: Self.passphraseKey(profileId)) + @discardableResult + func saveKeyPassphrase(_ passphrase: String, for profileId: UUID) -> Bool { + saveSecret(passphrase, .keyPassphrase, for: profileId) } func loadKeyPassphrase(for profileId: UUID) -> String? { - resolveString( - label: "SSH profile key passphrase", - profileId: profileId, - forKey: Self.passphraseKey(profileId) - ) + resolveString(label: "SSH profile key passphrase", profileId: profileId, secret: .keyPassphrase) } func deleteKeyPassphrase(for profileId: UUID) { - keychain.delete(forKey: Self.passphraseKey(profileId)) + deleteSecret(.keyPassphrase, for: profileId) } - // MARK: - TOTP Secret Storage - - func saveTOTPSecret(_ secret: String, for profileId: UUID) { - keychain.writeString(secret, forKey: Self.totpKey(profileId)) + @discardableResult + func saveTOTPSecret(_ secret: String, for profileId: UUID) -> Bool { + saveSecret(secret, .totpSecret, for: profileId) } func loadTOTPSecret(for profileId: UUID) -> String? { - resolveString(label: "SSH profile TOTP secret", profileId: profileId, forKey: Self.totpKey(profileId)) + resolveString(label: "SSH profile TOTP secret", profileId: profileId, secret: .totpSecret) } func deleteTOTPSecret(for profileId: UUID) { - keychain.delete(forKey: Self.totpKey(profileId)) - } - - private static func passwordKey(_ profileId: UUID) -> String { - "com.TablePro.sshprofile.password.\(profileId.uuidString)" + deleteSecret(.totpSecret, for: profileId) } - private static func passphraseKey(_ profileId: UUID) -> String { - "com.TablePro.sshprofile.keypassphrase.\(profileId.uuidString)" - } - - private static func totpKey(_ profileId: UUID) -> String { - "com.TablePro.sshprofile.totpsecret.\(profileId.uuidString)" + private static func key(_ secret: SSHSecret, _ profileId: UUID) -> String { + switch secret { + case .password: "com.TablePro.sshprofile.password.\(profileId.uuidString)" + case .keyPassphrase: "com.TablePro.sshprofile.keypassphrase.\(profileId.uuidString)" + case .totpSecret: "com.TablePro.sshprofile.totpsecret.\(profileId.uuidString)" + } } - private func resolveString(label: String, profileId: UUID, forKey key: String) -> String? { - keychain.readStringResult(forKey: key) + private func resolveString(label: String, profileId: UUID, secret: SSHSecret) -> String? { + keychain.readStringResult(forKey: Self.key(secret, profileId)) .value(label: "\(label) (profileId=\(profileId.uuidString))", logger: Self.logger) } } diff --git a/apple/TablePro/Core/Storage/SettingsSlice.swift b/apple/TablePro/Core/Storage/SettingsSlice.swift new file mode 100644 index 0000000000..989a4b0a1a --- /dev/null +++ b/apple/TablePro/Core/Storage/SettingsSlice.swift @@ -0,0 +1,41 @@ +import Combine +import Foundation + +// One settings category per object, so a write re-renders only the views that read that category. +@MainActor +final class SettingsSlice: ObservableObject { + @Published private var stored: Value + private let normalize: (Value) -> Value + private var onCommit: (@MainActor (_ old: Value, _ new: Value) -> Void)? + + init(_ initial: Value, normalize: @escaping (Value) -> Value = { $0 }) { + stored = initial + self.normalize = normalize + } + + var value: Value { + get { stored } + set { assign(newValue) } + } + + var publisher: Published.Publisher { $stored } + + func update(_ body: (inout Value) -> Void) { + var next = stored + body(&next) + assign(next) + } + + // Attached after init, so loading a value never saves it or marks it for sync. + func attach(_ onCommit: @escaping @MainActor (_ old: Value, _ new: Value) -> Void) { + self.onCommit = onCommit + } + + private func assign(_ newValue: Value) { + let candidate = normalize(newValue) + guard candidate != stored else { return } + let old = stored + stored = candidate + onCommit?(old, candidate) + } +} diff --git a/apple/TablePro/Models/AI/AIModels.swift b/apple/TablePro/Models/AI/AIModels.swift index d806eb1044..7ea2f4f765 100644 --- a/apple/TablePro/Models/AI/AIModels.swift +++ b/apple/TablePro/Models/AI/AIModels.swift @@ -1,12 +1,5 @@ -// -// AIModels.swift -// TablePro -// - import Foundation -// MARK: - AI Provider Type - enum AIProviderType: String, Codable, CaseIterable, Identifiable, Sendable { case copilot case chatgptCodex @@ -84,8 +77,7 @@ enum AIProviderType: String, Codable, CaseIterable, Identifiable, Sendable { } } - /// How the configured endpoint is turned into a request URL. Providers that reach a fixed - /// host ignore it, so they answer with `AIProviderFactory`'s own fallback transport. + // A provider that reaches a fixed host ignores it and answers with AIProviderFactory's fallback transport. var endpointStyle: AIEndpointStyle { switch self { case .claude: @@ -101,7 +93,6 @@ enum AIProviderType: String, Codable, CaseIterable, Identifiable, Sendable { } } - /// The types `OpenAICompatibleProvider` serves, which share one registration. static let openAICompatibleFamily: [AIProviderType] = [.openRouter, .openCode, .ollama, .llamaCpp, .mlx, .custom] var icon: BrandIcon { @@ -123,15 +114,11 @@ enum AIProviderType: String, Codable, CaseIterable, Identifiable, Sendable { } } -// MARK: - AI Provider Configuration - struct AIProviderConfig: Codable, Equatable, Identifiable, Sendable { let id: UUID var name: String var type: AIProviderType - /// Set on a `.custom` provider added from an `AIProviderPreset`. An id this build does not - /// know is kept as it stands, so a preset from a newer build survives a round trip through - /// this one and reads as a plain custom provider in the meantime. + // An id this build does not know is kept, so a newer build's preset survives a round trip through this one. var presetID: String? var model: String var endpoint: String @@ -161,14 +148,12 @@ struct AIProviderConfig: Codable, Equatable, Identifiable, Sendable { self.reasoningEffort = reasoningEffort } - /// The name is stored rather than derived, so a build without this preset still lists the - /// provider under the vendor's name. + // The name is stored, so a build without this preset still lists the provider under the vendor's name. init(preset: AIProviderPreset) { self.init(name: preset.displayName, type: .custom, presetID: preset.id) } - /// `id` and `type` are what make a row usable, so a row missing either one fails as a whole and - /// `AISettings` drops it. Every other field falls back on its own. + // A row missing its id or type fails as a whole and AISettings drops it; every other field falls back. init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) id = try container.decode(UUID.self, forKey: .id) @@ -188,7 +173,6 @@ struct AIProviderConfig: Codable, Equatable, Identifiable, Sendable { return AIProviderPreset.preset(withID: presetID) } - /// What kind of provider this is, as opposed to what the user named it. var kindName: String { preset?.displayName ?? type.displayName } var displayName: String { @@ -209,8 +193,6 @@ struct AIProviderConfig: Codable, Equatable, Identifiable, Sendable { } } -// MARK: - AI Connection Policy - enum AIConnectionPolicy: String, Codable, CaseIterable, Identifiable, Sendable { case alwaysAllow case askEachTime @@ -227,8 +209,6 @@ enum AIConnectionPolicy: String, Codable, CaseIterable, Identifiable, Sendable { } } -// MARK: - AI Chat Mode - enum AIChatMode: String, Codable, CaseIterable, Identifiable, Sendable { case ask case edit @@ -285,8 +265,6 @@ enum AIChatMode: String, Codable, CaseIterable, Identifiable, Sendable { } } -// MARK: - AI Settings - struct AISettings: Codable, Equatable, Sendable { var enabled: Bool var providers: [AIProviderConfig] @@ -302,14 +280,14 @@ struct AISettings: Codable, Equatable, Sendable { var maxToolRoundtripsEnabled: Bool var defaultConnectionPolicy: AIConnectionPolicy var chatMode: AIChatMode - /// Set from the composer's own context menu rather than the Settings window, because the only - /// place the highlight is worth thinking about is the field it wraps. + // Set from the composer's own context menu, not from Settings. var composerHighlightEnabled: Bool static let defaultInlineSuggestionDebounceMs: Int = 500 static let inlineSuggestionDebounceRange: ClosedRange = 100...3_000 static let defaultMaxToolRoundtrips: Int = 25 static let maxToolRoundtripsRange: ClosedRange = 5...200 + static let maxSchemaTablesRange: ClosedRange = 1...100 static let `default` = AISettings( enabled: true, @@ -413,13 +391,59 @@ struct AISettings: Codable, Equatable, Sendable { ) } - var effectiveMaxToolRoundtrips: Int? { - guard maxToolRoundtripsEnabled else { return nil } - return min( + var clampedMaxToolRoundtrips: Int { + min( max(maxToolRoundtrips, AISettings.maxToolRoundtripsRange.lowerBound), AISettings.maxToolRoundtripsRange.upperBound ) } + + var effectiveMaxToolRoundtrips: Int? { + guard maxToolRoundtripsEnabled else { return nil } + return clampedMaxToolRoundtrips + } + + // A synced or hand-edited value can be negative, and prefix(_:) traps on one. + var clampedMaxSchemaTables: Int { + min( + max(maxSchemaTables, AISettings.maxSchemaTablesRange.lowerBound), + AISettings.maxSchemaTablesRange.upperBound + ) + } + + func provider(withID id: UUID) -> AIProviderConfig? { + providers.first { $0.id == id } + } + + func upserting(_ provider: AIProviderConfig, makeActiveIfNone: Bool) -> AISettings { + var next = self + if let index = next.providers.firstIndex(where: { $0.id == provider.id }) { + next.providers[index] = provider + } else { + next.providers.append(provider) + } + if makeActiveIfNone, next.activeProvider == nil { + next.activeProviderID = provider.id + } + return next + } + + func removingProvider(_ id: UUID) -> AISettings { + var next = self + next.providers.removeAll { $0.id == id } + if next.activeProviderID == id { + next.activeProviderID = nil + } + return next + } + + // A provider another Mac removed stays removed: replacing never adds one back. + func replacingProvider(_ provider: AIProviderConfig) -> AISettings { + guard let index = providers.firstIndex(where: { $0.id == provider.id }) else { return self } + var next = self + next.providers[index] = provider + return next + } } struct AITokenUsage: Codable, Equatable, Sendable { diff --git a/apple/TablePro/Models/AI/AIProviderStatus.swift b/apple/TablePro/Models/AI/AIProviderStatus.swift index 84599b0fc4..6ae3a2ffda 100644 --- a/apple/TablePro/Models/AI/AIProviderStatus.swift +++ b/apple/TablePro/Models/AI/AIProviderStatus.swift @@ -1,12 +1,6 @@ -// -// AIProviderStatus.swift -// TablePro -// - import Foundation -// One answer to "can this provider answer right now", read by the Settings row, the provider sheet -// and the chat panel, so they never disagree. +// One answer to "can this provider answer right now", so the Settings row, the provider page and the chat panel agree. internal enum AIProviderStatus: Equatable, Sendable { case checking case ready(detail: String?) @@ -17,6 +11,7 @@ internal enum AIProviderStatus: Equatable, Sendable { case needsUpdate(version: String) case failed(message: String) case notConfigured + case notStarted internal var isReady: Bool { if case .ready = self { return true } @@ -34,13 +29,14 @@ internal enum AIProviderStatus: Equatable, Sendable { case .needsUpdate(let version): String(format: String(localized: "Claude Code %@ is too old"), version) case .failed(let message): message case .notConfigured: String(localized: "Not configured") + case .notStarted: String(localized: "Not started") } } // Only a state the user has to fix carries a symbol; a working or busy provider shows none. internal var severity: NoticeSeverity? { switch self { - case .checking, .ready, .signingIn: nil + case .checking, .ready, .signingIn, .notStarted: nil case .failed: .error case .needsAPIKey, .needsSignIn, .needsInstall, .needsUpdate, .notConfigured: .warning } @@ -51,7 +47,8 @@ internal enum AIProviderStatus: Equatable, Sendable { hasAPIKey: Bool, oauthState: OAuthAuthState?, serviceError: String?, - claudeAgent: ClaudeAgentService.InstallState + claudeAgent: ClaudeAgentService.InstallState, + serviceStopped: Bool = false ) -> AIProviderStatus { switch provider.authStyle { case .apiKey: @@ -61,8 +58,8 @@ internal enum AIProviderStatus: Equatable, Sendable { return endpointStatus(provider.endpoint.isEmpty ? provider.defaultEndpoint : provider.endpoint) case .oauth: if let serviceError, !serviceError.isEmpty { return .failed(message: serviceError) } - // No state yet: the sign-in lives in a service that has not answered. - guard let oauthState else { return .checking } + // No state yet: the sign-in lives in a service that has not answered, or has not been started. + guard let oauthState else { return serviceStopped ? .notStarted : .checking } switch oauthState { case .signedIn(let identity): return .ready(detail: identity.isEmpty diff --git a/apple/TablePro/Models/Connection/CredentialProfile.swift b/apple/TablePro/Models/Connection/CredentialProfile.swift index 19813c912a..726a4e5fce 100644 --- a/apple/TablePro/Models/Connection/CredentialProfile.swift +++ b/apple/TablePro/Models/Connection/CredentialProfile.swift @@ -1,21 +1,10 @@ -// -// CredentialProfile.swift -// TablePro -// - import Foundation -/// Where a profile's password comes from, which is the same vocabulary a connection already has. -/// -/// The payload of `.source` never leaves this Mac. It can name a shell command, and a command that -/// arrived over iCloud or inside a shared export file would be one this Mac never agreed to run. +// The .source payload never leaves this Mac: it can name a shell command this Mac never agreed to run. enum CredentialPasswordMode: Hashable, Sendable { - /// In the Keychain, under the profile's own id. case stored - /// Asked for on every connect. case prompt case source(PasswordSource) - /// Looked up in `~/.pgpass` by host, port, database and username. case pgpass } @@ -38,8 +27,7 @@ extension CredentialPasswordMode: Codable { case .pgpass: self = .pgpass case .source: - /// A malformed payload becomes a prompt rather than failing the whole store: one - /// unreadable profile must not take every other profile down with it. + // A malformed payload becomes a prompt, so one bad profile does not fail the whole store. guard let source = PasswordSource.resilientlyDecoded(from: container, forKey: .source) else { self = .prompt return @@ -64,24 +52,14 @@ extension CredentialPasswordMode: Codable { } } -/// One set of database credentials, named, that any number of connections point at. -/// -/// The point of the type is that the secret exists once. A connection linked to a profile holds no -/// Keychain item of its own, so rotating the password is one edit rather than one edit per -/// connection, which is what issue #2853 asked for. +// The secret exists once: a linked connection holds no Keychain item of its own (#2853). struct CredentialProfile: Identifiable, Hashable, Codable, Sendable { let id: UUID var name: String var username: String var passwordMode: CredentialPasswordMode - /// Plugin-declared secure fields this profile carries, such as an AWS secret access key. The - /// values are in the Keychain under the profile's id; only the ids are stored here. - /// - /// There is no database type on the profile, because a connection only ever reads the fields - /// its own type declares: `DatabaseDriverFactory.buildAdditionalFields` loops over - /// `secureConnectionFieldIds(for: connection.type)`, so a field another engine's profile - /// carries is never looked at. + // No database type here: a connection reads only the secure fields its own type declares. var secureFieldIds: [String] var sortOrder: Int @@ -115,7 +93,6 @@ struct CredentialProfile: Identifiable, Hashable, Codable, Sendable { sortOrder = try container.decodeIfPresent(Int.self, forKey: .sortOrder) ?? 0 } - /// What the picker and the profile list show beside the name. var summary: String { let trimmed = username.trimmingCharacters(in: .whitespaces) guard !trimmed.isEmpty else { return passwordMode.displayName } @@ -123,18 +100,54 @@ struct CredentialProfile: Identifiable, Hashable, Codable, Sendable { } } -extension CredentialPasswordMode { +// One vocabulary for the editor's picker, the profile list and the connection form. +enum CredentialPasswordKind: String, CaseIterable, Identifiable, Sendable { + case stored, prompt, pgpass, source + + var id: String { rawValue } + var displayName: String { switch self { - case .stored: String(localized: "Saved password") - case .prompt: String(localized: "Ask every time") + case .stored: String(localized: "Saved in Keychain") + case .prompt: String(localized: "Ask Every Time") case .pgpass: String(localized: "~/.pgpass") - case .source(.vaultDatabaseRole): String(localized: "Vault database role") - case .source: String(localized: "Password source") + case .source: String(localized: "Password Source") } } - /// Whether this mode keeps a secret in the Keychain under the profile's id. + var help: String { + switch self { + case .stored: + String(localized: "Saved in the Keychain once and used by every connection on this profile.") + case .prompt: + String(localized: "Every connection using this profile asks for the password once each time TablePro runs.") + case .pgpass: + String(localized: """ + Looked up in ~/.pgpass by the host, port, database and username of the PostgreSQL-family connection \ + that is opening. Other connections ask for the password. + """) + case .source: + String(localized: "It stays on this Mac and never syncs, because it can name a command to run.") + } + } +} + +extension CredentialPasswordMode { + var kind: CredentialPasswordKind { + switch self { + case .stored: .stored + case .prompt: .prompt + case .pgpass: .pgpass + case .source: .source + } + } + + // A Vault role also supplies the username, so the row and the connection form name it. + var displayName: String { + if case .source(.vaultDatabaseRole) = self { return String(localized: "Vault database role") } + return kind.displayName + } + var usesStoredSecret: Bool { if case .stored = self { return true } return false diff --git a/apple/TablePro/Models/Connection/SSHServerDraft.swift b/apple/TablePro/Models/Connection/SSHServerDraft.swift new file mode 100644 index 0000000000..02049977ae --- /dev/null +++ b/apple/TablePro/Models/Connection/SSHServerDraft.swift @@ -0,0 +1,190 @@ +import Foundation +import TableProSSHConfig +import TableProSSHTransport + +extension SSHProfile { + // user@host, plus :port when it is not the default; host alone when there is no user. + var address: String { + let trimmedHost = host.trimmingCharacters(in: .whitespaces) + let trimmedUser = username.trimmingCharacters(in: .whitespaces) + var address = trimmedUser.isEmpty ? trimmedHost : "\(trimmedUser)@\(trimmedHost)" + if let port, port != 22 { + address += ":\(String(port))" + } + return address + } +} + +enum SSHSecret: CaseIterable, Hashable, Sendable { + case password + case keyPassphrase + case totpSecret +} + +struct SSHServerDraft: Equatable, Sendable { + var host = "" + var port = "" + var username = "" + var authMethod: SSHAuthMethod = .password + var password = "" + var privateKeyPath = "" + var keyPassphrase = "" + var agentSocketOption: SSHAgentSocketOption = .systemDefault + var customAgentSocketPath = "" + var selectedConfigHost = "" + var jumpHosts: [SSHJumpHost] = [] + var totpMode: TOTPMode = .none + var totpSecret = "" + var totpAlgorithm: TOTPAlgorithm = .sha1 + var totpDigits = 6 + var totpPeriod = 30 + + init() {} + + init(profile: SSHProfile) { + host = profile.host + port = profile.port.map(String.init) ?? "" + username = profile.username + authMethod = profile.authMethod + privateKeyPath = profile.privateKeyPath + jumpHosts = profile.jumpHosts + totpMode = profile.totpMode + totpAlgorithm = profile.totpAlgorithm + totpDigits = profile.totpDigits + totpPeriod = profile.totpPeriod + applyAgentSocketPath(profile.agentSocketPath) + } + + var trimmedHost: String { + host.trimmingCharacters(in: .whitespacesAndNewlines) + } + + var trimmedUsername: String { + username.trimmingCharacters(in: .whitespacesAndNewlines) + } + + var portNumber: Int? { + Int(port.trimmingCharacters(in: .whitespaces)) + } + + var portIsValid: Bool { + let trimmed = port.trimmingCharacters(in: .whitespaces) + guard !trimmed.isEmpty else { return true } + return Int(trimmed).map { (1...65_535).contains($0) } ?? false + } + + var resolvedAgentSocketPath: String { + agentSocketOption.resolvedPath(customPath: customAgentSocketPath) + } + + var validationIssues: [String] { + var issues: [String] = [] + if trimmedHost.isEmpty { + issues.append(String(localized: "SSH host is required")) + } + if !portIsValid { + issues.append(String(localized: "SSH port must be between 1 and 65535")) + } + if !jumpHosts.allSatisfy(\.isValid) { + issues.append(String(localized: "Jump host configuration is invalid")) + } + return issues + } + + func applies(_ secret: SSHSecret) -> Bool { + switch secret { + case .password: authMethod == .password || authMethod == .keyboardInteractive + case .keyPassphrase: authMethod == .privateKey + case .totpSecret: totpMode == .autoGenerate + } + } + + func value(of secret: SSHSecret) -> String { + switch secret { + case .password: password + case .keyPassphrase: keyPassphrase + case .totpSecret: totpSecret + } + } + + var filledSecrets: Set { + Set(SSHSecret.allCases.filter { !value(of: $0).isEmpty }) + } + + mutating func setValue(_ value: String, of secret: SSHSecret) { + switch secret { + case .password: password = value + case .keyPassphrase: keyPassphrase = value + case .totpSecret: totpSecret = value + } + } + + func configuration() -> SSHConfiguration { + SSHConfiguration( + enabled: true, + host: trimmedHost, + port: portNumber, + username: trimmedUsername, + authMethod: authMethod, + privateKeyPath: privateKeyPath, + agentSocketPath: resolvedAgentSocketPath, + jumpHosts: jumpHosts, + totpMode: totpMode, + totpAlgorithm: totpAlgorithm, + totpDigits: totpDigits, + totpPeriod: totpPeriod + ) + } + + func apply(to profile: inout SSHProfile) { + profile.host = trimmedHost + profile.port = portNumber + profile.username = trimmedUsername + profile.authMethod = authMethod + profile.privateKeyPath = privateKeyPath + profile.agentSocketPath = resolvedAgentSocketPath + profile.jumpHosts = jumpHosts + profile.totpMode = totpMode + profile.totpAlgorithm = totpAlgorithm + profile.totpDigits = totpDigits + profile.totpPeriod = totpPeriod + } + + var testCredentials: SSHTunnelCredentials { + SSHTunnelCredentials( + sshPassword: password.isEmpty ? nil : password, + keyPassphrase: keyPassphrase.isEmpty ? nil : keyPassphrase, + totpSecret: totpSecret.isEmpty ? nil : totpSecret, + keyboardInteractivePromptProvider: nil + ) + } + + mutating func applyAgentSocketPath(_ socketPath: String) { + let option = SSHAgentSocketOption(socketPath: socketPath) + agentSocketOption = option + customAgentSocketPath = option == .custom ? socketPath.trimmingCharacters(in: .whitespacesAndNewlines) : "" + } + + // Picking a config host also points the server at it, in one write. + mutating func selectConfigHost(_ configHost: String) { + selectedConfigHost = configHost + if !configHost.isEmpty { + host = configHost + } + } + + mutating func addJumpHost() { + jumpHosts.append(SSHJumpHost()) + } + + mutating func removeJumpHost(id: UUID) { + jumpHosts.removeAll { $0.id == id } + } + + mutating func moveJumpHost(id: UUID, by offset: Int) { + guard let index = jumpHosts.firstIndex(where: { $0.id == id }) else { return } + let destination = index + offset + guard jumpHosts.indices.contains(destination) else { return } + jumpHosts.swapAt(index, destination) + } +} diff --git a/apple/TablePro/Models/Connection/SSHTunnelFormState.swift b/apple/TablePro/Models/Connection/SSHTunnelFormState.swift index aad25c6c8f..24ebc6a1a5 100644 --- a/apple/TablePro/Models/Connection/SSHTunnelFormState.swift +++ b/apple/TablePro/Models/Connection/SSHTunnelFormState.swift @@ -1,26 +1,16 @@ -// -// SSHTunnelFormState.swift -// TablePro -// - import Foundation import TableProSSHConfig import TableProSSHTransport -/// Encapsulates all SSH tunnel UI state for the connection form. -/// Replaces the 23 scattered @State variables in ConnectionFormView. struct SSHTunnelFormState { - // Mode var enabled: Bool = false var profileId: UUID? var profiles: [SSHProfile] = [] - // Sheet presentation var showingCreateProfile: Bool = false var editingProfile: SSHProfile? var showingSaveAsProfile: Bool = false - // Inline config fields var host: String = "" var port: String = "" var username: String = "" @@ -39,21 +29,18 @@ struct SSHTunnelFormState { var totpDigits: Int = 6 var totpPeriod: Int = 30 - /// What the keychain held for the inline namespace when the form opened, so an emptied field - /// can be told apart from a keychain that could not be read. + // What the Keychain held when the form opened, so an emptied field is told apart from an unreadable Keychain. private(set) var storedPasswordState: ConnectionStorage.StoredSecretState = .absent private(set) var storedKeyPassphraseState: ConnectionStorage.StoredSecretState = .absent + private(set) var loadedTOTPSecret = false + // Secrets read from a profile's Keychain stay in the fields after a switch to inline. + private(set) var profileSecrets: Set = [] - // Remote database file var remoteFilePath: String = "" - /// New connections default to running on the server, which is what a user reaching for a remote - /// SQLite database wants; loading an existing connection overwrites this with its saved value, - /// and a connection saved before the live mode existed decodes as the read-only copy. + // New connections run on the server; a connection saved before the live mode existed decodes as the copy. var remoteFileAccess: RemoteFileAccess = .onServer - // MARK: - Computed Properties - var selectedProfile: SSHProfile? { guard let id = profileId else { return nil } return profiles.first { $0.id == id } @@ -63,7 +50,55 @@ struct SSHTunnelFormState { agentSocketOption.resolvedPath(customPath: customAgentSocketPath) } - // MARK: - Build Methods + var server: SSHServerDraft { + get { + var draft = SSHServerDraft() + draft.host = host + draft.port = port + draft.username = username + draft.authMethod = authMethod + draft.password = password + draft.privateKeyPath = privateKeyPath + draft.keyPassphrase = keyPassphrase + draft.agentSocketOption = agentSocketOption + draft.customAgentSocketPath = customAgentSocketPath + draft.selectedConfigHost = selectedConfigHost + draft.jumpHosts = jumpHosts + draft.totpMode = totpMode + draft.totpSecret = totpSecret + draft.totpAlgorithm = totpAlgorithm + draft.totpDigits = totpDigits + draft.totpPeriod = totpPeriod + return draft + } + set { + host = newValue.host + port = newValue.port + username = newValue.username + authMethod = newValue.authMethod + password = newValue.password + privateKeyPath = newValue.privateKeyPath + keyPassphrase = newValue.keyPassphrase + agentSocketOption = newValue.agentSocketOption + customAgentSocketPath = newValue.customAgentSocketPath + selectedConfigHost = newValue.selectedConfigHost + jumpHosts = newValue.jumpHosts + totpMode = newValue.totpMode + totpSecret = newValue.totpSecret + totpAlgorithm = newValue.totpAlgorithm + totpDigits = newValue.totpDigits + totpPeriod = newValue.totpPeriod + } + } + + // Revealing a secret the Keychain handed over asks for authentication first. + var savedSecrets: Set { + var secrets: Set = [] + if storedPasswordState != .absent { secrets.insert(.password) } + if storedKeyPassphraseState != .absent { secrets.insert(.keyPassphrase) } + if loadedTOTPSecret { secrets.insert(.totpSecret) } + return secrets.union(profileSecrets) + } func buildInlineConfig() -> SSHConfiguration { SSHConfiguration( @@ -84,9 +119,7 @@ struct SSHTunnelFormState { ) } - /// A profile describes a server, not a file, so the remote path is overlaid onto whichever - /// configuration is in play. Two connections through one bastion routinely name two different - /// databases, so the path cannot live on the profile. + // The remote path lives on the connection: two connections through one bastion name different files. func buildSSHConfig() -> SSHConfiguration { guard let profileId, let profile = profiles.first(where: { $0.id == profileId }) else { return buildInlineConfig() @@ -97,8 +130,6 @@ struct SSHTunnelFormState { return config } - // MARK: - Load Methods - mutating func load(from connection: DatabaseConnection) { switch connection.sshTunnelMode { case .disabled: @@ -122,22 +153,31 @@ struct SSHTunnelFormState { @MainActor mutating func loadSecrets(connectionId: UUID, storage: ConnectionStorage) { if case .profile(let profileId, _) = buildTunnelMode() { - // Profile-mode: load secrets from profile keychain namespace - password = SSHProfileStorage.shared.loadSSHPassword(for: profileId) ?? "" - keyPassphrase = SSHProfileStorage.shared.loadKeyPassphrase(for: profileId) ?? "" - totpSecret = SSHProfileStorage.shared.loadTOTPSecret(for: profileId) ?? "" + adoptProfileSecrets( + password: SSHProfileStorage.shared.loadSSHPassword(for: profileId) ?? "", + keyPassphrase: SSHProfileStorage.shared.loadKeyPassphrase(for: profileId) ?? "", + totpSecret: SSHProfileStorage.shared.loadTOTPSecret(for: profileId) ?? "" + ) } else { - // Inline/disabled: load from connection keychain namespace + profileSecrets = [] storedPasswordState = storage.sshPasswordState(for: connectionId) storedKeyPassphraseState = storage.keyPassphraseState(for: connectionId) password = storage.loadSSHPassword(for: connectionId) ?? "" keyPassphrase = storage.loadKeyPassphrase(for: connectionId) ?? "" totpSecret = storage.loadTOTPSecret(for: connectionId) ?? "" + loadedTOTPSecret = !totpSecret.isEmpty } } - /// The user emptied an inline SSH secret that had a value. Without this the old secret stays in - /// the keychain and the next connect still authenticates with it. + mutating func adoptProfileSecrets(password: String, keyPassphrase: String, totpSecret: String) { + self.password = password + self.keyPassphrase = keyPassphrase + self.totpSecret = totpSecret + loadedTOTPSecret = false + profileSecrets = server.filledSecrets + } + + // Without this the old inline secret stays in the Keychain and the next connect still uses it. var clearsStoredPassword: Bool { password.isEmpty && storedPasswordState == .stored } @@ -146,7 +186,6 @@ struct SSHTunnelFormState { keyPassphrase.isEmpty && storedKeyPassphraseState == .stored } - /// Build the SSHTunnelMode for saving to the connection. func buildTunnelMode() -> SSHTunnelMode { guard enabled else { return .disabled } if let profileId, let profile = profiles.first(where: { $0.id == profileId }) { @@ -158,8 +197,6 @@ struct SSHTunnelFormState { return .inline(buildInlineConfig()) } - // MARK: - Mutation Methods - mutating func disable() { enabled = false profileId = nil @@ -179,6 +216,7 @@ struct SSHTunnelFormState { totpAlgorithm = .sha1 totpDigits = 6 totpPeriod = 30 + profileSecrets = [] } mutating func switchToInline(fromProfile profile: SSHProfile) { diff --git a/apple/TablePro/Models/Settings/AppSettings.swift b/apple/TablePro/Models/Settings/AppSettings.swift index eda5295543..d64571ceea 100644 --- a/apple/TablePro/Models/Settings/AppSettings.swift +++ b/apple/TablePro/Models/Settings/AppSettings.swift @@ -1,16 +1,6 @@ -// -// AppSettings.swift -// TablePro -// -// Application settings models - pure data structures -// - import Foundation import SwiftUI - -// MARK: - Appearance Settings - enum AppAppearanceMode: String, Codable, CaseIterable { case light case dark @@ -48,9 +38,6 @@ struct AppearanceSettings: Codable, Equatable { } } - -// MARK: - Data Grid Settings - enum DataGridRowHeight: Int, Codable, CaseIterable, Identifiable { case compact = 20 case normal = 24 @@ -216,44 +203,26 @@ struct DataGridSettings: Codable, Equatable { resultSetsKeptPerRun = container.decodeSetting(.resultSetsKeptPerRun, default: fallback.resultSetsKeptPerRun) } - // MARK: - Validated Properties - var validatedNullDisplay: String { - let sanitized = nullDisplay.sanitized - let maxLength = SettingsValidationRules.nullDisplayMaxLength - - if sanitized.isEmpty { - return "NULL" - } else if sanitized.count > maxLength { - return String(sanitized.prefix(maxLength)) - } - return sanitized + Self.normalizedNullDisplay(nullDisplay) } var validatedDefaultPageSize: Int { defaultPageSize.clamped(to: SettingsValidationRules.defaultPageSizeRange) } - var nullDisplayValidationError: String? { - let sanitized = nullDisplay.sanitized + // Blank is not an error: the field's prompt reads NULL, and a blank entry commits as NULL. + static func nullDisplayValidationError(for text: String) -> String? { let maxLength = SettingsValidationRules.nullDisplayMaxLength - - if sanitized.isEmpty { - return String(localized: "NULL display cannot be empty") - } else if sanitized.count > maxLength { - return String(format: String(localized: "NULL display must be %d characters or less"), maxLength) - } else if nullDisplay != sanitized { - return String(localized: "NULL display contains invalid characters (newlines/tabs)") - } - return nil + guard text.sanitized.count > maxLength else { return nil } + return String(format: String(localized: "Up to %lld characters"), maxLength) } - var defaultPageSizeValidationError: String? { - let range = SettingsValidationRules.defaultPageSizeRange - if defaultPageSize < range.lowerBound || defaultPageSize > range.upperBound { - return String(format: String(localized: "Page size must be between %@ and %@"), range.lowerBound.formatted(), range.upperBound.formatted()) - } - return nil + // Trimmed again after the cut, so a prefix that ends in a space never stores one. + static func normalizedNullDisplay(_ text: String) -> String { + let limited = String(text.sanitized.prefix(SettingsValidationRules.nullDisplayMaxLength)) + .trimmingCharacters(in: .whitespaces) + return limited.isEmpty ? "NULL" : limited } // Nil keeps every result. @@ -266,21 +235,25 @@ struct DataGridSettings: Codable, Equatable { return queryResultRowCap.clamped(to: SettingsValidationRules.queryResultRowCapRange) } - var queryResultRowCapValidationError: String? { - let range = SettingsValidationRules.queryResultRowCapRange - if queryResultRowCap != 0 && (queryResultRowCap < range.lowerBound || queryResultRowCap > range.upperBound) { - return String( - format: String(localized: "Query result row cap must be between %@ and %@"), - range.lowerBound.formatted(), - range.upperBound.formatted() - ) + var queryResultLimit: Int? { + guard truncateQueryResults else { return nil } + let cap = validatedQueryResultRowCap + return cap > 0 ? cap : nil + } + + // No limit keeps the stored cap, so turning the limit back on returns to it. + func withQueryResultLimit(_ limit: Int?) -> DataGridSettings { + var updated = self + if let limit { + updated.truncateQueryResults = true + updated.queryResultRowCap = limit + } else { + updated.truncateQueryResults = false } - return nil + return updated } } -// MARK: - Value Color Settings - struct ValueColorSettings: Codable, Equatable { var colorsValuesByType: Bool @@ -296,8 +269,6 @@ struct ValueColorSettings: Codable, Equatable { } } -// MARK: - History Settings - struct HistorySettings: Codable, Equatable { var maxEntries: Int // 0 = unlimited var maxDays: Int // 0 = unlimited @@ -328,8 +299,6 @@ struct HistorySettings: Codable, Equatable { keepRewindHistory = container.decodeSetting(.keepRewindHistory, default: fallback.keepRewindHistory) } - // MARK: - Validated Properties - var validatedMaxEntries: Int { max(0, maxEntries) } @@ -337,24 +306,8 @@ struct HistorySettings: Codable, Equatable { var validatedMaxDays: Int { max(0, maxDays) } - - var maxEntriesValidationError: String? { - if maxEntries < 0 { - return String(localized: "Maximum entries cannot be negative") - } - return nil - } - - var maxDaysValidationError: String? { - if maxDays < 0 { - return String(localized: "Maximum days cannot be negative") - } - return nil - } } -// MARK: - Tab Settings - struct TabSettings: Codable, Equatable { var enablePreviewTabs: Bool = true static let `default` = TabSettings() diff --git a/apple/TablePro/Models/Settings/ConnectionHealthCheck.swift b/apple/TablePro/Models/Settings/ConnectionHealthCheck.swift index a25c2cc721..6c4d204f34 100644 --- a/apple/TablePro/Models/Settings/ConnectionHealthCheck.swift +++ b/apple/TablePro/Models/Settings/ConnectionHealthCheck.swift @@ -1,20 +1,6 @@ -// -// ConnectionHealthCheck.swift -// TablePro -// - import Foundation -/// How often TablePro asks an open connection whether it still works. -/// -/// The check is a real query on almost every engine, so a connection nobody is using still costs -/// the server about 2,880 of them a day. That is invisible on a database you own and expensive on -/// one you rent: a serverless compute suspends only after some minutes with no queries, so a -/// steady heartbeat holds it awake and billing around the clock (#2700). -/// -/// `onDemand` is the answer for those, and it is not the same as having no answer. TablePro checks -/// the connection the first time it is used after a quiet spell instead, which costs one round -/// trip the user's own action paid for, rather than a stream of them nobody asked for. +// Every check is a real query, so a steady heartbeat keeps a serverless database awake and billing (#2700). internal enum ConnectionHealthCheck: Int, Codable, CaseIterable, Identifiable, Sendable { case onDemand = 0 case every30Seconds = 30 @@ -25,28 +11,21 @@ internal enum ConnectionHealthCheck: Int, Codable, CaseIterable, Identifiable, S internal var title: String { switch self { - case .onDemand: return String(localized: "Only when I use the connection") + case .onDemand: return String(localized: "Only when used") case .every30Seconds: return String(localized: "Every 30 seconds") case .every5Minutes: return String(localized: "Every 5 minutes") case .every15Minutes: return String(localized: "Every 15 minutes") } } - /// How long to wait between checks, or nil when nothing is scheduled at all. Nil is why - /// `onDemand` starts no monitor rather than starting one with a very long interval: a task - /// that never has anything to do is still a task that wakes up. + // Nil starts no monitor at all, rather than one with a long interval that still wakes up. internal var interval: Duration? { guard rawValue > 0 else { return nil } return .seconds(rawValue) } - /// How recently the connection must have answered for TablePro to take its word for it. - /// - /// One value for every setting rather than one per case, because it answers a question the - /// poll rate has no part in: how long a socket that worked stays worth believing. At the - /// default it never fires, since a check every 30 seconds keeps the answer far fresher than - /// this; on the long intervals and on `onDemand` it is what makes the first action after a - /// quiet spell verify before it runs. + // How long an answer stays believable whatever the poll rate; on long intervals and on demand it makes + // the first action after a quiet spell verify before it runs. internal static let freshness: Duration = .seconds(300) internal static func isFresh(_ lastVerifiedAt: Date, now: Date = Date()) -> Bool { diff --git a/apple/TablePro/Models/Settings/EditorSettings.swift b/apple/TablePro/Models/Settings/EditorSettings.swift index 61c096077e..243c81f3fa 100644 --- a/apple/TablePro/Models/Settings/EditorSettings.swift +++ b/apple/TablePro/Models/Settings/EditorSettings.swift @@ -1,9 +1,6 @@ -// -// EditorSettings.swift -// TablePro -// - import AppKit +import Combine +import CoreText import Foundation import TableProAutocomplete @@ -15,26 +12,28 @@ internal struct FontFamilyOption: Equatable, Identifiable, Sendable { internal enum EditorFontResolver { static let systemMonoId = "System Mono" - static let availableMonospacedFamilies: [FontFamilyOption] = { - var options: [FontFamilyOption] = [ - FontFamilyOption(id: systemMonoId, displayName: systemMonoId) - ] + // One CoreText query for monospaced faces; asking NSFontManager family by family took 83 to 863 ms. + static func availableMonospacedFamilies() -> [FontFamilyOption] { + familyOptions(from: monospacedFamilyNames()) + } - let familyNames = NSFontManager.shared.availableFontFamilies - .filter { $0 != systemMonoId } - .filter(isMonospacedFamily) - .sorted { lhs, rhs in - lhs.localizedCaseInsensitiveCompare(rhs) == .orderedAscending - } + static func familyOptions(from familyNames: [String]) -> [FontFamilyOption] { + let names = Set(familyNames) + .filter { !$0.hasPrefix(".") && $0 != systemMonoId } + .sorted { $0.localizedCaseInsensitiveCompare($1) == .orderedAscending } + return [FontFamilyOption(id: systemMonoId, displayName: systemMonoId)] + + names.map { FontFamilyOption(id: $0, displayName: $0) } + } - var seen: Set = [systemMonoId] - for family in familyNames where !seen.contains(family) { - seen.insert(family) - options.append(FontFamilyOption(id: family, displayName: family)) + private static func monospacedFamilyNames() -> [String] { + let traits = [kCTFontSymbolicTrait: CTFontSymbolicTraits.traitMonoSpace.rawValue] as CFDictionary + let descriptor = CTFontDescriptorCreateWithAttributes([kCTFontTraitsAttribute: traits] as CFDictionary) + let collection = CTFontCollectionCreateWithFontDescriptors([descriptor] as CFArray, nil) + guard let matches = CTFontCollectionCreateMatchingFontDescriptors(collection) as? [CTFontDescriptor] else { + return [] } - - return options - }() + return matches.compactMap { CTFontDescriptorCopyAttribute($0, kCTFontFamilyNameAttribute) as? String } + } static func resolve(familyId: String, size: CGFloat) -> NSFont { guard familyId != systemMonoId else { @@ -49,16 +48,34 @@ internal enum EditorFontResolver { return NSFont.monospacedSystemFont(ofSize: size, weight: .regular) } +} + +// The font pickers' list, rebuilt when a font is installed or removed while the app runs. +@MainActor +internal final class MonospacedFontFamilies: ObservableObject { + internal static let shared = MonospacedFontFamilies() + + @Published internal private(set) var families: [FontFamilyOption] + private let load: () -> [FontFamilyOption] + private var fontSetChanges: AnyCancellable? - static func isAvailable(familyId: String) -> Bool { - guard familyId != systemMonoId else { return true } - return isMonospacedFamily(familyId) + internal init( + notificationCenter: NotificationCenter = .default, + load: @escaping () -> [FontFamilyOption] = { EditorFontResolver.availableMonospacedFamilies() } + ) { + self.load = load + families = load() + fontSetChanges = notificationCenter.publisher(for: NSFont.fontSetChangedNotification) + .receive(on: DispatchQueue.main) + .sink { [weak self] _ in + self?.reload() + } } - private static func isMonospacedFamily(_ familyId: String) -> Bool { - let descriptor = NSFontDescriptor(fontAttributes: [.family: familyId]) - guard let font = NSFont(descriptor: descriptor, size: 12) else { return false } - return font.fontDescriptor.symbolicTraits.contains(.monoSpace) + internal func reload() { + let latest = load() + guard latest != families else { return } + families = latest } } @@ -73,11 +90,10 @@ internal enum EditorKeyBindings: String, Codable, CaseIterable { case emacs } -/// Editor settings struct EditorSettings: Codable, Equatable { var showLineNumbers: Bool var highlightCurrentLine: Bool - var tabWidth: Int // 2, 4, or 8 spaces + var tabWidth: Int var wordWrap: Bool var keyBindings: EditorKeyBindings var keywordCase: SQLKeywordCase @@ -156,9 +172,7 @@ struct EditorSettings: Codable, Equatable { ) } - // Spelled out so `uppercaseKeywords` and `vimModeEnabled` stay on the wire after their properties became - // `keywordCase` and `keyBindings`. Editor settings sync as one JSON blob, so it carries both the key an older - // build reads and the key this one writes. + // Synced as one blob, so the legacy uppercaseKeywords and vimModeEnabled keys stay for older builds. private enum CodingKeys: String, CodingKey { case showLineNumbers case highlightCurrentLine @@ -212,7 +226,6 @@ struct EditorSettings: Codable, Equatable { try container.encode(jsonViewerPreferredMode, forKey: .jsonViewerPreferredMode) } - /// Clamped tab width (1-16) var clampedTabWidth: Int { min(max(tabWidth, 1), 16) } diff --git a/apple/TablePro/Models/Settings/GeneralSettings.swift b/apple/TablePro/Models/Settings/GeneralSettings.swift index 4babe30e3f..97de3be62a 100644 --- a/apple/TablePro/Models/Settings/GeneralSettings.swift +++ b/apple/TablePro/Models/Settings/GeneralSettings.swift @@ -1,8 +1,3 @@ -// -// GeneralSettings.swift -// TablePro -// - import Foundation enum StartupBehavior: String, Codable, CaseIterable, Identifiable { @@ -118,6 +113,7 @@ struct GeneralSettings: Codable, Equatable { startupBehavior = container.decodeSetting(.startupBehavior, default: fallback.startupBehavior) language = container.decodeSetting(.language, default: fallback.language) queryTimeoutSeconds = container.decodeSetting(.queryTimeoutSeconds, default: fallback.queryTimeoutSeconds) + .clamped(to: DatabaseConnection.queryTimeoutSecondsRange) shareAnalytics = container.decodeSetting(.shareAnalytics, default: fallback.shareAnalytics) showRecentTables = container.decodeSetting(.showRecentTables, default: fallback.showRecentTables) showObjectComments = container.decodeSetting(.showObjectComments, default: fallback.showObjectComments) @@ -129,3 +125,17 @@ struct GeneralSettings: Codable, Equatable { connectionHealthCheck = container.decodeSetting(.connectionHealthCheck, default: fallback.connectionHealthCheck) } } + +extension GeneralSettings { + static let standardQueryTimeouts = [10, 20, 30, 40, 50, 60, 90, 120, 180, 300, 600] + + // A stored value off the standard list gets its own item, so the pop-up never draws blank. + static func queryTimeoutChoices(including current: Int) -> [Int] { + guard current > 0, !standardQueryTimeouts.contains(current) else { return standardQueryTimeouts } + return (standardQueryTimeouts + [current]).sorted() + } + + static func queryTimeoutTitle(_ seconds: Int, locale: Locale = .autoupdatingCurrent) -> String { + SettingsFormat.duration(seconds: seconds, locale: locale) + } +} diff --git a/apple/TablePro/Models/Settings/LanguageLaunchState.swift b/apple/TablePro/Models/Settings/LanguageLaunchState.swift new file mode 100644 index 0000000000..0de1818db6 --- /dev/null +++ b/apple/TablePro/Models/Settings/LanguageLaunchState.swift @@ -0,0 +1,26 @@ +import Foundation + +// Captured at launch: a language change needs a relaunch, so a pending choice is compared with this. +@MainActor +enum LanguageLaunchState { + private static var launch = LaunchLanguage() + + static var language: AppLanguage { + launch.capture(AppSettingsManager.shared.general.language) + } + + static func record() { + launch.capture(AppSettingsManager.shared.general.language) + } +} + +struct LaunchLanguage { + private(set) var language: AppLanguage? + + @discardableResult + mutating func capture(_ current: AppLanguage) -> AppLanguage { + if let language { return language } + language = current + return current + } +} diff --git a/apple/TablePro/Models/Settings/MCPConnectionApproval.swift b/apple/TablePro/Models/Settings/MCPConnectionApproval.swift index c4a5e17901..96b6d8dbfe 100644 --- a/apple/TablePro/Models/Settings/MCPConnectionApproval.swift +++ b/apple/TablePro/Models/Settings/MCPConnectionApproval.swift @@ -1,14 +1,7 @@ import Foundation -/// How the MCP server asks before a client may reach a saved connection. -/// -/// This is MCP's own decision and is deliberately not `AIConnectionPolicy`. That policy answers a -/// different question, whether a connection's schema may be sent to a model provider, and the -/// connection form describes it as governing in-app AI agents. Both of its controls disappear when -/// AI features are off, which left the MCP prompt with no control at all. -/// -/// `alwaysApprove` is the permissive end. `AIConnectionPolicy.never` is the restrictive end of the -/// other policy and still denies here, so the two spellings of "never" never meet. +// MCP's own gate. AIConnectionPolicy answers whether a schema may reach a model provider, and its +// controls hide when AI is off, so it cannot be this one. Its "never" still denies here. enum MCPConnectionApproval: String, Codable, CaseIterable, Identifiable, Sendable { case everyTime case oncePerConnection @@ -29,7 +22,7 @@ enum MCPConnectionApproval: String, Codable, CaseIterable, Identifiable, Sendabl case .everyTime: return String(localized: "Every call that reaches a connection asks first.") case .oncePerConnection: - return String(localized: "The first call asks. The answer is remembered for that client until you revoke it.") + return String(localized: "The first call asks. The answer is remembered for that client until you forget it.") case .alwaysApprove: return String(localized: "Connections are reached without asking.") } diff --git a/apple/TablePro/Models/Settings/MCPSettings.swift b/apple/TablePro/Models/Settings/MCPSettings.swift index 2738d6364e..fb257a6be1 100644 --- a/apple/TablePro/Models/Settings/MCPSettings.swift +++ b/apple/TablePro/Models/Settings/MCPSettings.swift @@ -87,4 +87,12 @@ struct MCPSettings: Codable, Equatable { var requestableRowLimitRange: ClosedRange { SettingsValidationRules.mcpRowLimitRange.lowerBound...validatedMaxRowLimit } + + // One write, so a lowered maximum never leaves the default above it for a moment. + func withMaxRowLimit(_ newValue: Int) -> MCPSettings { + var next = self + next.maxRowLimit = newValue.clamped(to: SettingsValidationRules.mcpRowLimitRange) + next.defaultRowLimit = min(next.defaultRowLimit, next.maxRowLimit) + return next + } } diff --git a/apple/TablePro/Models/Settings/NotificationSettings.swift b/apple/TablePro/Models/Settings/NotificationSettings.swift index f0664d81fc..8e377c24b0 100644 --- a/apple/TablePro/Models/Settings/NotificationSettings.swift +++ b/apple/TablePro/Models/Settings/NotificationSettings.swift @@ -1,15 +1,11 @@ -// -// NotificationSettings.swift -// TablePro -// - import Foundation -/// Whether a finished operation is worth a notification, and how long is long enough to count. +// The threshold also decides the tab's unseen mark, with the switch on or off. struct NotificationSettings: Codable, Equatable { static let minimumThresholdSeconds = 5 static let maximumThresholdSeconds = 600 static let defaultThresholdSeconds = 20 + static let thresholdChoices = [5, 10, 20, 30, 60, 120, 300, 600] var isEnabled: Bool var thresholdSeconds: Int @@ -20,6 +16,12 @@ struct NotificationSettings: Codable, Equatable { min(max(thresholdSeconds, Self.minimumThresholdSeconds), Self.maximumThresholdSeconds) } + var thresholdOptions: [Int] { + let current = validatedThresholdSeconds + guard !Self.thresholdChoices.contains(current) else { return Self.thresholdChoices } + return (Self.thresholdChoices + [current]).sorted() + } + init( isEnabled: Bool = true, thresholdSeconds: Int = NotificationSettings.defaultThresholdSeconds diff --git a/apple/TablePro/Models/Settings/ProFeature.swift b/apple/TablePro/Models/Settings/ProFeature.swift index 741fb45c3c..097a22179a 100644 --- a/apple/TablePro/Models/Settings/ProFeature.swift +++ b/apple/TablePro/Models/Settings/ProFeature.swift @@ -1,8 +1,3 @@ -// -// ProFeature.swift -// TablePro -// - import Foundation // Raw values are the feature codes the entitlement carries (product.md, Feature codes). @@ -58,9 +53,9 @@ internal enum ProFeature: String, CaseIterable { case .linkedFolders: return "folder.badge.gearshape" case .teamCatalog: - return "person.2.fill" + return "person.2" case .teamLibrary: - return "books.vertical.fill" + return "books.vertical" case .compareSync: return "arrow.left.arrow.right.square" case .dataRewind: diff --git a/apple/TablePro/Models/Settings/SyncSettings.swift b/apple/TablePro/Models/Settings/SyncSettings.swift index 55954bf595..d536309fc8 100644 --- a/apple/TablePro/Models/Settings/SyncSettings.swift +++ b/apple/TablePro/Models/Settings/SyncSettings.swift @@ -1,14 +1,6 @@ -// -// SyncSettings.swift -// TablePro -// -// User-configurable sync preferences -// - import Foundation import TableProSyncTransport -/// User preferences for iCloud sync behavior struct SyncSettings: Codable, Equatable { var enabled: Bool var syncConnections: Bool @@ -82,6 +74,16 @@ struct SyncSettings: Codable, Equatable { var syncsPasswords: Bool { enabled && syncConnections && syncPasswords } + + // Passwords ride on connection records, so turning Connections off turns them off in the same write. + func settingConnections(_ on: Bool) -> SyncSettings { + var copy = self + copy.syncConnections = on + if !on { + copy.syncPasswords = false + } + return copy + } } internal extension SyncSettings { diff --git a/apple/TablePro/Models/Settings/TokenExpiry.swift b/apple/TablePro/Models/Settings/TokenExpiry.swift new file mode 100644 index 0000000000..6a2ef16f3b --- /dev/null +++ b/apple/TablePro/Models/Settings/TokenExpiry.swift @@ -0,0 +1,51 @@ +import Foundation + +enum TokenExpiry: String, CaseIterable, Identifiable, Sendable { + case never + case oneDay + case sevenDays + case thirtyDays + case sixtyDays + case ninetyDays + case custom + + var id: String { rawValue } + + var displayName: String { + switch self { + case .never: String(localized: "Never") + case .oneDay: String(localized: "1 day") + case .sevenDays: String(localized: "7 days") + case .thirtyDays: String(localized: "30 days") + case .sixtyDays: String(localized: "60 days") + case .ninetyDays: String(localized: "90 days") + case .custom: String(localized: "Custom") + } + } + + var days: Int? { + switch self { + case .never, .custom: nil + case .oneDay: 1 + case .sevenDays: 7 + case .thirtyDays: 30 + case .sixtyDays: 60 + case .ninetyDays: 90 + } + } + + static func defaultCustomDate(from now: Date = .now, calendar: Calendar = .current) -> Date { + calendar.date(byAdding: .day, value: 30, to: now) ?? now + } + + func resolvedDate(custom: Date, from now: Date = .now, calendar: Calendar = .current) -> Date? { + switch self { + case .never: + nil + case .custom: + custom + case .oneDay, .sevenDays, .thirtyDays, .sixtyDays, .ninetyDays: + days.flatMap { calendar.date(byAdding: .day, value: $0, to: now) } + } + } +} diff --git a/apple/TablePro/Models/UI/BoundKey.swift b/apple/TablePro/Models/UI/BoundKey.swift index ba70973d23..5b02109b33 100644 --- a/apple/TablePro/Models/UI/BoundKey.swift +++ b/apple/TablePro/Models/UI/BoundKey.swift @@ -1,16 +1,7 @@ -// -// BoundKey.swift -// TablePro -// -// A keyboard shortcut stored as a hardware key code plus modifiers. Storing the -// physical key code (rather than the produced character) makes matching -// layout-independent and avoids the shifted-symbol ambiguity where "[" and "{" -// describe the same physical key. -// - import AppKit import SwiftUI +// Stored as the physical key code, so matching ignores the layout and "[" and "{" are one key. struct BoundKey: Codable, Equatable, Hashable { let keyCode: UInt16 let command: Bool @@ -26,10 +17,7 @@ struct BoundKey: Codable, Equatable, Hashable { self.control = control } - // MARK: - Recorder Capture - - /// Build from a recorded key event. Requires Command or Control, or one of the - /// bare keys allowed for grid actions (Escape, Delete, Forward Delete, Space). + // Requires Command or Control, or a bare key the grid can read (Escape, Delete, Forward Delete, Space, F-keys). init?(from event: NSEvent) { let flags = event.modifierFlags.intersection(.deviceIndependentFlagsMask) let hasCommand = flags.contains(.command) @@ -44,15 +32,19 @@ struct BoundKey: Codable, Equatable, Hashable { self.control = hasControl } - // MARK: - Default Construction + // The raw chord with no gate; ShortcutAction.accepts(_:) decides whether it can be bound. + init(capturing event: NSEvent) { + let flags = event.modifierFlags.intersection(.deviceIndependentFlagsMask) + self.init( + keyCode: event.keyCode, + command: flags.contains(.command), + shift: flags.contains(.shift), + option: flags.contains(.option), + control: flags.contains(.control) + ) + } - /// Build a binding from a base character, resolving it to a key code on the - /// active layout. Used to anchor default shortcuts to a semantic character. - /// A character with no key code on the active layout yields the cleared - /// sentinel, so the binding reads as unassigned rather than silently aliasing - /// some other physical key. Every default and reserved character is ASCII and - /// resolves through the US fallback, so the failure path is a programmer error - /// and trips an assertion in debug. + // A character with no key code on the active layout yields .cleared, so the binding reads as unassigned instead of aliasing another key. static func character( _ character: Character, command: Bool = false, @@ -67,7 +59,6 @@ struct BoundKey: Codable, Equatable, Hashable { return BoundKey(keyCode: keyCode, command: command, shift: shift, option: option, control: control) } - /// Build a binding from a named special key (layout-independent). static func special( _ key: KeyCode, command: Bool = false, @@ -78,9 +69,6 @@ struct BoundKey: Codable, Equatable, Hashable { BoundKey(keyCode: key.rawValue, command: command, shift: shift, option: option, control: control) } - // MARK: - Migration - - /// Convert a legacy character-string shortcut (pre-keyCode storage) to a BoundKey. init?(legacyKey: String, isSpecialKey: Bool, command: Bool, shift: Bool, option: Bool, control: Bool) { if legacyKey.isEmpty, !command, !shift, !option, !control { self = .cleared @@ -98,8 +86,6 @@ struct BoundKey: Codable, Equatable, Hashable { self.init(keyCode: keyCode, command: command, shift: shift, option: option, control: control) } - // MARK: - Matching - func matches(_ event: NSEvent) -> Bool { guard !isCleared else { return false } let flags = event.modifierFlags.intersection(.deviceIndependentFlagsMask) @@ -114,15 +100,15 @@ struct BoundKey: Codable, Equatable, Hashable { command || shift || option || control } - /// Function keys (F1-F12) are valid as bare shortcuts: they reach the menu as - /// key-equivalents without a modifier and never collide with typing. + // F-keys reach the menu as bare key equivalents and never collide with typing. var isFunctionKey: Bool { KeyCode(rawValue: keyCode)?.functionKeyIndex != nil } - // MARK: - SwiftUI Integration + var isBareRecordable: Bool { + Self.isBareRecordable(keyCode) + } - /// The SwiftUI key equivalent, or nil when the key code has no representable key. var swiftUIKeyEquivalent: KeyEquivalent? { if let special = Self.specialKeyEquivalent(for: keyCode) { return special @@ -134,12 +120,7 @@ struct BoundKey: Codable, Equatable, Hashable { return KeyEquivalent(character) } - // MARK: - AppKit Integration - - /// The `NSMenuItem.keyEquivalent` string, or nil when the key code has no - /// representable key. Always the unshifted character, because AppKit infers - /// Shift from an uppercase key equivalent and the modifier belongs in - /// `modifierFlags` instead. + // Always the unshifted character: AppKit infers Shift from an uppercase equivalent, and Shift belongs in modifierFlags. var menuKeyEquivalent: String? { swiftUIKeyEquivalent.map { String($0.character) } } @@ -162,9 +143,6 @@ struct BoundKey: Codable, Equatable, Hashable { return flags } - // MARK: - Display - - /// Human-readable representation (e.g. "⌘S", "⇧⌘P", "⌥⌫"). var displayString: String { guard !isCleared else { return "" } var parts: [String] = [] @@ -189,16 +167,12 @@ struct BoundKey: Codable, Equatable, Hashable { return "?" } - // MARK: - Cleared Sentinel - static let cleared = BoundKey(keyCode: 0xFFFF) var isCleared: Bool { keyCode == 0xFFFF } - // MARK: - Special Key Tables - private static let bareRecordableKeyCodes: Set = [ KeyCode.escape.rawValue, KeyCode.delete.rawValue, diff --git a/apple/TablePro/Models/UI/KeyboardShortcutModels.swift b/apple/TablePro/Models/UI/KeyboardShortcutModels.swift index d0c8b2e698..df77fa4a3d 100644 --- a/apple/TablePro/Models/UI/KeyboardShortcutModels.swift +++ b/apple/TablePro/Models/UI/KeyboardShortcutModels.swift @@ -1,47 +1,24 @@ -// -// KeyboardShortcutModels.swift -// TablePro -// -// Data models for keyboard shortcut customization. The binding type itself -// lives in BoundKey.swift. -// - import AppKit import SwiftUI -// MARK: - Shortcut Context - -/// Where an action can fire. The same physical combo can mean different things -/// in different contexts because the focused responder resolves it (e.g. Cmd+[ -/// is pagination in the grid and indent in the editor). Two actions only -/// conflict when their contexts can be active at the same time. +// The focused responder resolves a combo (Cmd-[ pages the grid and outdents the editor), so two actions conflict only when their contexts can be active at once. enum ShortcutContext: String { case global case editor case dataGrid - /// Two contexts overlap when they can be the active responder at the same - /// time. Non-overlapping contexts (editor vs data grid) may share a combo: - /// the editor's local key monitor consumes the keystroke while it is focused, - /// so the grid's menu key-equivalent only fires when the grid has focus. The - /// conflict resolver guards uniqueness within an overlapping context; it does - /// not stop a user from binding a grid combo that also reaches a global menu - /// item, which focus alone cannot disambiguate. + // Editor and grid may share a combo: the editor's local key monitor takes it while the editor has focus. func overlaps(_ other: ShortcutContext) -> Bool { self == .global || other == .global || self == other } } -// MARK: - Shortcut Category - -/// Groups shortcuts in the settings list by the surface they act on. enum ShortcutCategory: String, Codable, CaseIterable, Identifiable { case editor case dataGrid case navigation case connections case debug - case app var id: String { rawValue } @@ -52,13 +29,10 @@ enum ShortcutCategory: String, Codable, CaseIterable, Identifiable { case .navigation: return String(localized: "Navigation") case .connections: return String(localized: "Connections") case .debug: return String(localized: "Debug") - case .app: return String(localized: "App") } } } -// MARK: - Shortcut Action - enum ShortcutAction: String, Codable, CaseIterable, Identifiable { // Connections case manageConnections @@ -253,9 +227,7 @@ enum ShortcutAction: String, Codable, CaseIterable, Identifiable { allCases.filter { $0.category == category && $0.isAvailable(enabledModules: enabledModules) } } - /// A command that dispatches to whichever surface holds focus must be `.global`, or the - /// conflict resolver treats its combo as free in the other context and AppKit blanks one of - /// the two menu items that end up claiming it. The three find commands all route that way. + // A command that dispatches to whichever surface has focus must be .global, or AppKit blanks one of the two menu items that end up sharing its combo. var context: ShortcutContext { switch self { case .find, .findAndReplace, .findNext, .findPrevious, .useSelectionForFind: @@ -271,9 +243,7 @@ enum ShortcutAction: String, Codable, CaseIterable, Identifiable { .copyRowsExplicit, .copyWithHeaders, .copyAsJson, .toggleFilters, .jumpToColumn, .copyCellValue, .copyAsCsv, .copyAsCsvWithHeaders, .copyAsMarkdown, .copyAsInClause, .copyAsInsert, .copyAsUpdate, - /// Named rather than left to the `default:` below. It reverses a row the grid is - /// showing, so it belongs in the grid's context the way Add Row and Delete do, and - /// inheriting `.global` would let the recorder call a grid combo free for it. + // Named so it never falls to default: and .global, which would let the recorder call a grid combo free for it. .restorePreviousValues: return .dataGrid default: @@ -285,9 +255,7 @@ enum ShortcutAction: String, Codable, CaseIterable, Identifiable { self == .switchToRecentTab || self == .switchToLeastRecentTab } - /// The focused grid reads this action's key from `keyDown`, whatever its modifiers, so its menu - /// item never carries a key equivalent. Its default, Option-Return, breaks a line in a text - /// field, and AppKit hands an equivalent to the menu before the field sees the key. + // The grid reads this key in keyDown, so its menu item has no equivalent: Option-Return breaks a line in a text field, and AppKit hands an equivalent to the menu first. var isReadByFocusedGrid: Bool { self == .openValueEditor } @@ -297,13 +265,26 @@ enum ShortcutAction: String, Codable, CaseIterable, Identifiable { isReadByFocusedGrid || other.isReadByFocusedGrid || context.overlaps(other.context) } + // The focused grid reads a bare key only for this action; nothing dispatches one for Delete or Clear Selection. var allowsBareKey: Bool { - switch self { - case .previewFKReference, .clearSelection, .delete: + self == .previewFKReference + } + + func accepts(_ key: BoundKey) -> Bool { + if key.command || key.control || key.isFunctionKey { + return true + } + if key == KeyboardSettings.defaultShortcuts[self] { return true - default: - return false } + guard key.isBareRecordable else { return false } + return key.hasModifier || allowsBareKey + } + + var modifierRefusal: String { + self == .previewFKReference + ? String(localized: "Use ⌘ or ⌃, Space, or a function key.") + : String(localized: "Add ⌘ or ⌃ to this shortcut.") } var displayName: String { @@ -438,12 +419,44 @@ enum ShortcutAction: String, Codable, CaseIterable, Identifiable { } } -// MARK: - Built-in Editor Shortcuts +struct ShortcutSection: Identifiable, Equatable { + let category: ShortcutCategory + let actions: [ShortcutAction] + + var id: ShortcutCategory { category } +} + +extension ShortcutAction { + private static let modifierGlyphs: Set = ["⌃", "⌥", "⇧", "⌘"] + + // Every whitespace-separated term has to match; a term holding a modifier glyph can match the bound key too. + static func settingsSections( + matching query: String, + in settings: KeyboardSettings, + enabledModules: Set + ) -> [ShortcutSection] { + let terms = query.split(whereSeparator: \.isWhitespace).map(String.init) + return ShortcutCategory.allCases.compactMap { category in + let actions = settingsRows(in: category, enabledModules: enabledModules) + .filter { $0.matches(terms, in: settings) } + return actions.isEmpty ? nil : ShortcutSection(category: category, actions: actions) + } + } + + private func matches(_ terms: [String], in settings: KeyboardSettings) -> Bool { + terms.allSatisfy { term in + if displayName.localizedStandardContains(term) || category.displayName.localizedStandardContains(term) { + return true + } + guard term.contains(where: { Self.modifierGlyphs.contains($0) }), + let key = settings.boundKey(for: self) else { return false } + return key.displayString.localizedStandardContains(term) + } + } +} extension ShortcutAction { - /// Shortcuts owned by the embedded SQL editor. They are not customizable, but - /// the recorder surfaces them so a user does not silently shadow one with an - /// editor-context binding. + // Owned by the embedded editor and not rebindable; listed so an editor-context binding never shadows one. static let editorBuiltIns: [(key: BoundKey, name: String)] = [ (.character("/", command: true), String(localized: "Toggle Comment")), (.character("[", command: true), String(localized: "Outdent")), @@ -457,16 +470,16 @@ extension ShortcutAction { (.special(.downArrow, shift: true, option: true), String(localized: "Extend Selection to Next Statement")) ] - /// AppKit's own text-editing key bindings, taken from `StandardKeyBinding.dict`. - /// The editor's local key monitor claims `editorBuiltIns` before the menu bar - /// sees them, but these resolve at the very end of dispatch, inside the focused - /// responder's `interpretKeyEvents`. An enabled menu key equivalent is matched - /// long before that, so a data-grid action bound to one of these has to stand - /// down while a text input holds focus. + // StandardKeyBinding.dict and the text input keys: they resolve last, in interpretKeyEvents, so an enabled menu equivalent always beats them. static let standardTextEditingBindings: [(key: BoundKey, name: String)] = [ (.special(.delete, command: true), String(localized: "Delete to Beginning of Line")), (.special(.delete, option: true), String(localized: "Delete Word Backward")), (.special(.forwardDelete, option: true), String(localized: "Delete Word Forward")), + (.special(.delete, shift: true), String(localized: "Delete Backward")), + (.special(.forwardDelete, shift: true), String(localized: "Delete Forward")), + (.special(.space, shift: true), String(localized: "Insert Space")), + (.special(.space, option: true), String(localized: "Insert Non-Breaking Space")), + (.special(.escape, option: true), String(localized: "Complete Word")), (.special(.leftArrow, command: true), String(localized: "Move to Beginning of Line")), (.special(.rightArrow, command: true), String(localized: "Move to End of Line")), (.special(.upArrow, command: true), String(localized: "Move to Beginning of Document")), @@ -475,10 +488,7 @@ extension ShortcutAction { (.special(.rightArrow, option: true), String(localized: "Move Word Right")) ] - /// Every key equivalent a menu builder hardcodes, and so every combo no `ShortcutAction` - /// can be bound to. These fire regardless of focus, and AppKit blanks the loser when two - /// menu items claim one combo, so a binding the recorder let through would silently kill - /// the hardcoded command instead. An entry added to a menu builder belongs here too. + // Hardcoded by a menu builder: AppKit blanks the loser when two items share a combo, so no action may take one. A new menu-builder key goes here too. static let reservedAppShortcuts: [(key: BoundKey, name: String)] = { var shortcuts: [(key: BoundKey, name: String)] = [ (.character("=", command: true), String(localized: "Zoom In")), @@ -503,9 +513,6 @@ extension ShortcutAction { return shortcuts }() - /// The name of a reserved command this combo would shadow: an app-level menu - /// shortcut (always), or a built-in editor or system text command when the - /// action can fire while the editor is focused. static func reservedConflict(for key: BoundKey, context: ShortcutContext) -> String? { if let appName = reservedAppShortcuts.first(where: { $0.key == key })?.name { return appName @@ -517,24 +524,15 @@ extension ShortcutAction { return standardTextEditingBindings.first(where: { $0.key == key })?.name } - /// Whether this action's binding duplicates one of AppKit's standard - /// text-editing bindings, which the focused responder owns. Only data-grid - /// actions yield: an editor or global action is meant to fire while text is - /// focused, so it keeps its key equivalent and the recorder warns instead. + // Only grid actions stand down while text has focus; an editor or global action keeps its key and the recorder refuses the combo instead. func shadowsStandardTextEditingBinding(_ key: BoundKey?) -> Bool { guard context == .dataGrid, let key, !key.isCleared else { return false } return Self.standardTextEditingBindings.contains { $0.key == key } } } -// MARK: - Keyboard Settings - -/// User's keyboard shortcut customization settings. -/// Only stores overrides; an empty dictionary means all defaults. +// Only overrides are stored, keyed by action rawValue; a renamed action's stale entry never matches. struct KeyboardSettings: Codable, Equatable { - /// User-customized shortcuts (action rawValue -> BoundKey). - /// Only contains overrides; missing entries use defaults. A renamed action's - /// stale key becomes a harmless no-op (never matched by any action). var shortcuts: [String: BoundKey] static let `default` = KeyboardSettings(shortcuts: [:]) @@ -545,13 +543,9 @@ struct KeyboardSettings: Codable, Equatable { init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - // BoundKey requires `keyCode` and LegacyKeyCombo requires `key`, and - // neither field exists in the other shape, so the two never decode each - // other's payload. Modern data is tried first; a legacy file fails that - // decode and falls through to migration. Only then are unreadable - // entries dropped one by one, or a legacy file would lose every entry. + // The two shapes never decode each other (keyCode vs key); entries drop one by one only after both fail, or a legacy file would lose them all. if let modern = try? container.decodeIfPresent([String: BoundKey].self, forKey: .shortcuts) { - shortcuts = modern ?? [:] + shortcuts = modern } else if let legacy = try? container.decode([String: LegacyKeyCombo].self, forKey: .shortcuts) { shortcuts = legacy.compactMapValues { $0.migrated() } } else { @@ -559,14 +553,7 @@ struct KeyboardSettings: Codable, Equatable { } } - /// Get the effective shortcut for an action (user override or default). - /// Returns nil if the user explicitly cleared the shortcut, or if a chord the user assigned - /// by hand has already claimed this action's default. - /// - /// The yield is resolved here rather than written into `shortcuts`, which means only what the - /// user chose. Storing it would make the stand-down permanent: rebinding the conflicting chord - /// would leave the default cleared forever, Settings would show the action as customized, and - /// its Reset arrow would appear to work until the next launch re-applied the clear. + // A default an override claims yields here, never in `shortcuts`, so rebinding the claimant re-arms it and the action never reads as customized. func shortcut(for action: ShortcutAction) -> BoundKey? { if let override = shortcuts[action.rawValue] { return override @@ -576,8 +563,7 @@ struct KeyboardSettings: Codable, Equatable { return fallback } - /// The action whose user-assigned chord stands this default down, if any. Only overrides - /// claim: two defaults cannot collide, because `DefaultShortcutHygieneTests` forbids it. + // Only overrides claim: DefaultShortcutHygieneTests keeps two defaults from colliding. private func findOverrideClaimant(of key: BoundKey, excluding action: ShortcutAction) -> ShortcutAction? { guard !key.isCleared else { return nil } for (rawValue, override) in shortcuts { @@ -593,12 +579,24 @@ struct KeyboardSettings: Codable, Equatable { return nil } + func boundKey(for action: ShortcutAction) -> BoundKey? { + guard let key = shortcut(for: action), !key.isCleared else { return nil } + return key + } + func isCustomized(_ action: ShortcutAction) -> Bool { shortcuts[action.rawValue] != nil } - /// Find a conflicting action for the given combo within an overlapping - /// context, excluding the specified action. + var customizedCount: Int { + shortcuts.keys.filter { ShortcutAction(rawValue: $0) != nil }.count + } + + func defaultClaimant(for action: ShortcutAction) -> ShortcutAction? { + guard !isCustomized(action), let fallback = Self.defaultShortcuts[action] else { return nil } + return findOverrideClaimant(of: fallback, excluding: action) + } + func findConflict(for key: BoundKey, excluding action: ShortcutAction) -> ShortcutAction? { findConflict(for: key, excluding: action, enabledModules: AppModule.storedEnabledModules()) } @@ -608,32 +606,77 @@ struct KeyboardSettings: Codable, Equatable { excluding action: ShortcutAction, enabledModules: Set ) -> ShortcutAction? { - guard !key.isCleared else { return nil } - for other in ShortcutAction.allCases where other != action && other.isAvailable(enabledModules: enabledModules) { - guard action.contends(with: other), - let otherKey = shortcut(for: other), !otherKey.isCleared, - otherKey == key else { continue } - return other + conflicts(for: key, excluding: action, enabledModules: enabledModules).first + } + + func conflicts( + for key: BoundKey, + excluding action: ShortcutAction, + enabledModules: Set + ) -> [ShortcutAction] { + guard !key.isCleared else { return [] } + return ShortcutAction.allCases.filter { other in + other != action + && other.isAvailable(enabledModules: enabledModules) + && action.contends(with: other) + && boundKey(for: other) == key } - return nil } mutating func setShortcut(_ key: BoundKey, for action: ShortcutAction) { shortcuts[action.rawValue] = key } - /// Clear a shortcut so the action has no binding. mutating func clearShortcut(for action: ShortcutAction) { shortcuts[action.rawValue] = BoundKey.cleared } - /// Reset a specific action to its default shortcut. mutating func resetToDefault(for action: ShortcutAction) { shortcuts.removeValue(forKey: action.rawValue) } - /// Drop overrides that can never dispatch (bare keys on menu-driven actions), - /// reverting them to their default. Cleared and unknown overrides are kept. + // Picking the default again stores nothing, so the action stops reading as customized. + func assigning(_ key: BoundKey, to action: ShortcutAction) -> KeyboardSettings { + var next = self + if key == Self.defaultShortcuts[action], findOverrideClaimant(of: key, excluding: action) == nil { + next.resetToDefault(for: action) + } else { + next.setShortcut(key, for: action) + } + return next + } + + // An action with no default needs no cleared marker to have no key. + func clearing(_ action: ShortcutAction) -> KeyboardSettings { + var next = self + if Self.defaultShortcuts[action] == nil { + next.resetToDefault(for: action) + } else { + next.clearShortcut(for: action) + } + return next + } + + func resetting(_ action: ShortcutAction) -> KeyboardSettings { + var next = self + next.resetToDefault(for: action) + return next + } + + // A holder still on its default needs no write: the new override claims that default. + func reassigning( + _ key: BoundKey, + to action: ShortcutAction, + enabledModules: Set + ) -> KeyboardSettings { + var next = self + for holder in conflicts(for: key, excluding: action, enabledModules: enabledModules) where isCustomized(holder) { + next = next.clearing(holder) + } + return next.assigning(key, to: action) + } + + // Drops overrides that can never dispatch (a bare key on a menu action); cleared and unknown entries stay. func sanitized() -> KeyboardSettings { var cleaned = shortcuts for (rawValue, key) in shortcuts { @@ -645,10 +688,7 @@ struct KeyboardSettings: Codable, Equatable { return KeyboardSettings(shortcuts: cleaned) } - /// Build a SwiftUI KeyboardShortcut for the given action's menu item. - /// Returns nil when the shortcut is cleared, has no representable key, or is a - /// bare (modifier-less) key. Bare keys dispatch through the responder chain in - /// the focused view, not through a global menu key-equivalent. + // A bare key reaches the focused responder, never a menu key equivalent. func keyboardShortcut(for action: ShortcutAction) -> KeyboardShortcut? { guard !action.isReadByFocusedGrid, let key = shortcut(for: action), !key.isCleared, key.hasModifier || key.isFunctionKey, @@ -658,10 +698,6 @@ struct KeyboardSettings: Codable, Equatable { return KeyboardShortcut(equivalent, modifiers: key.eventModifiers) } - /// The AppKit key equivalent for the given action's menu item, resolved through - /// user overrides. Returns nil under the same conditions as `keyboardShortcut(for:)`: - /// a cleared binding, an unrepresentable key, or a bare key, which reaches the - /// focused responder directly rather than through a global menu key-equivalent. func menuKeyEquivalent(for action: ShortcutAction) -> (characters: String, modifiers: NSEvent.ModifierFlags)? { guard !action.isReadByFocusedGrid, let key = shortcut(for: action), !key.isCleared, key.hasModifier || key.isFunctionKey, @@ -671,19 +707,12 @@ struct KeyboardSettings: Codable, Equatable { return (characters, key.modifierFlags) } - /// A tooltip/help string that appends the action's resolved shortcut, e.g. - /// "Switch Connection (⌃⌘C)". Returns just the label when the shortcut is - /// cleared or unset. Reflects user overrides because it resolves through - /// `shortcut(for:)`. func shortcutHint(_ label: String, for action: ShortcutAction) -> String { guard let key = shortcut(for: action), !key.isCleared else { return label } return "\(label) (\(key.displayString))" } - // MARK: - Default Shortcuts - - // An action absent here shows as unassigned until the user binds it. Commit and Roll Back Transaction ship - // unbound: they are infrequent, and a stray Roll Back discards work. + // Commit and Roll Back Transaction ship unbound: they are infrequent, and a stray Roll Back discards work. static let defaultShortcuts: [ShortcutAction: BoundKey] = [ // Connections .newConnection: .character("n", command: true), @@ -750,12 +779,7 @@ struct KeyboardSettings: Codable, Equatable { .jumpToColumn: .character("j", command: true, shift: true), // Navigation - /// Not the Safari chord. Command+[ and Command+] are Previous/Next Page and are claimed - /// again by the editor's own indent and outdent, Option+Command+[ and ] are the result - /// tabs, Shift+Command+[ and ] are the editor tabs, Control+Command+Left and Right are - /// Previous/Next Statement, and Option+Command+Left is Toggle Fold. Two menu items cannot - /// share a key equivalent: AppKit blanks the loser's. This completes the bracket family - /// the app already reads as "step through something". + // Not Safari's chord: Cmd-[ ] page and indent, Opt-Cmd-[ ] step results, Shift-Cmd-[ ] step tabs, and two menu items cannot share one. .navigateBack: .character("[", command: true, control: true), .navigateForward: .character("]", command: true, control: true), .newTab: .character("t", command: true), @@ -765,8 +789,7 @@ struct KeyboardSettings: Codable, Equatable { .toggleTableBrowser: .character("0", command: true), .toggleInspector: .character("i", command: true, option: true), .toggleAssistant: .character("a", command: true, option: true), - /// Not Shift-Command-A, which Apple's own table assigns to Deselect All and which - /// `clearSelection` is waiting for. This keeps the "a is the assistant" family together. + // Not Shift-Cmd-A, Apple's Deselect All, which clearSelection waits for. .toggleAgentMode: .character("a", command: true, shift: true, option: true), .toggleFilters: .character("f", command: true, shift: true), .toggleHistory: .character("y", command: true), @@ -783,10 +806,7 @@ struct KeyboardSettings: Codable, Equatable { .focusAssistant: .character("a", command: true, option: true, control: true), .showPreviousTab: .character("[", command: true, shift: true), .showNextTab: .character("]", command: true, shift: true), - /// The one Control chord among the defaults. Control-Tab is not a system hotkey, it is the - /// chord AppKit itself gives tab switching in every app with window tabs, and it is what - /// DataGrip, VS Code and Zed switch recent tabs with. Show Previous and Next Window Tab - /// have no default, since this is the chord AppKit would otherwise give them. + // Control-Tab is AppKit's own tab-switching chord, not a system hotkey; window tabs get no default so they never take it. .switchToRecentTab: .special(.tab, control: true), .switchToLeastRecentTab: .special(.tab, shift: true, control: true), .toggleWorkspaceRail: .character("0", command: true, option: true), @@ -801,10 +821,7 @@ struct KeyboardSettings: Codable, Equatable { ] } -// MARK: - Legacy Migration - -/// The pre-keyCode stored shape of a shortcut. Used only to migrate persisted -/// settings to BoundKey. +// The pre-keyCode stored shape, read only to migrate. private struct LegacyKeyCombo: Codable { let key: String var command = false diff --git a/apple/TablePro/Models/UI/SharedSidebarState.swift b/apple/TablePro/Models/UI/SharedSidebarState.swift index 3b8d902ced..0f1ee2d55d 100644 --- a/apple/TablePro/Models/UI/SharedSidebarState.swift +++ b/apple/TablePro/Models/UI/SharedSidebarState.swift @@ -1,17 +1,7 @@ -// -// SharedSidebarState.swift -// TablePro -// -// Connection-scoped sidebar state shared across all windows of the same -// connection. Window-scoped state (table selection) lives in -// `WindowSidebarState`. -// - import Combine import Foundation import TableProUtilities -/// Which sidebar tab is active internal enum SidebarTab: String, CaseIterable { case tables case favorites @@ -20,8 +10,11 @@ internal enum SidebarTab: String, CaseIterable { internal enum SidebarLayout: String, CaseIterable, Sendable { case flat case tree + + static let fallback: SidebarLayout = .flat } +// Shared by every window of one connection; window-scoped state lives in WindowSidebarState. @MainActor final class SharedSidebarState: ObservableObject { @Published var redisKeyTreeViewModel: RedisKeyTreeViewModel? @@ -38,8 +31,7 @@ final class SharedSidebarState: ObservableObject { recentTables.filter { $0.database == normalizedDatabase(database) } } - /// `objectType` is what the object actually is, where the caller knew it. `isView` stays - /// beside it for the callers that know only that much, and is what an older build reads. + // isView stays beside objectType for callers that know only that much, and is what an older build reads. func recordTableOpen( database: String?, schema: String?, @@ -106,8 +98,7 @@ final class SharedSidebarState: ObservableObject { ) } - /// Removal matches on the entry's id, which is its database, schema and name, so the kind it - /// was recorded with is not part of the lookup. + // Matches on the id (database, schema, name), so the kind recorded with the entry is not part of the lookup. func removeRecentTable(database: String?, schema: String?, name: String) { let entry = RecentTableEntry( database: normalizedDatabase(database), schema: schema, name: name, @@ -116,9 +107,7 @@ final class SharedSidebarState: ObservableObject { recentTables = RecentTablesStore.shared.remove(connectionId: connectionId, entry: entry) } - /// A renamed table keeps its place in Recent. The store is asked directly rather than the live - /// list, because that list is empty while Show Recent Tables is off and the entry is still on - /// disk: renaming only what is on screen left a dead entry to reappear under the old name. + // Asks the store, not the live list: that list is empty while Show Recent Tables is off, and the entry is still on disk. func renameRecentTable(database: String?, schema: String?, from oldName: String, to newName: String) { let scope = normalizedDatabase(database) let existing = RecentTablesStore.shared.entries(connectionId: connectionId).first { @@ -128,8 +117,7 @@ final class SharedSidebarState: ObservableObject { publish(RecentTablesStore.shared.rename(connectionId: connectionId, entry: existing, to: newName)) } - /// Every Recent entry in a renamed container follows it, because the entries are keyed by the - /// container's name and would otherwise all point at one that has gone. + // Entries are keyed by the container's name, so each one has to follow the rename. func renameRecentDatabase(from oldName: String, to newName: String) { publish(RecentTablesStore.shared.renameDatabase( connectionId: connectionId, from: oldName, to: newName @@ -142,9 +130,7 @@ final class SharedSidebarState: ObservableObject { )) } - /// A table opened before the session knew its schema is recorded without one, and clicking that - /// entry opens the same name in whichever schema is browsed by then. It takes the schema the tab - /// resolved, in place. + // An entry recorded before the session knew its schema would open the name in whichever schema is browsed. func resolveRecentSchema(database: String?, name: String, to schema: String) { publish(RecentTablesStore.shared.resolveSchema( connectionId: connectionId, database: normalizedDatabase(database), name: name, to: schema @@ -206,8 +192,7 @@ final class SharedSidebarState: ObservableObject { } } - /// Keyed by database name, "" for an engine browsed without one. Written only through the - /// methods below, which keep the stored copy in step. + // Keyed by database name, "" without one. Written only through the methods below, which keep the stored copy in step. @Published private(set) var schemaFilterSelected: [String: Set] func schemaFilter(for database: String?) -> Set { @@ -237,8 +222,7 @@ final class SharedSidebarState: ObservableObject { setSchemaFilter(selected, for: database) } - /// A filter whose last schema was dropped is cleared rather than left naming nothing: an empty - /// selection is no filter, which is the list the user saw before picking the dropped one. + // An empty selection is no filter, which is the list the user saw before picking the dropped schema. func removeSchemaFromFilter(database: String?, schema: String) { var selected = schemaFilter(for: database) guard selected.remove(schema) != nil else { return } @@ -288,7 +272,7 @@ final class SharedSidebarState: ObservableObject { get { guard let raw = AppStorageEnvironment.shared.defaults.string(forKey: SidebarPersistenceKey.defaultLayout), let layout = SidebarLayout(rawValue: raw) else { - return .flat + return .fallback } return layout } @@ -329,11 +313,10 @@ final class SharedSidebarState: ObservableObject { } } - /// Default init for previews and tests init() { self.connectionId = UUID() self.selectedSidebarTab = .tables - self.sidebarLayout = .flat + self.sidebarLayout = .fallback self.databaseFilterSelected = [] self.schemaFilterSelected = [:] self.favoriteDatabaseEnvironmentFilter = .all diff --git a/apple/TablePro/Models/UI/SidebarDisplayPreferences.swift b/apple/TablePro/Models/UI/SidebarDisplayPreferences.swift new file mode 100644 index 0000000000..f5d05ad920 --- /dev/null +++ b/apple/TablePro/Models/UI/SidebarDisplayPreferences.swift @@ -0,0 +1,38 @@ +import Combine +import Foundation + +struct SidebarDisplayOptions: Equatable { + var showObjectIcons: Bool + var showObjectComments: Bool + var showSystemContainers: Bool + var showRecentTables: Bool + var showPartitions: Bool + var rowSize: SidebarRowSizePreference + + init(_ general: GeneralSettings) { + showObjectIcons = general.showObjectIcons + showObjectComments = general.showObjectComments + showSystemContainers = general.showSystemContainers + showRecentTables = general.showRecentTables + showPartitions = general.showPartitions + rowSize = general.sidebarRowSize + } +} + +// Publishes only when a General field the sidebar draws changes, so a query timeout or language write leaves every sidebar alone. +@MainActor +final class SidebarDisplayPreferences: ObservableObject { + static let shared = SidebarDisplayPreferences(general: AppSettingsManager.shared.generalSlice) + + @Published private(set) var options: SidebarDisplayOptions + private var subscription: AnyCancellable? + + init(general: SettingsSlice) { + options = SidebarDisplayOptions(general.value) + subscription = general.publisher + .map(SidebarDisplayOptions.init) + .removeDuplicates() + .dropFirst() + .sink { [weak self] in self?.options = $0 } + } +} diff --git a/apple/TablePro/Resources/Localizable.xcstrings b/apple/TablePro/Resources/Localizable.xcstrings index 4ab7887155..70deb85664 100644 --- a/apple/TablePro/Resources/Localizable.xcstrings +++ b/apple/TablePro/Resources/Localizable.xcstrings @@ -749,6 +749,9 @@ } } } + }, + "“%@”" : { + }, "“%@” already has a column with that name." : { @@ -2317,6 +2320,16 @@ }, "%@ · SSL" : { + }, + "%@ (%@)" : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "new", + "value" : "%1$@ (%2$@)" + } + } + } }, "%@ (%@@%@)" : { "localizations" : { @@ -2472,6 +2485,9 @@ } } } + }, + "%@ (Not Installed)" : { + }, "%@ (reader)" : { "localizations" : { @@ -3240,6 +3256,9 @@ }, "%@ connects with a token from Settings > MCP > Authentication, which can limit what it reaches. TablePro leaves it as is." : { + }, + "%@ connects with a token from Settings > MCP > Tokens, which can limit what it reaches. TablePro leaves it as is." : { + }, "%@ contains characters Spanner does not allow." : { "extractionState" : "manual", @@ -3492,6 +3511,9 @@ } } } + }, + "%@ Export" : { + }, "%@ failed" : { "comment" : "Failure count, %@ is a count", @@ -3736,6 +3758,9 @@ "%@ holds values that cannot be compared, so the row cannot be found again." : { "extractionState" : "manual", "generatesSymbol" : false + }, + "%@ Import" : { + }, "%@ in the workbook expands to far more data than it holds, so it was not read." : { "extractionState" : "manual", @@ -4324,6 +4349,19 @@ } } } + }, + "%@ is used by “%@”." : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "new", + "value" : "%1$@ is used by “%2$@”." + } + } + } + }, + "%@ is used by macOS." : { + }, "%@ is using %@. Only one app can open a DuckDB file for writing." : { "extractionState" : "manual", @@ -4340,6 +4378,12 @@ "%@ isn't compiled for debugging." : { "extractionState" : "manual", "generatesSymbol" : false + }, + "%@ isn't installed. Grids use System Mono." : { + + }, + "%@ isn't installed. The editor uses System Mono." : { + }, "%@ kept changing while TablePro wrote it. Try again." : { @@ -7827,6 +7871,9 @@ } } } + }, + "%1$@, approved %2$@" : { + }, "%1$@, entry %2$lld: %3$@" : { "localizations" : { @@ -10942,6 +10989,9 @@ } } } + }, + "%lld active" : { + }, "%lld additional errors are in Copy Details." : { @@ -11010,6 +11060,12 @@ }, "%lld connections" : { + }, + "%lld connections use this profile. They keep these credentials as their own." : { + + }, + "%lld connections use this profile. They keep this configuration as their own SSH tunnel." : { + }, "%lld connections were imported." : { "extractionState" : "stale", @@ -11059,6 +11115,9 @@ "%lld constraint(s) removed" : { "extractionState" : "manual", "generatesSymbol" : false + }, + "%lld customized" : { + }, "%lld dims" : { @@ -11769,6 +11828,9 @@ } } } + }, + "%lld profiles were saved by a newer version of TablePro and can't be shown here." : { + }, "%lld properties" : { @@ -11776,6 +11838,9 @@ "%lld property value(s) set" : { "extractionState" : "manual", "generatesSymbol" : false + }, + "%lld pt" : { + }, "%lld relationship(s) created" : { "extractionState" : "manual", @@ -12828,6 +12893,9 @@ }, "^[%lld change](inflect: true)" : { + }, + "^[%lld character](inflect: true)" : { + }, "^[%lld check](inflect: true) could not run. Select one to see why." : { @@ -12883,6 +12951,9 @@ } } } + }, + "^[%lld connection](inflect: true)" : { + }, "^[%lld connection](inflect: true) use this profile. They keep these credentials as their own." : { "localizations" : { @@ -13023,6 +13094,9 @@ } } } + }, + "^[%lld space](inflect: true)" : { + }, "^[%lld table](inflect: true) to export" : { "localizations" : { @@ -13718,6 +13792,12 @@ } } } + }, + "1 connection uses this profile. It keeps these credentials as its own." : { + + }, + "1 connection uses this profile. It keeps this configuration as its own SSH tunnel." : { + }, "1 connection was imported." : { "localizations" : { @@ -13875,6 +13955,9 @@ } } } + }, + "1 minute" : { + }, "1 more message." : { @@ -14008,6 +14091,9 @@ } } } + }, + "1 profile was saved by a newer version of TablePro and can't be shown here." : { + }, "1 property" : { @@ -15462,6 +15548,9 @@ } } } + }, + "A .sql-formatter.json in a linked SQL folder replaces these rules for files opened from that folder." : { + }, "A .sql-formatter.json in a linked SQL folder replaces these rules for the files opened from that folder." : { @@ -15786,6 +15875,9 @@ } } } + }, + "A command named “/%@” already exists." : { + }, "A comment is never closed." : { @@ -16216,6 +16308,9 @@ }, "A failed write may have made additional changes." : { + }, + "A faint band behind the statement the cursor is in." : { + }, "A field named “%@” can only be changed on MongoDB 5.0 or later, which can address a dot or a leading $ in a name." : { "extractionState" : "manual", @@ -16539,6 +16634,9 @@ }, "A larger binary value stays on the server until you open, copy or export it. Applies to tables with a primary key." : { + }, + "A link you chose Always Allow for connects without asking again. Only connections on this Mac can be trusted." : { + }, "A local secondary index is part of its table and is removed only with the table." : { "extractionState" : "manual", @@ -16824,6 +16922,9 @@ } } } + }, + "A paid plan adds the features listed under Features." : { + }, "A paired app, such as a launcher, can ask when it pairs to show connections whose AI Policy is Never, with their user names. It still cannot query them. Turning this off stops every app at once." : { "localizations" : { @@ -16973,6 +17074,9 @@ "A point's id cannot change. Insert a new row with the new id instead." : { "extractionState" : "manual", "generatesSymbol" : false + }, + "A profile needs a name." : { + }, "A publish to the team library is still running. Try again when it finishes." : { @@ -17282,6 +17386,9 @@ } } } + }, + "A run that returns more keeps only the newest. Pinned results always stay." : { + }, "A run that returns more results with rows keeps only the newest. Pinned results always stay." : { @@ -17361,6 +17468,9 @@ }, "A SELECT list, SET list or WHERE condition that fits in this width stays on one line." : { + }, + "A SELECT list, SET list or WHERE condition that fits stays on one line." : { + }, "A SELECT to export. Use instead of 'tables'." : { "localizations" : { @@ -17547,6 +17657,9 @@ } } } + }, + "A single cell still copies its value. Edit > Copy Special offers every format." : { + }, "A single click opens each table in the same preview tab. Double-click a table, or press Return, to keep it open." : { "localizations" : { @@ -17587,6 +17700,9 @@ } } } + }, + "A small query on each open connection catches a drop early. For a database that sleeps when idle or bills per query, pick Only when used: it checks when you next use the connection." : { + }, "A SQL condition, such as status = 'active'" : { "localizations" : { @@ -17701,6 +17817,9 @@ } } } + }, + "A strip on the window's leading edge with each open connection and database. It appears once more than one is open." : { + }, "A superuser bypasses all permission checks." : { "localizations" : { @@ -18902,6 +19021,9 @@ } } } + }, + "Actions for %@" : { + }, "Activate" : { "localizations" : { @@ -19305,6 +19427,9 @@ } } } + }, + "Active provider" : { + }, "Active Provider" : { "localizations" : { @@ -19913,6 +20038,9 @@ } } } + }, + "Add ⌘ or ⌃ to this shortcut." : { + }, "Add a connection first." : { "localizations" : { @@ -19950,6 +20078,9 @@ } } } + }, + "Add an API key to load this provider's models." : { + }, "Add Another SQL Folder…" : { "comment" : "Text for a menu item that adds a new linked SQL folder.", @@ -20250,6 +20381,9 @@ } } } + }, + "Add Command…" : { + }, "Add Connection" : { "localizations" : { @@ -20906,6 +21040,12 @@ }, "Add one row to a table on a saved connection. Provide the row as a JSON object or a CSV row." : { + }, + "Add one to reuse a prompt in the chat." : { + + }, + "Add one to use chat and Agent mode." : { + }, "Add plugin_debugger to shared_preload_libraries and restart the server." : { "extractionState" : "manual", @@ -21086,6 +21226,9 @@ } } } + }, + "Add SSH Profile…" : { + }, "Add SSH Server…" : { "localizations" : { @@ -21096,6 +21239,9 @@ } } } + }, + "Add TablePro to Claude, Cursor and other apps on this Mac." : { + }, "Add tags" : { "localizations" : { @@ -21572,6 +21718,9 @@ } } } + }, + "Adds a Recent section to the welcome window and the connection switcher." : { + }, "Adds a Recent section with the connections you opened lately to the welcome window and the connection switcher." : { "localizations" : { @@ -21989,6 +22138,9 @@ } } } + }, + "Agent mode pauses at the limit so you can continue. A higher limit uses more tokens per reply." : { + }, "Agent reply “%1$@” on %2$@" : { @@ -22458,6 +22610,9 @@ } } } + }, + "AI Policy applies to AI features and MCP clients. External Clients controls Raycast, Cursor, Claude Desktop, other MCP clients, AppleScript, and Shortcuts. Effective scope is the minimum of the requesting token's scope and the External Clients level." : { + }, "AI Policy controls in-app AI agents. External Clients controls Raycast, Cursor, Claude Desktop, other MCP clients, and AppleScript. Effective scope is the minimum of the requesting token's scope and the External Clients level." : { "extractionState" : "stale", @@ -24291,6 +24446,9 @@ }, "already saved" : { + }, + "Also deletes saved changes kept for Data Rewind and earlier versions of query tabs." : { + }, "Also drop the columns, functions and other objects that use this type" : { @@ -24337,6 +24495,9 @@ }, "Also include global saved queries" : { + }, + "Also the direction of the first click on a column header." : { + }, "Also updating:" : { @@ -25688,6 +25849,9 @@ }, "And %lld more" : { + }, + "AND and OR" : { + }, "AND and OR:" : { @@ -25982,6 +26146,9 @@ } } } + }, + "Answered with ^[%lld tool](inflect: true)." : { + }, "Answered with 1 tool." : { "localizations" : { @@ -26979,9 +27146,15 @@ } } } + }, + "Applied when a table first opens." : { + }, "Applies to columns added later. Existing columns keep their character set." : { + }, + "Applies to connections set to Use Default, in AI features and for MCP clients." : { + }, "Applies to grid cells, the inspector, cell popovers and the row diff." : { @@ -27853,6 +28026,9 @@ } } } + }, + "Approval is set to “%@”, so these approvals are not used now. They apply again if you choose Ask Once for Each Connection." : { + }, "Approve" : { "extractionState" : "manual", @@ -27935,6 +28111,15 @@ } } } + }, + "Approved %@" : { + + }, + "Approved connections" : { + + }, + "Approved Connections" : { + }, "Approximate row count reported by the engine" : { "extractionState" : "manual", @@ -27989,6 +28174,18 @@ } } } + }, + "Apps using it lose access now, and the token leaves this list." : { + + }, + "Apps using it lose access now. This can't be undone." : { + + }, + "Apps using them lose access now, and the tokens leave this list." : { + + }, + "Apps using them lose access now. This can't be undone." : { + }, "Archive" : { "extractionState" : "manual", @@ -29054,6 +29251,9 @@ } } } + }, + "Asks for a value for each :name placeholder before the query runs." : { + }, "Assistant" : { "localizations" : { @@ -30537,6 +30737,9 @@ "Automatic does not work through a tunnel to %@. DuckDB would use HTTPS and check the certificate against 127.0.0.1, not against the server's name. Set SSL Mode to Verify Fingerprint or Required (skip verify), or to Disabled if the server serves plain HTTP." : { "extractionState" : "manual", "generatesSymbol" : false + }, + "Automatic Updates" : { + }, "Automatically check for updates" : { "localizations" : { @@ -34758,6 +34961,9 @@ } } } + }, + "Cancel Update" : { + }, "Canceling" : { @@ -35893,6 +36099,9 @@ } } } + }, + "Case" : { + }, "Case-insensitive substring to look for" : { "localizations" : { @@ -37532,6 +37741,36 @@ "state" : "translated", "value" : "Jeu de caractères" } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "문자 집합" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Karakter Seti" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Bảng mã" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "字符集" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "字集" + } } } }, @@ -37857,6 +38096,15 @@ } } } + }, + "Chat, Agent mode, inline suggestions and query actions such as Explain and Optimize." : { + + }, + "ChatGPT account" : { + + }, + "ChatGPT Account" : { + }, "ChatGPT did not return an access token." : { "localizations" : { @@ -38162,6 +38410,9 @@ }, "Check Now" : { + }, + "Check open connections" : { + }, "Check Skipped" : { @@ -38349,6 +38600,9 @@ "Checkered Flag" : { "extractionState" : "manual", "generatesSymbol" : false + }, + "Checking for a compatible build" : { + }, "Checking for the Claude Code command line tool…" : { "localizations" : { @@ -38636,6 +38890,9 @@ } } } + }, + "Choose a .tableplugin bundle or a .zip archive, or drop one on this window." : { + }, "Choose a %@ export file to import" : { "localizations" : { @@ -38977,6 +39234,16 @@ } } }, + "Choose a port from %d to %d." : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "new", + "value" : "Choose a port from %1$d to %2$d." + } + } + } + }, "Choose a private key file" : { "localizations" : { "fr" : { @@ -39451,6 +39718,9 @@ } } } + }, + "Choose an active provider or turn on Apple Intelligence first." : { + }, "Choose an AI provider in Settings to chat." : { @@ -40253,6 +40523,9 @@ } } } + }, + "Claude Agent" : { + }, "Claude Agent can't use this connection: TablePro couldn't create its access token. Try again." : { @@ -40488,6 +40761,9 @@ } } } + }, + "Clause items" : { + }, "Clause items:" : { @@ -40931,6 +41207,9 @@ } } } + }, + "Clear query history" : { + }, "Clear Query History?" : { "localizations" : { @@ -41011,6 +41290,9 @@ } } } + }, + "Clear Recent Connections" : { + }, "Clear Recent Tables" : { "localizations" : { @@ -41609,6 +41891,9 @@ } } } + }, + "Click + to add a theme, or drop a TablePro or VS Code theme file here." : { + }, "Click a table" : { "localizations" : { @@ -41717,6 +42002,9 @@ } } } + }, + "Clicking a table opens it in a preview tab that the next click reuses. Double-click a table or press Return to keep its tab." : { + }, "Client" : { "localizations" : { @@ -42173,6 +42461,12 @@ }, "Client: %@" : { + }, + "Clients" : { + + }, + "Clients ask again the next time they reach a connection." : { + }, "Clients can connect once the MCP server is running." : { @@ -46179,6 +46473,9 @@ } } } + }, + "Command Line Tool" : { + }, "Command line tool failed: %@" : { "localizations" : { @@ -46232,6 +46529,9 @@ } } } + }, + "Commas" : { + }, "Commas:" : { @@ -46433,6 +46733,9 @@ }, "Committed" : { + }, + "Committed saves stay committed. Their previous values can no longer be restored." : { + }, "Committing…" : { @@ -46989,6 +47292,9 @@ } } } + }, + "Compare what each plan includes." : { + }, "Compare With" : { @@ -47440,6 +47746,9 @@ } } } + }, + "Complete Word" : { + }, "Composite Type" : { "localizations" : { @@ -49432,6 +49741,9 @@ } } } + }, + "Connection history" : { + }, "Connection is read only for external clients" : { "localizations" : { @@ -50017,6 +50329,9 @@ } } } + }, + "Connection test" : { + }, "Connection test failed" : { "localizations" : { @@ -50651,6 +50966,15 @@ }, "Connections on this profile share one database user. TablePro renews its lease while in use, revokes it once the last connection disconnects or after 10 minutes unused, and never saves the generated password." : { + }, + "Connections set to Local only are left out." : { + + }, + "Connections that use a profile sign in with its username and password. Edit it once to update them all." : { + + }, + "Connections that use an SSH profile tunnel through its server. Changes reach every connection that uses it." : { + }, "Connections the client may use, ordered by name" : { "localizations" : { @@ -50691,6 +51015,9 @@ } } } + }, + "Connections without their own AI Policy use it. Clients cannot query a connection set to Never." : { + }, "Connections:" : { "extractionState" : "stale", @@ -51205,6 +51532,9 @@ } } } + }, + "Controls, sidebars and Settings follow this. Applies to this Mac." : { + }, "Conversation History" : { "localizations" : { @@ -53142,6 +53472,9 @@ } } } + }, + "Copy rows as" : { + }, "Copy rows as:" : { @@ -53337,6 +53670,9 @@ }, "Copy the setup into %@" : { + }, + "Copy this token now. TablePro won't show it again." : { + }, "Copy to" : { "localizations" : { @@ -55961,6 +56297,12 @@ } } } + }, + "Couldn't Clear Query History" : { + + }, + "Couldn't Clear Saved Changes" : { + }, "Couldn't connect" : { "extractionState" : "manual", @@ -55978,6 +56320,9 @@ }, "Couldn't Create the Token" : { + }, + "Couldn't Delete Profile" : { + }, "Couldn't Detach Partition" : { @@ -55997,6 +56342,9 @@ }, "Couldn't Drop Partition" : { + }, + "Couldn't Duplicate Profile" : { + }, "Couldn't Duplicate the Theme" : { @@ -56067,6 +56415,9 @@ }, "Couldn't Move the Theme to the Trash" : { + }, + "Couldn't Move to Trash" : { + }, "Couldn't Optimize Table" : { @@ -56345,6 +56696,9 @@ } } } + }, + "Couldn't Save the Command" : { + }, "Couldn't Save the Deletion" : { @@ -56354,6 +56708,9 @@ }, "Couldn't start" : { + }, + "Couldn't Uninstall" : { + }, "Couldn't update" : { @@ -57788,6 +58145,9 @@ }, "Credential profiles can't be read right now, so connections keep their own credentials." : { + }, + "Credential profiles couldn't be read, so none are shown. TablePro won't save over them." : { + }, "Credentials" : { "localizations" : { @@ -58576,6 +58936,9 @@ } } } + }, + "Cursor on my Mac" : { + }, "Cursor position %d exceeds SQL length (%d)" : { "localizations" : { @@ -58853,6 +59216,9 @@ } } } + }, + "Custom Provider" : { + }, "Custom Slash Commands" : { "localizations" : { @@ -59234,6 +59600,9 @@ }, "Dark theme" : { + }, + "Dark, in use" : { + }, "Dashboard" : { "extractionState" : "stale", @@ -59832,6 +60201,9 @@ } } } + }, + "Data types" : { + }, "database" : { @@ -60050,6 +60422,9 @@ } } } + }, + "Database Drivers" : { + }, "Database engine" : { "localizations" : { @@ -61416,6 +61791,9 @@ } } } + }, + "Database type" : { + }, "Database Type" : { "localizations" : { @@ -61829,6 +62207,46 @@ }, "Date and Time" : { + }, + "Date format" : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Format de date" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "날짜 형식" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Tarih biçimi" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Định dạng ngày" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "日期格式" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "日期格式" + } + } + } }, "Date format:" : { "localizations" : { @@ -62580,6 +62998,19 @@ } } } + }, + "Default %@ is used by “%@”." : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "new", + "value" : "Default %1$@ is used by “%2$@”." + } + } + } + }, + "Default AI policy" : { + }, "Default collation" : { "localizations" : { @@ -62677,6 +63108,12 @@ } } } + }, + "Default JSON view" : { + + }, + "Default layout" : { + }, "Default layout for new connections:" : { "localizations" : { @@ -62804,6 +63241,9 @@ } } } + }, + "Default port" : { + }, "Default Port" : { "localizations" : { @@ -62967,6 +63407,9 @@ } } } + }, + "Default sort" : { + }, "Default sorting field: %@" : { "extractionState" : "manual", @@ -63330,6 +63773,9 @@ } } } + }, + "Delay" : { + }, "Delete" : { "localizations" : { @@ -63490,6 +63936,9 @@ }, "Delete %d tokens?" : { + }, + "Delete %d Tokens?" : { + }, "Delete %lld columns?" : { "localizations" : { @@ -63651,6 +64100,9 @@ } } } + }, + "Delete Backward" : { + }, "Delete Check Constraint" : { "localizations" : { @@ -63777,6 +64229,9 @@ } } } + }, + "Delete Command…" : { + }, "Delete Connection" : { "localizations" : { @@ -64016,6 +64471,9 @@ }, "Delete Foreign Key %@" : { + }, + "Delete Forward" : { + }, "Delete Group" : { "localizations" : { @@ -65592,6 +66050,36 @@ "state" : "translated", "value" : "Destination" } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "대상" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Hedef" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Đích" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "目标" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "目的地" + } } } }, @@ -68507,6 +68995,9 @@ } } } + }, + "Draws strings, numbers, dates and other typed values in the theme's Values colors." : { + }, "Driver Options" : { "comment" : "A section for driver-specific options.", @@ -70918,6 +71409,9 @@ }, "Each file below reports what happened to its changes." : { + }, + "Each link asks again before it connects. This applies only to this Mac." : { + }, "Each row takes a value that exists in the referenced table." : { @@ -70941,6 +71435,9 @@ } } } + }, + "Earlier versions of query tabs are kept this long too, up to 30 days." : { + }, "Earliest" : { "localizations" : { @@ -71031,6 +71528,9 @@ } } } + }, + "Edit %@" : { + }, "Edit %@ Connection" : { "localizations" : { @@ -72975,6 +73475,9 @@ } } } + }, + "Enable AI features" : { + }, "Enable AI Features" : { "localizations" : { @@ -73826,6 +74329,9 @@ } } } + }, + "Engines that match function and type names by exact case, such as ClickHouse, keep the case you typed." : { + }, "Engines that match function names by exact case, such as ClickHouse, keep the case you typed." : { @@ -74033,6 +74539,9 @@ }, "Enter a whole number from 1 to %@." : { + }, + "Enter a whole number." : { + }, "Enter an absolute path, as it appears on the SSH server." : { "localizations" : { @@ -74337,6 +74846,9 @@ } } } + }, + "Enter the code on GitHub" : { + }, "Enter the ElastiCache cache name (replication group ID) to use IAM authentication." : { "extractionState" : "manual", @@ -74600,6 +75112,9 @@ } } } + }, + "Enter where the password is read from." : { + }, "Enter whole numbers only." : { @@ -76433,6 +76948,9 @@ } } } + }, + "Every section returns to its default values. AI providers and their API keys, Enable AI features, Share usage data, linked folders, trusted links, connections and history are kept." : { + }, "Every shared column is generated, so there is nothing to write." : { "localizations" : { @@ -76473,6 +76991,9 @@ } } } + }, + "Every shortcut you changed goes back to its default." : { + }, "Every table needs at least one column. Click + to get started" : { "localizations" : { @@ -76622,6 +77143,9 @@ }, "Evictions" : { + }, + "Exact row count" : { + }, "Exact value" : { "localizations" : { @@ -79577,6 +80101,9 @@ } } } + }, + "Export Formats" : { + }, "Export multiple tables" : { "localizations" : { @@ -86280,6 +86807,9 @@ } } } + }, + "Font size" : { + }, "Font:" : { "extractionState" : "stale", @@ -86804,6 +87334,9 @@ }, "Forget %@" : { + }, + "Forget %1$@ for %2$@" : { + }, "Forget All" : { "localizations" : { @@ -86844,6 +87377,15 @@ } } } + }, + "Forget All Approvals?" : { + + }, + "Forget All Trusted Links?" : { + + }, + "Forget All…" : { + }, "Forgets which connections you opened and when. Sorting by Last Connected starts over." : { "localizations" : { @@ -86906,6 +87448,36 @@ "state" : "translated", "value" : "Format" } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "형식" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Biçim" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Định dạng" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "格式" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "格式" + } } } }, @@ -87108,6 +87680,9 @@ } } } + }, + "Formatted preview" : { + }, "Formatter" : { @@ -88166,6 +88741,9 @@ } } } + }, + "Generate Token…" : { + }, "Generate UUID" : { @@ -88771,6 +89349,12 @@ }, "Git stopped with the message below." : { + }, + "GitHub account" : { + + }, + "GitHub Account" : { + }, "GitHub Repository" : { "localizations" : { @@ -89956,6 +90540,9 @@ "Grid" : { "extractionState" : "manual", "generatesSymbol" : false + }, + "Grid cells, the inspector, cell popovers and the row diff. Applies to this Mac." : { + }, "Grid Line" : { "extractionState" : "manual", @@ -92507,6 +93094,9 @@ } } } + }, + "How plans, devices and offline files work." : { + }, "How to read value: percent is a fraction (0.25 means 25 percent), date is ISO 8601" : { @@ -94186,6 +94776,9 @@ } } } + }, + "Import Formats" : { + }, "Import from %@" : { "localizations" : { @@ -94457,6 +95050,36 @@ "state" : "translated", "value" : "Importer dans" } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "가져올 위치" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Şuraya içe aktar" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Nhập vào" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "导入到" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "匯入到" + } } } }, @@ -94602,6 +95225,9 @@ }, "Import Offline File…" : { + }, + "Import Options" : { + }, "Import rows into a table" : { "localizations" : { @@ -94759,6 +95385,9 @@ }, "Imported %d themes." : { + }, + "Imported ^[%lld Theme](inflect: true)" : { + }, "Imported 1 theme." : { @@ -95048,6 +95677,9 @@ } } } + }, + "In the sidebar, the inspector and data grid column header tooltips." : { + }, "In-memory data store and cache" : { "localizations" : { @@ -96073,12 +96705,21 @@ } } } + }, + "Indent width" : { + }, "Indent width:" : { + }, + "Indent with" : { + }, "Indent with:" : { + }, + "Indentation" : { + }, "Index" : { @@ -97162,6 +97803,9 @@ "INSERT needs a JSON object of cells, such as INSERT events/user#42 {\"profile:name\": \"Ann\"}." : { "extractionState" : "manual", "generatesSymbol" : false + }, + "Insert Non-Breaking Space" : { + }, "INSERT only sets cells. Leave %@ out, or delete it with PUT." : { "extractionState" : "manual", @@ -97458,6 +98102,9 @@ } } } + }, + "Insert Space" : { + }, "INSERT Statement(s)" : { "localizations" : { @@ -97804,9 +98451,15 @@ }, "Install %@…" : { + }, + "Install a plugin" : { + }, "Install adds TablePro to a client on this Mac. Select a client to see its settings and set it up by hand." : { + }, + "Install from File…" : { + }, "Install in %@" : { @@ -99817,6 +100470,19 @@ }, "It expires on %@. Create a new one in your account and import it." : { + }, + "It is used by “%@” in %@, which will have no shortcut." : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "new", + "value" : "It is used by “%1$@” in %2$@, which will have no shortcut." + } + } + } + }, + "It is used by %@. They will have no shortcut." : { + }, "It stays on this Mac and never syncs, because it can name a command to run." : { @@ -99830,12 +100496,21 @@ "It supports these host key types: %@." : { "extractionState" : "manual", "generatesSymbol" : false + }, + "It was changed outside TablePro and no longer loads. Settings > Appearance > Manage Themes lists it under Couldn't Load with the reason." : { + }, "It was changed outside TablePro and no longer loads. Settings > Appearance lists it under Not Loaded with the reason." : { }, "It was changed outside TablePro. The editor now shows the newer version." : { + }, + "It was copied to the clipboard and expires in 15 minutes." : { + + }, + "It was removed or replaced." : { + }, "Item count is approximate, updated about every six hours" : { "extractionState" : "manual", @@ -99981,10 +100656,22 @@ } } } + }, + "Its saved secrets couldn't be read or copied, so no copy was made." : { + + }, + "Its saved secrets or the connections that use it couldn't be updated, so nothing was deleted." : { + }, "Its server session may still be running and holding its locks." : { "extractionState" : "manual", "generatesSymbol" : false + }, + "Its settings are removed from every Mac that syncs settings, and its API key is deleted from the Keychain." : { + + }, + "Its settings are removed from every Mac that syncs settings." : { + }, "Its structure could not be read." : { "localizations" : { @@ -100016,6 +100703,9 @@ "JDWP error %d." : { "extractionState" : "manual", "generatesSymbol" : false + }, + "Join condition" : { + }, "Join condition:" : { @@ -100341,6 +101031,9 @@ }, "Jump host %1$@ failed: %2$@" : { + }, + "Jump Host %lld" : { + }, "Jump host configuration is invalid" : { "localizations" : { @@ -100729,6 +101422,46 @@ } } }, + "Keep entries for" : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Conserver les entrées pendant" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "항목 보관 기간" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Kayıtları saklama süresi" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Giữ mục trong" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "保留记录" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "保留記錄" + } + } + } + }, "Keep entries for:" : { "localizations" : { "fr" : { @@ -101101,6 +101834,9 @@ } } } + }, + "Keep your connections and the items you choose the same on devices signed in to your Apple Account." : { + }, "Keeps the first row of each group of matching rows. Rows hidden by a filter or search are not compared." : { "localizations" : { @@ -101124,6 +101860,9 @@ }, "Keeps up to %1$d versions from the last %2$d days on this Mac." : { + }, + "Keeps what rows looked like before each save, for 7 days, on this Mac only. Encrypted and never synced." : { + }, "Keeps what rows looked like before each save, on this Mac only, for 7 days. It is encrypted, and never synced." : { "localizations" : { @@ -101365,6 +102104,9 @@ } } } + }, + "Key bindings" : { + }, "Key bindings:" : { @@ -102003,6 +102745,16 @@ } } }, + "Keyword case" : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Casse des mots-clés" + } + } + } + }, "Keyword case:" : { "localizations" : { "fr" : { @@ -102093,6 +102845,9 @@ } } } + }, + "Keywords" : { + }, "killing a server session" : { "localizations" : { @@ -102380,6 +103135,46 @@ }, "Lakehouse analytics, MySQL protocol" : { + }, + "Language" : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Langue" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "언어" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Dil" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Ngôn ngữ" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "语言" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "語言" + } + } + } }, "Language %@" : { "localizations" : { @@ -102544,6 +103339,9 @@ } } } + }, + "Larger tables show an estimated count, which avoids a slow COUNT(*)." : { + }, "Largest INSERT written: %1$@ (%2$lld rows)." : { "extractionState" : "manual", @@ -103100,6 +103898,9 @@ }, "Last seen %@" : { + }, + "Last synced" : { + }, "Last Synced" : { "localizations" : { @@ -103456,6 +104257,9 @@ }, "Learn More About Licensing" : { + }, + "Learn More…" : { + }, "Lease can only be compared with a lease ID, such as 0x7b." : { "extractionState" : "manual", @@ -103528,6 +104332,12 @@ } } } + }, + "Leave blank to use Settings > Connections: %@." : { + + }, + "Leave blank to use Settings > Connections: no limit." : { + }, "Leave blank to use the global %d-second timeout. This setting applies only to database drivers that support it." : { "localizations" : { @@ -104069,6 +104879,9 @@ } } } + }, + "Lets AI apps such as Claude and Cursor work with your connections through TablePro." : { + }, "Library" : { "extractionState" : "manual", @@ -104942,6 +105755,9 @@ }, "Light theme" : { + }, + "Light, in use" : { + }, "Limit" : { "localizations" : { @@ -105268,6 +106084,9 @@ } } } + }, + "Line Breaks" : { + }, "Line Chart" : { "extractionState" : "manual", @@ -105354,9 +106173,15 @@ } } } + }, + "Line width" : { + }, "Line width:" : { + }, + "Lines up the AS of each SELECT item that sits on one line." : { + }, "Link" : { "extractionState" : "manual", @@ -107897,6 +108722,9 @@ } } } + }, + "Loading models…" : { + }, "Loading one sets the source, the target, the mode and these options. The Comparisons button in the toolbar lists them too." : { "localizations" : { @@ -108581,6 +109409,9 @@ } } } + }, + "Long values wrap onto up to 10 lines in new tabs. View > Wrap Text changes the open grid." : { + }, "Long values wrap onto up to 10 lines. Applies to new tabs; View > Wrap Text changes the open grid." : { @@ -109649,6 +110480,9 @@ } } } + }, + "Manage Themes" : { + }, "Manage…" : { @@ -109843,6 +110677,9 @@ }, "Marked for deletion. Undo or Undo Delete brings it back." : { + }, + "Marks zero-width, control and special space characters in cells and value fields." : { + }, "Mask" : { "localizations" : { @@ -110470,6 +111307,9 @@ } } } + }, + "Match System follows Sidebar icon size in System Settings." : { + }, "Match what I type" : { @@ -111210,6 +112050,46 @@ "extractionState" : "manual", "generatesSymbol" : false }, + "Maximum entries" : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Nombre maximal d’entrées" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "최대 항목 수" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Maksimum kayıt" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Số mục tối đa" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "最大条目数" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "最大項目數" + } + } + } + }, "Maximum entries cannot be negative" : { "localizations" : { "fr" : { @@ -111409,6 +112289,9 @@ } } } + }, + "Maximum output tokens" : { + }, "Maximum row limit" : { "localizations" : { @@ -111529,6 +112412,9 @@ } } } + }, + "Maximum tables" : { + }, "Maximum tabs to return (1-500, default 20)" : { "localizations" : { @@ -111779,6 +112665,9 @@ } } } + }, + "MCP server" : { + }, "MCP Server" : { "extractionState" : "stale", @@ -113564,6 +114453,9 @@ } } } + }, + "Model list" : { + }, "Moderate cost" : { "comment" : "Accessibility label for a moderate cost.", @@ -114171,6 +115063,9 @@ }, "Move “%@” to the Trash?" : { + }, + "Move %@ to the Trash" : { + }, "Move Column Down" : { "localizations" : { @@ -115053,6 +115948,9 @@ } } } + }, + "Move to Trash…" : { + }, "Move Up" : { "localizations" : { @@ -115227,6 +116125,9 @@ } } } + }, + "ms" : { + }, "Multi-model database with SurrealQL" : { "localizations" : { @@ -116287,6 +117188,9 @@ }, "Needs attention" : { + }, + "Needs line numbers." : { + }, "Needs MySQL 8.0 or later." : { @@ -118625,6 +119529,9 @@ }, "No analyze recorded in the server's statistics, and this user cannot read the table's statistics to confirm it." : { + }, + "No approved connections. A connection a client may reach without asking again appears here." : { + }, "No Attached Databases" : { @@ -119463,6 +120370,9 @@ } } } + }, + "No credential profiles" : { + }, "No credential profiles yet." : { "localizations" : { @@ -119553,6 +120463,9 @@ } } } + }, + "No custom shortcuts" : { + }, "No Data" : { "localizations" : { @@ -120026,6 +120939,9 @@ } } } + }, + "No devices are signed in." : { + }, "No Differences" : { "localizations" : { @@ -120833,6 +121749,9 @@ } } } + }, + "No linked folders" : { + }, "No linked folders. Add a folder to watch for shared connection files." : { "localizations" : { @@ -121067,6 +121986,9 @@ } } } + }, + "No matching connections" : { + }, "No Matching Connections" : { "localizations" : { @@ -122073,6 +122995,9 @@ } } } + }, + "No providers" : { + }, "No providers configured" : { "localizations" : { @@ -122679,6 +123604,9 @@ } } } + }, + "No Results for “%@”" : { + }, "No results for \"%@\"." : { "localizations" : { @@ -123320,6 +124248,9 @@ }, "No sequences" : { + }, + "No servers" : { + }, "No servers yet." : { "localizations" : { @@ -123350,6 +124281,9 @@ } } } + }, + "No slash commands" : { + }, "No slow queries" : { "localizations" : { @@ -123460,6 +124394,9 @@ } } } + }, + "No SSH profiles" : { + }, "No SSH servers yet." : { "localizations" : { @@ -123924,6 +124861,9 @@ } } } + }, + "No Tokens" : { + }, "No tokens created" : { "localizations" : { @@ -124068,6 +125008,9 @@ } } } + }, + "No trusted links" : { + }, "No typed documents. Update the database driver, save changes and reload before exporting MQL." : { "extractionState" : "manual", @@ -125720,6 +126663,9 @@ } } } + }, + "Not included" : { + }, "Not installed" : { "localizations" : { @@ -126012,6 +126958,9 @@ } } } + }, + "Not set" : { + }, "Not signed in" : { "localizations" : { @@ -126396,6 +127345,9 @@ } } } + }, + "Not used" : { + }, "Not valid %@. %@ Showing the stored bytes." : { "localizations" : { @@ -127038,6 +127990,9 @@ } } } + }, + "Notifications are off in System Settings" : { + }, "Notifications are turned off for TablePro in System Settings." : { "localizations" : { @@ -127283,6 +128238,46 @@ } } }, + "NULL display" : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Affichage de NULL" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "NULL 표시" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "NULL görünümü" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Hiển thị NULL" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "NULL 显示" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "NULL 顯示" + } + } + } + }, "NULL display cannot be empty" : { "localizations" : { "fr" : { @@ -128530,6 +129525,12 @@ "Offline" : { "extractionState" : "manual", "generatesSymbol" : false + }, + "Offline file" : { + + }, + "Offline File and License Key" : { + }, "Offline file expired on %@" : { @@ -129873,6 +130874,9 @@ } } } + }, + "Only when used" : { + }, "open" : { @@ -134262,6 +135266,9 @@ } } } + }, + "Page size" : { + }, "Page Size" : { "extractionState" : "stale", @@ -134390,6 +135397,9 @@ } } } + }, + "Pages and Limits" : { + }, "Pagination" : { "localizations" : { @@ -134470,9 +135480,15 @@ } } } + }, + "Paid features stop on this Mac until you sign in again." : { + }, "Paid plan" : { + }, + "Paid plans" : { + }, "Paid plans add the features below." : { @@ -134782,6 +135798,9 @@ } } } + }, + "Part of the history couldn't be deleted. Try again." : { + }, "Partial files may remain on disk." : { "localizations" : { @@ -135934,6 +136953,9 @@ } } } + }, + "Password Source" : { + }, "password value" : { "localizations" : { @@ -137031,6 +138053,9 @@ } } } + }, + "Permissions" : { + }, "Person" : { "extractionState" : "manual", @@ -137286,6 +138311,9 @@ } } } + }, + "Pick a model to add this provider." : { + }, "Pick a model to save this provider." : { "localizations" : { @@ -137842,6 +138870,9 @@ } } } + }, + "Plans and devices" : { + }, "Plans are not saved for queries that carry parameters, because a database can print the values into its plan output." : { "localizations" : { @@ -138335,6 +139366,9 @@ } } } + }, + "Plugin Not Available" : { + }, "Plugin not found" : { "localizations" : { @@ -138679,6 +139713,9 @@ }, "Plugin updates are ready" : { + }, + "Plugin updates install when TablePro relaunches." : { + }, "Plugin was built for PluginKit version %d; this release of TablePro needs version %d." : { "localizations" : { @@ -139522,6 +140559,9 @@ } } } + }, + "Preferences and custom themes. Some settings, such as fonts and the appearance mode, stay on this Mac." : { + }, "Preferred" : { "extractionState" : "manual", @@ -139997,6 +141037,12 @@ } } } + }, + "Press Tab to accept, Escape to dismiss." : { + + }, + "Press to record a new shortcut. Delete removes it, Escape cancels." : { + }, "PrestoDB distributed SQL query engine" : { @@ -142428,6 +143474,9 @@ } } } + }, + "Profile, sign-in methods and billing" : { + }, "Profiles" : { "localizations" : { @@ -142707,6 +143756,9 @@ } } } + }, + "Prompt Template" : { + }, "Propose indexes for a slow query" : { "localizations" : { @@ -144626,6 +145678,9 @@ } } } + }, + "Query parameters" : { + }, "Query parameters (:name syntax)" : { "localizations" : { @@ -144708,6 +145763,9 @@ } } } + }, + "Query result limit" : { + }, "Query Result Row Cap" : { "localizations" : { @@ -147700,6 +148758,16 @@ } } }, + "Reassign %@ to “%@”?" : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "new", + "value" : "Reassign %1$@ to “%2$@”?" + } + } + } + }, "Reassign owned objects" : { "localizations" : { "fr" : { @@ -147922,6 +148990,9 @@ } } } + }, + "Recent Connections" : { + }, "Recent Conversations" : { "localizations" : { @@ -148397,6 +149468,12 @@ } } } + }, + "Record Shortcut" : { + + }, + "Recording" : { + }, "Recording shortcut" : { "localizations" : { @@ -149636,6 +150713,9 @@ }, "Relaunch Now" : { + }, + "Relaunch TablePro to finish" : { + }, "Relaunch TablePro to finish removing plugins." : { @@ -151384,6 +152464,9 @@ } } } + }, + "Remove Jump Host" : { + }, "Remove Linked Folder?" : { "localizations" : { @@ -151424,6 +152507,9 @@ } } } + }, + "Remove old entries automatically" : { + }, "Remove one in Settings to use your plan on this Mac." : { @@ -151510,6 +152596,9 @@ } } } + }, + "Remove Provider…" : { + }, "Remove Rule" : { "localizations" : { @@ -151530,6 +152619,12 @@ } } } + }, + "Remove Server?" : { + + }, + "Remove Server…" : { + }, "Remove SET client_min_messages from the routine to debug it." : { "extractionState" : "manual", @@ -151538,6 +152633,9 @@ "Remove SET transaction_timeout from the routine to debug it." : { "extractionState" : "manual", "generatesSymbol" : false + }, + "Remove Shortcut" : { + }, "Remove TablePro from %@?" : { @@ -151659,6 +152757,9 @@ }, "Remove this change from the queue" : { + }, + "Remove this plugin" : { + }, "Remove this rule" : { "localizations" : { @@ -151732,6 +152833,12 @@ }, "Removed from the team library" : { + }, + "Removed plugins stay loaded until TablePro relaunches." : { + + }, + "Removes entries past these limits at launch, every 100 queries and when a limit changes. Removed entries can't be recovered." : { + }, "Removing" : { @@ -152836,6 +153943,9 @@ } } } + }, + "Requests go to" : { + }, "Requests to this host are sent unencrypted over http." : { "localizations" : { @@ -152846,6 +153956,9 @@ } } } + }, + "Requests, approvals and connected clients." : { + }, "Require authentication" : { "extractionState" : "stale", @@ -153161,6 +154274,12 @@ } } } + }, + "Reset %@ to default" : { + + }, + "Reset all settings" : { + }, "Reset All Settings" : { "localizations" : { @@ -153241,6 +154360,12 @@ } } } + }, + "Reset all settings?" : { + + }, + "Reset All Settings…" : { + }, "Reset All Shortcuts?" : { @@ -153524,6 +154649,9 @@ } } } + }, + "Reset to %@" : { + }, "Reset to default" : { "localizations" : { @@ -153564,6 +154692,9 @@ } } } + }, + "Reset to Default" : { + }, "Reset to Defaults" : { "localizations" : { @@ -153644,6 +154775,9 @@ } } } + }, + "Reset to None" : { + }, "Reset to System Default" : { "extractionState" : "stale", @@ -153725,6 +154859,9 @@ } } } + }, + "Reset…" : { + }, "Resident Memory" : { @@ -154133,9 +155270,18 @@ } } } + }, + "Restore default rules" : { + + }, + "Restore Default Shortcuts?" : { + }, "Restore Defaults" : { + }, + "Restore Defaults…" : { + }, "Restore Dump Cancelled" : { "comment" : "A title for a result sheet that indicates a restore operation was cancelled.", @@ -155243,6 +156389,9 @@ } } } + }, + "Results kept per run" : { + }, "Results kept per run:" : { @@ -155746,6 +156895,12 @@ } } } + }, + "Returns every rule on this page to its default." : { + + }, + "Returns every section to its defaults." : { + }, "Reuse Result For" : { @@ -156119,6 +157274,9 @@ } } } + }, + "Revoke %d Tokens?" : { + }, "Revoke All" : { "localizations" : { @@ -156199,6 +157357,9 @@ } } } + }, + "Revoke…" : { + }, "Revoked" : { "localizations" : { @@ -157438,6 +158599,46 @@ } } }, + "Row height" : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Hauteur des lignes" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "행 높이" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Satır yüksekliği" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Chiều cao dòng" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "行高" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "列高" + } + } + } + }, "Row height:" : { "localizations" : { "fr" : { @@ -157663,6 +158864,46 @@ } } }, + "Row size" : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Taille des lignes" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "행 크기" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Satır boyutu" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Cỡ hàng" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "行大小" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "列大小" + } + } + } + }, "Row size:" : { "comment" : "A label for the size of the sidebar rows.", "isCommentAutoGenerated" : true, @@ -157790,6 +159031,9 @@ } } } + }, + "Rows a query returns when the client sets no limit." : { + }, "Rows already transferred stay." : { @@ -158565,6 +159809,12 @@ } } } + }, + "Rules file" : { + + }, + "Rules File" : { + }, "Rules file:" : { @@ -159616,6 +160866,9 @@ } } } + }, + "Runs on this Mac and sends nothing over the network. Chat and Agent mode keep the active provider." : { + }, "Runs statements on the SSH server so a database file there can be read and written in place." : { "localizations" : { @@ -159707,6 +160960,9 @@ } } } + }, + "Runs the claude command line tool, so chat bills against your Claude subscription. Database tools need the MCP server, in Settings > MCP." : { + }, "Runs the Google Cloud SQL Auth Proxy against an instance connection name." : { "localizations" : { @@ -160015,6 +161271,9 @@ }, "Same as editor (%@)" : { + }, + "Same as editor (%lld)" : { + }, "same element" : { "localizations" : { @@ -161353,6 +162612,9 @@ } } } + }, + "Saved connections that use it stay in your library." : { + }, "Saved Customizations" : { "extractionState" : "stale", @@ -161404,6 +162666,9 @@ } } } + }, + "Saved in Keychain" : { + }, "Saved in the Keychain" : { "localizations" : { @@ -161414,6 +162679,9 @@ } } } + }, + "Saved in the Keychain once and used by every connection on this profile." : { + }, "Saved password" : { "localizations" : { @@ -164046,6 +165314,9 @@ } } } + }, + "Search Shortcuts" : { + }, "Search shortcuts…" : { "localizations" : { @@ -164234,6 +165505,9 @@ }, "Seat" : { + }, + "Seat assigned" : { + }, "Seats on a team license are managed on tablepro.app." : { "localizations" : { @@ -165682,6 +166956,9 @@ } } } + }, + "Select None" : { + }, "Select objects of the same kind to edit their privileges." : { "localizations" : { @@ -165805,6 +167082,9 @@ } } } + }, + "SELECT queries without their own LIMIT stop at this many rows. The editor text never changes. Fetch All and Execute Without Limit skip it once." : { + }, "Select Tab %d" : { "localizations" : { @@ -166249,6 +167529,9 @@ }, "Sending this Mac's environment variables to the server was not approved." : { + }, + "Sends one short request with this key and Base URL." : { + }, "Sends the code to %@" : { "localizations" : { @@ -168329,6 +169612,9 @@ }, "Set up" : { + }, + "Set Up a Client" : { + }, "Set up an app to use TablePro's MCP server" : { @@ -168499,6 +169785,9 @@ }, "Settings file" : { + }, + "Settings sections" : { + }, "Settings:" : { "extractionState" : "stale", @@ -169824,6 +171113,9 @@ } } } + }, + "Show comments" : { + }, "Show Completions" : { "localizations" : { @@ -170038,6 +171330,9 @@ } } } + }, + "Show Devices" : { + }, "Show edited fields only" : { "localizations" : { @@ -170159,6 +171454,9 @@ } } } + }, + "Show icons" : { + }, "Show Identical Objects" : { "localizations" : { @@ -170242,6 +171540,9 @@ } } } + }, + "Show in Theme Editor" : { + }, "Show Inspector" : { "localizations" : { @@ -170282,6 +171583,9 @@ } } } + }, + "Show inspector when a row is selected" : { + }, "Show invisible characters" : { "extractionState" : "manual", @@ -170500,6 +171804,9 @@ } } } + }, + "Show notifications" : { + }, "Show object comments" : { "localizations" : { @@ -170630,6 +171937,9 @@ } } } + }, + "Show passphrase" : { + }, "Show password" : { "localizations" : { @@ -171015,6 +172325,9 @@ }, "Show rows in %@" : { + }, + "Show secret" : { + }, "Show Sidebar" : { "localizations" : { @@ -171204,6 +172517,9 @@ }, "Show the messages that arrived while paused" : { + }, + "Show Themes Folder in Finder" : { + }, "Show Toolbar" : { "localizations" : { @@ -172003,6 +173319,9 @@ } } } + }, + "Shows UUIDs, Unix timestamps, JSON and serialized values in a readable form, judged from the first rows." : { + }, "Side" : { "localizations" : { @@ -172053,6 +173372,9 @@ } } } + }, + "Sidebar & Tabs" : { + }, "Sidebar as List" : { "localizations" : { @@ -172464,6 +173786,9 @@ }, "Sign In With" : { + }, + "Sign In With an Account" : { + }, "Sign In with Browser…" : { "localizations" : { @@ -172694,6 +174019,15 @@ } } } + }, + "Sign out of TablePro on this Mac?" : { + + }, + "Sign Out…" : { + + }, + "Sign this Mac in with a key from an older version of TablePro." : { + }, "Sign-in cancelled" : { "localizations" : { @@ -173227,6 +174561,9 @@ } } } + }, + "Signs in with your account" : { + }, "Silent" : { "localizations" : { @@ -173931,6 +175268,9 @@ } } } + }, + "Slash Commands" : { + }, "Slow" : { "extractionState" : "stale", @@ -175040,6 +176380,46 @@ } } }, + "Sort direction" : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Sens du tri" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "정렬 방향" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Sıralama yönü" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Hướng sắp xếp" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "排序方向" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "排序方向" + } + } + } + }, "Sort direction (default ascending)" : { "localizations" : { "fr" : { @@ -175227,6 +176607,9 @@ } } } + }, + "Sorting" : { + }, "Sorting will reload data and discard all unsaved changes." : { "localizations" : { @@ -176001,6 +177384,9 @@ } } } + }, + "SQL Formatting" : { + }, "SQL Functions" : { "localizations" : { @@ -177200,6 +178586,9 @@ } } } + }, + "SSH profiles couldn't be read, so none are shown. TablePro won't save over them." : { + }, "SSH Servers" : { "localizations" : { @@ -178386,7 +179775,44 @@ } }, "Statement" : { - + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Instruction" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "SQL 문" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Statement" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Câu lệnh" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "语句" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "陳述式" + } + } + } }, "Statement %1$d of %2$d failed: %3$@" : { "extractionState" : "manual", @@ -180290,6 +181716,9 @@ } } } + }, + "Stops longer queries on drivers that support it. A connection's own timeout overrides this. Applies to connections opened after a change." : { + }, "Storage engine" : { "localizations" : { @@ -180419,6 +181848,9 @@ }, "Store in Keychain" : { + }, + "Stored in iCloud Keychain, end-to-end encrypted. Applies to each password the next time you save it." : { + }, "Stored in the macOS Keychain and written to a temporary file only while the proxy runs." : { "localizations" : { @@ -181088,6 +182520,9 @@ } } } + }, + "Such as mysql and information_schema, in the sidebar and its database filter. The database switcher always lists them." : { + }, "Suggest indexes for a slow query from its plan and the indexes the tables already have" : { "localizations" : { @@ -181168,6 +182603,9 @@ } } } + }, + "Suggest SQL while typing" : { + }, "Suggested Actions" : { "localizations" : { @@ -183573,6 +185011,46 @@ } } }, + "Tab width" : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Largeur de tabulation" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "탭 너비" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Sekme genişliği" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Độ rộng tab" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "制表符宽度" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "Tab 寬度" + } + } + } + }, "Tab width (%d)" : { }, @@ -185290,10 +186768,16 @@ "TablePro can't read %@. Check that this account can see its source." : { "extractionState" : "manual", "generatesSymbol" : false + }, + "TablePro can't read some saved connections, so it can't tell whether they use this profile." : { + }, "TablePro can't read this unit's source." : { "extractionState" : "manual", "generatesSymbol" : false + }, + "TablePro can't show any notification until you allow it there." : { + }, "TablePro can't turn text into a %2$@ value for %1$@." : { "extractionState" : "manual", @@ -185572,6 +187056,9 @@ } } } + }, + "TablePro could not read the saved token. Type it to test." : { + }, "TablePro could not read the Table Health history: %@" : { @@ -185605,6 +187092,9 @@ }, "TablePro could not save the token to the Keychain, so it was not created. Try again." : { + }, + "TablePro could not save the token to the Keychain, so the server was not saved. Try again." : { + }, "TablePro could not tell how this Dameng server treats backslashes, so it will not send a value that contains one. Reconnect, then try again." : { "extractionState" : "manual", @@ -186343,6 +187833,9 @@ } } } + }, + "TablePro reads .tablepro files saved without a passphrase from these folders. Their connections appear read only in the sidebar." : { + }, "TablePro reads this file with a driver it downloads from the plugin registry." : { "localizations" : { @@ -187884,6 +189377,9 @@ } } } + }, + "Team library changes that were not sent yet are discarded." : { + }, "Team library updated %@" : { @@ -188524,6 +190020,9 @@ } } } + }, + "Testing…" : { + }, "text" : { "localizations" : { @@ -189806,6 +191305,9 @@ } } } + }, + "The API key could not be saved to the Keychain." : { + }, "The API key will be permanently deleted." : { "localizations" : { @@ -190480,6 +191982,9 @@ }, "The cache must be at least 1." : { + }, + "The case completions use. UPPERCASE and lowercase also change keywords as you type." : { + }, "The catalog location is not a folder: %@" : { "localizations" : { @@ -193394,6 +194899,9 @@ } } } + }, + "The first call asks. The answer is remembered for that client until you forget it." : { + }, "The first call asks. The answer is remembered for that client until you revoke it." : { "localizations" : { @@ -193695,6 +195203,9 @@ }, "the import's transaction was rolled back" : { + }, + "The imported offline file is removed." : { + }, "The increment cannot be zero." : { @@ -194803,6 +196314,9 @@ } } } + }, + "The most rows a client can ask for." : { + }, "The name a statement uses for this database, as in name.table." : { @@ -195604,6 +197118,12 @@ } } } + }, + "The plugin moves to the Trash and its settings are deleted." : { + + }, + "The plugin moves to the Trash and its settings are deleted. It stays loaded until TablePro relaunches." : { + }, "The plugin was built for an incompatible runtime." : { "localizations" : { @@ -195829,6 +197349,9 @@ } } } + }, + "The profile was saved, but its password couldn't be saved to the Keychain." : { + }, "The profile's region, or us-east-1" : { "extractionState" : "manual", @@ -196896,6 +198419,9 @@ }, "The save will fail: the rows listed below still reference rows this deletes, and their foreign key doesn't allow it." : { + }, + "The saved changes couldn't be deleted. Try again." : { + }, "The saved extension list is not in a format TablePro can read." : { "extractionState" : "manual", @@ -198401,6 +199927,9 @@ } } } + }, + "The SQL editor, the JSON viewer's Text mode and SQL previews. Applies to this Mac." : { + }, "The SQL Server Kerberos service principal name is not registered." : { "extractionState" : "manual", @@ -206175,6 +207704,9 @@ } } } + }, + "This provider was removed." : { + }, "This query belongs to another connection. Load it in the editor to run it there." : { "comment" : "A description of why the \"Load in Editor\" button is disabled.", @@ -209905,12 +211437,18 @@ } } } + }, + "Tokens" : { + }, "Tokens are not available" : { }, "Tokens load while the MCP server is running." : { + }, + "Tokens Unavailable" : { + }, "Too Large to Compare" : { @@ -210146,6 +211684,9 @@ } } } + }, + "Tool call limit" : { + }, "Tool call limit: %d" : { "localizations" : { @@ -211096,6 +212637,9 @@ }, "Transferring tables to %@" : { + }, + "Treat work as long-running after" : { + }, "Tree" : { "localizations" : { @@ -212438,6 +213982,9 @@ }, "Type @ in the message to find any other table" : { + }, + "Type / in the chat to run one. A template can use {{query}}, {{schema}}, {{database}} and {{body}}." : { + }, "Type %@ in the query to set where the cursor lands after keyword expansion." : { "extractionState" : "stale", @@ -212509,6 +214056,9 @@ } } } + }, + "Type Shortcut" : { + }, "Type shortcut…" : { "localizations" : { @@ -212549,6 +214099,9 @@ } } } + }, + "Type the server's token. A saved token stays with the address it was saved for." : { + }, "Type: %@" : { "localizations" : { @@ -212809,6 +214362,9 @@ } } } + }, + "Unavailable" : { + }, "unbalanced quotes" : { "extractionState" : "manual", @@ -212883,6 +214439,9 @@ }, "Uncommitted changes on %@ are rolled back when TablePro relaunches." : { + }, + "Under ^[%lld row](inflect: true)" : { + }, "Under MCP Servers click \"+ Add Custom Server\", select the Local tab, paste the JSON below, then click Add Server" : { "localizations" : { @@ -213374,6 +214933,9 @@ } } } + }, + "Uninstall “%@”?" : { + }, "Uninstall %@" : { "localizations" : { @@ -213534,6 +215096,12 @@ } } } + }, + "Uninstall this plugin" : { + + }, + "Uninstall…" : { + }, "Unique" : { "localizations" : { @@ -215262,6 +216830,9 @@ }, "Unused Indexes" : { + }, + "Up to %lld characters" : { + }, "Up to Date" : { "extractionState" : "manual", @@ -215365,6 +216936,9 @@ }, "Update changes the rows whose key is in the file. Insert or Update also adds the rest, and Insert, Skip Existing adds only rows whose key is not in the table. Columns not mapped keep their values." : { + }, + "Update channel" : { + }, "Update channel:" : { @@ -215380,6 +216954,9 @@ } } } + }, + "Update failed" : { + }, "Update in %@" : { @@ -216431,6 +218008,9 @@ } } } + }, + "Use ⌘ or ⌃, Space, or a function key." : { + }, "Use a license key" : { @@ -216987,9 +218567,18 @@ } } } + }, + "Used for chat context, {{schema}} commands and Copilot suggestions." : { + }, "Used Memory" : { + }, + "Used only with Ask Once for Each Connection." : { + + }, + "Used when a connection opens, unless you picked a layout for it from the View menu. For servers with a database tree." : { + }, "User" : { "localizations" : { @@ -217581,6 +219170,9 @@ } } } + }, + "Uses your Plus, Pro, Business or Enterprise subscription under OpenAI's terms. This interface is unofficial and may change." : { + }, "using %@" : { "localizations" : { @@ -217929,6 +219521,9 @@ } } } + }, + "Valid until %@" : { + }, "Validate" : { @@ -218978,6 +220573,9 @@ } } } + }, + "Verified %@" : { + }, "Verified %@, valid until %@" : { "localizations" : { @@ -219894,6 +221492,9 @@ } } } + }, + "View Plans…" : { + }, "View that was read" : { "localizations" : { @@ -220127,6 +221728,9 @@ } } } + }, + "Waiting for your browser…" : { + }, "Waiting for your password" : { "localizations" : { @@ -220384,6 +221988,9 @@ }, "Was %@" : { + }, + "Watch %@" : { + }, "Watch PostgreSQL notifications, Redis channels and Kafka topics as messages arrive." : { @@ -220928,6 +222535,9 @@ } } } + }, + "What Syncs" : { + }, "What the check looks for, with its threshold" : { @@ -221175,6 +222785,49 @@ } } }, + "When long-running work finishes out of sight, an agent needs your answer or its reply fails, or an extension can't load or update." : { + + }, + "When TablePro starts" : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Au démarrage de TablePro" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "TablePro 시작 시" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "TablePro başlarken" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Khi TablePro khởi động" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "TablePro 启动时" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "TablePro 啟動時" + } + } + } + }, "When TablePro starts:" : { "localizations" : { "fr" : { @@ -221224,6 +222877,12 @@ } } } + }, + "When work this long finishes out of sight, its tab is marked and, with notifications on, a notification shows." : { + + }, + "When you last opened each connection, used by Recent and the Last Connected sort. Stays on this Mac." : { + }, "Where" : { "localizations" : { @@ -221234,6 +222893,9 @@ } } } + }, + "Where a broken SELECT, SET, WITH, WHERE or HAVING list starts. A single item stays beside its keyword." : { + }, "Where AND and OR go when a WHERE or HAVING condition breaks across lines." : { @@ -221280,6 +222942,9 @@ }, "Where the items of a SELECT list, SET list, WITH list, or WHERE or HAVING condition start once it breaks across lines. A single item stays beside its keyword." : { + }, + "Where they go when a WHERE or HAVING condition breaks." : { + }, "Whether a session is open" : { "localizations" : { @@ -224018,6 +225683,12 @@ } } } + }, + "You are not on a team." : { + + }, + "You can put it back from the Trash." : { + }, "You have %lld live links." : { "localizations" : { diff --git a/apple/TablePro/ViewModels/AIChatViewModel+SchemaContext.swift b/apple/TablePro/ViewModels/AIChatViewModel+SchemaContext.swift index c89b794567..34a3fc3e8d 100644 --- a/apple/TablePro/ViewModels/AIChatViewModel+SchemaContext.swift +++ b/apple/TablePro/ViewModels/AIChatViewModel+SchemaContext.swift @@ -121,7 +121,7 @@ extension AIChatViewModel { let scope = schemaCacheScope let schema = browsedSchema(connId) let settings = services.appSettings.ai - let tablesToFetch = Array(orderedTables().prefix(settings.maxSchemaTables)) + let tablesToFetch = Array(orderedTables().prefix(settings.clampedMaxSchemaTables)) guard !tablesToFetch.isEmpty else { return } await withTaskGroup(of: (String, [ColumnInfo]).self) { group in @@ -208,7 +208,7 @@ extension AIChatViewModel { let section = AISchemaContext.buildSchemaSection( tables: schemaTables(), defaultSchema: connection.flatMap { defaultSchema(for: $0) }, - maxTables: settings.maxSchemaTables, + maxTables: settings.clampedMaxSchemaTables, identifierQuote: identifierQuote ) return section.isEmpty ? nil : section @@ -232,7 +232,7 @@ extension AIChatViewModel { question: question, queryReferences: editorQueryReferences(), defaultSchema: connection.flatMap { defaultSchema(for: $0) }, - maxTables: services.appSettings.ai.maxSchemaTables + maxTables: services.appSettings.ai.clampedMaxSchemaTables ) guard input.tables.count > input.maxTables else { return } let scope = schemaCacheScope @@ -257,7 +257,7 @@ extension AIChatViewModel { private func loadEveryColumnForRanking() async { guard let connection else { return } let tableCount = tables.count - guard tableCount > services.appSettings.ai.maxSchemaTables, + guard tableCount > services.appSettings.ai.clampedMaxSchemaTables, tableCount <= SQLSchemaProvider.maxCachedTables, bulkColumnReadTableCount != tableCount else { return } diff --git a/apple/TablePro/ViewModels/AIChatViewModel.swift b/apple/TablePro/ViewModels/AIChatViewModel.swift index 6253afffe7..058dc3c544 100644 --- a/apple/TablePro/ViewModels/AIChatViewModel.swift +++ b/apple/TablePro/ViewModels/AIChatViewModel.swift @@ -114,6 +114,11 @@ final class AIChatViewModel: ObservableObject { var inFlightSchemaLoad: Task? var relevantTableNames: [String] = [] var schemaRanker: @Sendable (AISchemaRankingInput) -> [String] = AISchemaContext.relevantTableNames(for:) + var customSlashCommandNamed: @MainActor (String) -> CustomSlashCommand? = { + CustomSlashCommandStorage.shared.command(named: $0) + } + // A custom command picked from the menu keeps its identity, so Send runs it even when a built-in shares its name. + var composedCustomCommand: CustomSlashCommand? @Published var tableMentions = TableMentionIndex.empty var tableMentionSource: [TableInfo] = [] var tableMentionBuild: Task? @@ -194,11 +199,33 @@ final class AIChatViewModel: ObservableObject { let text = inputText.trimmingCharacters(in: .whitespacesAndNewlines) guard !text.isEmpty || !attachedImages.isEmpty else { return } + if let composed = composedCustomCommand, + let invocation = SlashCommand.invocation(in: text), + invocation.name.caseInsensitiveCompare(composed.name) == .orderedSame, + composed.isValid { + guard !isStreaming else { return } + composedCustomCommand = nil + inputText = "" + Task { await runCustomSlashCommand(composed, body: invocation.body) } + return + } + composedCustomCommand = nil + if let parsed = SlashCommand.parse(text) { runSlashCommand(parsed.command, body: parsed.body) return } + if let invocation = SlashCommand.invocation(in: text), + let command = customSlashCommandNamed(invocation.name), + command.isValid { + guard !isStreaming else { return } + // Cleared now, so a second Return before the task runs finds nothing to send. + inputText = "" + Task { await runCustomSlashCommand(command, body: invocation.body) } + return + } + var blocks: [ChatContentBlock] = [] if !text.isEmpty { blocks.append(.text(text)) diff --git a/apple/TablePro/ViewModels/WelcomeViewModel+TeamCatalog.swift b/apple/TablePro/ViewModels/WelcomeViewModel+TeamCatalog.swift index 01ee7fe723..7e74aad27c 100644 --- a/apple/TablePro/ViewModels/WelcomeViewModel+TeamCatalog.swift +++ b/apple/TablePro/ViewModels/WelcomeViewModel+TeamCatalog.swift @@ -1,10 +1,3 @@ -// -// WelcomeViewModel+TeamCatalog.swift -// TablePro -// -// Publishing connections to the shared team catalog. -// - import AppKit extension WelcomeViewModel { @@ -47,8 +40,8 @@ extension WelcomeViewModel { format: String( localized: "Choose a shared folder for your team's connection catalog. Teammates add this folder under Settings > %1$@ > %2$@ to see published connections." ), - SettingsPane.general.title, - LinkedFoldersSection.title + SettingsPane.connections.title, + SettingsPage.linkedFolders.title ) } diff --git a/apple/TablePro/Views/AIChat/AIChatPanelView.swift b/apple/TablePro/Views/AIChat/AIChatPanelView.swift index b830982a3b..1ddcda83ab 100644 --- a/apple/TablePro/Views/AIChat/AIChatPanelView.swift +++ b/apple/TablePro/Views/AIChat/AIChatPanelView.swift @@ -1,13 +1,5 @@ -// -// AIChatPanelView.swift -// TablePro -// -// AI chat panel view - right-side panel for conversing with AI about database queries. -// - import SwiftUI -/// AI chat panel displayed alongside the main editor content struct AIChatPanelView: View { @ObservedObject private var slashCommandStorage = CustomSlashCommandStorage.shared @@ -18,15 +10,14 @@ struct AIChatPanelView: View { var editorSnapshot: (() -> AssistantEditorSnapshot)? @ObservedObject var viewModel: AIChatViewModel - /// Fills its column in the trailing pane, and takes a reading measure in the window's content - /// column, where filling it would run a line the whole width of the window. + // A reading measure in the window's content column, where filling it would run a line the whole window wide. var contentWidth: ChatContentWidth = .pane - @ObservedObject private var settingsManager = AppSettingsManager.shared + @ObservedObject private var aiSettings = AppSettingsManager.shared.aiSlice @ObservedObject private var copilotService = CopilotService.shared @StateObject private var mentionState = MentionPopoverState() private var hasConfiguredProvider: Bool { - settingsManager.ai.hasActiveProvider + aiSettings.value.hasActiveProvider } // Only a card a turn still waits on may take Return and Escape. @@ -75,7 +66,7 @@ struct AIChatPanelView: View { viewModel.connection = connection } .task(id: ModelListTrigger( - sources: settingsManager.ai.providers.map(AIModelListSource.init(config:)), + sources: aiSettings.value.providers.map(AIModelListSource.init(config:)), savedRevision: viewModel.providerSettingsRevision, isCopilotRunning: copilotService.status == .running )) { @@ -99,8 +90,6 @@ struct AIChatPanelView: View { } } - // MARK: - Empty States - private var emptyState: some View { EmptyStateView( icon: "sparkles", @@ -148,8 +137,6 @@ struct AIChatPanelView: View { .frame(maxWidth: .infinity, maxHeight: .infinity) } - // MARK: - Error Banner - private func errorBanner(_ message: String) -> some View { PaneNoticeBar( severity: .warning, @@ -175,8 +162,6 @@ struct AIChatPanelView: View { .paneBarBackground() } - // MARK: - Input Area - private var inputArea: some View { VStack(spacing: 0) { Divider() @@ -191,7 +176,7 @@ struct AIChatPanelView: View { } let acceptsImages = viewModel.activeProviderSupportsImages - let highlightEnabled = settingsManager.ai.composerHighlightEnabled + let highlightEnabled = aiSettings.value.composerHighlightEnabled ChatComposerDraftReader(draft: viewModel.composerDraft) { text in composer(text: text, acceptsImages: acceptsImages, highlightEnabled: highlightEnabled) } @@ -205,14 +190,13 @@ struct AIChatPanelView: View { sendOrStopButton } } - /// Capped before the padding, the way the transcript above it is, so the composer's - /// leading edge lines up with the first character of the conversation. + // Capped before the padding, so the composer's leading edge lines up with the transcript's first character. .chatColumn(contentWidth) .padding(8) } } - /// Built by the draft reader on each keystroke, so it takes what it shows rather than looking it up again. + // Built by the draft reader on each keystroke, so it takes what it shows rather than looking it up again. private func composer(text: Binding, acceptsImages: Bool, highlightEnabled: Bool) -> some View { ChatComposerView( text: text, @@ -241,7 +225,7 @@ struct AIChatPanelView: View { }, highlightEnabled: highlightEnabled, onToggleHighlight: { - settingsManager.ai.composerHighlightEnabled.toggle() + aiSettings.value.composerHighlightEnabled.toggle() } ) } @@ -260,16 +244,8 @@ struct AIChatPanelView: View { } private var modeMenu: some View { - let binding = Binding( - get: { settingsManager.ai.chatMode }, - set: { newValue in - var settings = settingsManager.ai - settings.chatMode = newValue - settingsManager.ai = settings - } - ) - return Menu { - Picker(String(localized: "Mode"), selection: binding) { + Menu { + Picker(String(localized: "Mode"), selection: $aiSettings.value.chatMode) { ForEach(AIChatMode.allCases) { mode in Label(mode.displayName, systemImage: mode.symbolName) .tag(mode) @@ -279,8 +255,8 @@ struct AIChatPanelView: View { .labelsHidden() } label: { HStack(spacing: 4) { - Image(systemName: settingsManager.ai.chatMode.symbolName) - Text(settingsManager.ai.chatMode.displayName) + Image(systemName: aiSettings.value.chatMode.symbolName) + Text(aiSettings.value.chatMode.displayName) .lineLimit(1) } .font(.caption) @@ -289,7 +265,7 @@ struct AIChatPanelView: View { .menuStyle(.button) .buttonStyle(.borderless) .fixedSize() - .help(settingsManager.ai.chatMode.helpText) + .help(aiSettings.value.chatMode.helpText) } @ViewBuilder @@ -325,11 +301,11 @@ struct AIChatPanelView: View { // No frame and no .fixedSize(): a 44-character model name held a fixed-size button at 339 pt, 85 pt past a 240 pt pane (macOS 27). @ViewBuilder private var modelPicker: some View { - let providers = settingsManager.ai.providers + let providers = aiSettings.value.providers if providers.isEmpty { EmptyView() } else { - let activeProvider = settingsManager.ai.activeProvider + let activeProvider = aiSettings.value.activeProvider let selectedProviderId = viewModel.selectedProviderId ?? activeProvider?.id let selectedProvider = providers.first(where: { $0.id == selectedProviderId }) ?? activeProvider let resolvedModel = viewModel.selectedModel ?? selectedProvider?.model ?? "" @@ -435,8 +411,7 @@ struct AIChatPanelView: View { Section(String(localized: "Custom")) { ForEach(customCommands) { command in Button { - updateContext() - Task { await viewModel.runCustomSlashCommand(command) } + pick(command) } label: { if command.description.isEmpty { Text("/\(command.name)") @@ -509,8 +484,6 @@ struct AIChatPanelView: View { } } - // MARK: - Helpers - private func updateContext() { let live = editorSnapshot?() viewModel.currentQuery = live.map(\.currentQuery) ?? currentQuery @@ -518,6 +491,16 @@ struct AIChatPanelView: View { viewModel.editorTarget = live.map(\.target) ?? editorTarget } + private func pick(_ command: CustomSlashCommand) { + switch CustomSlashCommandPick.resolve(command, draft: viewModel.inputText) { + case .compose(let text): + viewModel.inputText = text + viewModel.composedCustomCommand = command + case .run: + updateContext() + Task { await viewModel.runCustomSlashCommand(command) } + } + } private func updateMentionState(text: String, caret: Int) { guard let match = MentionDetector.detect(in: text, caret: caret) else { @@ -598,3 +581,21 @@ private struct ModelListTrigger: Equatable { let savedRevision: Int let isCopilotRunning: Bool } + +enum CustomSlashCommandPick: Equatable { + case run + case compose(String) + + // A template that reads `{{body}}` would run on an empty body, so the command waits in the composer for it. + static func resolve(_ command: CustomSlashCommand, draft: String) -> Self { + guard command.promptTemplate.contains(CustomSlashCommandVariable.body.placeholder) else { return .run } + let body: String + if let invocation = SlashCommand.invocation(in: draft), + invocation.name.caseInsensitiveCompare(command.name) == .orderedSame { + body = invocation.body + } else { + body = draft.trimmingCharacters(in: .whitespacesAndNewlines) + } + return .compose("/\(command.name) " + body) + } +} diff --git a/apple/TablePro/Views/AIChat/ChatComposerTextView.swift b/apple/TablePro/Views/AIChat/ChatComposerTextView.swift index 9be8004b76..03c02c0025 100644 --- a/apple/TablePro/Views/AIChat/ChatComposerTextView.swift +++ b/apple/TablePro/Views/AIChat/ChatComposerTextView.swift @@ -1,8 +1,3 @@ -// -// ChatComposerTextView.swift -// TablePro -// - import AppKit import SwiftUI import UniformTypeIdentifiers @@ -75,18 +70,9 @@ struct ChatComposerTextView: NSViewRepresentable { scrollView.noteFocusRingMaskChanged() } - // Replacing the string outright while an input method has marked text cancels the - // composition. Routing through shouldChangeText/didChangeText also keeps the undo - // stack and the delegate notifications intact. + // Replacing the string under marked text cancels the input method's composition. if textView.string != text, !textView.hasMarkedText() { - let selected = textView.selectedRange() - let full = NSRange(location: 0, length: (textView.string as NSString).length) - if textView.shouldChangeText(in: full, replacementString: text) { - textView.textStorage?.replaceCharacters(in: full, with: text) - textView.didChangeText() - } - let clampedLocation = min(selected.location, (text as NSString).length) - textView.setSelectedRange(NSRange(location: clampedLocation, length: 0)) + textView.replaceAll(with: text) } textView.placeholder = placeholder @@ -198,11 +184,7 @@ struct ChatComposerTextView: NSViewRepresentable { } final class ChatComposerNSTextView: NSTextView { - /// The placeholder is painted in `draw(_:)`, which the accessibility tree never sees, so the - /// only thing that names this field to VoiceOver is the value set here. Keeping the two - /// together means no assignment path can leave the field nameless: guarding the call at one - /// caller is what left it unset since #2097, because `makeNSView` had already stored the same - /// string and the caller's comparison was never true again. + // draw(_:) paints the placeholder where VoiceOver never looks, so this setter is the only thing that names the field. var placeholder: String = "" { didSet { guard oldValue != placeholder else { return } @@ -282,10 +264,7 @@ final class ChatComposerNSTextView: NSTextView { return resigned } - /// Measured on macOS 27: unparenting the pane moves the window's first responder away without - /// ever sending `resignFirstResponder` here, so focus has to be re-read from the window rather - /// than waited for. Switching the trailing pane away and back otherwise left the composer - /// believing it still held focus, and the highlight painted over a field that did not. + // Measured on macOS 27: unparenting the pane moves first responder away without resignFirstResponder. override func viewDidMoveToWindow() { super.viewDidMoveToWindow() onFocusChange?(window?.firstResponder === self) @@ -316,6 +295,21 @@ final class ChatComposerNSTextView: NSTextView { onSizeChange?() } + // Through shouldChangeText and didChangeText, so undo and the delegate see the edit. + func replaceAll(with text: String) { + let selected = selectedRange() + let oldLength = (string as NSString).length + let full = NSRange(location: 0, length: oldLength) + if shouldChangeText(in: full, replacementString: text) { + textStorage?.replaceCharacters(in: full, with: text) + didChangeText() + } + let newLength = (string as NSString).length + // A caret at the old end, an empty composer included, follows the text, so typing after a slash pick lands after "/name ". + let caret = selected.location >= oldLength ? newLength : min(selected.location, newLength) + setSelectedRange(NSRange(location: caret, length: 0)) + } + override func draw(_ dirtyRect: NSRect) { super.draw(dirtyRect) guard string.isEmpty, !placeholder.isEmpty else { return } @@ -359,10 +353,7 @@ final class ChatComposerNSTextView: NSTextView { } if let urls = pasteboard.readObjects(forClasses: [NSURL.self]) as? [URL], let fileURL = urls.first(where: { (try? $0.resourceValues(forKeys: [.contentTypeKey]))?.contentType?.conforms(to: .image) ?? false }) { - /// Identifying the file and reading it are separate answers. Folding the read into the - /// same `if let` made an unreadable image (an iCloud file still in the cloud, a network - /// volume that went away) fall through to `super.paste`, which pastes its path as text - /// into the prompt. The user asked for the picture and silently got a file URL. + // A separate read, so an unreadable image reports a failure instead of falling through to pasting its path. do { let data = try Data(contentsOf: fileURL) let uti = (try? fileURL.resourceValues(forKeys: [.contentTypeKey]))?.contentType?.identifier @@ -412,13 +403,7 @@ final class ChatComposerScrollView: NSScrollView { return scrollView } - /// The composer's rounded surface is drawn by SwiftUI, so AppKit has to be told the shape to - /// wrap; left to itself it rings the square bounds. This is the shape `ShortcutRecorderNSView` - /// uses for the same job, and the radius is the one the SwiftUI background reads. - /// - /// The document view carries the focus, but the ring belongs on the scroll view: measured on - /// macOS 27, `focusRingType` on the text view never produces a `drawFocusRingMask` call, while - /// on the scroll view it does, `.noBorder` included. + // SwiftUI draws the rounded surface, so AppKit needs its shape; on macOS 27 only the scroll view, not the text view, gets drawFocusRingMask. override func drawFocusRingMask() { NSBezierPath( roundedRect: bounds, @@ -429,8 +414,7 @@ final class ChatComposerScrollView: NSScrollView { override var focusRingMaskBounds: NSRect { bounds } - /// The mask is derived from `bounds`, and the composer grows from one line to five as the user - /// types, so the cached ring has to be invalidated with the size that produced it. + // The composer grows as the user types, and the cached ring keeps the size that produced it. override func setFrameSize(_ newSize: NSSize) { let changed = newSize != frame.size super.setFrameSize(newSize) diff --git a/apple/TablePro/Views/Account/DeviceLimitSheet.swift b/apple/TablePro/Views/Account/DeviceLimitSheet.swift index 759af1efac..9c475b2cf1 100644 --- a/apple/TablePro/Views/Account/DeviceLimitSheet.swift +++ b/apple/TablePro/Views/Account/DeviceLimitSheet.swift @@ -1,8 +1,3 @@ -// -// DeviceLimitSheet.swift -// TablePro -// - import SwiftUI internal struct DeviceLimitSheet: View { @@ -16,66 +11,53 @@ internal struct DeviceLimitSheet: View { } var body: some View { - VStack(alignment: .leading, spacing: 16) { - HStack(alignment: .top, spacing: 12) { - Image(systemName: "laptopcomputer.and.iphone") - .font(.largeTitle) - .foregroundStyle(.secondary) - .accessibilityHidden(true) - - VStack(alignment: .leading, spacing: 4) { - Text("Your plan is in use on 3 other devices") - .font(.headline) - - Text("Remove one to use your plan on this Mac. Until then, TablePro works on the Free plan here.") - .foregroundStyle(.secondary) - .fixedSize(horizontal: false, vertical: true) - } - } - - VStack(spacing: 0) { - ForEach(model.rows) { row in - if row.id != model.rows.first?.id { - Divider() + VStack(spacing: 0) { + header + + Divider() + + Form { + Section { + ForEach(model.rows) { row in + DeviceLimitRow( + row: row, + isRemoving: model.removing == row.id, + isDisabled: model.removing != nil + ) { + pendingRemoval = row + } } - DeviceLimitRow( - row: row, - isRemoving: model.removing == row.id, - isDisabled: model.removing != nil - ) { - pendingRemoval = row + + if let failure = model.failure { + NoticeLabel(failure) + .font(.subheadline) + .accessibilityElement(children: .combine) + .accessibilityIdentifier("device-limit-error") } } } - .background(.background, in: RoundedRectangle(cornerRadius: 8)) - .overlay(RoundedRectangle(cornerRadius: 8).strokeBorder(Color(nsColor: .separatorColor))) + .formStyle(.grouped) + // A grouped Form answers any proposal with the whole height, so it alone is capped. + .frame(height: 260) - if let failure = model.failure { - Label(failure, systemImage: "exclamationmark.triangle.fill") - .font(.callout) - .foregroundStyle(.orange) - .fixedSize(horizontal: false, vertical: true) - .accessibilityIdentifier("device-limit-error") - } + Divider() - HStack { + DialogFooter { Button(String(localized: "Manage Devices…")) { openURL(model.services.configuration.portalDevices) } - - Spacer() - + } actions: { Button(String(localized: "Not Now")) { dismiss() } .keyboardShortcut(.cancelAction) .accessibilityIdentifier("device-limit-not-now") } + .padding(16) } - .padding(20) .frame(width: 480) .onChange(of: model.isResolved) { isResolved in if isResolved { dismiss() } } - .confirmationDialog( + .alert( pendingRemoval.map { String(format: String(localized: "Remove “%@”?"), $0.name) } ?? "", isPresented: Binding(get: { pendingRemoval != nil }, set: { if !$0 { pendingRemoval = nil } }), presenting: pendingRemoval @@ -83,12 +65,34 @@ internal struct DeviceLimitSheet: View { Button(String(localized: "Remove"), role: .destructive) { Task { await model.remove(row) } } + Button(String(localized: "Cancel"), role: .cancel) {} } message: { _ in Text("TablePro on that device signs out the next time it checks your account, and this Mac takes its place.") } .accessibilityElement(children: .contain) .accessibilityIdentifier("device-limit-sheet") } + + private var header: some View { + HStack(alignment: .top, spacing: 12) { + Image(systemName: "desktopcomputer") + .font(.largeTitle) + .foregroundStyle(.secondary) + .accessibilityHidden(true) + + VStack(alignment: .leading, spacing: 4) { + Text("Your plan is in use on 3 other devices") + .font(.headline) + + Text("Remove one to use your plan on this Mac. Until then, TablePro works on the Free plan here.") + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + } + + Spacer(minLength: 0) + } + .padding(20) + } } private struct DeviceLimitRow: View { @@ -98,38 +102,32 @@ private struct DeviceLimitRow: View { let onRemove: () -> Void var body: some View { - HStack(spacing: 10) { - VStack(alignment: .leading, spacing: 2) { - Text(row.name) - .lineLimit(1) - .truncationMode(.middle) - - Text(AccountDeviceText.detail(system: row.system, lastSeenAt: row.lastSeenAt)) - .font(.callout) - .foregroundStyle(.secondary) - .lineLimit(1) - } - - Spacer(minLength: 12) - + SettingsRecordRow( + title: row.name, + subtitle: AccountDeviceText.detail(system: row.system, lastSeenAt: row.lastSeenAt) + ) { if let offlineUntil = row.offlineUntil { Text(AccountDeviceText.offlineFile(until: offlineUntil)) - .font(.callout) .foregroundStyle(.secondary) - .multilineTextAlignment(.trailing) + .lineLimit(1) + .layoutPriority(1) } else if isRemoving { ProgressView() .controlSize(.small) .accessibilityLabel(Text("Removing")) } else { - Button(String(localized: "Remove"), action: onRemove) + Button(String(localized: "Remove…"), action: onRemove) .disabled(isDisabled) + .fixedSize() .accessibilityLabel(Text(String(format: String(localized: "Remove %@"), row.name))) } } - .padding(.horizontal, 12) - .padding(.vertical, 8) - .accessibilityElement(children: .contain) + .contextMenu { + if row.offlineUntil == nil { + Button(String(localized: "Remove…"), action: onRemove) + .disabled(isDisabled) + } + } } } @@ -143,6 +141,12 @@ internal enum AccountDeviceText { return String(format: String(localized: "%@ · %@"), system, lastSeen) } + // This Mac is the one showing the list, so it is seen now whatever the server last recorded. + static func detail(system: String, lastSeenAt: Date, isThisMac: Bool) -> String { + guard isThisMac else { return detail(system: system, lastSeenAt: lastSeenAt) } + return String(format: String(localized: "%@ · %@"), String(localized: "This Mac"), detail(system: system, lastSeenAt: Date())) + } + static func offlineFile(until date: Date) -> String { String(format: String(localized: "Offline file until %@"), date.formatted(date: .abbreviated, time: .omitted)) } diff --git a/apple/TablePro/Views/Account/LicenseKeySheet.swift b/apple/TablePro/Views/Account/LicenseKeySheet.swift index b68ae5e34d..82f1dfbb55 100644 --- a/apple/TablePro/Views/Account/LicenseKeySheet.swift +++ b/apple/TablePro/Views/Account/LicenseKeySheet.swift @@ -1,8 +1,3 @@ -// -// LicenseKeySheet.swift -// TablePro -// - import SwiftUI // Use License Key…: a key an older build saved here is offered filled in, and deleted once it is exchanged. @@ -15,6 +10,7 @@ internal struct LicenseKeySheet: View { @Environment(\.dismiss) private var dismiss @State private var key: String @State private var failure: String? + @State private var exchange: Task? @FocusState private var isFieldFocused: Bool init(storedKey: String?, signedInEmail: String?, isWorking: Bool, onUse: @escaping (String) async -> String?) { @@ -57,29 +53,26 @@ internal struct LicenseKeySheet: View { if storedKey != nil, trimmedKey == storedKey { Text("An older version of TablePro saved this key on this Mac. It is deleted once it is used.") - .font(.callout) + .font(.subheadline) .foregroundStyle(.secondary) .fixedSize(horizontal: false, vertical: true) } if let failure { - Label(failure, systemImage: "exclamationmark.triangle.fill") - .font(.callout) - .foregroundStyle(.orange) - .fixedSize(horizontal: false, vertical: true) + NoticeLabel(failure) + .font(.subheadline) + .accessibilityElement(children: .combine) .accessibilityIdentifier("license-key-error") } - HStack { - Spacer() - + DialogFooter { if isWorking { ProgressView() .controlSize(.small) .accessibilityLabel(Text("Checking the license key")) } - Button(String(localized: "Cancel")) { dismiss() } + Button(String(localized: "Cancel"), action: cancel) .keyboardShortcut(.cancelAction) Button(String(localized: "Use Key"), action: use) @@ -91,14 +84,22 @@ internal struct LicenseKeySheet: View { .padding(20) .frame(width: 440) .onAppear { isFieldFocused = true } + .onDisappear { exchange?.cancel() } } private func use() { guard !trimmedKey.isEmpty, !isWorking else { return } failure = nil let key = trimmedKey - Task { - failure = await onUse(key) + exchange = Task { + let result = await onUse(key) + guard !Task.isCancelled else { return } + failure = result } } + + private func cancel() { + exchange?.cancel() + dismiss() + } } diff --git a/apple/TablePro/Views/Components/AddRemoveControlGroup.swift b/apple/TablePro/Views/Components/AddRemoveControlGroup.swift index 3311733336..34f3e84361 100644 --- a/apple/TablePro/Views/Components/AddRemoveControlGroup.swift +++ b/apple/TablePro/Views/Components/AddRemoveControlGroup.swift @@ -1,20 +1,13 @@ -// -// AddRemoveControlGroup.swift -// TablePro -// -// The add/remove pair that sits under a list, which is where macOS puts a list's own +/-. -// Shared by the structure editor's footer and the Users & Roles list. -// - +import AppKit import SwiftUI +// Borderless glyphs split by a separator, as System Settings draws a list's bar; the navigation ControlGroup is back and forward. struct AddRemoveControlGroup: View { let addLabel: String let removeLabel: String var canAdd = true var canRemove = true - /// What the tooltip says. Defaults to the label; a withheld control sets it to the reason - /// instead, which is the only place a disabled button has to explain itself. + // A withheld control sets its help to the reason, the only place a disabled button explains itself. var addHelp: String? var removeHelp: String? var addIdentifier: String? @@ -23,27 +16,88 @@ struct AddRemoveControlGroup: View { let onRemove: () -> Void var body: some View { - ControlGroup { - Button(action: onAdd) { - Label(addLabel, systemImage: "plus") - .labelStyle(.iconOnly) - } - .help(addHelp ?? addLabel) - .accessibilityLabel(addLabel) - .accessibilityIdentifier(addIdentifier ?? "") + HStack(spacing: 0) { + ListBarButton( + label: addLabel, + systemImage: "plus", + help: addHelp, + identifier: addIdentifier, + action: onAdd + ) .disabled(!canAdd) - Button(action: onRemove) { - Label(removeLabel, systemImage: "minus") - .labelStyle(.iconOnly) - } - .help(removeHelp ?? removeLabel) - .accessibilityLabel(removeLabel) - .accessibilityIdentifier(removeIdentifier ?? "") + ListBarSeparator() + + ListBarButton( + label: removeLabel, + systemImage: "minus", + help: removeHelp, + identifier: removeIdentifier, + action: onRemove + ) .disabled(!canRemove) } - .controlGroupStyle(.navigation) - .controlSize(.small) .fixedSize() } } + +// Measured from System Settings > General > Login Items on macOS 27. +enum ListBarMetrics { + static let contentHeight: CGFloat = 23 + static let height: CGFloat = contentHeight + 1 + static let buttonWidth: CGFloat = 24 + static let separatorHeight: CGFloat = 16 +} + +struct ListBarButton: View { + let label: String + let systemImage: String + var help: String? + var identifier: String? + let action: () -> Void + + var body: some View { + Button(action: action) { + Label(label, systemImage: systemImage) + .labelStyle(.iconOnly) + .font(.system(size: NSFont.smallSystemFontSize)) + .frame(width: ListBarMetrics.buttonWidth, height: ListBarMetrics.contentHeight) + .contentShape(Rectangle()) + } + .buttonStyle(.borderless) + .help(help ?? label) + .accessibilityLabel(label) + .accessibilityIdentifier(identifier ?? "") + } +} + +struct ListBarSeparator: View { + var body: some View { + Divider() + .frame(height: ListBarMetrics.separatorHeight) + } +} + +struct ListBar: View { + @ViewBuilder let content: Content + + var body: some View { + VStack(spacing: 0) { + Divider() + HStack(spacing: 0) { + content + Spacer(minLength: 0) + } + .frame(minHeight: ListBarMetrics.contentHeight) + } + } +} + +extension View { + // An overlay for a fixed-height list whose height already counts ListBarMetrics.height; a scrolling list uses SettingsFullPageList's inset. + func listBar(@ViewBuilder _ content: () -> Content) -> some View { + overlay(alignment: .bottom) { + ListBar(content: content) + } + } +} diff --git a/apple/TablePro/Views/Components/HighlightedSQLTextView.swift b/apple/TablePro/Views/Components/HighlightedSQLTextView.swift index 16611ae0f3..2d2978ce2c 100644 --- a/apple/TablePro/Views/Components/HighlightedSQLTextView.swift +++ b/apple/TablePro/Views/Components/HighlightedSQLTextView.swift @@ -1,8 +1,3 @@ -// -// HighlightedSQLTextView.swift -// TablePro -// - import AppKit import Combine import SwiftUI @@ -11,14 +6,12 @@ import TableProGrammars import TableProPluginKit import TableProTheme -/// A code view: `ThemeTextViewStyle` puts it on the editor's background, text, caret and selection, and its -/// syntax comes from the editor's own grammar and `EditorTheme`, so every token draws in the slot the SQL -/// editor gives it. +// A code view in the editor's theme slots and grammar, so every token draws as it does in the SQL editor. struct HighlightedSQLTextView: NSViewRepresentable { internal enum LineLayout: Equatable { case unwrapped case wrapped - /// Wraps, and is as tall as its text up to `maxLines`; it scrolls vertically past that. + // Wraps, and grows with its text up to maxLines; it scrolls past that. case fitted(maxLines: Int) } @@ -30,9 +23,9 @@ struct HighlightedSQLTextView: NSViewRepresentable { let sql: String var databaseType: DatabaseType = .mysql var highlighting: Highlighting = .engine - /// A SwiftUI `.accessibilityIdentifier` lands on the representable's wrapper, not on the text - /// view AppKit publishes, so the only way to name this element is to set it on the text view. + // A SwiftUI accessibilityIdentifier lands on the representable's wrapper, never on the text view AppKit publishes. var accessibilityIdentifier: String? + var accessibilityLabel = String(localized: "Query preview") var lineLayout: LineLayout = .unwrapped @ObservedObject private var themeEngine = ThemeEngine.shared @@ -45,7 +38,7 @@ struct HighlightedSQLTextView: NSViewRepresentable { } textView.setAccessibilityIdentifier(accessibilityIdentifier) - textView.setAccessibilityLabel(String(localized: "Query preview")) + textView.setAccessibilityLabel(accessibilityLabel) textView.isEditable = false textView.isSelectable = true textView.font = themeEngine.editorFonts.font @@ -113,6 +106,9 @@ struct HighlightedSQLTextView: NSViewRepresentable { if textChanged { textView.string = sql } + if textView.accessibilityLabel() != accessibilityLabel { + textView.setAccessibilityLabel(accessibilityLabel) + } // A short query would otherwise show the scroll view's own color below its last line. if scrollView.backgroundColor !== textView.backgroundColor { scrollView.backgroundColor = textView.backgroundColor @@ -171,8 +167,6 @@ struct HighlightedSQLTextView: NSViewRepresentable { } } - // MARK: - Syntax Highlighting - private var language: CodeLanguage { switch highlighting { case .json: diff --git a/apple/TablePro/Views/Components/LicenseNoticeControls.swift b/apple/TablePro/Views/Components/LicenseNoticeControls.swift index a57692e680..ddce936471 100644 --- a/apple/TablePro/Views/Components/LicenseNoticeControls.swift +++ b/apple/TablePro/Views/Components/LicenseNoticeControls.swift @@ -1,8 +1,3 @@ -// -// LicenseNoticeControls.swift -// TablePro -// - import AppKit import SwiftUI import TableProHTTP @@ -21,8 +16,10 @@ struct LicenseNoticeActionButton: View { case .purchase, .upgrade, .renew: Link(action.title, destination: SupportLinks.pricing(referrer)) .countsUpgradeClicks(from: referrer) - case .openAccountSettings: - Button(action.title) { WindowOpener.shared.openSettings(tab: .account) } + case .openAccountSettings(let page): + Button(action.title) { + WindowOpener.shared.openSettings(page.map(SettingsLocation.init(page:)) ?? .root(.account)) + } case .retryValidation: HStack(spacing: 6) { Button(action.title) { @@ -50,20 +47,12 @@ struct LicenseCheckFailureLine: View { var body: some View { if let failure = LicensePresentation.checkFailureMessage(featureAccess.state.refresh) { - Label { - Text(failure) - .foregroundStyle(.secondary) - .fixedSize(horizontal: false, vertical: true) - } icon: { - Image(systemName: "exclamationmark.triangle.fill") - .foregroundStyle(.orange) - } - .font(.callout) + NoticeLabel(failure, severity: .warning) + .font(.subheadline) } } } -// A control a plan unlocks says what it needs and offers the way there. struct LicenseGateRow: View { let feature: ProFeature @@ -76,7 +65,7 @@ struct LicenseGateRow: View { Text(notice.title) Text(notice.message) - .font(.callout) + .font(.subheadline) .foregroundStyle(.secondary) .fixedSize(horizontal: false, vertical: true) @@ -112,8 +101,8 @@ extension LicenseNoticeAction { case .purchase, .upgrade, .renew: Telemetry.shared.upgradeClicked(from: referrer) WebPageOpener.open(SupportLinks.pricing(referrer), scope: .https) - case .openAccountSettings: - WindowOpener.shared.openSettings(tab: .account) + case .openAccountSettings(let page): + WindowOpener.shared.openSettings(page.map(SettingsLocation.init(page:)) ?? .root(.account)) case .retryValidation: WindowOpener.shared.openSettings(tab: .account) Task { await AccountServices.shared.checkNow() } diff --git a/apple/TablePro/Views/Components/PaginationControlsView.swift b/apple/TablePro/Views/Components/PaginationControlsView.swift index 14db7bf6aa..466b35ceb9 100644 --- a/apple/TablePro/Views/Components/PaginationControlsView.swift +++ b/apple/TablePro/Views/Components/PaginationControlsView.swift @@ -1,26 +1,16 @@ -// -// PaginationControlsView.swift -// TablePro -// - import SwiftUI struct PaginationControlsView: View { - @ObservedObject private var settingsManager = AppSettingsManager.shared + @ObservedObject private var keyboard = AppSettingsManager.shared.keyboardSlice let pagination: PaginationState let loadedRowCount: Int - /// Identity of the tab these controls describe. Not used for display: a change to it is what - /// discards a half-typed page number so it cannot be submitted against the next tab. + // Not displayed: a change discards a half-typed page number so it cannot be submitted against the next tab. let tabId: UUID? var showsPageNavigation = true - /// First and Last. The Query menu carries all four page commands, so the two edges are the first - /// thing this cluster gives up when the bar runs out of room. + // The Query menu carries all four page commands, so First and Last go first when the bar runs out of room. var showsEdgePageButtons = true - /// Whether rows-per-page stands beside the page indicator or moves inside its menu. Rows-per-page - /// has no menu-bar home, so the narrow bar folds it in rather than dropping it, which is where - /// TablePlus and Sequel Ace both keep theirs. + // Rows-per-page has no menu-bar home, so a narrow bar folds it into the page menu rather than dropping it. var pageSizeIsInline = true - /// The most rows the engine returns from one statement, when it caps them. var maximumPageSize: Int? let onFirst: () -> Void let onPrevious: () -> Void @@ -39,8 +29,7 @@ struct PaginationControlsView: View { private static let pageSizePresets = [5, 10, 20, 100, 500, 1_000] - /// Anything past this is a mistake rather than an intent, and it used to be unbounded: pasting - /// `9223372036854775807` set the page size to `Int.max` and the next status-bar render trapped. + // Bounded: pasting `Int.max` as the page size trapped the next status bar render. static let maximumPageSize = 1_000_000 static func pageSizePresets(upTo maximum: Int?) -> [Int] { @@ -52,8 +41,7 @@ struct PaginationControlsView: View { min(maximumPageSize ?? Self.maximumPageSize, Self.maximumPageSize) } - /// An engine that cannot seek shows no page indicator, so there is nowhere to fold rows-per-page - /// into and it has to stand on its own however narrow the bar is. + // An engine that cannot seek has no page indicator to fold rows-per-page into. private var showsInlinePageSize: Bool { pageSizeIsInline || !showsPageNavigation } @@ -75,11 +63,7 @@ struct PaginationControlsView: View { } } - // MARK: - Page Size - - /// A bordered pull-down rather than a borderless one. Measured on macOS 27, a borderless - /// `NSPopUpButton` reports a 16pt fitting height and ignores `controlSize` at every size, so it - /// sat visibly shorter than the 20pt bordered controls beside it. + // Bordered: a borderless `NSPopUpButton` ignores `controlSize` and sat shorter than the controls beside it. private var pageSizeMenu: some View { Menu { pageSizeMenuItems @@ -100,8 +84,7 @@ struct PaginationControlsView: View { } } - /// Shared by the standalone pull-down and by the page indicator that swallows it when the bar is - /// narrow, so rows-per-page offers the same choices whichever control carries it. + // Shared, so rows-per-page offers the same choices whichever control carries it. @ViewBuilder private var pageSizeMenuItems: some View { Picker(String(localized: "Rows per page"), selection: pageSizeBinding) { @@ -127,11 +110,7 @@ struct PaginationControlsView: View { Binding(get: { pagination.pageSize }, set: { onPageSizeChange($0) }) } - // MARK: - Navigation - - /// A progress indicator never goes inside this cluster. Sitting between the page indicator and - /// Next, it would push both nav buttons sideways every time a page loaded, which is the reflow - /// the readout's own indicator already reports without moving anything. + // No progress indicator here: it would push the nav buttons sideways on every page load. private var navigationCluster: some View { HStack(spacing: 0) { if showsEdgePageButtons { @@ -189,12 +168,10 @@ struct PaginationControlsView: View { } private func helpText(_ label: String, for shortcut: ShortcutAction) -> String { - settingsManager.keyboard.shortcutHint(label, for: shortcut) + keyboard.value.shortcutHint(label, for: shortcut) } - /// A button straight to the jump popover while rows-per-page has its own control, and a menu - /// carrying both once it does not. The menu is what keeps rows-per-page reachable on a narrow - /// bar: it has no menu-bar equivalent, so it cannot simply be dropped. + // A menu once rows-per-page has no control of its own, so it stays reachable on a narrow bar. @ViewBuilder private var pageIndicator: some View { if showsInlinePageSize { @@ -213,9 +190,7 @@ struct PaginationControlsView: View { } } else { Menu { - /// The catalog's existing spelling, which is also this control's tooltip when it is - /// a plain button. A new string here would fall back to English in every translated - /// locale at exactly the width where the menu is the only route to these commands. + // The catalog's existing spelling: a new string would fall back to English where this menu is the only route. Button(String(localized: "Go to page")) { jumpPage = pagination.currentPage showJumpPopover = true @@ -250,8 +225,7 @@ struct PaginationControlsView: View { .frame(minWidth: 44) } - /// The total is marked when it came from a driver estimate, so a page count the user cannot - /// trust never looks like one they can. + // An estimated total is marked, so a page count the user cannot trust never looks exact. @ViewBuilder private var pageIndicatorText: some View { if pagination.hasExactRowCount { @@ -270,15 +244,12 @@ struct PaginationControlsView: View { return String(format: String(localized: "Page %d of %d"), pagination.currentPage, pagination.totalPages) } - // MARK: - Popovers - private var jumpPopover: some View { NumberEntryPopover( caption: String(localized: "Go to page"), value: $jumpPage, minimum: 1, - /// An estimated total is not a ceiling. Clamping to it here would put back the wall that - /// `PaginationState.goToPage` was opened up to remove. + // An estimated total is not a ceiling for `PaginationState.goToPage`. maximum: pagination.hasExactRowCount ? pagination.totalPages : nil, fieldWidth: 80, isFocused: $isJumpFocused, @@ -331,8 +302,7 @@ struct PaginationControlsView: View { } private extension View { - /// One home for the page indicator's accessibility, because XCUITest keys on the identifier and - /// the control is a button or a menu depending on how much room the bar has. + // XCUITest keys on the identifier, and the control is a button or a menu depending on the room. func pageIndicatorAccessibility(value: String) -> some View { accessibilityLabel(String(localized: "Page")) .accessibilityValue(value) diff --git a/apple/TablePro/Views/Components/SQLStatementPreview.swift b/apple/TablePro/Views/Components/SQLStatementPreview.swift index f9e6ca751f..1bae6a856a 100644 --- a/apple/TablePro/Views/Components/SQLStatementPreview.swift +++ b/apple/TablePro/Views/Components/SQLStatementPreview.swift @@ -1,18 +1,12 @@ -// -// SQLStatementPreview.swift -// TablePro -// - import AppKit import SwiftUI import TableProEditorKit import TableProGrammars import TableProPluginKit -/// One owner for the choice between the editor and the plain text view, so two surfaces never show the -/// same statement two ways. +// One owner for editor versus plain text, so two surfaces never show the same statement two ways. struct SQLStatementPreview: View { - @ObservedObject private var settingsManager = AppSettingsManager.shared + @ObservedObject private var editorSettings = AppSettingsManager.shared.editorSlice let prepared: SQLReviewSheet.Prepared let databaseType: DatabaseType @@ -43,7 +37,7 @@ struct SQLStatementPreview: View { .onReceive(AppEvents.shared.themeChanged) { _ in editorConfiguration = Self.makeConfiguration() } - .onChange(of: settingsManager.editor) { _ in + .onChange(of: editorSettings.value) { _ in editorConfiguration = Self.makeConfiguration() } .clipShape(RoundedRectangle(cornerRadius: 6)) @@ -53,7 +47,7 @@ struct SQLStatementPreview: View { ) } - /// A text view, since this path carries a statement of any length and a `Text` that size lays out for seconds. + // A text view: this path carries a statement of any length, and a `Text` that size lays out for seconds. private func plainTextEditor(_ text: String) -> some View { HighlightedSQLTextView(sql: text, databaseType: databaseType) .clipShape(RoundedRectangle(cornerRadius: 6)) diff --git a/apple/TablePro/Views/Connection/HostListFieldRow.swift b/apple/TablePro/Views/Connection/HostListFieldRow.swift index 6f04a92dd4..4e0bc05cbf 100644 --- a/apple/TablePro/Views/Connection/HostListFieldRow.swift +++ b/apple/TablePro/Views/Connection/HostListFieldRow.swift @@ -10,7 +10,6 @@ struct HostEntry: Identifiable { var value: String } -/// Selection arithmetic for `HostListFieldRow`. enum HostListSelection { static func nextSelection( afterRemoving removedIds: Set, @@ -40,25 +39,14 @@ struct HostListFieldRow: View { } .listStyle(.bordered(alternatesRowBackgrounds: false)) .frame(height: listHeight) - .safeAreaInset(edge: .bottom, spacing: 0) { - VStack(spacing: 0) { - Divider() - HStack(spacing: 0) { - AddRemoveControlGroup( - addLabel: String(localized: "Add Host"), - removeLabel: String(localized: "Remove Host"), - canRemove: !selectedId.isEmpty && entries.count > 1, - onAdd: { addEntry() }, - onRemove: { removeSelected() } - ) - .controlSize(.small) - - Spacer() - } - .padding(.horizontal, 4) - .padding(.vertical, 2) - } - .background(.bar) + .listBar { + AddRemoveControlGroup( + addLabel: String(localized: "Add Host"), + removeLabel: String(localized: "Remove Host"), + canRemove: !selectedId.isEmpty && entries.count > 1, + onAdd: { addEntry() }, + onRemove: { removeSelected() } + ) } } label: { Text(label) @@ -67,8 +55,7 @@ struct HostListFieldRow: View { .onChange(of: value) { _ in parseValue() } } - /// A plugin can declare a per-field example, which matters when one form has two host lists - /// on different default ports: Sentinel answers on 26379 and a cluster seed on 6379. + // A plugin's per-field example, since one form can hold host lists on different default ports (Sentinel 26379, cluster 6379). private var prompt: String { placeholder.isEmpty ? "hostname:\(defaultPort)" : placeholder } @@ -76,11 +63,8 @@ struct HostListFieldRow: View { private var listHeight: CGFloat { let rowHeight: CGFloat = 24 let rows = CGFloat(max(entries.count, 1)) - /// The control group brings its own intrinsic height, which is taller than the two - /// hand-sized 20pt buttons this row used to draw. - let buttonBarHeight: CGFloat = 32 // No cap: a List in a grouped Form never scrolls, so it shows every row and the Form scrolls. - return rows * rowHeight + buttonBarHeight + 8 + return rows * rowHeight + ListBarMetrics.height + 8 } private func bindingForEntry(_ entry: HostEntry) -> Binding { diff --git a/apple/TablePro/Views/Connection/SSHProfileEditorView.swift b/apple/TablePro/Views/Connection/SSHProfileEditorView.swift index b989517cf0..719919896a 100644 --- a/apple/TablePro/Views/Connection/SSHProfileEditorView.swift +++ b/apple/TablePro/Views/Connection/SSHProfileEditorView.swift @@ -1,13 +1,32 @@ -// -// SSHProfileEditorView.swift -// TablePro -// - import SwiftUI import TableProSSHConfig import TableProSSHTransport +struct SSHProfileDraft: Equatable { + var name = "" + var server = SSHServerDraft() + + var trimmedName: String { + name.trimmingCharacters(in: .whitespaces) + } + + var validationIssues: [String] { + var issues: [String] = [] + if trimmedName.isEmpty { + issues.append(String(localized: "A profile needs a name.")) + } + return issues + server.validationIssues + } +} + struct SSHProfileEditorView: View { + private enum TestState: Equatable { + case idle + case running + case succeeded + case failed(String) + } + @Environment(\.dismiss) private var dismiss let existingProfile: SSHProfile? @@ -17,551 +36,240 @@ struct SSHProfileEditorView: View { var onSave: ((SSHProfile) -> Void)? var onDelete: (() -> Void)? - @State private var profileName: String = "" - - @State private var host: String = "" - @State private var port: String = "22" - @State private var username: String = "" - - @State private var authMethod: SSHAuthMethod = .password - @State private var sshPassword: String = "" - @State private var privateKeyPath: String = "" - @State private var keyPassphrase: String = "" - @State private var agentSocketOption: SSHAgentSocketOption = .systemDefault - @State private var customAgentSocketPath: String = "" - - @State private var totpMode: TOTPMode = .none - @State private var totpSecret: String = "" - @State private var totpAlgorithm: TOTPAlgorithm = .sha1 - @State private var totpDigits: Int = 6 - @State private var totpPeriod: Int = 30 - - @State private var jumpHosts: [SSHJumpHost] = [] - - @State private var sshConfigEntries: [SSHConfigEntry] = [] - @State private var selectedSSHConfigHost: String = "" - - @State private var showingDeleteConfirmation = false + @State private var draft = SSHProfileDraft() + @State private var baseline = SSHProfileDraft() + @State private var hasLoaded = false + @State private var isStored = false + @State private var newProfileId = UUID() + @State private var secretReads: [SSHSecret: ProfileSecretRead] = [:] + @State private var inheritedSecrets: Set = [] + @State private var usageUnknown = false + @State private var configEntries: [SSHConfigEntry] = [] + @State private var pendingDeletion: PendingProfileDeletion? @State private var saveError: String? - @State private var connectionsUsingProfile = 0 - @State private var isTesting = false - @State private var testSucceeded = false - @State private var testError: String? + @State private var test = TestState.idle @State private var testTask: Task? - private var isStoredProfile: Bool { - guard let profile = existingProfile else { return false } - return SSHProfileStorage.shared.profile(for: profile.id) != nil - } + private var storage: SSHProfileStorage { .shared } - private var isValid: Bool { - let nameValid = !profileName.trimmingCharacters(in: .whitespaces).isEmpty - let hostValid = !host.trimmingCharacters(in: .whitespaces).isEmpty - let portValid = port.isEmpty || (Int(port).map { (1...65_535).contains($0) } ?? false) - let authValid = authMethod == .password || authMethod == .sshAgent - || authMethod == .keyboardInteractive || authMethod == .none || !privateKeyPath.isEmpty - let jumpValid = jumpHosts.allSatisfy(\.isValid) - return nameValid && hostValid && portValid && authValid && jumpValid + private var profileId: UUID { + existingProfile?.id ?? newProfileId } - private var resolvedAgentSocketPath: String { - agentSocketOption.resolvedPath(customPath: customAgentSocketPath) + private var savedSecrets: Set { + Set(secretReads.filter { $0.value != .absent }.map(\.key)).union(inheritedSecrets) } var body: some View { VStack(spacing: 0) { Form { Section(String(localized: "Profile")) { - TextField(String(localized: "Name"), text: $profileName, prompt: Text("My Server")) + TextField(String(localized: "Name"), text: $draft.name, prompt: Text("My Server")) + .accessibilityIdentifier("ssh-profile-name") } - - serverSection - authenticationSection - - if authMethod.supportsTwoFactorAuthentication { - totpSection + if secretReads.values.contains(.unreadable) { + Section { + NoticeLabel( + String(localized: "The Keychain could not be read, so the stored secrets are not shown. Editing the name is safe; they are left as they are.") + ) + } } - - jumpHostsSection + SSHServerFields( + draft: $draft.server, + configEntries: configEntries, + identifierPrefix: "ssh-profile", + savedSecrets: savedSecrets + ) } .formStyle(.grouped) Divider() bottomBar } - .frame(minWidth: 480, idealHeight: 500) - .onAppear { - loadExistingProfile() - } + .frame(minWidth: 520, idealWidth: 520, minHeight: 440, idealHeight: 560) + .onAppear(perform: load) .task { - let entries = await Task.detached { SSHConfigParser.parse() }.value - sshConfigEntries = entries + configEntries = await Task.detached { SSHConfigParser.parse() }.value + } + .onChange(of: draft) { _ in + cancelTest() } - .onChange(of: host) { _ in testSucceeded = false } - .onChange(of: port) { _ in testSucceeded = false } - .onChange(of: username) { _ in testSucceeded = false } - .onChange(of: authMethod) { _ in testSucceeded = false } - .onChange(of: sshPassword) { _ in testSucceeded = false } - .onChange(of: privateKeyPath) { _ in testSucceeded = false } - .onChange(of: keyPassphrase) { _ in testSucceeded = false } - .onChange(of: agentSocketOption) { _ in testSucceeded = false } - .onChange(of: customAgentSocketPath) { _ in testSucceeded = false } - .onChange(of: totpMode) { _ in testSucceeded = false } - .onChange(of: totpSecret) { _ in testSucceeded = false } - .onChange(of: jumpHosts) { _ in testSucceeded = false } .onDisappear { testTask?.cancel() } } - // MARK: - Server Section - - private var serverSection: some View { - Section(String(localized: "Server")) { - if !sshConfigEntries.isEmpty { - Picker(String(localized: "Config Host"), selection: $selectedSSHConfigHost) { - Text(String(localized: "Manual")).tag("") - ForEach(sshConfigEntries) { entry in - Text(entry.displayName).tag(entry.host) - } - } - .onChange(of: selectedSSHConfigHost) { _ in - applySSHConfigEntry(selectedSSHConfigHost) - } - } - if selectedSSHConfigHost.isEmpty || sshConfigEntries.isEmpty { - TextField(String(localized: "SSH Host"), text: $host, prompt: Text("ssh.example.com")) - } - TextField(String(localized: "SSH Port"), text: $port, prompt: Text("22")) - TextField(String(localized: "SSH User"), text: $username, prompt: Text("username")) - } - } - - // MARK: - Authentication Section - - private var authenticationSection: some View { - Section(String(localized: "Authentication")) { - Picker(String(localized: "Method"), selection: $authMethod) { - ForEach(SSHAuthMethod.allCases) { method in - Text(method.rawValue).tag(method) - } - } - if authMethod == .password { - SecureField(String(localized: "Password"), text: $sshPassword) - } else if authMethod == .sshAgent { - Picker(String(localized: "Agent Socket"), selection: $agentSocketOption) { - ForEach(SSHAgentSocketOption.allCases) { option in - Text(option.displayName).tag(option) - } - } - if agentSocketOption == .custom { - TextField( - String(localized: "Custom Path"), - text: $customAgentSocketPath, - prompt: Text("/path/to/agent.sock") - ) - } - Text(agentSocketOption.explanation) - .font(.caption) - .foregroundStyle(.secondary) - LabeledContent(String(localized: "Identity File")) { - HStack { - TextField("", text: $privateKeyPath, prompt: Text("~/.ssh/id_ed25519.pub")) - Button(String(localized: "Browse")) { browseForPrivateKey() } - .controlSize(.small) - } - } - Text(String(localized: """ - Offers the agent key matching this public key file first. With IdentitiesOnly yes \ - in ~/.ssh/config, only that key is offered. - """)) - .font(.caption) - .foregroundStyle(.secondary) - } else if authMethod == .keyboardInteractive { - SecureField(String(localized: "Password"), text: $sshPassword) - Text(String(localized: "Password is sent via keyboard-interactive challenge-response.")) - .font(.caption) - .foregroundStyle(.secondary) - } else if authMethod == .none { - Text("No credentials are sent. Use this when the server handles authentication itself, such as a Tailscale SSH host.") - .font(.caption) - .foregroundStyle(.secondary) - } else { - LabeledContent(String(localized: "Key File")) { - HStack { - TextField("", text: $privateKeyPath, prompt: Text("~/.ssh/id_rsa")) - Button(String(localized: "Browse")) { browseForPrivateKey() } - .controlSize(.small) - } - } - SecureField(String(localized: "Passphrase"), text: $keyPassphrase) - } - } - } - - // MARK: - TOTP Section - - private var totpSection: some View { - Section(String(localized: "Two-Factor Authentication")) { - Picker(String(localized: "TOTP"), selection: $totpMode) { - ForEach(TOTPMode.allCases) { mode in - Text(mode.displayName).tag(mode) - } - } - - if totpMode == .autoGenerate { - SecureField(String(localized: "TOTP Secret"), text: $totpSecret) - .help(String(localized: "Base32-encoded secret from your authenticator setup")) - - Picker(String(localized: "Algorithm"), selection: $totpAlgorithm) { - ForEach(TOTPAlgorithm.allCases) { algo in - Text(algo.rawValue).tag(algo) - } - } - - Picker(String(localized: "Digits"), selection: $totpDigits) { - Text("6").tag(6) - Text("8").tag(8) - } - - Picker(String(localized: "Period"), selection: $totpPeriod) { - Text("30s").tag(30) - Text("60s").tag(60) + private var bottomBar: some View { + DialogFooter { + if isStored { + Button(String(localized: "Delete Profile"), role: .destructive) { + pendingDeletion = PendingProfileDeletion.make(kind: .ssh, id: profileId, name: baseline.trimmedName) } - } else { - Text(String(localized: "If the SSH server asks for a verification code, TablePro prompts you for it when you connect.")) - .font(.caption) - .foregroundStyle(.secondary) - } - } - } - - // MARK: - Jump Hosts Section - - private var jumpHostsSection: some View { - Section { - DisclosureGroup(String(localized: "Jump Hosts")) { - ForEach(jumpHosts) { jumpHost in - let jumpHostBinding = $jumpHosts.element(jumpHost) - DisclosureGroup { - TextField(String(localized: "Host"), text: jumpHostBinding.host, prompt: Text("bastion.example.com")) - HStack { - TextField( - String(localized: "Port"), - text: Binding( - get: { jumpHostBinding.wrappedValue.port.map(String.init) ?? "" }, - set: { jumpHostBinding.wrappedValue.port = Int($0) } - ), - prompt: Text("22") - ) - .frame(width: 80) - TextField(String(localized: "Username"), text: jumpHostBinding.username, prompt: Text("admin")) - } - Picker(String(localized: "Auth"), selection: jumpHostBinding.authMethod) { - ForEach(SSHJumpAuthMethod.allCases) { method in - Text(method.rawValue).tag(method) - } - } - if jumpHost.authMethod == .privateKey { - LabeledContent(String(localized: "Key File")) { - HStack { - TextField("", text: jumpHostBinding.privateKeyPath, prompt: Text("~/.ssh/id_rsa")) - Button(String(localized: "Browse")) { - browseForJumpHostKey(jumpHost: jumpHostBinding) - } - .controlSize(.small) - } - } - } - } label: { - HStack { - Text( - jumpHost.host.isEmpty - ? String(localized: "New Jump Host") - : "\(jumpHost.username)@\(jumpHost.host)" - ) - .foregroundStyle(jumpHost.host.isEmpty ? .secondary : .primary) - Spacer() - Button { - let idToRemove = jumpHost.id - withMotion { jumpHosts.removeAll { $0.id == idToRemove } } - } label: { - Image(systemName: "minus.circle.fill") - .frame(width: 24, height: 24) - .foregroundStyle(.red) - } - .buttonStyle(.plain) - .accessibilityLabel(String(localized: "Remove jump host")) - } - } - } - .onMove { indices, destination in - jumpHosts.move(fromOffsets: indices, toOffset: destination) - } - - Button { - jumpHosts.append(SSHJumpHost()) - } label: { - Label(String(localized: "Add Jump Host"), systemImage: "plus") - } - - Text("Jump hosts are connected in order before reaching the SSH server above. Only key and agent auth are supported for jumps.") - .font(.caption) - .foregroundStyle(.secondary) + .disabled(usageUnknown) + .accessibilityIdentifier("ssh-profile-delete") + .profileDeletionAlert($pendingDeletion) { _ in deleteProfile() } } + statusLabel + } actions: { + Button(String(localized: "Test Connection"), action: testConnection) + .disabled(test == .running || !draft.server.validationIssues.isEmpty) + .accessibilityIdentifier("ssh-profile-test") + Button(String(localized: "Cancel")) { dismiss() } + .keyboardShortcut(.cancelAction) + .accessibilityIdentifier("ssh-profile-cancel") + Button(isStored ? String(localized: "Save") : String(localized: "Create")) { saveProfile() } + .keyboardShortcut(.defaultAction) + .disabled(!draft.validationIssues.isEmpty) + .accessibilityIdentifier("ssh-profile-save") } + .padding() } - // MARK: - Bottom Bar - - private var bottomBar: some View { - HStack { - if isStoredProfile { - Button(role: .destructive) { - connectionsUsingProfile = ConnectionStorage.shared.loadConnections() - .filter { connection in - guard case .profile(let id, _) = connection.sshTunnelMode else { return false } - return id == existingProfile?.id - } - .count - showingDeleteConfirmation = true - } label: { - Text("Delete Profile") - } - .alert( - "Delete SSH Profile?", - isPresented: $showingDeleteConfirmation - ) { - Button("Delete", role: .destructive) { deleteProfile() } - Button("Cancel", role: .cancel) {} - } message: { - if connectionsUsingProfile > 0 { - Text("\(connectionsUsingProfile) connection(s) use this profile. They keep this configuration as their own SSH tunnel.") - } else { - Text("This profile will be permanently deleted.") - } - } - } - - Button(action: testSSHConnection) { + @ViewBuilder private var statusLabel: some View { + if let saveError { + NoticeLabel(saveError, severity: .error) + .lineLimit(2) + .truncationMode(.tail) + } else { + switch test { + case .running: HStack(spacing: 6) { - if isTesting { - ProgressView() - .controlSize(.small) - } else if testSucceeded { - Image(systemName: "checkmark.circle.fill") - .foregroundStyle(.green) - } else if testError != nil { - Image(systemName: "xmark.circle.fill") - .foregroundStyle(.red) - } else { - Image(systemName: "antenna.radiowaves.left.and.right") - .foregroundStyle(.secondary) - } - Text("Test Connection") + ProgressView() + .controlSize(.small) + .accessibilityHidden(true) + Text("Testing…") + .foregroundStyle(.secondary) } - } - .disabled(isTesting || !isValid) - - if let saveError { - NoticeLabel(saveError, severity: .error) - .font(.caption) - .lineLimit(2) - .truncationMode(.tail) - } else if testSucceeded { + case .succeeded: NoticeLabel(String(localized: "Connected"), severity: .success) - .font(.caption) - } else if let testError { - NoticeLabel(testError) - .font(.caption) + case .failed(let message): + NoticeLabel(message, severity: .error) .lineLimit(2) .truncationMode(.tail) + case .idle: + if hasLoaded, draft != baseline, let issue = draft.validationIssues.first { + NoticeLabel(issue) + .lineLimit(2) + } } - - Spacer() - - Button("Cancel") { dismiss() } - .keyboardShortcut(.cancelAction) - - Button(isStoredProfile ? "Save" : "Create") { saveProfile() } - .keyboardShortcut(.defaultAction) - .disabled(!isValid) } - .padding() } - // MARK: - Actions + private func load() { + guard !hasLoaded else { return } + hasLoaded = true - private func loadExistingProfile() { - guard let profile = existingProfile else { return } - profileName = profile.name - host = profile.host - port = profile.port.map(String.init) ?? "" - username = profile.username - authMethod = profile.authMethod - privateKeyPath = profile.privateKeyPath - jumpHosts = profile.jumpHosts - totpMode = profile.totpMode - totpAlgorithm = profile.totpAlgorithm - totpDigits = profile.totpDigits - totpPeriod = profile.totpPeriod + let stored = existingProfile.flatMap { storage.profile(for: $0.id) } + isStored = stored != nil + usageUnknown = ConnectionStorage.shared.isLibraryUnreadable - let option = SSHAgentSocketOption(socketPath: profile.agentSocketPath) - agentSocketOption = option - if option == .custom { - customAgentSocketPath = profile.agentSocketPath + var loaded = SSHProfileDraft() + if let record = stored ?? existingProfile { + loaded.name = record.name + loaded.server = SSHServerDraft(profile: record) } - - // Load secrets from Keychain, falling back to initial values (e.g. from "Save as Profile") - sshPassword = SSHProfileStorage.shared.loadSSHPassword(for: profile.id) ?? initialPassword ?? "" - keyPassphrase = SSHProfileStorage.shared.loadKeyPassphrase(for: profile.id) ?? initialKeyPassphrase ?? "" - totpSecret = SSHProfileStorage.shared.loadTOTPSecret(for: profile.id) ?? initialTOTPSecret ?? "" + // A profile not saved yet has no Keychain items; its secrets come from the connection that promoted it. + if let stored { + for secret in SSHSecret.allCases { + let read = storage.readSecret(secret, for: stored.id) + secretReads[secret] = read + loaded.server.setValue(read.value ?? "", of: secret) + } + } else { + loaded.server.password = initialPassword ?? "" + loaded.server.keyPassphrase = initialKeyPassphrase ?? "" + loaded.server.totpSecret = initialTOTPSecret ?? "" + // They came out of the connection's Keychain, so revealing them asks for authentication like a stored secret. + inheritedSecrets = loaded.server.filledSecrets + } + draft = loaded + baseline = loaded } private func saveProfile() { - let profileId = existingProfile?.id ?? UUID() - - let profile = SSHProfile( - id: profileId, - name: profileName.trimmingCharacters(in: .whitespaces), - host: host, - port: Int(port), - username: username, - authMethod: authMethod, - privateKeyPath: privateKeyPath, - agentSocketPath: resolvedAgentSocketPath, - jumpHosts: jumpHosts, - totpMode: totpMode, - totpAlgorithm: totpAlgorithm, - totpDigits: totpDigits, - totpPeriod: totpPeriod - ) - - let persisted = isStoredProfile - ? SSHProfileStorage.shared.updateProfile(profile) - : SSHProfileStorage.shared.addProfile(profile) - - /// The keychain writes below are keyed by the profile id, so running them for a profile - /// that never reached disk would leave secrets nothing can name. Dismissing would also - /// report a save that did not happen. + // Read, then modify: the stored record may have changed since this sheet opened. + let stored = isStored ? storage.profile(for: profileId) : nil + var record = stored ?? SSHProfile(id: profileId, name: draft.trimmedName) + record.name = draft.trimmedName + draft.server.apply(to: &record) + + let persisted = isStored ? storage.updateProfile(record) : storage.addProfile(record) + // Keychain items are keyed by the profile id, so writing them for a profile that never reached disk strands them. guard persisted else { saveError = String(localized: "Could not save the profile. Reopen the SSH settings and try again.") return } - saveError = nil - - if (authMethod == .password || authMethod == .keyboardInteractive) && !sshPassword.isEmpty { - SSHProfileStorage.shared.saveSSHPassword(sshPassword, for: profileId) - } else { - SSHProfileStorage.shared.deleteSSHPassword(for: profileId) - } - - if authMethod == .privateKey && !keyPassphrase.isEmpty { - SSHProfileStorage.shared.saveKeyPassphrase(keyPassphrase, for: profileId) - } else { - SSHProfileStorage.shared.deleteKeyPassphrase(for: profileId) + isStored = true + + var secretsSaved = true + for secret in SSHSecret.allCases { + let before = secretReads[secret] ?? .absent + switch ProfileSecretChange.decide( + applies: draft.server.applies(secret), + value: draft.server.value(of: secret), + read: before + ) { + case .write(let value): + if storage.saveSecret(value, secret, for: profileId) { + secretReads[secret] = .found(value) + } else { + secretsSaved = false + } + case .keep: + break + case .delete: + storage.deleteSecret(secret, for: profileId) + secretReads[secret] = .absent + } } - - if totpMode == .autoGenerate && !totpSecret.isEmpty { - SSHProfileStorage.shared.saveTOTPSecret(totpSecret, for: profileId) - } else { - SSHProfileStorage.shared.deleteTOTPSecret(for: profileId) + guard secretsSaved else { + saveError = String(localized: "The profile was saved, but its password couldn't be saved to the Keychain.") + return } - - onSave?(profile) + saveError = nil + onSave?(record) dismiss() } - func testSSHConnection() { - isTesting = true - testSucceeded = false - testError = nil - - let config = SSHConfiguration( - enabled: true, - host: host, - port: Int(port), - username: username, - authMethod: authMethod, - privateKeyPath: privateKeyPath, - agentSocketPath: resolvedAgentSocketPath, - jumpHosts: jumpHosts, - totpMode: totpMode, - totpAlgorithm: totpAlgorithm, - totpDigits: totpDigits, - totpPeriod: totpPeriod - ) - - let credentials = SSHTunnelCredentials( - sshPassword: sshPassword.isEmpty ? nil : sshPassword, - keyPassphrase: keyPassphrase.isEmpty ? nil : keyPassphrase, - totpSecret: totpSecret.isEmpty ? nil : totpSecret, - keyboardInteractivePromptProvider: nil - ) - + private func testConnection() { + cancelTest() + test = .running + let config = draft.server.configuration() + let credentials = draft.server.testCredentials testTask = Task { do { - try await SSHTunnelManager.shared.testSSHProfile( - config: config, - credentials: credentials - ) - await MainActor.run { - isTesting = false - testSucceeded = true - } + try await SSHTunnelManager.shared.testSSHProfile(config: config, credentials: credentials) + guard !Task.isCancelled else { return } + test = .succeeded } catch { guard !Task.isCancelled else { return } - await MainActor.run { - isTesting = false - testSucceeded = false - testError = error.localizedDescription - } + test = .failed(error.localizedDescription) } } } - private func deleteProfile() { - guard let profile = existingProfile else { return } - guard SSHProfileStorage.shared.deleteProfile(profile) else { - saveError = String(localized: "Could not delete the profile. Reopen the SSH settings and try again.") - return - } - onDelete?() - dismiss() - } - - // MARK: - SSH Config Helpers - - private func applySSHConfigEntry(_ configHost: String) { - guard !configHost.isEmpty else { return } - host = configHost + // An edit makes the last result stale, and a test still running answers for values no longer on screen. + private func cancelTest() { + testTask?.cancel() + testTask = nil + test = .idle } - private func browseForPrivateKey() { - guard let window = NSApp.keyWindow else { return } - let panel = NSOpenPanel() - panel.allowsMultipleSelection = false - panel.canChooseDirectories = false - panel.directoryURL = FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent(".ssh") - panel.showsHiddenFiles = true - panel.beginSheetModal(for: window) { response in - if response == .OK, let url = panel.url { - privateKeyPath = url.path(percentEncoded: false) + private func deleteProfile() { + guard let stored = storage.profile(for: profileId) else { + guard storage.lastLoadFailed else { + onDelete?() + dismiss() + return } + saveError = ConnectionCountCopy.deleteFailedMessage + return } - } - - private func browseForJumpHostKey(jumpHost: Binding) { - guard let window = NSApp.keyWindow else { return } - let panel = NSOpenPanel() - panel.allowsMultipleSelection = false - panel.canChooseDirectories = false - panel.directoryURL = FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent(".ssh") - panel.showsHiddenFiles = true - panel.beginSheetModal(for: window) { response in - if response == .OK, let url = panel.url { - jumpHost.wrappedValue.privateKeyPath = url.path(percentEncoded: false) - } + guard storage.deleteProfile(stored) else { + saveError = ConnectionCountCopy.deleteFailedMessage + return } + onDelete?() + dismiss() } } diff --git a/apple/TablePro/Views/Connection/SSHServerFields.swift b/apple/TablePro/Views/Connection/SSHServerFields.swift new file mode 100644 index 0000000000..936b4e0500 --- /dev/null +++ b/apple/TablePro/Views/Connection/SSHServerFields.swift @@ -0,0 +1,306 @@ +import AppKit +import SwiftUI +import TableProSSHConfig +import TableProSSHTransport + +// Server, Authentication, Two-Factor and Jump Hosts sections, shared by the SSH profile editor and the connection form. +struct SSHServerFields: View { + @Binding var draft: SSHServerDraft + let configEntries: [SSHConfigEntry] + let identifierPrefix: String + // Revealing a secret the Keychain handed over asks for authentication first. + var savedSecrets: Set = [] + + var body: some View { + serverSection + authenticationSection + if draft.authMethod.supportsTwoFactorAuthentication { + twoFactorSection + } + jumpHostsSection + ForEach(draft.jumpHosts) { hop in + jumpHostSection(hop) + } + } + + private var serverSection: some View { + Section(String(localized: "Server")) { + if !configEntries.isEmpty { + Picker(String(localized: "Config Host"), selection: configHost) { + Text("Manual").tag("") + ForEach(configEntries) { entry in + Text(verbatim: entry.displayName).tag(entry.host) + } + } + .accessibilityIdentifier("\(identifierPrefix)-config-host") + } + if draft.selectedConfigHost.isEmpty || configEntries.isEmpty { + TextField(String(localized: "Host"), text: $draft.host, prompt: Text(verbatim: "ssh.example.com")) + .accessibilityIdentifier("\(identifierPrefix)-host") + } + TextField(text: $draft.port, prompt: Text(verbatim: "22")) { + Text("Port") + if !draft.portIsValid { + NoticeLabel(String(localized: "SSH port must be between 1 and 65535"), severity: .error) + } + } + .accessibilityIdentifier("\(identifierPrefix)-port") + TextField(String(localized: "Username"), text: $draft.username, prompt: Text("username")) + .accessibilityIdentifier("\(identifierPrefix)-username") + } + } + + private var configHost: Binding { + Binding( + get: { draft.selectedConfigHost }, + set: { draft.selectConfigHost($0) } + ) + } + + private var authenticationSection: some View { + Section(String(localized: "Authentication")) { + Picker(selection: $draft.authMethod) { + ForEach(SSHAuthMethod.allCases) { method in + Text(method.displayName).tag(method) + } + } label: { + Text("Method") + if let help = methodHelp { + Text(help) + } + } + .accessibilityIdentifier("\(identifierPrefix)-auth-method") + + switch draft.authMethod { + case .password, .keyboardInteractive: + RevealablePasswordField( + title: String(localized: "Password"), + text: $draft.password, + requiresAuthentication: savedSecrets.contains(.password) + ) + case .sshAgent: + Picker(selection: $draft.agentSocketOption) { + ForEach(SSHAgentSocketOption.allCases) { option in + Text(option.displayName).tag(option) + } + } label: { + Text("Agent Socket") + Text(draft.agentSocketOption.explanation) + } + if draft.agentSocketOption == .custom { + TextField( + String(localized: "Custom Path"), + text: $draft.customAgentSocketPath, + prompt: Text(verbatim: "/path/to/agent.sock") + ) + } + keyFileRow( + title: String(localized: "Identity File"), + subtitle: String(localized: """ + Offers the agent key matching this public key file first. With IdentitiesOnly yes \ + in ~/.ssh/config, only that key is offered. + """), + path: $draft.privateKeyPath, + prompt: "~/.ssh/id_ed25519.pub", + panelMessage: String(localized: "Choose a public key file"), + identifier: "\(identifierPrefix)-identity-file" + ) + case .privateKey: + keyFileRow( + title: String(localized: "Key File"), + subtitle: draft.privateKeyPath.isEmpty + ? String(localized: "Auto-detects from ~/.ssh/config and default key locations.") + : nil, + path: $draft.privateKeyPath, + prompt: "~/.ssh/id_rsa", + panelMessage: String(localized: "Choose a private key file"), + identifier: "\(identifierPrefix)-key-file" + ) + RevealablePasswordField( + title: String(localized: "Passphrase"), + text: $draft.keyPassphrase, + requiresAuthentication: savedSecrets.contains(.keyPassphrase), + revealTitle: String(localized: "Show passphrase") + ) + case .none: + EmptyView() + } + } + } + + private var methodHelp: String? { + switch draft.authMethod { + case .keyboardInteractive: + String(localized: "Password is sent via keyboard-interactive challenge-response.") + case .none: + String(localized: "No credentials are sent. Use this when the server handles authentication itself, such as a Tailscale SSH host.") + case .password, .privateKey, .sshAgent: + nil + } + } + + private var twoFactorSection: some View { + Section(String(localized: "Two-Factor Authentication")) { + Picker(String(localized: "TOTP"), selection: $draft.totpMode) { + ForEach(TOTPMode.allCases) { mode in + Text(mode.displayName).tag(mode) + } + } + .accessibilityIdentifier("\(identifierPrefix)-totp-mode") + + if draft.totpMode == .autoGenerate { + RevealablePasswordField( + title: String(localized: "TOTP Secret"), + subtitle: String(localized: "Base32-encoded secret from your authenticator setup"), + text: $draft.totpSecret, + requiresAuthentication: savedSecrets.contains(.totpSecret), + revealTitle: String(localized: "Show secret") + ) + Picker(String(localized: "Algorithm"), selection: $draft.totpAlgorithm) { + ForEach(TOTPAlgorithm.allCases) { algorithm in + Text(verbatim: algorithm.rawValue).tag(algorithm) + } + } + Picker(String(localized: "Digits"), selection: $draft.totpDigits) { + SettingsChoiceItems([6, 8], including: draft.totpDigits) { digits in + Text(verbatim: SettingsFormat.identifier(digits)) + } + } + Picker(String(localized: "Period"), selection: $draft.totpPeriod) { + SettingsChoiceItems([30, 60], including: draft.totpPeriod) { seconds in + Text(verbatim: SettingsFormat.duration(seconds: seconds)) + } + } + } else { + SettingsHelpRow( + "If the SSH server asks for a verification code, TablePro prompts you for it when you connect." + ) + } + } + } + + private var jumpHostsSection: some View { + Section { + SettingsHelpRow( + "Jump hosts are connected in order before reaching the SSH server above. Only key and agent auth are supported for jumps." + ) + } header: { + Text("Jump Hosts") + } footer: { + SettingsSectionActions { + Button(String(localized: "Add Jump Host")) { + withMotion { draft.addJumpHost() } + } + .accessibilityIdentifier("\(identifierPrefix)-add-jump-host") + } + } + } + + private func jumpHostSection(_ hop: SSHJumpHost) -> some View { + let position = draft.jumpHosts.firstIndex { $0.id == hop.id } ?? 0 + let binding = $draft.jumpHosts.element(hop) + let identifier = "\(identifierPrefix)-jump-host-\(position + 1)" + return Section(String(format: String(localized: "Jump Host %lld"), Int64(position + 1))) { + TextField(String(localized: "Host"), text: binding.host, prompt: Text(verbatim: "bastion.example.com")) + .accessibilityIdentifier("\(identifier)-host") + TextField(String(localized: "Port"), text: Self.portText(binding.port), prompt: Text(verbatim: "22")) + .accessibilityIdentifier("\(identifier)-port") + TextField(String(localized: "Username"), text: binding.username, prompt: Text(verbatim: "admin")) + .accessibilityIdentifier("\(identifier)-username") + Picker(String(localized: "Authentication"), selection: binding.authMethod) { + ForEach(SSHJumpAuthMethod.allCases) { method in + Text(method.displayName).tag(method) + } + } + if hop.authMethod == .privateKey { + keyFileRow( + title: String(localized: "Key File"), + subtitle: nil, + path: binding.privateKeyPath, + prompt: "~/.ssh/id_rsa", + panelMessage: String(localized: "Choose a private key file"), + identifier: "\(identifier)-key-file" + ) + } + HStack(spacing: 8) { + Button { + withMotion { draft.moveJumpHost(id: hop.id, by: -1) } + } label: { + Label(String(localized: "Move Up"), systemImage: "chevron.up") + .labelStyle(.iconOnly) + } + .help(String(localized: "Move Up")) + .disabled(position == 0) + Button { + withMotion { draft.moveJumpHost(id: hop.id, by: 1) } + } label: { + Label(String(localized: "Move Down"), systemImage: "chevron.down") + .labelStyle(.iconOnly) + } + .help(String(localized: "Move Down")) + .disabled(position == draft.jumpHosts.count - 1) + Spacer() + Button(String(localized: "Remove Jump Host"), role: .destructive) { + withMotion { draft.removeJumpHost(id: hop.id) } + } + .accessibilityIdentifier("\(identifier)-remove") + } + .buttonStyle(.bordered) + } + } + + private static func portText(_ port: Binding) -> Binding { + Binding( + get: { port.wrappedValue.map(String.init) ?? "" }, + set: { port.wrappedValue = Int($0.trimmingCharacters(in: .whitespaces)) } + ) + } + + private func keyFileRow( + title: String, + subtitle: String?, + path: Binding, + prompt: String, + panelMessage: String, + identifier: String + ) -> some View { + LabeledContent { + HStack(spacing: 8) { + TextField(title, text: path, prompt: Text(verbatim: prompt)) + .labelsHidden() + .accessibilityIdentifier(identifier) + Button(String(localized: "Choose…")) { + Self.chooseKeyFile(message: panelMessage) { path.wrappedValue = $0 } + } + .accessibilityIdentifier("\(identifier)-choose") + } + } label: { + Text(verbatim: title) + if let subtitle { + Text(verbatim: subtitle) + } + } + } + + // A sheet on the window that asked, so the panel cannot slip behind it. + private static func chooseKeyFile(message: String, onSelect: @escaping (String) -> Void) { + let panel = NSOpenPanel() + panel.allowsMultipleSelection = false + panel.canChooseDirectories = false + panel.canChooseFiles = true + panel.showsHiddenFiles = true + panel.directoryURL = FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent(".ssh") + panel.message = message + guard let window = NSApp.keyWindow else { + panel.begin { response in + guard response == .OK, let url = panel.url else { return } + onSelect(url.path(percentEncoded: false)) + } + return + } + panel.beginSheetModal(for: window) { response in + guard response == .OK, let url = panel.url else { return } + onSelect(url.path(percentEncoded: false)) + } + } +} diff --git a/apple/TablePro/Views/Connection/SecretReveal.swift b/apple/TablePro/Views/Connection/SecretReveal.swift index ea1f9dd7b0..859072c7a8 100644 --- a/apple/TablePro/Views/Connection/SecretReveal.swift +++ b/apple/TablePro/Views/Connection/SecretReveal.swift @@ -1,8 +1,3 @@ -// -// SecretReveal.swift -// TablePro -// - import Combine import SwiftUI @@ -43,9 +38,10 @@ final class SecretReveal: ObservableObject { struct SecretRevealToggle: View { @ObservedObject var reveal: SecretReveal let requiresAuthentication: Bool + var title = String(localized: "Show password") var body: some View { - Toggle(String(localized: "Show password"), isOn: Binding( + Toggle(title, isOn: Binding( get: { reveal.isRevealed }, set: { newValue in Task { await reveal.setRevealed(newValue, requiresAuthentication: requiresAuthentication) } @@ -57,18 +53,41 @@ struct SecretRevealToggle: View { // NSSecureTextField has no reveal of its own, so revealing swaps in a plain field, as the system's password fields do. struct RevealablePasswordField: View { let title: String + let subtitle: String? @Binding var text: String let requiresAuthentication: Bool + let revealTitle: String @StateObject private var reveal = SecretReveal() + init( + title: String, + subtitle: String? = nil, + text: Binding, + requiresAuthentication: Bool, + revealTitle: String = String(localized: "Show password") + ) { + self.title = title + self.subtitle = subtitle + self._text = text + self.requiresAuthentication = requiresAuthentication + self.revealTitle = revealTitle + } + var body: some View { if reveal.isRevealed { - TextField(title, text: $text) + TextField(text: $text) { label } .autocorrectionDisabled() } else { - SecureField(title, text: $text) + SecureField(text: $text) { label } + } + SecretRevealToggle(reveal: reveal, requiresAuthentication: requiresAuthentication, title: revealTitle) + } + + @ViewBuilder private var label: some View { + Text(verbatim: title) + if let subtitle { + Text(verbatim: subtitle) } - SecretRevealToggle(reveal: reveal, requiresAuthentication: requiresAuthentication) } } diff --git a/apple/TablePro/Views/ConnectionForm/Components/AttachedDatabaseListEditor.swift b/apple/TablePro/Views/ConnectionForm/Components/AttachedDatabaseListEditor.swift index c3ea5aa3f7..89a893ff1c 100644 --- a/apple/TablePro/Views/ConnectionForm/Components/AttachedDatabaseListEditor.swift +++ b/apple/TablePro/Views/ConnectionForm/Components/AttachedDatabaseListEditor.swift @@ -6,7 +6,7 @@ import AppKit import SwiftUI -/// Built like the Extensions list below it, so the two lists in Options behave the same. +// Built like the Extensions list below it, so the two lists in Options behave the same. struct AttachedDatabaseListEditor: View { @Binding var value: String let databaseType: DatabaseType @@ -53,38 +53,28 @@ struct AttachedDatabaseListEditor: View { if model.rows.isEmpty { Text("No Attached Databases") .foregroundStyle(.secondary) - .padding(.bottom, buttonBarHeight) + .padding(.bottom, ListBarMetrics.height) } } - .safeAreaInset(edge: .bottom, spacing: 0) { - VStack(spacing: 0) { - Divider() - HStack(spacing: 0) { - AddRemoveControlGroup( - addLabel: String(localized: "Attach Database…"), - removeLabel: String(localized: "Remove Attached Database"), - canRemove: !selection.isEmpty, - addIdentifier: "connection-attached-databases-add", - removeIdentifier: "connection-attached-databases-remove", - onAdd: { chooseFiles() }, - onRemove: { removeSelection() } - ) - Spacer() - } - .padding(.horizontal, 4) - .padding(.vertical, 2) - } - .background(.bar) + .listBar { + AddRemoveControlGroup( + addLabel: String(localized: "Attach Database…"), + removeLabel: String(localized: "Remove Attached Database"), + canRemove: !selection.isEmpty, + addIdentifier: "connection-attached-databases-add", + removeIdentifier: "connection-attached-databases-remove", + onAdd: { chooseFiles() }, + onRemove: { removeSelection() } + ) } } private let rowHeight: CGFloat = 26 - private let buttonBarHeight: CGFloat = 32 private var listHeight: CGFloat { // No cap: a List in a grouped Form never scrolls, so it shows every row and the Form scrolls. let rows = CGFloat(max(model.rows.count, 2)) - return rows * rowHeight + buttonBarHeight + 8 + return rows * rowHeight + ListBarMetrics.height + 8 } private func nameBinding(for id: UUID) -> Binding { diff --git a/apple/TablePro/Views/ConnectionForm/Components/LoadableExtensionListEditor.swift b/apple/TablePro/Views/ConnectionForm/Components/LoadableExtensionListEditor.swift index 182eea6353..b7e97dd830 100644 --- a/apple/TablePro/Views/ConnectionForm/Components/LoadableExtensionListEditor.swift +++ b/apple/TablePro/Views/ConnectionForm/Components/LoadableExtensionListEditor.swift @@ -7,12 +7,7 @@ import AppKit import SwiftUI import UniformTypeIdentifiers -/// The ordered list of SQLite extension libraries a connection loads, edited in place. -/// -/// Built like the other lists in this form: a bordered list with the add and remove pair beneath -/// it, rows reordered by dragging or with the Move Up and Move Down accessibility actions, and -/// Delete removing the selection. Add opens a file panel, the only way a row is created; once it -/// exists, its path and entry point are edited in place. +// Add opens a file panel, the only way a row is created; a row's path and entry point are then edited in place. struct LoadableExtensionListEditor: View { @Binding var value: String @@ -58,38 +53,28 @@ struct LoadableExtensionListEditor: View { if model.rows.isEmpty { Text("No Extensions") .foregroundStyle(.secondary) - .padding(.bottom, buttonBarHeight) + .padding(.bottom, ListBarMetrics.height) } } - .safeAreaInset(edge: .bottom, spacing: 0) { - VStack(spacing: 0) { - Divider() - HStack(spacing: 0) { - AddRemoveControlGroup( - addLabel: String(localized: "Add Extension…"), - removeLabel: String(localized: "Remove Extension"), - canRemove: !selection.isEmpty, - addIdentifier: "connection-extensions-add", - removeIdentifier: "connection-extensions-remove", - onAdd: { chooseFiles() }, - onRemove: { removeSelection() } - ) - Spacer() - } - .padding(.horizontal, 4) - .padding(.vertical, 2) - } - .background(.bar) + .listBar { + AddRemoveControlGroup( + addLabel: String(localized: "Add Extension…"), + removeLabel: String(localized: "Remove Extension"), + canRemove: !selection.isEmpty, + addIdentifier: "connection-extensions-add", + removeIdentifier: "connection-extensions-remove", + onAdd: { chooseFiles() }, + onRemove: { removeSelection() } + ) } } private let rowHeight: CGFloat = 26 - private let buttonBarHeight: CGFloat = 32 private var listHeight: CGFloat { // No cap: a List in a grouped Form never scrolls, so it shows every row and the Form scrolls. let rows = CGFloat(max(model.rows.count, 2)) - return rows * rowHeight + buttonBarHeight + 8 + return rows * rowHeight + ListBarMetrics.height + 8 } private func pathBinding(for id: UUID) -> Binding { @@ -203,8 +188,7 @@ private struct LoadableExtensionRowView: View { } } -/// Refuses a file that is not a Mach-O library before it reaches the list. The panel's content types -/// only dim other files, and `.so` has no type of its own, so the choice is checked here as well. +// The panel's content types only dim other files, and .so has no type of its own, so the choice is checked here too. private final class LoadableExtensionPanelValidator: NSObject, NSOpenSavePanelDelegate { static let contentTypes: [UTType] = [ UTType(filenameExtension: "dylib"), diff --git a/apple/TablePro/Views/ConnectionForm/Panes/OptionsPaneView.swift b/apple/TablePro/Views/ConnectionForm/Panes/OptionsPaneView.swift index 3bd7c4acd5..c97c39b866 100644 --- a/apple/TablePro/Views/ConnectionForm/Panes/OptionsPaneView.swift +++ b/apple/TablePro/Views/ConnectionForm/Panes/OptionsPaneView.swift @@ -1,19 +1,16 @@ -// -// OptionsPaneView.swift -// TablePro -// - import AppKit import SwiftUI import TableProAutocomplete import TableProPluginKit struct OptionsPaneView: View { - @ObservedObject private var settingsManager = AppSettingsManager.shared + @ObservedObject private var aiSettings = AppSettingsManager.shared.aiSlice + @ObservedObject private var generalSettings = AppSettingsManager.shared.generalSlice + @ObservedObject private var syncSettings = AppSettingsManager.shared.syncSlice @ObservedObject var coordinator: ConnectionFormCoordinator private var databaseType: DatabaseType { coordinator.network.type } - private var aiIsEnabled: Bool { settingsManager.ai.enabled } + private var aiIsEnabled: Bool { aiSettings.value.enabled } // Nil until this connection is open as the type the form shows. private var liveDriverRunsReadOnly: Bool? { @@ -40,14 +37,12 @@ struct OptionsPaneView: View { if aiIsEnabled { aiRulesSection } - if settingsManager.sync.enabled { + if syncSettings.value.enabled { syncSection } } } - // MARK: - Timeouts - private var timeoutSection: some View { Section { LabeledContent(String(localized: "Connect timeout")) { @@ -68,13 +63,13 @@ struct OptionsPaneView: View { } .help(connectTimeoutHelp) - LabeledContent(String(localized: "Query timeout")) { + LabeledContent { HStack(spacing: 4) { TextField( String(localized: "Query timeout"), value: $coordinator.customization.queryTimeoutSeconds, format: .number.grouping(.never), - prompt: Text(verbatim: queryTimeoutPlaceholder) + prompt: Text(verbatim: Self.queryTimeoutPlaceholder(globalSeconds: globalQueryTimeoutSeconds)) ) .labelsHidden() .frame(width: 100) @@ -83,8 +78,10 @@ struct OptionsPaneView: View { Text(String(localized: "seconds")) .foregroundStyle(.secondary) } + } label: { + Text(String(localized: "Query timeout")) + Text(verbatim: Self.queryTimeoutInheritance(globalSeconds: globalQueryTimeoutSeconds)) } - .help(queryTimeoutHelp) } header: { Text(String(localized: "Timeouts")) } footer: { @@ -116,32 +113,35 @@ struct OptionsPaneView: View { ) } - private var queryTimeoutPlaceholder: String { - String( - format: String(localized: "Global (%d)"), - settingsManager.general.queryTimeoutSeconds + private var globalQueryTimeoutSeconds: Int { generalSettings.value.queryTimeoutSeconds } + + // The field is 100 points wide beside a "seconds" label, so words go in the subtitle and the prompt stays short. + nonisolated static func queryTimeoutPlaceholder(globalSeconds: Int) -> String { + let seconds = ConnectionTimeoutPolicy.effectiveQueryTimeoutSeconds( + configuredSeconds: nil, + globalSeconds: globalSeconds ) + guard seconds > 0 else { return String(localized: "No limit") } + return String(format: String(localized: "Global (%d)"), seconds) } - private var queryTimeoutHelp: String { - let globalQueryTimeoutSeconds = settingsManager.general.queryTimeoutSeconds - guard globalQueryTimeoutSeconds > 0 else { - return String(localized: """ - Leave blank to use the global setting, which has no limit. \ - This setting applies only to database drivers that support it. - """) + nonisolated static func queryTimeoutInheritance( + globalSeconds: Int, + locale: Locale = .autoupdatingCurrent + ) -> String { + let seconds = ConnectionTimeoutPolicy.effectiveQueryTimeoutSeconds( + configuredSeconds: nil, + globalSeconds: globalSeconds + ) + guard seconds > 0 else { + return String(localized: "Leave blank to use Settings > Connections: no limit.") } - return String( - format: String(localized: """ - Leave blank to use the global %d-second timeout. \ - This setting applies only to database drivers that support it. - """), - globalQueryTimeoutSeconds + let duration = Duration.seconds(seconds).formatted( + .units(allowed: [.hours, .minutes, .seconds], width: .wide).locale(locale) ) + return String(format: String(localized: "Leave blank to use Settings > Connections: %@."), duration) } - // MARK: - Binary values - @ViewBuilder private var binaryValuesSection: some View { if PluginManager.shared.binaryLengthFunction(for: databaseType) != nil { @@ -179,8 +179,6 @@ struct OptionsPaneView: View { String(format: String(localized: "Default (%d)"), UnloadedValuePlan.defaultInlineByteLimit / 1_024) } - // MARK: - Autocomplete - @ViewBuilder private var completionSection: some View { if databaseType.identifierRules != nil { @@ -217,8 +215,6 @@ struct OptionsPaneView: View { } } - // MARK: - Driver options - @ViewBuilder private var driverSection: some View { let fields = coordinator.advanced.advancedFields @@ -246,8 +242,6 @@ struct OptionsPaneView: View { ) } - // MARK: - Attached Databases - @ViewBuilder private var attachedDatabasesSection: some View { if let field = coordinator.advanced.attachedDatabaseListField { @@ -263,8 +257,6 @@ struct OptionsPaneView: View { } } - // MARK: - Extensions - @ViewBuilder private var extensionsSection: some View { if let field = coordinator.advanced.extensionListField { @@ -280,8 +272,6 @@ struct OptionsPaneView: View { } } - // MARK: - Startup - private var startupSection: some View { Section { StartupCommandsEditor(text: $coordinator.advanced.startupCommands, style: .code) @@ -349,22 +339,21 @@ struct OptionsPaneView: View { String(format: String(localized: "Default (%d)"), ConnectionScriptRunner.defaultTimeoutSeconds) } - // MARK: - Safety - private var safetySection: some View { Section { safeModeRow Toggle(String(localized: "Manual Commit"), isOn: $coordinator.effectiveManualCommit) .disabled(!coordinator.isManualCommitAvailable) - if aiIsEnabled { - Picker(String(localized: "AI Policy"), selection: $coordinator.advanced.aiPolicy) { - Text(String(localized: "Use Default")) - .tag(AIConnectionPolicy?.none as AIConnectionPolicy?) - ForEach(AIConnectionPolicy.allCases) { policy in - Text(policy.displayName) - .tag(AIConnectionPolicy?.some(policy) as AIConnectionPolicy?) - } + // MCP enforces the policy whether or not AI features are on, so it stays editable. + Picker(String(localized: "AI Policy"), selection: $coordinator.advanced.aiPolicy) { + Text(String(localized: "Use Default")) + .tag(AIConnectionPolicy?.none as AIConnectionPolicy?) + ForEach(AIConnectionPolicy.allCases) { policy in + Text(policy.displayName) + .tag(AIConnectionPolicy?.some(policy) as AIConnectionPolicy?) } + } + if aiIsEnabled { ForEach(coordinator.advanced.aiAlwaysAllowedTools, id: \.self) { tool in alwaysAllowedRow(tool) } @@ -420,15 +409,10 @@ struct OptionsPaneView: View { } else { Text(ManualCommit.unavailableExplanation) } - if aiIsEnabled { - // swiftlint:disable:next line_length - Text(String(localized: "AI Policy controls in-app AI agents. External Clients controls Raycast, Cursor, Claude Desktop, other MCP clients, AppleScript, and Shortcuts. Effective scope is the minimum of the requesting token's scope and the External Clients level.")) - if !coordinator.advanced.aiAlwaysAllowedTools.isEmpty { - Text(String(localized: "Always Allow on an assistant tool card adds the tool here. Forget makes its next call ask again.")) - } - } else { - // swiftlint:disable:next line_length - Text(String(localized: "Controls how external clients (Raycast, Cursor, Claude Desktop, AppleScript, Shortcuts) access this connection. Tokens cannot exceed this level even with full-access scope.")) + // swiftlint:disable:next line_length + Text(String(localized: "AI Policy applies to AI features and MCP clients. External Clients controls Raycast, Cursor, Claude Desktop, other MCP clients, AppleScript, and Shortcuts. Effective scope is the minimum of the requesting token's scope and the External Clients level.")) + if aiIsEnabled, !coordinator.advanced.aiAlwaysAllowedTools.isEmpty { + Text(String(localized: "Always Allow on an assistant tool card adds the tool here. Forget makes its next call ask again.")) } if coordinator.advanced.externalAccess == .readOnly { Text( @@ -443,8 +427,6 @@ struct OptionsPaneView: View { .foregroundStyle(.secondary) } - // MARK: - AI rules - private var aiRulesSection: some View { Section { StartupCommandsEditor(text: $coordinator.aiRules.rules, style: .plain) @@ -458,8 +440,6 @@ struct OptionsPaneView: View { } } - // MARK: - Sync - private var syncSection: some View { Section { Toggle(String(localized: "Local only"), isOn: $coordinator.advanced.localOnly) @@ -478,7 +458,7 @@ struct OptionsPaneView: View { } } -/// Columns whose values TablePro hides, for this connection, in the grid, exports, the assistant and MCP. +// Columns whose values TablePro hides, for this connection, in the grid, exports, the assistant and MCP. private struct MaskingRulesSection: View { @ObservedObject var model: MaskingRulesPaneViewModel diff --git a/apple/TablePro/Views/ConnectionForm/Panes/Transports/SSHServerSections.swift b/apple/TablePro/Views/ConnectionForm/Panes/Transports/SSHServerSections.swift index 8e2e2e197a..14147b79f0 100644 --- a/apple/TablePro/Views/ConnectionForm/Panes/Transports/SSHServerSections.swift +++ b/apple/TablePro/Views/ConnectionForm/Panes/Transports/SSHServerSections.swift @@ -1,17 +1,8 @@ -// -// SSHServerSections.swift -// TablePro -// - import SwiftUI import TableProSSHConfig import TableProSSHTransport -/// Which SSH server to reach, and how to sign in to it. -/// -/// Sections rather than a `Form`, because the Network tab is the form. It used to wrap itself in -/// one and be embedded inside another by the Remote File pane, which is a grouped form nested in a -/// grouped form and inset twice. +// Sections, not a Form: the Network tab is the form, and the Remote File pane embeds these in it too. struct SSHServerSections: View { @Binding var sshState: SSHTunnelFormState @@ -26,18 +17,21 @@ struct SSHServerSections: View { } } } else if sshState.selectedProfile == nil { - sshInlineFields + SSHServerFields( + draft: $sshState.server, + configEntries: sshState.configEntries, + identifierPrefix: "connection-form-ssh", + savedSecrets: sshState.savedSecrets + ) } } - // MARK: - SSH Profile Section - private var sshProfileSection: some View { Section(String(localized: "Profile")) { Picker(String(localized: "Profile"), selection: $sshState.profileId) { Text("Inline Configuration").tag(UUID?.none) ForEach(sshState.profiles) { profile in - Text("\(profile.name) (\(profile.username)@\(profile.host))").tag(UUID?.some(profile.id)) + Text(verbatim: "\(profile.name) (\(profile.address))").tag(UUID?.some(profile.id)) } } @@ -65,9 +59,11 @@ struct SSHServerSections: View { if let profile = sshState.selectedProfile { DisclosureGroup(String(localized: "Profile Details")) { LabeledContent(String(localized: "Host"), value: profile.host) - LabeledContent(String(localized: "Port"), value: profile.port.map(String.init) ?? "22") + LabeledContent(String(localized: "Port")) { + Text(verbatim: SettingsFormat.identifier(profile.port ?? 22)) + } LabeledContent(String(localized: "Username"), value: profile.username) - LabeledContent(String(localized: "Authentication Method"), value: profile.authMethod.rawValue) + LabeledContent(String(localized: "Authentication Method"), value: profile.authMethod.displayName) if !profile.privateKeyPath.isEmpty { LabeledContent( profile.authMethod == .sshAgent @@ -77,7 +73,9 @@ struct SSHServerSections: View { ) } if !profile.jumpHosts.isEmpty { - LabeledContent(String(localized: "Jump Hosts"), value: "\(profile.jumpHosts.count)") + LabeledContent(String(localized: "Jump Hosts")) { + Text(profile.jumpHosts.count, format: .number) + } } } } @@ -133,241 +131,4 @@ struct SSHServerSections: View { totpPeriod: sshState.totpPeriod ) } - - // MARK: - SSH Inline Fields - - private var sshInlineFields: some View { - Group { - Section(String(localized: "Server")) { - if !sshState.configEntries.isEmpty { - Picker(String(localized: "Config Host"), selection: $sshState.selectedConfigHost) { - Text(String(localized: "Manual")).tag("") - ForEach(sshState.configEntries) { entry in - Text(entry.displayName).tag(entry.host) - } - } - .onChange(of: sshState.selectedConfigHost) { _ in - applySSHConfigEntry(sshState.selectedConfigHost) - } - } - if sshState.selectedConfigHost.isEmpty || sshState.configEntries.isEmpty { - TextField(String(localized: "SSH Host"), text: $sshState.host, prompt: Text("ssh.example.com")) - .accessibilityIdentifier("connection-form-ssh-host") - } - TextField(String(localized: "SSH Port"), text: $sshState.port, prompt: Text("22")) - TextField(String(localized: "SSH User"), text: $sshState.username, prompt: Text("username")) - } - - Section(String(localized: "Authentication")) { - Picker(String(localized: "Method"), selection: $sshState.authMethod) { - ForEach(SSHAuthMethod.allCases) { method in - Text(method.rawValue).tag(method) - } - } - if sshState.authMethod == .password { - SecureField(String(localized: "Password"), text: $sshState.password) - } else if sshState.authMethod == .sshAgent { - Picker(String(localized: "Agent Socket"), selection: $sshState.agentSocketOption) { - ForEach(SSHAgentSocketOption.allCases) { option in - Text(option.displayName).tag(option) - } - } - if sshState.agentSocketOption == .custom { - TextField( - String(localized: "Custom Path"), - text: $sshState.customAgentSocketPath, - prompt: Text("/path/to/agent.sock") - ) - } - Text(sshState.agentSocketOption.explanation) - .font(.caption) - .foregroundStyle(.secondary) - LabeledContent(String(localized: "Identity File")) { - HStack { - TextField( - "", - text: $sshState.privateKeyPath, - prompt: Text("~/.ssh/id_ed25519.pub") - ) - Button(String(localized: "Browse")) { - browseForKeyFile( - message: String(localized: "Choose a public key file") - ) { sshState.privateKeyPath = $0 } - } - .controlSize(.small) - } - } - Text(String(localized: """ - Offers the agent key matching this public key file first. With IdentitiesOnly yes \ - in ~/.ssh/config, only that key is offered. - """)) - .font(.caption) - .foregroundStyle(.secondary) - } else if sshState.authMethod == .keyboardInteractive { - SecureField(String(localized: "Password"), text: $sshState.password) - Text(String(localized: "Password is sent via keyboard-interactive challenge-response.")) - .font(.caption) - .foregroundStyle(.secondary) - } else if sshState.authMethod == .none { - Text("No credentials are sent. Use this when the server handles authentication itself, such as a Tailscale SSH host.") - .font(.caption) - .foregroundStyle(.secondary) - } else { - LabeledContent(String(localized: "Key File")) { - HStack { - TextField("", text: $sshState.privateKeyPath, prompt: Text("~/.ssh/id_rsa")) - Button(String(localized: "Browse")) { browseForKeyFile { sshState.privateKeyPath = $0 } } - .controlSize(.small) - } - } - SecureField(String(localized: "Passphrase"), text: $sshState.keyPassphrase) - if sshState.privateKeyPath.isEmpty { - Text(String(localized: "Auto-detects from ~/.ssh/config and default key locations.")) - .font(.caption) - .foregroundStyle(.secondary) - } - } - } - - if sshState.authMethod.supportsTwoFactorAuthentication { - Section(String(localized: "Two-Factor Authentication")) { - Picker(String(localized: "TOTP"), selection: $sshState.totpMode) { - ForEach(TOTPMode.allCases) { mode in - Text(mode.displayName).tag(mode) - } - } - - if sshState.totpMode == .autoGenerate { - SecureField(String(localized: "TOTP Secret"), text: $sshState.totpSecret) - .help(String(localized: "Base32-encoded secret from your authenticator setup")) - Picker(String(localized: "Algorithm"), selection: $sshState.totpAlgorithm) { - ForEach(TOTPAlgorithm.allCases) { algo in - Text(algo.rawValue).tag(algo) - } - } - Picker(String(localized: "Digits"), selection: $sshState.totpDigits) { - Text("6").tag(6) - Text("8").tag(8) - } - Picker(String(localized: "Period"), selection: $sshState.totpPeriod) { - Text("30s").tag(30) - Text("60s").tag(60) - } - } else { - Text(String(localized: "If the SSH server asks for a verification code, TablePro prompts you for it when you connect.")) - .font(.caption) - .foregroundStyle(.secondary) - } - } - } - - Section { - DisclosureGroup(String(localized: "Jump Hosts")) { - ForEach(sshState.jumpHosts) { jumpHost in - let jumpHostBinding = $sshState.jumpHosts.element(jumpHost) - DisclosureGroup { - TextField( - String(localized: "Host"), - text: jumpHostBinding.host, - prompt: Text("bastion.example.com") - ) - HStack { - TextField( - String(localized: "Port"), - text: Binding( - get: { jumpHostBinding.wrappedValue.port.map(String.init) ?? "" }, - set: { jumpHostBinding.wrappedValue.port = Int($0) } - ), - prompt: Text("22") - ) - .frame(width: 80) - TextField( - String(localized: "Username"), - text: jumpHostBinding.username, - prompt: Text("admin") - ) - } - Picker(String(localized: "Auth"), selection: jumpHostBinding.authMethod) { - ForEach(SSHJumpAuthMethod.allCases) { method in - Text(method.rawValue).tag(method) - } - } - if jumpHost.authMethod == .privateKey { - LabeledContent(String(localized: "Key File")) { - HStack { - TextField( - "", - text: jumpHostBinding.privateKeyPath, - prompt: Text("~/.ssh/id_rsa") - ) - Button(String(localized: "Browse")) { - browseForKeyFile { jumpHostBinding.wrappedValue.privateKeyPath = $0 } - } - .controlSize(.small) - } - } - } - } label: { - HStack { - Text( - jumpHost.host.isEmpty - ? String(localized: "New Jump Host") - : "\(jumpHost.username)@\(jumpHost.host)" - ) - .foregroundStyle(jumpHost.host.isEmpty ? .secondary : .primary) - Spacer() - Button { - let idToRemove = jumpHost.id - withMotion { sshState.jumpHosts.removeAll { $0.id == idToRemove } } - } label: { - Image(systemName: "minus.circle") - } - .buttonStyle(.borderless) - .accessibilityLabel(String(localized: "Remove jump host")) - } - } - } - .onMove { indices, destination in - sshState.jumpHosts.move(fromOffsets: indices, toOffset: destination) - } - - Button { - sshState.jumpHosts.append(SSHJumpHost()) - } label: { - Label(String(localized: "Add Jump Host"), systemImage: "plus") - } - - Text( - "Jump hosts are connected in order before reaching the SSH server above. Only key and agent auth are supported for jumps." - ) - .font(.caption) - .foregroundStyle(.secondary) - } - } - } - } - - // MARK: - Helper Methods - - private func browseForKeyFile( - message: String = String(localized: "Choose a private key file"), - onSelect: @escaping (String) -> Void - ) { - let panel = NSOpenPanel() - panel.allowsMultipleSelection = false - panel.canChooseDirectories = false - panel.directoryURL = FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent(".ssh") - panel.showsHiddenFiles = true - panel.message = message - panel.begin { response in - if response == .OK, let url = panel.url { - onSelect(url.path(percentEncoded: false)) - } - } - } - - private func applySSHConfigEntry(_ host: String) { - guard !host.isEmpty else { return } - sshState.host = host - } } diff --git a/apple/TablePro/Views/ERDiagram/ERDiagramEditSheets.swift b/apple/TablePro/Views/ERDiagram/ERDiagramEditSheets.swift index 206e1e56b3..1210702226 100644 --- a/apple/TablePro/Views/ERDiagram/ERDiagramEditSheets.swift +++ b/apple/TablePro/Views/ERDiagram/ERDiagramEditSheets.swift @@ -147,34 +147,25 @@ struct ERDiagramForeignKeySheet: View { .listStyle(.bordered(alternatesRowBackgrounds: false)) .frame(height: listHeight) .onDeleteCommand { removeSelection() } - .safeAreaInset(edge: .bottom, spacing: 0) { - VStack(spacing: 0) { - Divider() - HStack(spacing: 0) { - AddRemoveControlGroup( - addLabel: String(localized: "Add Column Pair"), - removeLabel: String(localized: "Remove Column Pair"), - canRemove: canRemoveSelection, - addIdentifier: "er-diagram-foreign-key-add-pair", - removeIdentifier: "er-diagram-foreign-key-remove-pair", - onAdd: addPair, - onRemove: removeSelection - ) - Spacer() - } - .padding(.horizontal, 4) - .padding(.vertical, 2) - } - .background(.bar) + .listBar { + AddRemoveControlGroup( + addLabel: String(localized: "Add Column Pair"), + removeLabel: String(localized: "Remove Column Pair"), + canRemove: canRemoveSelection, + addIdentifier: "er-diagram-foreign-key-add-pair", + removeIdentifier: "er-diagram-foreign-key-remove-pair", + onAdd: addPair, + onRemove: removeSelection + ) } } - private let rowHeight: CGFloat = 26 - private let buttonBarHeight: CGFloat = 32 + // A row of two pop-up buttons is 32pt on macOS 27, taller than a text field row. + private let rowHeight: CGFloat = 32 // No cap: a List in a grouped Form never scrolls, so it shows every pair and the Form scrolls. private var listHeight: CGFloat { - CGFloat(max(draft.pairs.count, 2)) * rowHeight + buttonBarHeight + 8 + CGFloat(max(draft.pairs.count, 2)) * rowHeight + ListBarMetrics.height + 8 } private var canRemoveSelection: Bool { diff --git a/apple/TablePro/Views/Editor/QueryEditorPaneController.swift b/apple/TablePro/Views/Editor/QueryEditorPaneController.swift index 0e2ad9d64e..701e680d5d 100644 --- a/apple/TablePro/Views/Editor/QueryEditorPaneController.swift +++ b/apple/TablePro/Views/Editor/QueryEditorPaneController.swift @@ -1,16 +1,9 @@ -// -// QueryEditorPaneController.swift -// TablePro -// - import AppKit import Combine import SwiftUI import TableProEditorKit -/// What the query tab's editor pane shows: the header above the editor, and the editor's input. struct QueryEditorPaneInput { - /// The banner, the command bar and the parameter panel, given the Vim mode to show or nil. var header: (VimMode?) -> AnyView var editor: SQLEditorInput } @@ -21,17 +14,16 @@ final class QueryEditorPaneModel: ObservableObject { } struct QueryEditorHeader: View { - @ObservedObject private var settingsManager = AppSettingsManager.shared + @ObservedObject private var editorSettings = AppSettingsManager.shared.editorSlice @ObservedObject var model: QueryEditorPaneModel let content: (VimMode?) -> AnyView var body: some View { - content(settingsManager.editor.keyBindings == .vim ? model.vimMode : nil) + content(editorSettings.value.keyBindings == .vim ? model.vimMode : nil) } } -/// The SQL editor under its command bar. The editor takes whatever height the header leaves, with no minimum of its -/// own: the pane bottoms out at the query split's top minimum, and an editor that also insisted on one overflowed it. +// No editor minimum: the pane bottoms out at the query split's top minimum, and a second one overflowed it. @MainActor final class QueryEditorPaneController: NSViewController { let editor: SQLEditorController diff --git a/apple/TablePro/Views/Editor/SQLEditorController.swift b/apple/TablePro/Views/Editor/SQLEditorController.swift index b0f49a3245..1e88ef5b96 100644 --- a/apple/TablePro/Views/Editor/SQLEditorController.swift +++ b/apple/TablePro/Views/Editor/SQLEditorController.swift @@ -1,8 +1,3 @@ -// -// SQLEditorController.swift -// TablePro -// - import AppKit import Combine import SwiftUI @@ -12,7 +7,6 @@ import TableProPluginKit import TableProSQLGrammar import TableProTextEngine -/// What a query tab hands the SQL editor on every update. struct SQLEditorInput { var text: Binding var cursorPositions: Binding<[CursorPosition]> @@ -24,7 +18,7 @@ struct SQLEditorInput { var undoHistories: EditorUndoHistories? var sourceFileURL: URL? var claimFocusOnAppear = false - /// Called once the editor has latched a focus claim, so the owner's one-shot intent is cleared. + // Called once the editor latched a focus claim, so the owner clears its one-shot intent. var onFocusClaimed: (() -> Void)? var restoredCursorRange: NSRange? var pendingStatementJump: StatementAnchor? @@ -37,7 +31,7 @@ struct SQLEditorInput { var onSelectAdjacentTab: ((Int) -> Void)? var tabCount: (() -> Int)? var onRunStatement: ((String, Int) -> Bool)? - /// A tab runs one thing at a time, so the gutter's run controls go dim for the length of a query. + // A tab runs one thing at a time, so the gutter's run controls go dim for the length of a query. var isExecuting = false var currentAIAvailability: (() -> AIQueryActionAvailability)? var onAIAction: ((AIQueryAction, AIQueryTarget) -> Void)? @@ -45,12 +39,10 @@ struct SQLEditorInput { var onShareQuery: ((String) -> Void)? } -/// The SQL editor in AppKit, so the query tab hosts it with no SwiftUI host around it: each one above an editor -/// forced the window to lay out every hosting view again as the editor's views went in. +// AppKit, so no SwiftUI host wraps the editor: each one made the window lay out every hosting view as the editor went in. @MainActor final class SQLEditorController { let coordinator = SQLEditorCoordinator() - /// Reports Vim's mode to whatever draws it beside the editor. var onVimModeChange: ((VimMode) -> Void)? private let completionAdapter = QueryCompletionAdapter(schemaProvider: nil, databaseType: nil) @@ -127,9 +119,7 @@ final class SQLEditorController { configureCompletion() setupFavoritesObserver() } - /// A tab rebound to another database keeps its editor and its connection, so only the scope moves. Without - /// this the editor keeps completing against the previous database's provider until the profile resolution - /// returns, which leases a metadata driver and on a non-poolable engine can queue behind a running query. + // Otherwise completion keeps the old database's provider until the profile resolves, which can queue behind a query. if newInput.databaseScope != old.databaseScope { completionProfile = nil configureCompletion() @@ -138,8 +128,7 @@ final class SQLEditorController { resolveCompletionProfileIfNeeded() } - /// The editor's terminal teardown, run when its query tab area goes away for good, never when it only leaves - /// the window. + // Runs when the query tab area goes away for good, never when it only leaves the window. func teardown() { guard !isTornDown else { return } isTornDown = true @@ -153,8 +142,7 @@ final class SQLEditorController { host?.dismantle() } - // A large document's last keys are still on their way to the binding when the editor moves to another tab or - // goes away. Both run inside a SwiftUI update, where writing the tab would publish mid-update, so it lands next turn. + // Late keys arrive inside a SwiftUI update, where writing the tab would publish mid-update, so they land next turn. private func handOverPendingText(to binding: Binding) { guard let text = host?.takePendingTextWriteback() else { return } Task { @MainActor in binding.wrappedValue = text } @@ -215,8 +203,7 @@ final class SQLEditorController { refreshSessionGrammar() } - /// The grammar the session lexes with: KingbaseES in Oracle mode, MySQL under `NO_BACKSLASH_ESCAPES`, or - /// PostgreSQL with `standard_conforming_strings` off each split text differently from the engine's default. + // KingbaseES in Oracle mode, MySQL under NO_BACKSLASH_ESCAPES or PostgreSQL without standard_conforming_strings lex differently. private func refreshSessionGrammar() { guard let databaseType = input.databaseType else { return } let grammar: SQLLexicalGrammar @@ -278,8 +265,7 @@ final class SQLEditorController { } } - // An edit reports its caret before its text is written back, so the caret waits for the text; one from a document - // the binding does not hold, as across a tab switch, is never passed on. + // The caret arrives before its text, so it waits; one from a document the binding does not hold is dropped. private func passPendingCaretOn() { guard let positions = pendingCaret else { return } let editorLength = (textViewController.textView.string as NSString).length @@ -288,11 +274,9 @@ final class SQLEditorController { input.cursorPositions.wrappedValue = positions } - // MARK: - Settings - private func observeEditorSettings() { - // `$editor` publishes before the value is stored; the theme reads the stored settings too. - AppSettingsManager.shared.$editor + // The slice publishes before the value is stored; the theme reads the stored settings too. + AppSettingsManager.shared.editorSlice.publisher .dropFirst() .receive(on: RunLoop.main) .sink { [weak self] editor in @@ -346,10 +330,7 @@ final class SQLEditorController { ) } - // MARK: - Completion - - /// The one place the completion service is configured. Configuring without a profile anywhere else put the - /// editor back on the app's own dialect after the resolver had run, with nothing scheduled to correct it. + // The only place completion is configured: doing it elsewhere without a profile reverted the dialect the resolver set. private func configureCompletion() { completionAdapter.configure( schemaProvider: input.schemaProvider, @@ -360,9 +341,7 @@ final class SQLEditorController { ) } - /// This scope's box alone, never the registry: the registry publishes on every fetch, and resolving again for - /// each of them would run while the user types. A `@Published` publisher delivers its current value on - /// subscribe, so the revision starts in step with the box. + // This scope's box, not the registry, which publishes on every fetch and would resolve again while the user types. private func subscribeToCompletionRevision() { revisionSubscription = nil guard let scope = input.databaseScope else { return } @@ -383,7 +362,7 @@ final class SQLEditorController { ) } - /// The revision is part of the request, so an invalidation of this scope restarts the resolution. + // The revision is part of the request, so an invalidation of this scope restarts the resolution. private func resolveCompletionProfileIfNeeded() { let request = completionProfileRequest guard request != profileRequest, !isTornDown else { return } @@ -404,8 +383,6 @@ final class SQLEditorController { } } - // MARK: - Favorites - private func setupFavoritesObserver() { favoritesCancellables.removeAll() refreshFavoriteKeywords() diff --git a/apple/TablePro/Views/Editor/SQLEditorCoordinator.swift b/apple/TablePro/Views/Editor/SQLEditorCoordinator.swift index 816b4b1399..0cff4ab7fb 100644 --- a/apple/TablePro/Views/Editor/SQLEditorCoordinator.swift +++ b/apple/TablePro/Views/Editor/SQLEditorCoordinator.swift @@ -1,11 +1,3 @@ -// -// SQLEditorCoordinator.swift -// TablePro -// -// TextViewCoordinator for the TableProEditorKit-based SQL editor. -// Handles find panel workarounds and horizontal scrolling fix. -// - import AppKit import Combine import os @@ -15,15 +7,11 @@ import TableProPluginKit import TableProSQLGrammar import TableProTextEngine -/// Coordinator for the SQL editor — manages find panel, horizontal scrolling, and scroll-to-match @MainActor final class SQLEditorCoordinator: ObservableObject, TextViewCoordinator, TextViewDelegate { - // MARK: - Properties - nonisolated private static let logger = Logger(subsystem: "com.TablePro", category: "SQLEditorCoordinator") - /// Above this document length inline AI features are suspended, at the same cutoff where syntax highlighting stops, - /// so a large document does not copy its whole contents to the assistant on every keystroke. + // Above this length inline AI is suspended, like highlighting, so a large document is not sent on every keystroke. private static let languageServiceLengthLimit = EditorHighlighting.maxHighlightableCharacters weak var controller: TextViewController? @@ -33,7 +21,6 @@ final class SQLEditorCoordinator: ObservableObject, TextViewCoordinator, TextVie clock: diagnosticsClock ) private let statementRunController = StatementRunController() - /// Shared schema provider for inline AI suggestions (avoids duplicate schema fetches) var schemaProvider: SQLSchemaProvider? var databaseScope: DatabaseScope? private let inlineAccessGate: AIConnectionAccessGate = .live @@ -47,15 +34,14 @@ final class SQLEditorCoordinator: ObservableObject, TextViewCoordinator, TextVie private var aiSettingsCancellable: AnyCancellable? private var connectionAccessCancellable: AnyCancellable? private var lastInlineSourceKind: InlineSuggestionSourceKind = .off - /// Debounce work item for frame-change notification to avoid - /// triggering syntax highlight viewport recalculation on every keystroke. + // Debounced so a keystroke does not recompute the highlight viewport. private var frameChangeTask: Task? private var isUppercasing = false private var wasEditorFocused = false private var didDestroy = false private var focusClaimPending = false - /// One way. `destroy()` runs when the editor is dismantled, which it never comes back from. + // One way: destroy() runs when the editor is dismantled, which it never comes back from. var isDestroyed: Bool { didDestroy } private var hasInstalledEditorServices = false @@ -80,12 +66,7 @@ final class SQLEditorCoordinator: ObservableObject, TextViewCoordinator, TextVie focusClaimPending = true } - /// Latches a saved selection to apply once, the moment the editor is in a window. - /// - /// The caller sets this from `body`, which runs many times before the text view exists, so the - /// setter is idempotent and the value is consumed exactly once in `installEditorServices`. - /// Pushing it through the SwiftUI cursor binding instead would fight live typing, because the - /// binding is written on every selection change the user makes. + // Set from body many times before the text view exists, so it latches once; the cursor binding would fight live typing. func scheduleCursorRestore(_ range: NSRange) { guard !hasInstalledEditorServices else { return } cursorRestorePending = range @@ -93,16 +74,13 @@ final class SQLEditorCoordinator: ObservableObject, TextViewCoordinator, TextVie private var foldRestorePending: [Range]? - /// Collapsed folds are replayed once, the same way the cursor is, because the fold state the editor reports back - /// is written on every collapse the user makes. + // Replayed once, like the cursor, because the fold state reported back is written on every collapse. func scheduleFoldRestore(_ ranges: [Range]) { guard !hasInstalledEditorServices, !ranges.isEmpty else { return } foldRestorePending = ranges } - /// Query tabs share one editor, so a tab switch replays the incoming tab's collapsed regions over a document the - /// editor has just been handed. The outgoing tab's folds are already gone: replacing the document drops them, - /// which is what keeps this from having to clear anything and from reporting a collapse the reader never made. + // Replacing the document already dropped the outgoing tab's folds, so nothing is cleared or reported here. func repointFolds(to ranges: [Range]?) { guard let controller else { foldRestorePending = ranges @@ -126,7 +104,6 @@ final class SQLEditorCoordinator: ObservableObject, TextViewCoordinator, TextVie vimEngine.restoreDocumentMarks(marks) } - /// Vim mode for UI observation @Published private(set) var vimMode: VimMode = .normal private var vimEngine: VimEngine? // Vim is installed once the editor is in a window, so marks restored before that wait here. @@ -149,18 +126,14 @@ final class SQLEditorCoordinator: ObservableObject, TextViewCoordinator, TextVie var tabID: UUID? var connectionId: UUID? var sourceFileURL: URL? - /// The connection's execution grammar, which `SQLEditorController` sets from the live session. + // SQLEditorController sets this from the live session. private(set) var sessionGrammar: SQLLexicalGrammar? var lexicalGrammar: SQLLexicalGrammar { sessionGrammar ?? (databaseType ?? .mysql).lexicalGrammar } - /// Whether the editor text view is currently the first responder. - /// Used to guard cursor propagation — when the find panel highlights - /// a match it changes the selection programmatically, and propagating - /// that to SwiftUI triggers a re-render that disrupts the find panel's - /// @FocusState. + // Guards cursor propagation: a find-panel highlight that reached SwiftUI would re-render and break its focus. var isEditorFirstResponder: Bool { guard let textView = controller?.textView else { return false } return textView.window?.firstResponder === textView @@ -178,8 +151,6 @@ final class SQLEditorCoordinator: ObservableObject, TextViewCoordinator, TextVie frameChangeTask = nil } - // MARK: - TextViewCoordinator - func prepareCoordinator(controller: TextViewController) { self.controller = controller @@ -379,8 +350,6 @@ final class SQLEditorCoordinator: ObservableObject, TextViewCoordinator, TextVie cleanupMonitors() } - // MARK: - AI Context Menu - private func installFoldPreview(controller: TextViewController) { foldPreview.language = PluginManager.shared .editorLanguage(for: databaseType ?? .mysql) @@ -398,7 +367,6 @@ final class SQLEditorCoordinator: ObservableObject, TextViewCoordinator, TextVie statementRunController.install(on: controller) } - /// Moves the run controls and diagnostics to `grammar`, as a connect, a reconnect or a `SET` changes it. func setSessionGrammar(_ grammar: SQLLexicalGrammar) { guard grammar != sessionGrammar else { return } sessionGrammar = grammar @@ -413,31 +381,23 @@ final class SQLEditorCoordinator: ObservableObject, TextViewCoordinator, TextVie ) } - /// Turns the run controls off for the length of a query, because a tab runs one at a time. + // A tab runs one query at a time. func setStatementRunControlsEnabled(_ isEnabled: Bool) { statementRunController.setEnabled(isEnabled, in: controller) } - /// Follows the Settings toggle, so turning the band off also stops resolving the caret's statement for it. + // Turning the band off also stops resolving the caret's statement for it. func setStatementHighlightEnabled(_ isEnabled: Bool) { guard statementRunController.isHighlightEnabled != isEnabled else { return } statementRunController.isHighlightEnabled = isEnabled statementRunController.refreshHighlight(in: controller) } - /// Moves the caret to the neighbouring statement. func moveCursorToStatement(_ direction: StatementNavigationDirection) { statementRunController.moveCursor(direction, in: controller) } - /// Takes the reader to the statement a result came from. - /// - /// Resolved here rather than by the caller because the anchor has to be matched against the text this editor is - /// showing, which the tab's binding can lag behind by a keystroke. A statement that has since been edited away - /// resolves to nothing and the caret stays where it is, which is the right answer: there is nowhere to go. - /// - /// Reports whether it moved, so the caller can retire the request either way and a statement that is gone does - /// not leave one pending forever. + // Matched against the text this editor shows, which the tab's binding can lag; an edited-away statement resolves to nothing. @discardableResult func jumpToStatement(_ anchor: StatementAnchor) -> Bool { guard let controller, let textView = controller.textView else { return false } @@ -452,13 +412,7 @@ final class SQLEditorCoordinator: ObservableObject, TextViewCoordinator, TextVie return true } - /// Runs the statement the caret is in, then moves the caret to the next one. - /// - /// Both halves go through this one editor. Reading the SQL here and executing it somewhere else would let the two - /// name different editors: a window hosts a workspace per connection and their editors all stay registered, so a - /// command that resolves its text through the window and its execution through the selected workspace can send - /// one connection's statement to another connection's database. `onRunStatement` is the same callback the gutter - /// control uses, and the view binds it to the coordinator that owns this editor. + // Reading and running through this one editor keeps one connection's statement out of another connection's database. func runStatementAtCursorAndAdvance() { guard let statement = statementRunController.statementAtCursor(in: controller), let run = onRunStatement else { @@ -521,7 +475,7 @@ final class SQLEditorCoordinator: ObservableObject, TextViewCoordinator, TextVie controller?.unfoldAll() } - /// Whether the fold containing the cursor is collapsed. `nil` when the cursor is not inside a fold. + // nil when the cursor is not inside a fold. func foldStateAtCursor() -> Bool? { controller?.foldStateAtCursor() } @@ -585,8 +539,6 @@ final class SQLEditorCoordinator: ObservableObject, TextViewCoordinator, TextVie ) } - // MARK: - Inline Suggestion Manager - private func installInlineSuggestionManager(controller: TextViewController) { let manager = InlineSuggestionManager() manager.install(controller: controller, sourceResolver: { [weak self] in @@ -690,7 +642,7 @@ final class SQLEditorCoordinator: ObservableObject, TextViewCoordinator, TextVie databaseName: databaseName, databaseType: databaseType, grammar: lexicalGrammar, - budget: max(AppSettingsManager.shared.ai.maxSchemaTables, 0) + budget: AppSettingsManager.shared.ai.clampedMaxSchemaTables ) } @@ -708,8 +660,6 @@ final class SQLEditorCoordinator: ObservableObject, TextViewCoordinator, TextVie } } - // MARK: - Key Bindings - private func applyKeyBindings(controller: TextViewController) { let keyBindings = AppSettingsManager.shared.editor.keyBindings if keyBindings != .vim, vimKeyInterceptor != nil { @@ -733,8 +683,6 @@ final class SQLEditorCoordinator: ObservableObject, TextViewCoordinator, TextVie emacsKeyInterceptor = nil } - // MARK: - Vim Mode - private func installVimKeyInterceptor(controller: TextViewController) { guard let textView = controller.textView else { return } @@ -787,15 +735,7 @@ final class SQLEditorCoordinator: ObservableObject, TextViewCoordinator, TextVie vimMode = .normal } - /// Takes Vim out of the editor without touching `vimMode`, which is what teardown needs. - /// - /// `destroy()` runs from `dismantleNSViewController`, and when the editor goes because its - /// `NSHostingView` is deallocated, SwiftUI calls that while `GraphHost.invalidate()` holds exclusive - /// access to the host. A `@Published` write there reaches a view in the same host, whose subscriber - /// asks that host for a transaction, and Swift aborts with "Fatal access conflict detected". That - /// shipped as a crash on switching away from a query tab on macOS 26, where the write happened even - /// with Vim mode off because `@Published` notifies on every assignment. Nothing reads the mode of an - /// editor that is being destroyed. + // No @Published write during teardown: it ran inside GraphHost.invalidate() and aborted with an access conflict. private func removeVimKeyInterceptor() { vimKeyInterceptor?.uninstall() vimCursorManager?.uninstall() @@ -804,14 +744,7 @@ final class SQLEditorCoordinator: ObservableObject, TextViewCoordinator, TextVie vimEngine = nil } - // MARK: - Menu Escape Routing - - /// Called by `EditorEventRouter.handleEscapeFromMenu()` when the "Clear Selection" menu item is - /// chosen with the pointer, which is the only way that item fires: an unmodified Escape is - /// never dispatched as a key equivalent and reaches the editor's own key chain instead. - /// Dismisses an open completion popup, hands the keystroke to Vim when it is mid-command, and - /// restores first responder and the caret when this editor was the focused surface. Returns - /// whether the editor consumed the escape so the menu skips its cancelOperation fallback. + // The Clear Selection item fires only from a pointer click; returns whether the editor consumed the escape. @discardableResult func handleEscapeFromMenu() -> Bool { let wasFocused = wasEditorFocused @@ -829,15 +762,12 @@ final class SQLEditorCoordinator: ObservableObject, TextViewCoordinator, TextVie vimKeyInterceptor?.handleEscapeFromExternalSource() ?? false } - /// Restores editor focus after another view in the same window took it. private func reclaimFirstResponder() { guard let controller, let textView = controller.textView, let window = textView.window, window.firstResponder !== textView else { return } _ = window.makeFirstResponder(textView) } - // MARK: - First Responder Tracking - func checkFirstResponderChange() { let focused = isEditorFirstResponder guard focused != wasEditorFocused else { return } @@ -852,8 +782,6 @@ final class SQLEditorCoordinator: ObservableObject, TextViewCoordinator, TextVie } } - // MARK: - Editor Settings Observer - private func installEditorSettingsObserver(controller: TextViewController) { editorSettingsCancellable = AppEvents.shared.editorSettingsChanged .receive(on: RunLoop.main) @@ -884,13 +812,7 @@ final class SQLEditorCoordinator: ObservableObject, TextViewCoordinator, TextVie lastInlineSourceKind = kind } - // MARK: - Keyword Case - - /// Rewrites the keyword just completed by a word boundary to the configured case. - /// - /// Only the two absolute `SQLKeywordCase` values rewrite what the user typed. Under either - /// `matchTyped` value this does nothing, so an accepted lowercase completion is not flipped - /// back to uppercase by the next space. + // Only the two absolute SQLKeywordCase values rewrite typed text, so matchTyped never flips an accepted completion. private func uppercaseKeywordIfNeeded(textView: TextView, range: NSRange, string: String) { let keywordCase = AppSettingsManager.shared.editor.keywordCase guard !isUppercasing, @@ -934,8 +856,6 @@ final class SQLEditorCoordinator: ObservableObject, TextViewCoordinator, TextVie } } - // MARK: - Find Panel - func showFindPanel() { controller?.showFindPanel() } diff --git a/apple/TablePro/Views/Import/SQLCodePreview.swift b/apple/TablePro/Views/Import/SQLCodePreview.swift index cd7aff1d2c..54c883ee8b 100644 --- a/apple/TablePro/Views/Import/SQLCodePreview.swift +++ b/apple/TablePro/Views/Import/SQLCodePreview.swift @@ -1,17 +1,9 @@ -// -// SQLCodePreview.swift -// TablePro -// -// Read-only SQL code preview with tree-sitter syntax highlighting -// - import SwiftUI import TableProEditorKit import TableProGrammars -/// Read-only SQL code preview with syntax highlighting powered by TableProEditorKit struct SQLCodePreview: View { - @ObservedObject private var settingsManager = AppSettingsManager.shared + @ObservedObject private var editorSettings = AppSettingsManager.shared.editorSlice @Binding var text: String @State private var editorState = SourceEditorState() @@ -28,10 +20,11 @@ struct SQLCodePreview: View { .onReceive(AppEvents.shared.themeChanged) { _ in editorConfiguration = Self.makeConfiguration() } + .onChange(of: editorSettings.value) { _ in + editorConfiguration = Self.makeConfiguration() + } } - // MARK: - Configuration - private static func makeConfiguration() -> SourceEditorConfiguration { SourceEditorConfiguration( appearance: .init( diff --git a/apple/TablePro/Views/Integrations/IntegrationsActivityLogPane.swift b/apple/TablePro/Views/Integrations/IntegrationsActivityLogPane.swift index 427480ed39..99dc81fd8a 100644 --- a/apple/TablePro/Views/Integrations/IntegrationsActivityLogPane.swift +++ b/apple/TablePro/Views/Integrations/IntegrationsActivityLogPane.swift @@ -222,8 +222,7 @@ struct IntegrationsActivityLogPane: View { } if let store = mcpServerManager.tokenStore { - // TablePro mints these afresh every rotation and every agent turn, so they are filtered by name. - tokens = await store.list().filter { !$0.isBridgeCredential && !$0.isClaudeAgentCredential } + tokens = await store.list().filter(\.isUserManaged) } connections = ConnectionStorage.shared.loadConnections() diff --git a/apple/TablePro/Views/Main/Child/MainEditorContentView.swift b/apple/TablePro/Views/Main/Child/MainEditorContentView.swift index b923862b75..d6e71b3a62 100644 --- a/apple/TablePro/Views/Main/Child/MainEditorContentView.swift +++ b/apple/TablePro/Views/Main/Child/MainEditorContentView.swift @@ -1,11 +1,3 @@ -// -// MainEditorContentView.swift -// TablePro -// -// Main editor content view containing tab bar and tab content. -// Extracted from MainContentView for better separation. -// - import AppKit import SwiftUI import TableProEditorKit @@ -24,12 +16,10 @@ internal enum ContainerChangeRerunPolicy { struct MainEditorContentView: View { @ObservedObject private var featureAccess = FeatureAccess.shared - @ObservedObject private var settingsManager = AppSettingsManager.shared + @ObservedObject private var keyboard = AppSettingsManager.shared.keyboardSlice // Must clear the nested editor/results split's required minimums, or dragging the drawer asks AppKit for an unreachable height. static let tabContentMinimumHeight = CollapsibleSplitController.combinedMinimumThickness - // MARK: - Dependencies - @ObservedObject var tabManager: QueryTabManager @ObservedObject var coordinator: MainContentCoordinator @@ -42,8 +32,6 @@ struct MainEditorContentView: View { let windowId: UUID let connectionId: UUID - // MARK: - Callbacks - let onFirstPage: () -> Void let onPreviousPage: () -> Void let onNextPage: () -> Void @@ -67,8 +55,6 @@ struct MainEditorContentView: View { return !historyState.isVisible && !historyState.isCapturePaused } - // MARK: - Body - var body: some View { EditorAreaHost(input: EditorAreaInput( content: editorAreaContent, @@ -168,8 +154,6 @@ struct MainEditorContentView: View { } } - // MARK: - Tab Content - private var selectedQueryTab: QueryTab? { guard let tab = tabManager.selectedTab, tab.tabType == .query else { return nil } return tab @@ -221,8 +205,6 @@ struct MainEditorContentView: View { } } - // MARK: - Table Listing Tab Content - private func tableListingContent(tab: QueryTab) -> some View { let model = tableListingModels.model(forTab: tab.id) { TableListingViewModel( @@ -242,8 +224,6 @@ struct MainEditorContentView: View { .id(tab.id) } - // MARK: - Version History Tab Content - @ViewBuilder private func versionHistoryContent(tab: QueryTab) -> some View { if let subject = tab.display.versionHistorySubject { @@ -274,8 +254,6 @@ struct MainEditorContentView: View { } } - // MARK: - Object Source Tab Content - @ViewBuilder private func objectSourceContent(tab: QueryTab) -> some View { if let objectRef = tab.display.objectRef, objectRef.kind == .userType { @@ -299,8 +277,6 @@ struct MainEditorContentView: View { } } - // MARK: - Query Insights Tab Content - private func queryInsightsContent(tab: QueryTab) -> some View { Group { if let vm = queryInsightsViewModels[tab.id] { @@ -325,8 +301,6 @@ struct MainEditorContentView: View { .id(tab.id) } - // MARK: - Table Health Tab Content - private func tableHealthContent(tab: QueryTab) -> some View { Group { if let model = coordinator.tableHealthModels[tab.id] { @@ -345,8 +319,6 @@ struct MainEditorContentView: View { .id(tab.id) } - // MARK: - Users & Roles Tab Content - @ViewBuilder private func usersRolesContent(tab: QueryTab) -> some View { Group { @@ -368,8 +340,6 @@ struct MainEditorContentView: View { .id(tab.id) } - // MARK: - Server Dashboard Tab Content - @ViewBuilder private func serverDashboardContent(tab: QueryTab) -> some View { Group { @@ -395,8 +365,6 @@ struct MainEditorContentView: View { .id(tab.id) } - // MARK: - ER Diagram Tab Content - @ViewBuilder private func erDiagramContent(tab: QueryTab) -> some View { Group { @@ -430,8 +398,6 @@ struct MainEditorContentView: View { } } - // MARK: - Per-tab container picker - private var containerSwitchTarget: ContainerSwitchTarget? { PluginManager.shared.containerSwitchTarget(for: connection.type) } @@ -536,8 +502,6 @@ struct MainEditorContentView: View { ) } - // MARK: - Table Tab Content - @ViewBuilder private func tableTabContent(tab: QueryTab) -> some View { VStack(spacing: 0) { @@ -548,8 +512,6 @@ struct MainEditorContentView: View { } } - // MARK: - Results Section - @ViewBuilder private func executionErrorBanner(tab: QueryTab) -> some View { if let error = tab.shownError { @@ -923,8 +885,6 @@ struct MainEditorContentView: View { ) } - // MARK: - Status Bar - private func statusBar(tab: QueryTab, selectedRowCount: Int) -> some View { let resolvedRows = resolvedTableRows(for: tab) let isExecuting = coordinator.tabExecution.isBusy(tab.id) @@ -1059,8 +1019,6 @@ struct MainEditorContentView: View { ) } - // MARK: - Empty State - private var emptyStateView: some View { VStack(spacing: 20) { Image(systemName: "tablecells") @@ -1136,7 +1094,7 @@ extension MainEditorContentView { supportsFormatting: QueryFormatterFactory.supportsFormatting(coordinator.connection.type), aiActions: coordinator.aiQueryActionAvailability(for: tab), shortcutHint: { label, action in - settingsManager.keyboard.shortcutHint(label, for: action) + keyboard.value.shortcutHint(label, for: action) } ) } @@ -1174,8 +1132,6 @@ fileprivate extension MainEditorContentView { } } -// MARK: - Query Tab Content - extension MainEditorContentView { private func queryTabInput(tab: QueryTab) -> QueryTabInput { let claimFocus = coordinator.tabManager.pendingFocusTabId == tab.id diff --git a/apple/TablePro/Views/ObjectSource/UserType/UserTypeMembersPane.swift b/apple/TablePro/Views/ObjectSource/UserType/UserTypeMembersPane.swift index d10f859689..a948160cf6 100644 --- a/apple/TablePro/Views/ObjectSource/UserType/UserTypeMembersPane.swift +++ b/apple/TablePro/Views/ObjectSource/UserType/UserTypeMembersPane.swift @@ -6,8 +6,7 @@ import SwiftUI import TableProPluginKit -/// An enum's labels, a composite's fields or a domain's checks, as they will be after the queue -/// runs. Each row says what the queue does to it. +// Members as they will be after the queue runs; each row says what the queue does to it. struct UserTypeMembersPane: View { @ObservedObject var model: UserTypeEditorModel let draft: UserTypeDraft @@ -41,32 +40,31 @@ struct UserTypeMembersPane: View { .width(min: 120, ideal: 180) } .accessibilityIdentifier("user-type-labels") - Divider() - HStack(spacing: 8) { - Button { - present(.addLabel) - } label: { - Label(String(localized: "Add Label"), systemImage: "plus") - .labelStyle(.iconOnly) - } - .help(String(localized: "Add Label")) + ListBar { + ListBarButton( + label: String(localized: "Add Label"), + systemImage: "plus", + identifier: "user-type-add-label", + action: { present(.addLabel) } + ) .disabled(isDisabled || !model.support.addLabel) - .accessibilityIdentifier("user-type-add-label") - Button(String(localized: "Rename…")) { - if let label = selectedLabel { present(.renameLabel(label.name)) } + HStack(spacing: 8) { + Button(String(localized: "Rename…")) { + if let label = selectedLabel { present(.renameLabel(label.name)) } + } + .disabled(isDisabled || selectedLabel == nil || !model.support.renameLabel) + .help(model.support.renameLabel + ? String(localized: "Rename the selected label") + : String(localized: "This server cannot rename a label.")) + Text("A label cannot be removed or moved once it exists.") + .font(.caption) + .foregroundStyle(.secondary) + .lineLimit(2) + .padding(.vertical, 4) } - .disabled(isDisabled || selectedLabel == nil || !model.support.renameLabel) - .help(model.support.renameLabel - ? String(localized: "Rename the selected label") - : String(localized: "This server cannot rename a label.")) - Text("A label cannot be removed or moved once it exists.") - .font(.caption) - .foregroundStyle(.secondary) - .lineLimit(2) - Spacer() + .controlSize(.small) + .padding(.horizontal, 8) } - .controlSize(.small) - .padding(8) } } @@ -91,8 +89,7 @@ struct UserTypeMembersPane: View { .width(min: 120, ideal: 180) } .accessibilityIdentifier("user-type-fields") - Divider() - HStack(spacing: 8) { + ListBar { AddRemoveControlGroup( addLabel: String(localized: "Add Field"), removeLabel: String(localized: "Drop Field"), @@ -107,10 +104,9 @@ struct UserTypeMembersPane: View { if let field = selectedField { present(.editField(name: field.name, type: field.type)) } } .disabled(isDisabled || !canEditSelectedField) - Spacer() + .controlSize(.small) + .padding(.horizontal, 8) } - .controlSize(.small) - .padding(8) } } @@ -128,7 +124,7 @@ struct UserTypeMembersPane: View { selectedField != nil && (model.support.renameField || model.support.changeFieldType) } - /// A field this queue added is taken back by removing its addition, not by queuing a drop. + // A field this queue added is taken back by removing its addition, not by queuing a drop. private func removeSelectedField() { guard let field = selectedField else { return } if case .added(let changeId) = field.origin { @@ -168,8 +164,7 @@ struct UserTypeMembersPane: View { .width(min: 120, ideal: 180) } .accessibilityIdentifier("user-type-constraints") - Divider() - HStack(spacing: 8) { + ListBar { AddRemoveControlGroup( addLabel: String(localized: "Add Check"), removeLabel: String(localized: "Drop Constraint"), @@ -185,10 +180,9 @@ struct UserTypeMembersPane: View { } .disabled(isDisabled || !canValidateSelectedConstraint) .help(String(localized: "Check the values already stored against the selected constraint")) - Spacer() + .controlSize(.small) + .padding(.horizontal, 8) } - .controlSize(.small) - .padding(8) } } diff --git a/apple/TablePro/Views/Results/ColumnVisibilityPopover.swift b/apple/TablePro/Views/Results/ColumnVisibilityPopover.swift index 3755e81ea8..0b7a1eaac0 100644 --- a/apple/TablePro/Views/Results/ColumnVisibilityPopover.swift +++ b/apple/TablePro/Views/Results/ColumnVisibilityPopover.swift @@ -1,12 +1,7 @@ -// -// ColumnVisibilityPopover.swift -// TablePro -// - import SwiftUI struct ColumnVisibilityPopover: View { - @ObservedObject private var settingsManager = AppSettingsManager.shared + @ObservedObject private var keyboard = AppSettingsManager.shared.keyboardSlice let columns: [GridColumnEntry] let hiddenColumns: Set let onToggleColumn: (String) -> Void @@ -42,7 +37,7 @@ struct ColumnVisibilityPopover: View { Button("Jump to Column…") { onJumpToColumn(searchText) } .buttonStyle(.link) .controlSize(.small) - .help(settingsManager.keyboard.shortcutHint( + .help(keyboard.value.shortcutHint( String(localized: "Scroll to a column and put the cell cursor in it"), for: .jumpToColumn )) diff --git a/apple/TablePro/Views/Results/ExecutionIndicatorView.swift b/apple/TablePro/Views/Results/ExecutionIndicatorView.swift index 9c7c120b3b..decdbda73a 100644 --- a/apple/TablePro/Views/Results/ExecutionIndicatorView.swift +++ b/apple/TablePro/Views/Results/ExecutionIndicatorView.swift @@ -1,40 +1,19 @@ -// -// ExecutionIndicatorView.swift -// TablePro -// - import SwiftUI import TableProPluginKit import TableProUtilities -/// What the query is doing, in the bar under the result it produces. -/// -/// It used to sit in the centred toolbar item, where it reported the window rather than the tab and -/// where AppKit dropped it whole as soon as the window narrowed. Every comparable client puts this -/// in a bottom bar, and so does the rest of what this bar already reports. struct ExecutionIndicatorView: View { - @ObservedObject private var settingsManager = AppSettingsManager.shared - /// Held back rather than the spinner inside it, so a query too fast to report leaves the - /// previous duration standing instead of emptying the readout and changing its width twice. - /// Clicking a table on a local database runs in single-digit milliseconds, and "Executing…" - /// appearing and going in that time is churn the user reads as a flicker. - /// - /// The Stop button goes with it. Nothing needs cancelling inside the grace, and past it the - /// button is there, which is what the HIG asks: "When it's feasible, let people halt - /// processing." + @ObservedObject private var keyboard = AppSettingsManager.shared.keyboardSlice + // Held back as a whole, Stop included, so a query too fast to report leaves the previous duration standing. let report: ExecutionSlot.Report let isExecuting: Bool - /// Defaulted so a preview and a caller with nothing to protect read the same as before. A batch - /// whose commit is on the wire passes false: the spinner stays and the button dims, rather than - /// offering a cancel that cannot reach the server. + // False while a batch's commit is on the wire: a cancel then cannot reach the server. var canStop = true var onCancel: (() -> Void)? @State private var showsBreakdown = false - /// Why the two numbers differ, in the popover's own words. A client-measured first row carries - /// one network round trip and a server-reported figure does not, and a reader comparing them - /// has no other way to know that. + // A client-measured first row includes one network round trip; a server figure does not. private static let clientExplanation = String(localized: """ Time to the first row is measured here, so it includes one network round trip. """) @@ -43,10 +22,9 @@ struct ExecutionIndicatorView: View { The server figure is the engine's own report, so it excludes network time. """) - /// Resolved from the user's own binding rather than written into the string. A hint naming a - /// key nobody bound is the same defect as a toolbar tooltip that outlived a rebind (#2185). + // From the user's own binding, so the hint never names a key nobody bound (#2185). private var cancelHint: String { - settingsManager.keyboard.shortcutHint(String(localized: "Cancel Query"), for: .cancelQuery) + keyboard.value.shortcutHint(String(localized: "Cancel Query"), for: .cancelQuery) } var body: some View { @@ -81,11 +59,7 @@ struct ExecutionIndicatorView: View { } } - // MARK: - Readout - - /// The elapsed number stays the label, because that is what a reader already knows how to read. - /// The split lives one click away rather than widening the bar with a second figure whose - /// meaning nothing on screen explains. + // The split lives one click away rather than widening the bar with a second unexplained figure. @ViewBuilder private func durationReadout(_ timing: PluginQueryTiming) -> some View { let text = QueryDurationFormatter.string(from: timing.total) @@ -123,8 +97,6 @@ struct ExecutionIndicatorView: View { } } -// MARK: - Preview - #Preview("Executing") { ExecutionIndicatorView(report: .running, isExecuting: true) .padding() diff --git a/apple/TablePro/Views/Results/JSONCodeEditor.swift b/apple/TablePro/Views/Results/JSONCodeEditor.swift index 1b310abff9..e9850d3007 100644 --- a/apple/TablePro/Views/Results/JSONCodeEditor.swift +++ b/apple/TablePro/Views/Results/JSONCodeEditor.swift @@ -1,18 +1,10 @@ -// -// JSONCodeEditor.swift -// TablePro -// -// JSON text view backed by TableProEditorKit (tree-sitter), sharing the -// app's editor theme and font with the SQL editor. -// - import AppKit import SwiftUI import TableProEditorKit import TableProGrammars internal struct JSONCodeEditor: View { - @ObservedObject private var settingsManager = AppSettingsManager.shared + @ObservedObject private var editorSettings = AppSettingsManager.shared.editorSlice @ObservedObject private var themeEngine = ThemeEngine.shared @Binding var text: String let isEditable: Bool @@ -21,9 +13,7 @@ internal struct JSONCodeEditor: View { @State private var editorState = SourceEditorState() @State private var configuration: SourceEditorConfiguration - /// Held in `@State` so the editor is handed the same coordinator on every update. It names the - /// text view itself, which is where an accessibility identifier has to land: the SwiftUI - /// modifier names the representable and never reaches it. + // One coordinator across updates; it names the text view, which the SwiftUI accessibility modifier never reaches. @State private var coordinators: [any TextViewCoordinator] init( @@ -58,7 +48,7 @@ internal struct JSONCodeEditor: View { .onChange(of: isEditable) { _ in rebuildConfiguration() } - .onChange(of: settingsManager.editor) { _ in + .onChange(of: editorSettings.value) { _ in rebuildConfiguration() } .onReceive(AppEvents.shared.accessibilityTextSizeChanged) { _ in diff --git a/apple/TablePro/Views/Results/ResultStatusBar.swift b/apple/TablePro/Views/Results/ResultStatusBar.swift index dbea74b74b..82fb81aa72 100644 --- a/apple/TablePro/Views/Results/ResultStatusBar.swift +++ b/apple/TablePro/Views/Results/ResultStatusBar.swift @@ -1,38 +1,9 @@ -// -// ResultStatusBar.swift -// TablePro -// - import AppKit import SwiftUI -/// The window's bottom bar: what the result is, and the controls that change what of it you see. -/// -/// Two zones, never three. Centring a variable-width sentence between two variable-width clusters -/// only holds while the clusters happen to match, which is why the row count sat visibly left of -/// centre. Anchoring the readout to the leading edge and the controls to the trailing edge also -/// keeps the controls still when a mode change removes one of them. -/// -/// The view switcher leads the bar. It was briefly a strip of its own above the result, which cost -/// a band of height in every mode and left the structure editor with two segmented rows stacked, -/// the child louder than the parent. -/// -/// Adding a row still belongs to the toolbar: it changes the document. The structure editor's -/// add and remove pair is this bar's trailing cluster while the structure editor is the content, -/// because a second bar underneath it would be the stacking problem again, one bar lower. -/// -/// The bar gives up chrome rather than overflowing its pane. Its clusters used to be pinned at full -/// width, which made the bar's own minimum wider than the pane and clipped the data grid along with -/// it; see `StatusBarTier`. `ViewThatFits` picks the widest tier whose ideal width fits, and the -/// narrowest tier holds its shape down to 280pt, measured, against a pane whose own floor is 400pt. -/// Two rules keep that true. No candidate row carries `.fixedSize()`: the clusters carry their own, -/// and the readout's constant `idealWidth` is what makes a candidate's ideal width equal its floor, -/// so the mounted row still grows to fill the pane and anchor the controls to the trailing edge. And -/// no tier drops a control that opens a popover: one anchored to a button that has left the view -/// tree cannot present, so giving up the Highlight Rules button would have made -/// `View > Highlight Rules…` do nothing. See `StatusBarTier` for what a tier may give up. +// Two zones: `ViewThatFits` picks the widest `StatusBarTier` that fits, and no tier drops a control that anchors a popover. struct ResultStatusBar: View { - @ObservedObject private var settingsManager = AppSettingsManager.shared + @ObservedObject private var keyboard = AppSettingsManager.shared.keyboardSlice let model: ResultStatusModel let snapshot: StatusBarSnapshot let filterState: TabFilterState @@ -40,10 +11,8 @@ struct ResultStatusBar: View { let highlightState: StatusBarHighlightState let paginationCallbacks: PaginationCallbacks let execution: ExecutionReadout - /// Held, not observed: only the readout inside the report slot re-renders when it changes. + // Held, not observed: only the readout inside the report slot re-renders when it changes. let selectionSummary: SelectionSummaryState - /// The object tree's own reload, reported where every other piece of background activity in - /// this window is. It had no surface at all between the centred toolbar item going and this. let isRefreshingSchema: Bool @Binding var viewMode: ResultsViewMode // Empty unless the tab holds exactly one result: two or more are chosen from the tab row above the result. @@ -55,10 +24,7 @@ struct ResultStatusBar: View { @State private var showColumnPopover = false @State private var showHighlightPopover = false - /// The tab the rules popover was opened for. Switching tab closes the popover, and by the time - /// the close is seen this view already belongs to the tab that was switched to, so pruning - /// "the selected tab" pruned the wrong one and left an unfinished rule saved on the tab the - /// user actually opened it from. + // By the time the close is seen this view belongs to the new tab, so pruning "the selected tab" pruned the wrong one. @State private var highlightPopoverTabId: UUID? @State private var revealedExecutionTabId: UUID? @State private var showSelectionSummaryPopover = false @@ -97,8 +63,7 @@ struct ResultStatusBar: View { } } - /// One row of the bar, drawn the way its tier says. `ViewThatFits` measures each of these and - /// mounts the first that fits, so this is both the measurement and the result. + // `ViewThatFits` measures each row and mounts the first that fits. @ViewBuilder private func row(_ tier: StatusBarTier) -> some View { let presentation = ResultStatusPresentation(tier: tier) @@ -122,9 +87,7 @@ struct ResultStatusBar: View { } } - /// Segmented while the modes fit, and a pull-down naming the current one once they do not. The - /// pull-down is capped, because it takes the width of its widest item and a long locale would - /// otherwise decide the narrow tier's floor. + // Capped: the pull-down takes its widest item's width, and a long locale would set the narrow tier's floor. @ViewBuilder private func modeSwitcher(_ presentation: ResultStatusPresentation) -> some View { let picker = Picker(String(localized: "View Mode"), selection: $viewMode) { @@ -147,11 +110,7 @@ struct ResultStatusBar: View { } } - // MARK: - Readout - - /// The zone that absorbs the bar's slack, which is why `row` gives it the flexible frame and the - /// clusters on either side keep their intrinsic widths. Its three parts are the slots - /// `ReadoutZoneLayout` sizes: the sentence, the actions beside it, and the report after them. + // Takes the bar's slack; the clusters on either side keep their intrinsic widths. private var readoutCluster: some View { ReadoutZoneLayout(spacing: StatusBarChrome.clusterSpacing, sentenceIdealWidth: StatusBarLayoutMetrics.readoutIdealWidth) { HStack(spacing: Self.readoutSpacing) { @@ -204,9 +163,7 @@ struct ResultStatusBar: View { } } - /// Drawn at the bar's small control size, as every other control on the bar is, and never - /// truncated: the sentence beside them gives way first, and `ReadoutZoneLayout` counts their - /// width into the tier choice so the bar drops a tier before either has to. + // Never truncated: `ReadoutZoneLayout` counts their width, so the bar drops a tier first. @ViewBuilder private var readoutActions: some View { if model.controls.showsExactCountAction { @@ -234,10 +191,7 @@ struct ResultStatusBar: View { @ViewBuilder private var readoutMessage: some View { if let statusMessage = model.statusMessage { - /// Yields its width before the execution report beside it does, so a wordy driver - /// message truncates instead of squeezing anything else out. Which tier the bar draws - /// is not its business: `ReadoutZoneLayout` leaves it out of the ideal width, so no - /// message length can change that choice. + // Truncates first, and `ReadoutZoneLayout` leaves it out of the ideal width, so no message changes the tier. Text(statusMessage) .font(.caption) .foregroundStyle(.secondary) @@ -273,16 +227,13 @@ struct ResultStatusBar: View { model.selectionSummaryCoversLoadedRowsOnly ? String(localized: "Covers the loaded rows only.") : nil } - /// No `idealWidth` here: `ReadoutZoneLayout` reports the zone's ideal itself, and a frame that - /// named one would replace it. + // No `idealWidth`: `ReadoutZoneLayout` reports the zone's ideal, and a frame naming one would replace it. private func readoutZone(_ content: some View) -> some View { content.frame(minWidth: 0, maxWidth: .infinity, alignment: .leading) } private static let readoutSpacing: CGFloat = 6 - // MARK: - Controls - @ViewBuilder private func controlCluster(_ presentation: ResultStatusPresentation) -> some View { HStack(spacing: StatusBarChrome.clusterSpacing) { @@ -305,10 +256,7 @@ struct ResultStatusBar: View { .fixedSize() } - /// The tab identity is passed in rather than applied as `.id()`. Keying the view by tab did stop - /// a page number typed for one tab being submitted against the next, but it also tore the whole - /// cluster down and rebuilt it on every switch, which is a second source of the churn this bar - /// exists to avoid. The view resets the same `@State` on the same signal instead. + // The tab id is passed, not applied as `.id()`, which rebuilt the cluster on every switch. private func paginationControls(_ presentation: ResultStatusPresentation) -> some View { PaginationControlsView( pagination: snapshot.pagination, @@ -341,8 +289,7 @@ struct ResultStatusBar: View { } .statusBarLabelStyle(showsTitle: presentation.showsControlTitles) .controlSize(.small) - /// Present but inert until the result names its columns, so a reload dims the button rather - /// than removing it and shifting everything beside it. + // Dimmed, not removed, while columns load, so nothing beside it shifts. .disabled(columnState.columns.isEmpty) .help(String(localized: "Choose which columns the grid shows")) .accessibilityLabel(String(localized: "Columns")) @@ -377,9 +324,7 @@ struct ResultStatusBar: View { .statusBarControlIcon(besideTitle: false) } } - /// A glyph at every tier. Its title would add 88pt, and measured at the window's default - /// 1200pt with the sidebar open the regular tier then no longer fits, so drawing it would - /// take the titles off Columns and Filters at the size most windows are. + // A glyph at every tier: its title would cost the regular tier at the default 1200pt window. .labelStyle(.iconOnly) .controlSize(.small) .disabled(highlightState.columns.isEmpty) @@ -466,7 +411,7 @@ struct ResultStatusBar: View { .statusBarLabelStyle(showsTitle: presentation.showsControlTitles) .toggleStyle(.button) .controlSize(.small) - .help(settingsManager.keyboard.shortcutHint(String(localized: "Filters"), for: .toggleFilters)) + .help(keyboard.value.shortcutHint(String(localized: "Filters"), for: .toggleFilters)) .accessibilityLabel(String(localized: "Filters")) .accessibilityValue(filtersAccessibilityValue) .accessibilityAddTraits(filterState.isVisible ? .isSelected : []) @@ -477,8 +422,7 @@ struct ResultStatusBar: View { !columnState.hidden.isEmpty } - /// The count is a value, not part of the name. Folding it into the label made VoiceOver read a - /// different control name depending on how many columns happened to be hidden. + // A value, not part of the name, so VoiceOver reads one control name however many columns are hidden. private var columnsAccessibilityValue: String { guard hasHiddenColumns else { return String(localized: "All columns visible") } let total = columnState.visibilityColumns.count @@ -491,18 +435,7 @@ struct ResultStatusBar: View { } } -/// The readout zone: the sentence, the actions beside it, and the report after them, left to right. -/// -/// It exists for the ideal width it reports, which is the width `ViewThatFits` picks a tier by. The -/// sentence and the report count as one constant, `StatusBarLayoutMetrics.readoutIdealWidth`, so -/// neither a long count, a wordy driver message nor a selection summary drops the bar a tier by -/// itself. The actions add their own width on top. Counted inside the constant, they left a table -/// with an estimate on the regular tier with no room for both, and the bar drew "1-22 of ~22 r…" -/// beside "Count Ex…". -/// -/// Placed, the actions keep their width and the report keeps what it cannot give up. The sentence -/// takes the rest up to its own width, and whatever is left after that goes to the report, whose -/// driver message truncates into it. +// Reports the ideal width `ViewThatFits` picks a tier by: the sentence and report count as one constant, the actions on top. private struct ReadoutZoneLayout: Layout { let spacing: CGFloat let sentenceIdealWidth: CGFloat @@ -550,7 +483,6 @@ private struct ReadoutZoneLayout: Layout { ] } - /// The width of slots laid side by side, with one gap between each pair that draws anything. private func span(of widths: [CGFloat]) -> CGFloat { let drawn = widths.filter { $0 > 0 } return drawn.reduce(0, +) + spacing * CGFloat(max(0, drawn.count - 1)) @@ -558,9 +490,7 @@ private struct ReadoutZoneLayout: Layout { } private extension View { - /// `titleAndIcon` and `iconOnly` are different types, so a tier choosing between them cannot do - /// it with a ternary. Branching here keeps each control's modifier chain written once, and keeps - /// the system's own label metrics rather than a hand-rolled stack's. + // `titleAndIcon` and `iconOnly` are different types, so a ternary cannot choose between them. @ViewBuilder func statusBarLabelStyle(showsTitle: Bool) -> some View { if showsTitle { diff --git a/apple/TablePro/Views/Results/ValueSourceEditor.swift b/apple/TablePro/Views/Results/ValueSourceEditor.swift index 21cfa3124d..0e3fdf92c0 100644 --- a/apple/TablePro/Views/Results/ValueSourceEditor.swift +++ b/apple/TablePro/Views/Results/ValueSourceEditor.swift @@ -1,14 +1,9 @@ -// -// ValueSourceEditor.swift -// TablePro -// - import AppKit import SwiftUI internal struct ValueSourceEditor: View { @ObservedObject private var themeEngine = ThemeEngine.shared - @ObservedObject private var settingsManager = AppSettingsManager.shared + @ObservedObject private var dataGridSettings = AppSettingsManager.shared.dataGridSlice @Binding var text: String var isEditable: Bool var textContainerInset = NSSize(width: 4, height: 6) @@ -20,7 +15,7 @@ internal struct ValueSourceEditor: View { font: themeEngine.valueFont, textContainerInset: textContainerInset, style: .code, - marksInvisibleCharacters: settingsManager.dataGrid.showInvisibleCharacters + marksInvisibleCharacters: dataGridSettings.value.showInvisibleCharacters ) } } diff --git a/apple/TablePro/Views/RowInspector/FieldEditors/MultiLineEditorView.swift b/apple/TablePro/Views/RowInspector/FieldEditors/MultiLineEditorView.swift index 9e392e782b..b762c48990 100644 --- a/apple/TablePro/Views/RowInspector/FieldEditors/MultiLineEditorView.swift +++ b/apple/TablePro/Views/RowInspector/FieldEditors/MultiLineEditorView.swift @@ -1,13 +1,8 @@ -// -// MultiLineEditorView.swift -// TablePro -// - import SwiftUI internal struct MultiLineEditorView: View { @ObservedObject private var themeEngine = ThemeEngine.shared - @ObservedObject private var settingsManager = AppSettingsManager.shared + @ObservedObject private var dataGridSettings = AppSettingsManager.shared.dataGridSlice let context: FieldEditorContext var onPopOut: ((String) -> Void)? var isExpanded = false @@ -29,7 +24,7 @@ internal struct MultiLineEditorView: View { font: themeEngine.valueFont, movesFocusOnTab: true, style: .code, - marksInvisibleCharacters: settingsManager.dataGrid.showInvisibleCharacters, + marksInvisibleCharacters: dataGridSettings.value.showInvisibleCharacters, documentID: context.documentID.map { AnyHashable($0) } ) .valueWell(clipsContent: true) diff --git a/apple/TablePro/Views/RowInspector/TableInfoView.swift b/apple/TablePro/Views/RowInspector/TableInfoView.swift index 1927087b00..9c88cbd7c0 100644 --- a/apple/TablePro/Views/RowInspector/TableInfoView.swift +++ b/apple/TablePro/Views/RowInspector/TableInfoView.swift @@ -1,8 +1,3 @@ -// -// TableInfoView.swift -// TablePro -// - import SwiftUI // The table's own statistics, when the inspector has a table but no row selected. Not a grouped `Form`: its 30pt @@ -22,7 +17,7 @@ internal struct TableInfoView: View { // The statistics alone, for a pane that scrolls them with its own content. internal struct TableInfoSections: View { - @ObservedObject private var settingsManager = AppSettingsManager.shared + @ObservedObject private var generalSettings = AppSettingsManager.shared.generalSlice internal let metadata: TableMetadata internal var includesComment = true @@ -33,7 +28,7 @@ internal struct TableInfoSections: View { var body: some View { VStack(alignment: .leading, spacing: 14) { - if includesComment, settingsManager.general.showObjectComments, + if includesComment, generalSettings.value.showObjectComments, let comment = metadata.comment, !comment.isEmpty { section(String(localized: "Comment")) { Text(comment) diff --git a/apple/TablePro/Views/RowInspector/TrailingPaneHeaderView.swift b/apple/TablePro/Views/RowInspector/TrailingPaneHeaderView.swift index 9fe7349c6e..f823cd68a8 100644 --- a/apple/TablePro/Views/RowInspector/TrailingPaneHeaderView.swift +++ b/apple/TablePro/Views/RowInspector/TrailingPaneHeaderView.swift @@ -1,26 +1,11 @@ -// -// TrailingPaneHeaderView.swift -// TablePro -// - import SwiftUI -/// One height for the header on every surface, so switching surface moves nothing beneath it. -/// -/// Fixed rather than grown from padding, because the leading slot is a picker on one surface and a -/// title on another and the two are not the same height: measured on macOS 27, the small segmented -/// control is 20pt and a headline 18pt, beside a menu whose hit target is 22pt. Grown from its -/// content, the header changed height with the surface, which is the jump this view exists to remove. +// Fixed, not grown from content: the picker, a headline and the menu differ in height, and the header jumped with the surface. internal enum TrailingPaneHeaderMetrics { internal static let height: CGFloat = 30 } -/// The trailing pane's header, drawn by each surface at its own top. -/// -/// A picker between the surfaces the user may choose, or the surface's name where there is nothing to -/// choose, and one menu of that surface's commands. `TrailingPaneHeaderModel` decides all of it, so -/// the three surfaces cannot draw it three ways again; this view only draws what the model says, and -/// each surface supplies the commands in the menu sections the model names. +// `TrailingPaneHeaderModel` decides the picker, title and menu, so the three surfaces cannot draw it three ways. internal struct TrailingPaneHeaderView: View { private let surface: TrailingPaneSurface private let contentMode: ConnectionWorkspaceContentMode @@ -29,14 +14,10 @@ internal struct TrailingPaneHeaderView: View { private let hasContent: Bool private let menuSection: (TrailingPaneMenuSection) -> MenuSectionContent - /// Read live rather than captured when the pane was built. Turning the assistant off changes - /// nothing the pane's render key holds while browsing, so a captured value would go on offering - /// the assistant's segment over a pane that can no longer draw it. - @ObservedObject private var settings = AppSettingsManager.shared + // Live: turning the assistant off changes nothing the pane's render key holds while browsing. + @ObservedObject private var aiSettings = AppSettingsManager.shared.aiSlice - /// `paneState` is nil for the result column, whose surface the mode chose, and for a connection - /// whose session went and took its pane state with it. Either way there is no stored surface to - /// write, so the header names its surface instead of offering a picker that could not answer. + // `paneState` is nil for the result column and for a session that went; there is no stored surface to write. internal init( surface: TrailingPaneSurface, contentMode: ConnectionWorkspaceContentMode, @@ -57,7 +38,7 @@ internal struct TrailingPaneHeaderView: View { TrailingPaneHeaderModel( surface: surface, contentMode: contentMode, - isAIEnabled: settings.ai.enabled, + isAIEnabled: aiSettings.value.enabled, inspectorRendering: inspectorRendering, hasContent: hasContent ) @@ -91,18 +72,7 @@ internal struct TrailingPaneHeaderView: View { } } - /// The ellipsis draws no text, so the only name VoiceOver has for this control is the one the - /// accessibility modifiers give it, and it takes all three of them. - /// - /// Measured on macOS 27, naming it through the label does not work in any arrangement. A `Label` - /// whose title `.labelStyle(.iconOnly)` has resolved away carries no name, whichever view the - /// style sits on, and `.accessibilityLabel` inside the label closure, which is how - /// `ResultSetMenu` names a pull-down that also draws text, does not reach this one either. - /// `.accessibilityLabel` on the `Menu` alone is likewise ignored. In all three the control falls - /// back to AppKit's own name for an unnamed pull-down, which reads "More" locally and the empty - /// string on the CI runner. Only `.accessibilityElement` publishes the name, and it has to be - /// `.contain`: `.ignore` names the button and then takes the menu's own items out of the tree - /// with it, so nothing can reach Fields, JSON or any other command in it. + // Only `.accessibilityElement(children: .contain)` publishes the name here; label-based naming is ignored on macOS 27. private func menu(_ model: TrailingPaneHeaderModel) -> some View { Menu { ForEach(Array(model.menuSections.enumerated()), id: \.element) { index, section in @@ -132,8 +102,7 @@ internal struct TrailingPaneHeaderView: View { } } -/// The surface picker, observing the connection's pane state itself so that the segment it draws is -/// the surface the controller parents next rather than the one the pane was built with. +// Observes the pane state itself, so the segment is the surface the controller parents next. private struct TrailingPaneSurfacePicker: View { @ObservedObject var state: TrailingPaneState let segments: [TrailingPaneSurface] @@ -152,10 +121,7 @@ private struct TrailingPaneSurfacePicker: View { .accessibilityIdentifier("trailing-pane-surface") } - /// The segment's name travels in the symbol image's own description. Measured on macOS 27, a - /// segmented picker names each segment from the image it was handed and never reads - /// `.accessibilityLabel` on the view, so `Image(systemName:)` published "info" and "sparkle" to - /// VoiceOver whatever label it carried. The image is the same template at the same size. + // A segmented picker names each segment from its image and never reads `.accessibilityLabel`. private static func symbol(for segment: TrailingPaneSurface) -> Image { guard let image = NSImage( systemSymbolName: segment.symbolName, @@ -166,11 +132,7 @@ private struct TrailingPaneSurfacePicker: View { return Image(nsImage: image) } - /// Writes the stored surface and nothing else. A segment is a choice the user made, so it is - /// remembered for the connection, which a suggestion such as a grid click never is. The controller - /// watches the state of the connection on screen and parents the new surface on the next turn of - /// the run loop, so the view whose segment was clicked leaves the window after its action has - /// returned rather than from inside it. + // Writes the stored surface only; the controller parents it a turn later, after this action returns. private var selection: Binding { Binding( get: { state.surface }, diff --git a/apple/TablePro/Views/Settings/AI/AIModelListLoader.swift b/apple/TablePro/Views/Settings/AI/AIModelListLoader.swift new file mode 100644 index 0000000000..92d6708300 --- /dev/null +++ b/apple/TablePro/Views/Settings/AI/AIModelListLoader.swift @@ -0,0 +1,71 @@ +import Combine +import Foundation + +@MainActor +final class AIModelListLoader: ObservableObject { + private struct Connection: Equatable { + let providerID: UUID + let endpoint: String + let apiKey: String + } + + @Published private(set) var models: [AIModelInfo] = [] + @Published private(set) var isLoading = false + @Published private(set) var error: String? + @Published private(set) var blocker: AIModelListFetchGate.Blocker? + // True once a list loaded for the key and Base URL of the last request. + @Published private(set) var isCurrent = false + + private var loadedFor: Connection? + private var generation = 0 + + func load(config: AIProviderConfig, apiKey: String) async { + generation += 1 + let mine = generation + let descriptor = AIProviderRegistry.shared.descriptor(for: config.type.rawValue) + let connection = Connection(providerID: config.id, endpoint: config.endpoint, apiKey: apiKey) + + if let blocked = AIProviderDraftRules.modelListBlocker(descriptor: descriptor, draft: config, apiKey: apiKey) { + blocker = blocked + models = [] + isCurrent = false + loadedFor = nil + error = nil + isLoading = false + return + } + + blocker = nil + error = nil + isLoading = true + let transport = AIProviderFactory.makeUncachedProvider(for: config, apiKey: apiKey) + do { + let fetched = try await transport.fetchAvailableModels() + guard mine == generation else { return } + models = fetched + loadedFor = connection + isCurrent = true + isLoading = false + } catch { + guard mine == generation else { return } + // A list from another key or Base URL does not describe the server that just failed. + if loadedFor != connection { + models = [] + isCurrent = false + loadedFor = nil + } + self.error = error.localizedDescription + isLoading = false + } + } + + // The draft's key or Base URL changed, so the list on screen no longer answers for it. + func markStale() { + isCurrent = false + } + + func cancel() { + generation += 1 + isLoading = false + } +} diff --git a/apple/TablePro/Views/Settings/AI/AIProviderAddMenu.swift b/apple/TablePro/Views/Settings/AI/AIProviderAddMenu.swift new file mode 100644 index 0000000000..43538471de --- /dev/null +++ b/apple/TablePro/Views/Settings/AI/AIProviderAddMenu.swift @@ -0,0 +1,137 @@ +import SwiftUI + +enum AIProviderAddChoice: Hashable, Identifiable { + case type(AIProviderType) + case preset(String) + case custom + + var id: String { + switch self { + case .type(let type): "type.\(type.rawValue)" + case .preset(let id): "preset.\(id)" + case .custom: "custom" + } + } + + var preset: AIProviderPreset? { + guard case .preset(let id) = self else { return nil } + return AIProviderPreset.preset(withID: id) + } + + var title: String { + switch self { + case .type(let type): type.displayName + case .preset: preset?.displayName ?? AIProviderType.custom.displayName + case .custom: String(localized: "Custom Provider") + } + } + + var icon: BrandIcon { + switch self { + case .type(let type): type.icon + case .preset: preset?.icon ?? AIProviderType.custom.icon + case .custom: AIProviderType.custom.icon + } + } + + func makeProvider(descriptor: (AIProviderType) -> AIProviderDescriptor?) -> AIProviderConfig { + switch self { + case .type(let type): + return AIProviderConfig( + type: type, + endpoint: type.defaultEndpoint, + telemetryEnabled: descriptor(type)?.defaultTelemetryEnabled ?? false + ) + case .preset: + guard let preset else { return AIProviderConfig(type: .custom) } + return AIProviderConfig(preset: preset) + case .custom: + return AIProviderConfig( + type: .custom, + telemetryEnabled: descriptor(.custom)?.defaultTelemetryEnabled ?? false + ) + } + } +} + +enum AIProviderAddMenu { + struct Groups: Equatable { + var signIn: [AIProviderAddChoice] = [] + var apiKey: [AIProviderAddChoice] = [] + var onThisMac: [AIProviderAddChoice] = [] + var includesCustom = false + } + + static func groups(registry: AIProviderRegistry = .shared) -> Groups { + groups { registry.descriptor(for: $0.rawValue) != nil } + } + + static func groups( + isRegistered: (AIProviderType) -> Bool, + presets: [AIProviderPreset] = AIProviderPreset.all + ) -> Groups { + var groups = Groups() + for type in AIProviderType.allCases where type != .custom && isRegistered(type) { + if type.authStyle == .oauth || type == .claudeAgent { + groups.signIn.append(.type(type)) + } else if type.authStyle.usesAPIKey { + groups.apiKey.append(.type(type)) + } else { + groups.onThisMac.append(.type(type)) + } + } + if isRegistered(.custom) { + groups.apiKey += presets.map { .preset($0.id) } + groups.includesCustom = true + } + return groups + } +} + +struct AIProviderAddMenuButton: View { + let onChoose: (AIProviderAddChoice) -> Void + + var body: some View { + let groups = AIProviderAddMenu.groups() + Menu { + if !groups.signIn.isEmpty { + Section(String(localized: "Sign In With an Account")) { items(groups.signIn) } + } + if !groups.apiKey.isEmpty { + Section(String(localized: "API Key")) { items(groups.apiKey) } + } + if !groups.onThisMac.isEmpty { + Section(String(localized: "On This Mac")) { items(groups.onThisMac) } + } + if groups.includesCustom { + Divider() + item(.custom) + } + } label: { + Text("Add Provider") + } + .menuStyle(.button) + .buttonStyle(.bordered) + .fixedSize() + .accessibilityIdentifier("settings-ai-add-provider") + } + + private func items(_ choices: [AIProviderAddChoice]) -> some View { + ForEach(choices) { choice in + item(choice) + } + } + + private func item(_ choice: AIProviderAddChoice) -> some View { + Button { + onChoose(choice) + } label: { + Label { + Text(verbatim: "\(choice.title)…") + } icon: { + choice.icon.menuImage() + } + .labelStyle(.titleAndIcon) + } + } +} diff --git a/apple/TablePro/Views/Settings/AI/AIProviderAddSheet.swift b/apple/TablePro/Views/Settings/AI/AIProviderAddSheet.swift new file mode 100644 index 0000000000..00cc18a3d1 --- /dev/null +++ b/apple/TablePro/Views/Settings/AI/AIProviderAddSheet.swift @@ -0,0 +1,122 @@ +import Combine +import SwiftUI + +struct AIProviderAddSession: Identifiable { + let provider: AIProviderConfig + + var id: UUID { provider.id } +} + +struct AIProviderAddSheet: View { + @StateObject private var model: AIProviderEditorModel + private let onAdd: (AIProviderConfig, Bool) -> Void + + init(session: AIProviderAddSession, onAdd: @escaping (_ provider: AIProviderConfig, _ hasKey: Bool) -> Void) { + self._model = StateObject(wrappedValue: AIProviderEditorModel(provider: session.provider, isNew: true)) + self.onAdd = onAdd + } + + var body: some View { + AIProviderAddSheetContent(model: model, loader: model.loader, onAdd: onAdd) + } +} + +private struct AIProviderAddSheetContent: View { + @Environment(\.dismiss) private var dismiss + @ObservedObject var model: AIProviderEditorModel + @ObservedObject var loader: AIModelListLoader + let onAdd: (AIProviderConfig, Bool) -> Void + + var body: some View { + VStack(spacing: 0) { + Form { + Section { + header + } + AIProviderEditorSections(model: model, parts: .all) + } + .formStyle(.grouped) + + Divider() + + DialogFooter { + if let error = model.saveError { + NoticeLabel(error, severity: .error) + } + } actions: { + Button(String(localized: "Cancel"), role: .cancel) { + model.cancelTasks() + dismiss() + } + .keyboardShortcut(.cancelAction) + .accessibilityIdentifier("ai-provider-cancel") + + Button(String(localized: "Add")) { + add() + } + .keyboardShortcut(.defaultAction) + .disabled(!model.canAdd) + .accessibilityIdentifier("ai-provider-save") + } + .padding() + } + .frame(minWidth: 520, minHeight: 480) + .task { + model.prepare() + switch model.draft.type { + case .copilot: + await CopilotService.shared.start() + case .chatgptCodex: + await ChatGPTCodexService.shared.refreshAuthState() + case .claudeAgent: + await ClaudeAgentService.shared.performRefresh() + default: + break + } + await model.fetchModels() + } + .onDisappear { + model.cancelTasks() + CopilotService.shared.stopIfDisallowed(by: AppSettingsManager.shared.aiSlice.value) + } + } + + private var header: some View { + HStack(spacing: 12) { + BrandIconView(icon: model.draft.icon) + .foregroundStyle(.secondary) + .frame(width: 32, height: 32) + VStack(alignment: .leading, spacing: 2) { + Text(verbatim: String(format: String(localized: "Add %@"), model.draft.kindName)) + .font(.headline) + if let subtitle { + Text(verbatim: subtitle) + .font(.subheadline) + .foregroundStyle(.secondary) + } + } + } + .accessibilityElement(children: .combine) + } + + private var subtitle: String? { + if let host = URL(string: model.draft.endpoint.trimmingCharacters(in: .whitespacesAndNewlines))?.host, + !host.isEmpty { + return host + } + switch model.draft.type { + case .copilot, .chatgptCodex, .claudeAgent: + return String(localized: "Signs in with your account") + default: + return nil + } + } + + private func add() { + guard model.canAdd, let provider = model.providerToAdd() else { return } + onAdd(provider, provider.authStyle.usesAPIKey && !model.apiKey.isEmpty) + AIProviderFactory.invalidateCache(for: provider.id) + AppEvents.shared.aiProviderSaved.send(provider.id) + dismiss() + } +} diff --git a/apple/TablePro/Views/Settings/AI/AIProviderConnectionSheet.swift b/apple/TablePro/Views/Settings/AI/AIProviderConnectionSheet.swift new file mode 100644 index 0000000000..cea20fc71e --- /dev/null +++ b/apple/TablePro/Views/Settings/AI/AIProviderConnectionSheet.swift @@ -0,0 +1,91 @@ +import Combine +import SwiftUI + +struct AIProviderConnectionSaved: Equatable { + let connectionChanged: Bool + let hasKey: Bool +} + +// Edits the name, Base URL and key of a saved provider; the page commits everything else live. +struct AIProviderConnectionSheet: View { + @StateObject private var model: AIProviderEditorModel + private let slice: SettingsSlice + private let onSaved: (AIProviderConnectionSaved) -> Void + + init( + provider: AIProviderConfig, + slice: SettingsSlice, + onSaved: @escaping (AIProviderConnectionSaved) -> Void + ) { + self._model = StateObject(wrappedValue: AIProviderEditorModel(provider: provider, isNew: false)) + self.slice = slice + self.onSaved = onSaved + } + + var body: some View { + AIProviderConnectionSheetContent(model: model, slice: slice, onSaved: onSaved) + } +} + +private struct AIProviderConnectionSheetContent: View { + @Environment(\.dismiss) private var dismiss + @ObservedObject var model: AIProviderEditorModel + let slice: SettingsSlice + let onSaved: (AIProviderConnectionSaved) -> Void + + var body: some View { + VStack(spacing: 0) { + Form { + AIProviderEditorSections(model: model, parts: [.connection, .apiKey]) + } + .formStyle(.grouped) + + Divider() + + DialogFooter { + if let error = model.saveError { + NoticeLabel(error, severity: .error) + } + } actions: { + Button(String(localized: "Cancel"), role: .cancel) { + model.cancelTasks() + dismiss() + } + .keyboardShortcut(.cancelAction) + .accessibilityIdentifier("ai-provider-cancel") + + Button(String(localized: "Save")) { + save() + } + .keyboardShortcut(.defaultAction) + .disabled(!model.canSaveConnection) + .accessibilityIdentifier("ai-provider-save") + } + .padding() + } + .frame(minWidth: 480, minHeight: 320) + .task { + await model.loadKey() + } + .onDisappear { + model.cancelTasks() + } + } + + private func save() { + guard model.canSaveConnection else { return } + guard let current = slice.value.provider(withID: model.draft.id) else { + model.saveError = String(localized: "This provider was removed.") + return + } + guard let saved = model.connectionSave(current: current) else { return } + if saved.connectionChanged { + AIModelCatalog.shared.remove(providerID: current.id) + } + slice.value = slice.value.replacingProvider(saved.provider) + AIProviderFactory.invalidateCache(for: current.id) + AppEvents.shared.aiProviderSaved.send(current.id) + onSaved(AIProviderConnectionSaved(connectionChanged: saved.connectionChanged, hasKey: saved.hasKey)) + dismiss() + } +} diff --git a/apple/TablePro/Views/Settings/AI/AIProviderEditorModel.swift b/apple/TablePro/Views/Settings/AI/AIProviderEditorModel.swift new file mode 100644 index 0000000000..168743bf53 --- /dev/null +++ b/apple/TablePro/Views/Settings/AI/AIProviderEditorModel.swift @@ -0,0 +1,422 @@ +import Combine +import Foundation + +enum AIModelSelection: Hashable { + case curated(String) + case fetched(String) + case custom +} + +struct AIModelChoices: Equatable { + let curated: [CuratedModel] + let fetched: [String] + + init(curated: [CuratedModel], fetched: [AIModelInfo]) { + self.curated = curated + let curatedIDs = Set(curated.map(\.id)) + self.fetched = fetched.map(\.id).filter { !curatedIDs.contains($0) } + } + + func contains(_ modelID: String) -> Bool { + curated.contains { $0.id == modelID } || fetched.contains(modelID) + } + + func selection(for modelID: String, choseOther: Bool) -> AIModelSelection { + if choseOther { return .custom } + if curated.contains(where: { $0.id == modelID }) { return .curated(modelID) } + if fetched.contains(modelID) { return .fetched(modelID) } + return .custom + } +} + +// The rules the Edit Connection sheet saves by, kept pure so they can be tested. +enum AIProviderConnectionRules { + enum KeyWrite: Equatable { + case keep + case save(String) + case delete + } + + // A key that failed to load or was never touched is never written over. + static func keyWrite(edited: Bool, typed: String) -> KeyWrite { + guard edited else { return .keep } + return typed.isEmpty ? .delete : .save(typed) + } + + static func canSave(isKeyLoaded: Bool, authStyle: AIProviderType.AuthStyle, apiKey: String) -> Bool { + guard isKeyLoaded else { return false } + guard authStyle == .apiKey else { return true } + return !apiKey.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + } + + // Only the fields this sheet edits move; the model and the rest keep what the page committed meanwhile. + static func merged( + _ current: AIProviderConfig, + with draft: AIProviderConfig, + allowsName: Bool, + allowsEndpoint: Bool + ) -> AIProviderConfig { + var merged = current + if allowsName { merged.name = draft.name.trimmingCharacters(in: .whitespacesAndNewlines) } + if allowsEndpoint { merged.endpoint = draft.endpoint } + return merged + } + + static func connectionChanged( + from current: AIProviderConfig, + to merged: AIProviderConfig, + keyWrite: KeyWrite, + savedKey: String + ) -> Bool { + if current.endpoint != merged.endpoint { return true } + switch keyWrite { + case .keep: return false + case .save(let key): return key != savedKey + case .delete: return !savedKey.isEmpty + } + } +} + +enum AIProviderKeychain { + @concurrent + static func key(for providerID: UUID) async -> String? { + AIKeyStorage.shared.loadAPIKey(for: providerID) + } + + @concurrent + static func providersWithKey(_ providerIDs: [UUID]) async -> Set { + var found: Set = [] + for id in providerIDs { + if let key = AIKeyStorage.shared.loadAPIKey(for: id), !key.isEmpty { + found.insert(id) + } + } + return found + } +} + +// The draft behind the Add Provider and Edit Connection sheets. Nothing reaches settings or the Keychain before Save. +@MainActor +final class AIProviderEditorModel: ObservableObject { + enum TestResult: Equatable { + case success + case failure(String) + } + + private struct FetchInputs: Equatable { + let endpoint: String + let apiKey: String + } + + let loader: AIModelListLoader + + @Published var draft: AIProviderConfig + @Published var maxOutputTokensText: String + @Published var saveError: String? + @Published private(set) var apiKey = "" + @Published private(set) var keyEdited = false + @Published private(set) var isKeyLoaded: Bool + @Published private(set) var choseOtherModel = false + @Published private(set) var isTesting = false + @Published private(set) var testResult: TestResult? + + private let savedEndpoint: String + private var savedAPIKey = "" + private var lastFetch: FetchInputs? + private var connectionRevision = 0 + private var testTask: Task? + + init(provider: AIProviderConfig, isNew: Bool, loader: AIModelListLoader = AIModelListLoader()) { + self.loader = loader + self.draft = provider + self.savedEndpoint = provider.endpoint + self.maxOutputTokensText = provider.maxOutputTokens.map(String.init) ?? "" + self.isKeyLoaded = isNew || !provider.authStyle.usesAPIKey + } + + var descriptor: AIProviderDescriptor? { + AIProviderRegistry.shared.descriptor(for: draft.type.rawValue) + } + + var allowsName: Bool { descriptor?.allowsNameConfiguration == true } + var allowsEndpoint: Bool { descriptor?.allowsEndpointConfiguration == true } + var usesAPIKey: Bool { draft.authStyle.usesAPIKey } + var showsMaxOutputTokens: Bool { descriptor?.allowsMaxOutputTokens == true } + var showsTelemetryToggle: Bool { descriptor?.showsTelemetryToggle == true } + var fetchesModelList: Bool { descriptor?.fetchesModelList == true } + + var normalizedDraft: AIProviderConfig { + var provider = draft + provider.name = draft.name.trimmingCharacters(in: .whitespacesAndNewlines) + provider.model = draft.model.trimmingCharacters(in: .whitespacesAndNewlines) + provider.endpoint = AIProviderDraftRules.endpoint(draft.endpoint, defaultEndpoint: draft.defaultEndpoint) + provider.maxOutputTokens = Self.maxOutputTokens(from: maxOutputTokensText) + return provider + } + + // Empty or below 1 means the provider's default. + nonisolated static func maxOutputTokens(from text: String) -> Int? { + guard let value = SettingsIntegerInput.parse(text), value > 0 else { return nil } + return value + } + + var resolvedEndpoint: AIEndpoint? { + AIEndpoint(normalizedDraft.endpoint, style: draft.type.endpointStyle) + } + + var resolvedChatURL: String? { + resolvedEndpoint?.chatURL(model: draft.model, style: draft.type.endpointStyle)?.absoluteString + } + + // Keyless local servers send no authorization header, so the key is named only when one goes out. + var cleartextCaution: String? { + guard resolvedEndpoint?.isPlaintextToRemoteHost == true else { return nil } + guard usesAPIKey, !apiKey.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { + return String(localized: "Requests to this host are sent unencrypted over http.") + } + return String(localized: "Your API key is sent unencrypted over http to this host.") + } + + var curatedModels: [CuratedModel] { + descriptor?.curatedModels(for: draft.preset) ?? [] + } + + var choices: AIModelChoices { + AIModelChoices(curated: curatedModels, fetched: loader.models) + } + + var modelSelection: AIModelSelection { + choices.selection(for: draft.model, choseOther: choseOtherModel) + } + + var isCustomModel: Bool { + modelSelection == .custom + } + + func reasoning(forModelID id: String) -> AIReasoningSupport { + descriptor?.reasoning( + forModelID: id, + fetched: loader.models.first { $0.id == id }, + preset: draft.preset + ) ?? .unsupported + } + + var reasoningForCurrentModel: AIReasoningSupport { + reasoning(forModelID: draft.model) + } + + var showsReasoningPicker: Bool { + descriptor?.supportsReasoning == true && !reasoningForCurrentModel.effortLevels.isEmpty + } + + var needsModelChoice: Bool { + AIProviderDraftRules.needsModelChoice(model: draft.model, fetched: loader.models) + } + + var canAdd: Bool { + guard !needsModelChoice else { return false } + guard draft.authStyle == .apiKey else { return true } + return !apiKey.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + } + + var canSaveConnection: Bool { + AIProviderConnectionRules.canSave(isKeyLoaded: isKeyLoaded, authStyle: draft.authStyle, apiKey: apiKey) + } + + var keyWrite: AIProviderConnectionRules.KeyWrite { + AIProviderConnectionRules.keyWrite(edited: keyEdited, typed: apiKey) + } + + func loadKey() async { + guard !isKeyLoaded else { return } + let key = await AIProviderKeychain.key(for: draft.id) ?? "" + savedAPIKey = key + if !keyEdited { apiKey = key } + isKeyLoaded = true + } + + func editKey(_ typed: String) { + guard typed != apiKey else { return } + apiKey = typed + keyEdited = true + connectionEdited() + } + + func connectionEdited() { + connectionRevision += 1 + testResult = nil + loader.markStale() + } + + func select(_ selection: AIModelSelection) { + switch selection { + case .curated(let id), .fetched(let id): + choseOtherModel = false + selectModel(id, picked: true) + case .custom: + choseOtherModel = true + if choices.contains(draft.model) { + selectModel("", picked: false) + } + } + } + + func typeModel(_ typed: String) { + choseOtherModel = true + selectModel(typed, picked: false) + } + + // The model and the effort it allows change together, in one write. + func selectModel(_ id: String, picked: Bool) { + var next = draft + next.model = id + next.reasoningEffort = picked + ? AIProviderDraftRules.effort( + afterPicking: draft.reasoningEffort, + reasoning: reasoning(forModelID: id), + curated: curatedModels.first { $0.id == id } + ) + : AIProviderDraftRules.effort(keeping: draft.reasoningEffort, reasoning: reasoning(forModelID: id)) + draft = next + } + + func selectInitialModel() { + guard draft.model.isEmpty, !choseOtherModel, + let initial = AIProviderDraftRules.initialModel(curated: curatedModels, fetched: loader.models) + else { return } + selectModel(initial, picked: false) + } + + // Before any fetch, so a provider whose list cannot load yet still starts on its curated default. + func prepare() { + selectInitialModel() + selectModel(draft.model, picked: false) + } + + // The automatic fetch reads the Base URL as typed: resolving an empty field to the default would send the key elsewhere. + func fetchModels(force: Bool = false) async { + var config = normalizedDraft + if allowsEndpoint { + config.endpoint = draft.endpoint.trimmingCharacters(in: .whitespacesAndNewlines) + } + let inputs = FetchInputs(endpoint: config.endpoint, apiKey: apiKey) + guard force || inputs != lastFetch else { return } + lastFetch = inputs + let revision = connectionRevision + await loader.load(config: config, apiKey: apiKey) + // An edit made while the list loaded leaves it describing the previous key or Base URL. + if revision != connectionRevision { + loader.markStale() + } + selectInitialModel() + } + + func test() { + if draft.authStyle == .apiKey, apiKey.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { + testResult = .failure(String(localized: "API key is required")) + return + } + let transport = AIProviderFactory.makeUncachedProvider(for: normalizedDraft, apiKey: apiKey) + isTesting = true + testResult = nil + testTask?.cancel() + testTask = Task { [weak self] in + let outcome: TestResult + do { + outcome = try await transport.testConnection() + ? .success + : .failure(String(localized: "Connection test failed")) + } catch { + outcome = .failure(error.localizedDescription) + } + guard !Task.isCancelled, let self else { return } + self.isTesting = false + self.testResult = outcome + } + } + + func cancelTasks() { + testTask?.cancel() + testTask = nil + isTesting = false + loader.cancel() + } + + // The sheet's list reaches the shared catalog only on Save, and only if it describes what was saved. + func commitModelList() { + let saved = normalizedDraft + let update = AIProviderDraftRules.catalogUpdate( + listIsCurrent: loader.isCurrent, + listIsEmpty: loader.models.isEmpty, + connectionChanged: saved.endpoint != savedEndpoint || apiKey != savedAPIKey + ) + switch update { + case .store: + AIModelCatalog.shared.store(providerID: saved.id, models: loader.models) + case .remove: + AIModelCatalog.shared.remove(providerID: saved.id) + case .refetch: + AIModelCatalog.shared.remove(providerID: saved.id) + guard fetchesModelList else { return } + let transport = AIProviderFactory.makeUncachedProvider(for: saved, apiKey: apiKey) + let providerID = saved.id + Task { await AIModelCatalog.shared.refresh(providerID: providerID, using: transport) } + case .keep: + break + } + } + + // Returns the provider to store, or nil when the Keychain refused the key and the sheet stays open. + func providerToAdd() -> AIProviderConfig? { + let provider = normalizedDraft + let key = apiKey + if provider.authStyle.usesAPIKey, !key.isEmpty { + guard AIKeyStorage.shared.saveAPIKey(key, for: provider.id) else { + saveError = String(localized: "The API key could not be saved to the Keychain.") + return nil + } + } + cancelTasks() + commitModelList() + return provider + } + + struct ConnectionSave: Equatable { + let provider: AIProviderConfig + let connectionChanged: Bool + let hasKey: Bool + } + + func connectionSave(current: AIProviderConfig) -> ConnectionSave? { + let write = keyWrite + switch write { + case .keep: + break + case .save(let key): + guard AIKeyStorage.shared.saveAPIKey(key, for: current.id) else { + saveError = String(localized: "The API key could not be saved to the Keychain.") + return nil + } + case .delete: + AIKeyStorage.shared.deleteAPIKey(for: current.id) + } + cancelTasks() + let merged = AIProviderConnectionRules.merged( + current, + with: normalizedDraft, + allowsName: allowsName, + allowsEndpoint: allowsEndpoint + ) + let changed = AIProviderConnectionRules.connectionChanged( + from: current, + to: merged, + keyWrite: write, + savedKey: savedAPIKey + ) + return ConnectionSave( + provider: merged, + connectionChanged: changed, + hasKey: !apiKey.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + ) + } +} diff --git a/apple/TablePro/Views/Settings/AI/AIProviderEditorSections.swift b/apple/TablePro/Views/Settings/AI/AIProviderEditorSections.swift new file mode 100644 index 0000000000..613d86c9f5 --- /dev/null +++ b/apple/TablePro/Views/Settings/AI/AIProviderEditorSections.swift @@ -0,0 +1,554 @@ +import SwiftUI + +struct AIProviderEditorParts: OptionSet { + let rawValue: Int + + static let connection = AIProviderEditorParts(rawValue: 1 << 0) + static let apiKey = AIProviderEditorParts(rawValue: 1 << 1) + static let account = AIProviderEditorParts(rawValue: 1 << 2) + static let model = AIProviderEditorParts(rawValue: 1 << 3) + static let advanced = AIProviderEditorParts(rawValue: 1 << 4) + + static let all: AIProviderEditorParts = [.connection, .apiKey, .account, .model, .advanced] +} + +// Shared by the Add Provider and Edit Connection sheets; every edit stays in the model's draft until Save. +struct AIProviderEditorSections: View { + private enum Field: Hashable { + case apiKey + case endpoint + } + + @ObservedObject private var model: AIProviderEditorModel + @ObservedObject private var loader: AIModelListLoader + private let parts: AIProviderEditorParts + + @FocusState private var focus: Field? + @State private var focusedField: Field? + + init(model: AIProviderEditorModel, parts: AIProviderEditorParts) { + self._model = ObservedObject(wrappedValue: model) + self._loader = ObservedObject(wrappedValue: model.loader) + self.parts = parts + } + + var body: some View { + Group { + if parts.contains(.connection), model.allowsName || model.allowsEndpoint { + connectionSection + } + if parts.contains(.apiKey), model.usesAPIKey { + apiKeySection + } + if parts.contains(.account), !model.usesAPIKey { + AIProviderAccountSections(type: model.draft.type) + } + if parts.contains(.model) { + modelSection + } + if parts.contains(.advanced), model.showsMaxOutputTokens || model.showsTelemetryToggle { + advancedSection + } + } + .onChange(of: focus) { newFocus in + // Leaving the key or Base URL field commits it, which is when the model list loads. + if focusedField != nil, newFocus != focusedField { + commitConnection() + } + focusedField = newFocus + } + } + + private func commitConnection() { + guard parts.contains(.model) else { return } + Task { await model.fetchModels() } + } + + private var connectionSection: some View { + Section { + if model.allowsName { + TextField(text: $model.draft.name, prompt: Text(verbatim: model.draft.kindName)) { + Text("Name") + } + .accessibilityIdentifier("ai-provider-name") + } + if model.allowsEndpoint { + TextField(text: endpointBinding, prompt: Text(verbatim: endpointPrompt)) { + Text("Base URL") + Text("Include the version segment your server uses, such as /v1 or /v4.") + } + .focused($focus, equals: .endpoint) + .onSubmit(commitConnection) + .accessibilityIdentifier("ai-provider-base-url") + + if let url = model.resolvedChatURL { + LabeledContent("Requests go to") { + Text(verbatim: url) + .foregroundStyle(.secondary) + .lineLimit(1) + .truncationMode(.middle) + .textSelection(.enabled) + .help(url) + } + } + if let caution = model.cleartextCaution { + NoticeLabel(caution) + } + } + } header: { + Text("Connection") + } + } + + private var endpointPrompt: String { + model.draft.defaultEndpoint.isEmpty ? "https://" : model.draft.defaultEndpoint + } + + private var endpointBinding: Binding { + let model = model + return Binding( + get: { model.draft.endpoint }, + set: { typed in + guard typed != model.draft.endpoint else { return } + model.draft.endpoint = typed + model.connectionEdited() + } + ) + } + + private var apiKeySection: some View { + Section { + SecureField(text: keyBinding, prompt: model.draft.authStyle == .apiKey ? Text("Required") : Text("Optional")) { + Text("API key") + } + .focused($focus, equals: .apiKey) + .onSubmit(commitConnection) + .disabled(!model.isKeyLoaded) + .accessibilityIdentifier("ai-provider-api-key") + + LabeledContent { + HStack(spacing: 6) { + if model.isTesting { + ProgressView() + .controlSize(.small) + .accessibilityHidden(true) + } + Button("Test Connection") { + model.test() + } + .disabled(!canTest) + .accessibilityIdentifier("ai-provider-test") + } + } label: { + Text("Connection test") + testResultLine + } + } header: { + Text("Authentication") + } + } + + private var canTest: Bool { + guard model.isKeyLoaded, !model.isTesting else { return false } + guard model.draft.authStyle == .apiKey else { return true } + return !model.apiKey.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + } + + @ViewBuilder + private var testResultLine: some View { + switch model.testResult { + case .success: + NoticeLabel(String(localized: "Connection successful"), severity: .success) + case .failure(let message): + NoticeLabel(message, severity: .error) + case nil: + if model.isTesting { + Text("Testing…") + } else { + Text("Sends one short request with this key and Base URL.") + } + } + } + + private var keyBinding: Binding { + let model = model + return Binding( + get: { model.apiKey }, + set: { model.editKey($0) } + ) + } + + private var modelSection: some View { + Section { + Picker(selection: selectionBinding) { + AIModelPickerItems(choices: model.choices) + } label: { + Text("Model") + AIModelListSubtitle(loader: loader, needsChoice: model.needsModelChoice) + } + .pickerStyle(.menu) + .accessibilityIdentifier("ai-provider-model") + + if model.isCustomModel { + TextField(text: typedModelBinding, prompt: Text(verbatim: "model-id")) { + Text("Model ID") + } + } + if model.showsReasoningPicker { + Picker(selection: $model.draft.reasoningEffort) { + AIReasoningPickerItems(reasoning: model.reasoningForCurrentModel) + } label: { + Text("Reasoning") + } + .pickerStyle(.menu) + } + if model.fetchesModelList { + LabeledContent("Model list") { + Button("Reload") { + Task { await model.fetchModels(force: true) } + } + .disabled(loader.isLoading) + } + } + } header: { + Text("Model") + } + } + + private var selectionBinding: Binding { + let model = model + return Binding( + get: { model.modelSelection }, + set: { model.select($0) } + ) + } + + private var typedModelBinding: Binding { + let model = model + return Binding( + get: { model.draft.model }, + set: { model.typeModel($0) } + ) + } + + private var advancedSection: some View { + Section { + if model.showsMaxOutputTokens { + TextField(text: $model.maxOutputTokensText, prompt: Text("Default")) { + Text("Maximum output tokens") + } + } + if model.showsTelemetryToggle { + Toggle("Send telemetry to GitHub", isOn: $model.draft.telemetryEnabled) + } + } header: { + Text("Advanced") + } + } +} + +struct AIModelPickerItems: View { + let choices: AIModelChoices + + var body: some View { + if !choices.curated.isEmpty { + Section { + ForEach(choices.curated) { model in + Text(verbatim: model.displayName).tag(AIModelSelection.curated(model.id)) + } + } + } + if !choices.fetched.isEmpty { + Section { + ForEach(choices.fetched, id: \.self) { id in + Text(verbatim: id).tag(AIModelSelection.fetched(id)) + } + } + } + Text("Other…").tag(AIModelSelection.custom) + } +} + +struct AIReasoningPickerItems: View { + let reasoning: AIReasoningSupport + + var body: some View { + if !reasoning.isMandatory { + Text("Off").tag(ReasoningEffort?.none) + } + ForEach(reasoning.effortLevels) { effort in + Text(effort.displayName).tag(ReasoningEffort?.some(effort)) + } + } +} + +// The second line of the Model picker's label: one state at a time. +struct AIModelListSubtitle: View { + @ObservedObject var loader: AIModelListLoader + var needsChoice = false + + var body: some View { + if loader.isLoading { + Label { + Text("Loading models…") + } icon: { + ProgressView() + .controlSize(.mini) + .accessibilityHidden(true) + } + } else if let error = loader.error { + NoticeLabel(error, severity: .error) + } else if loader.blocker == .missingAPIKey { + Text("Add an API key to load this provider's models.") + } else if needsChoice { + Text("Pick a model to add this provider.") + } + } +} + +// The sign-in part of an account-based provider, the same on the provider page and in the Add sheet. +struct AIProviderAccountSections: View { + let type: AIProviderType + + var body: some View { + switch type { + case .copilot: + CopilotAccountSection() + case .chatgptCodex: + ChatGPTAccountSection() + case .claudeAgent: + ClaudeAgentAccountSection() + default: + EmptyView() + } + } +} + +private struct CopilotAccountSection: View { + @ObservedObject private var copilot = CopilotService.shared + @State private var signInError: String? + + var body: some View { + Section { + switch copilot.authState { + case .signedOut: + LabeledContent { + Button("Sign In…") { + Task { await signIn() } + } + .disabled(copilot.status != .running) + } label: { + Text("GitHub account") + accountNote(otherwise: String(localized: "Not signed in")) + } + case .signingIn(let userCode, _): + LabeledContent("Code") { + HStack(spacing: 8) { + Text(verbatim: userCode) + .font(.system(.title3, design: .monospaced).weight(.semibold)) + .textSelection(.enabled) + Button("Copy") { + ClipboardService.shared.writeText(userCode) + } + } + } + LabeledContent { + HStack(spacing: 8) { + Button("Cancel") { + Task { await copilot.signOut() } + } + Button("Complete Sign In") { + Task { await completeSignIn() } + } + } + } label: { + Text("Enter the code on GitHub") + accountNote(otherwise: String(localized: "It was copied to the clipboard and expires in 15 minutes.")) + } + case .signedIn(let username): + LabeledContent { + Button("Sign Out") { + Task { await copilot.signOut() } + } + } label: { + Text("GitHub account") + accountNote(otherwise: username) + } + } + } header: { + Text("GitHub Account") + } + } + + @ViewBuilder + private func accountNote(otherwise fallback: String) -> some View { + if let message = signInError ?? copilot.statusMessage { + NoticeLabel(message, severity: .error) + } else { + switch copilot.status { + case .starting: + Label { + Text("Starting…") + } icon: { + ProgressView() + .controlSize(.mini) + .accessibilityHidden(true) + } + case .stopped where !copilot.authState.isSignedIn: + Text("Not started") + case .error(let message): + NoticeLabel(message, severity: .error) + default: + Text(verbatim: fallback) + } + } + } + + private func signIn() async { + signInError = nil + do { + try await copilot.signIn() + } catch { + signInError = error.localizedDescription + } + } + + private func completeSignIn() async { + signInError = nil + do { + try await copilot.completeSignIn() + } catch { + signInError = error.localizedDescription + } + } +} + +private struct ChatGPTAccountSection: View { + @ObservedObject private var service = ChatGPTCodexService.shared + + var body: some View { + Section { + switch service.authState { + case .signedOut: + LabeledContent { + HStack(spacing: 8) { + Button("Import from Codex CLI") { + Task { await service.importFromCodexCLI() } + } + Button("Sign In…") { + Task { await service.signIn() } + } + } + } label: { + Text("ChatGPT account") + accountNote(otherwise: String(localized: "Not signed in")) + } + case .signingIn: + LabeledContent { + EmptyView() + } label: { + Text("ChatGPT account") + Label { + Text("Waiting for your browser…") + } icon: { + ProgressView() + .controlSize(.mini) + .accessibilityHidden(true) + } + } + case .signedIn(let email, let planType): + LabeledContent { + Button("Sign Out") { + Task { await service.signOut() } + } + } label: { + Text("ChatGPT account") + accountNote(otherwise: email.isEmpty ? String(localized: "Signed in") : email) + } + if let planType, !planType.isEmpty { + LabeledContent("Plan") { + Text(verbatim: planType) + } + } + } + SettingsHelpRow( + "Uses your Plus, Pro, Business or Enterprise subscription under OpenAI's terms. This interface is unofficial and may change." + ) + } header: { + Text("ChatGPT Account") + } + } + + @ViewBuilder + private func accountNote(otherwise fallback: String) -> some View { + if let message = service.errorMessage { + NoticeLabel(message, severity: .error) + } else { + Text(verbatim: fallback) + } + } +} + +private struct ClaudeAgentAccountSection: View { + @ObservedObject private var service = ClaudeAgentService.shared + + var body: some View { + Section { + LabeledContent { + Button("Check Again") { + service.refreshStatus() + } + .disabled(service.isRefreshing) + } label: { + Text("Status") + AIProviderStatusLabel(status: status) + } + if let plan { + LabeledContent("Plan") { + Text(verbatim: plan) + } + } + if let command = service.remedyCommand { + LabeledContent { + Button("Copy") { + ClipboardService.shared.writeText(command) + } + } label: { + Text(verbatim: command) + .font(.system(.body, design: .monospaced)) + .textSelection(.enabled) + if let requirement { + Text(verbatim: requirement) + } + } + } + SettingsHelpRow( + "Runs the claude command line tool, so chat bills against your Claude subscription. Database tools need the MCP server, in Settings > MCP." + ) + } header: { + Text("Claude Agent") + } + + ClaudeAgentDisclosureSection() + } + + private var status: AIProviderStatus { + AIProviderStatus.resolve( + provider: AIProviderConfig(type: .claudeAgent), + hasAPIKey: false, + oauthState: nil, + serviceError: nil, + claudeAgent: service.state + ) + } + + private var plan: String? { + guard case .signedIn(_, let plan?) = service.state, !plan.isEmpty else { return nil } + return plan + } + + private var requirement: String? { + guard case .outdated = service.state else { return nil } + return String(format: String(localized: "Version %@ or newer is required."), ClaudeAgentCLI.minimumVersion) + } +} diff --git a/apple/TablePro/Views/Settings/AI/AIProviderPage.swift b/apple/TablePro/Views/Settings/AI/AIProviderPage.swift new file mode 100644 index 0000000000..585a3f454c --- /dev/null +++ b/apple/TablePro/Views/Settings/AI/AIProviderPage.swift @@ -0,0 +1,352 @@ +import Combine +import SwiftUI + +// One provider's live settings. Opening it never writes: only a user edit commits, one whole-provider write at a time. +struct AIProviderPage: View { + let providerID: UUID + @ObservedObject var slice: SettingsSlice + + @EnvironmentObject private var paneModel: AISettingsPaneModel + @StateObject private var loader = AIModelListLoader() + @State private var loadedKey: String? + @State private var loadToken = 0 + @State private var choseOtherModel = false + @State private var isEditingConnection = false + + var body: some View { + Group { + if let provider = slice.value.provider(withID: providerID) { + form(provider) + } else { + UnavailableStateView(String(localized: "This provider was removed."), systemImage: "sparkles") + } + } + .task(id: loadToken) { + await loadModels() + } + .task { + guard slice.value.enabled, let type = slice.value.provider(withID: providerID)?.type else { return } + await paneModel.refreshAccounts(AIProviderAccountProbes.probedTypes.intersection([type])) + } + .onDisappear { + CopilotService.shared.stopIfDisallowed(by: slice.value) + } + .sheet(isPresented: $isEditingConnection) { + if let provider = slice.value.provider(withID: providerID) { + AIProviderConnectionSheet(provider: provider, slice: slice) { saved in + loadedKey = nil + paneModel.setHasKey(saved.hasKey, for: providerID) + if saved.connectionChanged { + loadToken += 1 + } + } + } + } + } + + private func form(_ provider: AIProviderConfig) -> some View { + let descriptor = AIProviderRegistry.shared.descriptor(for: provider.type.rawValue) + let showsAdvanced = descriptor?.allowsMaxOutputTokens == true || descriptor?.showsTelemetryToggle == true + return Form { + if !provider.authStyle.usesAPIKey { + AIProviderAccountSections(type: provider.type) + } + if showsConnection(provider, descriptor: descriptor) { + connectionSection(provider, descriptor: descriptor) + } + modelSection(provider, descriptor: descriptor, isLast: !showsAdvanced) + if showsAdvanced { + advancedSection(provider, descriptor: descriptor) + } + } + .formStyle(.grouped) + .accessibilityElement(children: .contain) + .accessibilityIdentifier("settings-page-ai-provider") + } + + // A search result can open this page with AI off, which starts no service and sends no key. + private func loadModels() async { + guard slice.value.enabled, let provider = slice.value.provider(withID: providerID) else { return } + if provider.type == .copilot, CopilotLifecycle.allowsRunning(slice.value) { + await CopilotService.shared.start() + } + var key = "" + if provider.authStyle.usesAPIKey { + key = await AIProviderKeychain.key(for: providerID) ?? "" + loadedKey = key + paneModel.setHasKey(!key.isEmpty, for: providerID) + } + guard let current = slice.value.provider(withID: providerID) else { return } + await loader.load(config: current, apiKey: key) + guard loader.isCurrent, loader.error == nil else { return } + switch AIProviderDraftRules.catalogUpdate(listIsCurrent: true, listIsEmpty: loader.models.isEmpty, connectionChanged: false) { + case .store: + AIModelCatalog.shared.store(providerID: providerID, models: loader.models) + case .remove: + AIModelCatalog.shared.remove(providerID: providerID) + case .refetch, .keep: + break + } + } + + private func commit(_ change: (inout AIProviderConfig) -> Void) { + guard var updated = slice.value.provider(withID: providerID) else { return } + let original = updated + change(&updated) + guard updated != original else { return } + slice.value = slice.value.replacingProvider(updated) + AIProviderFactory.invalidateCache(for: providerID) + AppEvents.shared.aiProviderSaved.send(providerID) + } + + private func hasKey(_ provider: AIProviderConfig) -> Bool { + if let loadedKey { return !loadedKey.isEmpty } + return paneModel.hasKey(provider.id) + } + + private func showsConnection(_ provider: AIProviderConfig, descriptor: AIProviderDescriptor?) -> Bool { + descriptor?.allowsNameConfiguration == true + || descriptor?.allowsEndpointConfiguration == true + || provider.authStyle.usesAPIKey + } + + private func connectionSection(_ provider: AIProviderConfig, descriptor: AIProviderDescriptor?) -> some View { + Section { + if descriptor?.allowsNameConfiguration == true { + LabeledContent("Name") { + Text(verbatim: provider.displayName) + } + } + if descriptor?.allowsEndpointConfiguration == true { + LabeledContent("Base URL") { + Text(verbatim: provider.endpoint) + .foregroundStyle(.secondary) + .lineLimit(1) + .truncationMode(.middle) + .textSelection(.enabled) + .help(provider.endpoint) + } + } + if provider.authStyle.usesAPIKey { + LabeledContent("API key") { + hasKey(provider) ? Text("Set") : Text("Not set") + } + } + if let caution = cleartextCaution(provider) { + NoticeLabel(caution) + } + } header: { + Text("Connection") + } footer: { + SettingsSectionActions { + Button("Edit Connection…") { + isEditingConnection = true + } + .accessibilityIdentifier("ai-provider-edit-connection") + } + } + } + + private func cleartextCaution(_ provider: AIProviderConfig) -> String? { + guard AIEndpoint(provider.endpoint, style: provider.type.endpointStyle)?.isPlaintextToRemoteHost == true else { + return nil + } + guard provider.authStyle.usesAPIKey, hasKey(provider) else { + return String(localized: "Requests to this host are sent unencrypted over http.") + } + return String(localized: "Your API key is sent unencrypted over http to this host.") + } + + private func modelSection( + _ provider: AIProviderConfig, + descriptor: AIProviderDescriptor?, + isLast: Bool + ) -> some View { + let choices = AIModelChoices(curated: descriptor?.curatedModels(for: provider.preset) ?? [], fetched: loader.models) + let selection = choices.selection(for: provider.model, choseOther: choseOtherModel) + let reasoning = reasoning(for: provider, modelID: provider.model, descriptor: descriptor) + return Section { + Picker(selection: selectionBinding(choices: choices, descriptor: descriptor)) { + AIModelPickerItems(choices: choices) + } label: { + Text("Model") + AIModelListSubtitle(loader: loader) + } + .pickerStyle(.menu) + .accessibilityIdentifier("ai-provider-model") + + if selection == .custom { + SettingsTextField( + "Model ID", + text: modelIDBinding(descriptor: descriptor), + prompt: Text(verbatim: "model-id"), + normalize: { $0.trimmingCharacters(in: .whitespacesAndNewlines) } + ) + .accessibilityIdentifier("ai-provider-model-id") + } + if descriptor?.supportsReasoning == true, !reasoning.effortLevels.isEmpty { + Picker(selection: reasoningBinding(reasoning)) { + AIReasoningPickerItems(reasoning: reasoning) + } label: { + Text("Reasoning") + } + .pickerStyle(.menu) + } + if descriptor?.fetchesModelList == true { + LabeledContent("Model list") { + Button("Reload") { + loadToken += 1 + } + .disabled(loader.isLoading) + } + } + } header: { + Text("Model") + } footer: { + if isLast { + removeAction(provider) + } + } + } + + private func advancedSection(_ provider: AIProviderConfig, descriptor: AIProviderDescriptor?) -> some View { + Section { + if descriptor?.allowsMaxOutputTokens == true { + SettingsTextField( + "Maximum output tokens", + text: maxOutputTokensBinding, + prompt: Text("Default"), + validate: { text in + let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty, SettingsIntegerInput.parse(trimmed) == nil else { return nil } + return String(localized: "Enter a whole number.") + }, + normalize: { $0.trimmingCharacters(in: .whitespacesAndNewlines) } + ) + } + if descriptor?.showsTelemetryToggle == true { + Toggle("Send telemetry to GitHub", isOn: telemetryBinding) + } + } header: { + Text("Advanced") + } footer: { + removeAction(provider) + } + } + + private func removeAction(_ provider: AIProviderConfig) -> some View { + SettingsSectionActions { + Button(String(localized: "Remove Provider…"), role: .destructive) { + paneModel.pendingRemoval = provider + } + .accessibilityIdentifier("ai-provider-remove") + } + } + + private func reasoning( + for provider: AIProviderConfig, + modelID: String, + descriptor: AIProviderDescriptor? + ) -> AIReasoningSupport { + descriptor?.reasoning( + forModelID: modelID, + fetched: loader.models.first { $0.id == modelID }, + preset: provider.preset + ) ?? .unsupported + } + + // What the Reasoning picker shows for a saved effort the model does not take; it is written only when picked. + private func displayedEffort(_ provider: AIProviderConfig, descriptor: AIProviderDescriptor?) -> ReasoningEffort? { + AIProviderDraftRules.effort( + keeping: provider.reasoningEffort, + reasoning: reasoning(for: provider, modelID: provider.model, descriptor: descriptor) + ) + } + + // The model and the effort it allows change together, in one write. + private func selectModel(_ id: String, picked: Bool, descriptor: AIProviderDescriptor?) { + commit { provider in + let current = displayedEffort(provider, descriptor: descriptor) + let reasoning = reasoning(for: provider, modelID: id, descriptor: descriptor) + provider.reasoningEffort = picked + ? AIProviderDraftRules.effort( + afterPicking: current, + reasoning: reasoning, + curated: descriptor?.curatedModel(forID: id, preset: provider.preset) + ) + : AIProviderDraftRules.effort(keeping: current, reasoning: reasoning) + provider.model = id + } + } + + private func selectionBinding(choices: AIModelChoices, descriptor: AIProviderDescriptor?) -> Binding { + let slice = slice + let providerID = providerID + let choseOther = choseOtherModel + return Binding( + get: { choices.selection(for: slice.value.provider(withID: providerID)?.model ?? "", choseOther: choseOther) }, + set: { selection in + switch selection { + case .curated(let id), .fetched(let id): + choseOtherModel = false + selectModel(id, picked: true, descriptor: descriptor) + case .custom: + choseOtherModel = true + } + } + ) + } + + // An empty Model ID is never committed: the field reads the saved model back. + private func modelIDBinding(descriptor: AIProviderDescriptor?) -> Binding { + let slice = slice + let providerID = providerID + return Binding( + get: { slice.value.provider(withID: providerID)?.model ?? "" }, + set: { typed in + let trimmed = typed.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty else { return } + selectModel(trimmed, picked: false, descriptor: descriptor) + } + ) + } + + private func reasoningBinding(_ reasoning: AIReasoningSupport) -> Binding { + let slice = slice + let providerID = providerID + return Binding( + get: { + AIProviderDraftRules.effort( + keeping: slice.value.provider(withID: providerID)?.reasoningEffort, + reasoning: reasoning + ) + }, + set: { effort in + commit { $0.reasoningEffort = effort } + } + ) + } + + private var maxOutputTokensBinding: Binding { + let slice = slice + let providerID = providerID + return Binding( + get: { slice.value.provider(withID: providerID)?.maxOutputTokens.map(String.init) ?? "" }, + set: { typed in + let value = AIProviderEditorModel.maxOutputTokens(from: typed) + commit { $0.maxOutputTokens = value } + } + ) + } + + private var telemetryBinding: Binding { + let slice = slice + let providerID = providerID + return Binding( + get: { slice.value.provider(withID: providerID)?.telemetryEnabled ?? false }, + set: { enabled in + commit { $0.telemetryEnabled = enabled } + } + ) + } +} diff --git a/apple/TablePro/Views/Settings/AIProviderDetailSheet.swift b/apple/TablePro/Views/Settings/AIProviderDetailSheet.swift deleted file mode 100644 index 2f02da8516..0000000000 --- a/apple/TablePro/Views/Settings/AIProviderDetailSheet.swift +++ /dev/null @@ -1,915 +0,0 @@ -// -// AIProviderDetailSheet.swift -// TablePro -// -// Drill-down detail sheet for configuring a single AI provider. -// - -import AppKit -import SwiftUI - -struct AIProviderDetailSheet: View { - let isNew: Bool - let onSave: (AIProviderConfig, String) -> Void - let onDelete: (() -> Void)? - let onCancel: () -> Void - - private let savedEndpoint: String - private let savedAPIKey: String - - @State private var draft: AIProviderConfig - @State private var apiKey: String - @State private var fetched: [AIModelInfo] = [] - @State private var fetchedListIsCurrent = false - @State private var isFetchingModels = false - @State private var modelFetchError: String? - @State private var modelFetchTask: Task? - @State private var choseOtherModel = false - - @State private var isTesting = false - @State private var testResult: TestResult? - @State private var testTask: Task? - - @ObservedObject private var copilotService = CopilotService.shared - @State private var copilotErrorMessage: String? - - @ObservedObject private var chatGPTCodexService = ChatGPTCodexService.shared - - @ObservedObject private var claudeAgentService = ClaudeAgentService.shared - - @State private var showRemoveConfirmation = false - - enum TestResult: Equatable { - case success - case failure(String) - } - - init( - provider: AIProviderConfig, - initialAPIKey: String, - isNew: Bool, - onSave: @escaping (AIProviderConfig, String) -> Void, - onDelete: (() -> Void)? = nil, - onCancel: @escaping () -> Void - ) { - self.savedEndpoint = provider.endpoint - self.savedAPIKey = initialAPIKey - self._draft = State(initialValue: provider) - self._apiKey = State(initialValue: initialAPIKey) - self.isNew = isNew - self.onSave = onSave - self.onDelete = onDelete - self.onCancel = onCancel - } - - var body: some View { - NavigationStack { - Form { - authSection - connectionSection - modelSection - advancedSection - if let onDelete, !isNew { - deleteSection(onDelete: onDelete) - } - } - .formStyle(.grouped) - .navigationTitle(navigationTitle) - .toolbar { - ToolbarItem(placement: .cancellationAction) { - Button(String(localized: "Cancel")) { - cancelTasks() - onCancel() - } - .keyboardShortcut(.cancelAction) - } - ToolbarItem(placement: .confirmationAction) { - Button(String(localized: "Save")) { - cancelTasks() - commitModelList() - onSave(normalizedDraft, apiKey) - } - .keyboardShortcut(.defaultAction) - .disabled(!isSaveEnabled) - .accessibilityIdentifier("ai-provider-save") - } - } - .onAppear { - // Before any fetch, so a provider whose list cannot load yet still starts on its curated default. - selectInitialModel() - selectModel(draft.model, picked: false) - if draft.type == .copilot { - Task { - await ensureCopilotRunning() - fetchModels() - } - } else { - if draft.type == .chatgptCodex { - Task { await chatGPTCodexService.refreshAuthState() } - } - if draft.type == .claudeAgent { - Task { await claudeAgentService.performRefresh() } - } - fetchModels() - } - } - .onDisappear { - cancelTasks() - if draft.type == .copilot { - copilotService.stopIfDisallowed(by: AppSettingsManager.shared.ai) - } - } - } - .frame(minWidth: 520, minHeight: 480) - .confirmationDialog( - String(format: String(localized: "Remove “%@”?"), draft.displayName), - isPresented: $showRemoveConfirmation, - titleVisibility: .visible - ) { - Button(String(localized: "Remove Provider"), role: .destructive) { - onDelete?() - } - Button(String(localized: "Cancel"), role: .cancel) {} - } message: { - Text(String(localized: "The provider configuration and stored API key will be deleted.")) - } - } - - private var navigationTitle: String { - if isNew { - return String(format: String(localized: "Add %@"), draft.kindName) - } - return draft.displayName - } - - private var needsModelChoice: Bool { - AIProviderDraftRules.needsModelChoice(model: draft.model, fetched: fetched) - } - - private var isSaveEnabled: Bool { - guard !needsModelChoice else { return false } - switch draft.authStyle { - case .apiKey: - return !apiKey.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty - case .optionalApiKey, .oauth, .none: - return true - } - } - - private var normalizedDraft: AIProviderConfig { - var provider = draft - provider.model = draft.model.trimmingCharacters(in: .whitespacesAndNewlines) - provider.endpoint = AIProviderDraftRules.endpoint(draft.endpoint, defaultEndpoint: draft.defaultEndpoint) - return provider - } - - // MARK: - Auth - - @ViewBuilder - private var authSection: some View { - switch draft.authStyle { - case .apiKey, .optionalApiKey: - apiKeyAuthSection - case .oauth: - switch descriptor?.oauthFlowKind { - case .deviceCode: - copilotAuthSection - case .browserRedirect: - chatGPTCodexAuthSection - case .none: - EmptyView() - } - case .none: - if draft.type == .claudeAgent { - claudeAgentAuthSection - } else { - EmptyView() - } - } - } - - @ViewBuilder - private var claudeAgentAuthSection: some View { - Section { - HStack(spacing: 8) { - AIProviderStatusLabel(status: claudeAgentStatus) - .font(.callout) - Spacer() - Button(String(localized: "Recheck")) { - claudeAgentService.refreshStatus() - } - .disabled(claudeAgentService.isRefreshing) - } - switch claudeAgentService.state { - case .signedIn(_, let plan?) where !plan.isEmpty: - Text(String(format: String(localized: "Plan: %@"), plan)) - .font(.caption) - .foregroundStyle(.secondary) - case .outdated: - Text(String(format: String(localized: "Version %@ or newer is required."), ClaudeAgentCLI.minimumVersion)) - .font(.caption) - .foregroundStyle(.secondary) - default: - EmptyView() - } - if let command = claudeAgentService.remedyCommand { - HStack { - Text(command) - .font(.system(.caption, design: .monospaced)) - .textSelection(.enabled) - Spacer() - Button(String(localized: "Copy")) { - copyToPasteboard(command) - } - } - } - } header: { - Text("Claude Code") - } footer: { - Text("Runs the claude command line tool so chat bills against your Claude subscription. Database tools need the MCP server turned on in Settings > MCP.") - .font(.caption) - .foregroundStyle(.secondary) - } - - ClaudeAgentDisclosureSection() - } - - private var claudeAgentStatus: AIProviderStatus { - AIProviderStatus.resolve( - provider: draft, - hasAPIKey: false, - oauthState: nil, - serviceError: nil, - claudeAgent: claudeAgentService.state - ) - } - - private var apiKeyAuthSection: some View { - Section { - SecureField(String(localized: "API Key"), text: $apiKey) - .onChange(of: apiKey) { _ in - scheduleFetchModels() - testResult = nil - } - HStack { - Spacer() - Button { - testProvider() - } label: { - HStack(spacing: 6) { - if isTesting { - ProgressView().controlSize(.small) - } - Text("Test Connection") - } - } - .disabled(isTesting || (draft.authStyle == .apiKey && apiKey.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)) - } - if case .success = testResult { - NoticeLabel(String(localized: "Connection successful"), severity: .success) - .font(.caption) - } else if case .failure(let message) = testResult { - NoticeLabel(message, severity: .error) - .font(.caption) - .lineLimit(3) - } - } header: { - Text("Authentication") - } - } - - private func copyToPasteboard(_ string: String) { - NSPasteboard.general.clearContents() - NSPasteboard.general.setString(string, forType: .string) - } - - private var copilotAuthSection: some View { - Section { - switch copilotService.authState { - case .signedOut: - signInRow - - case .signingIn(let userCode, _): - VStack(alignment: .leading, spacing: 8) { - Text("Enter this code on GitHub:") - Text(userCode) - .font(.system(.title2, design: .monospaced)) - .fontWeight(.bold) - .textSelection(.enabled) - Text("The code has been copied to your clipboard.") - .font(.caption) - .foregroundStyle(.secondary) - Text("The code expires in 15 minutes.") - .font(.caption) - .foregroundStyle(.secondary) - HStack(spacing: 8) { - Button("Complete Sign In") { - Task { await completeCopilotSignIn() } - } - .buttonStyle(.borderedProminent) - Button(String(localized: "Cancel"), role: .cancel) { - Task { await copilotService.signOut() } - } - } - } - - case .signedIn(let username): - HStack { - NoticeLabel(String(format: String(localized: "Signed in as %@"), username), severity: .success) - Spacer() - Button(String(localized: "Sign Out")) { - Task { await copilotService.signOut() } - } - } - } - - if let message = copilotErrorMessage ?? copilotService.statusMessage { - NoticeLabel(message, severity: .error) - .font(.caption) - } - - statusRow - } header: { - Text("Account") - } - } - - private var signInRow: some View { - HStack { - Text("Authentication required") - .foregroundStyle(.secondary) - Spacer() - Button(String(localized: "Sign in with GitHub")) { - Task { await copilotSignIn() } - } - .disabled(copilotService.status != .running) - } - } - - private var chatGPTCodexAuthSection: some View { - Section { - switch chatGPTCodexService.authState { - case .signedOut: - chatGPTCodexSignInRows - - case .signingIn: - HStack(spacing: 8) { - ProgressView().controlSize(.small) - Text("Opening your browser to sign in…") - .font(.caption) - .foregroundStyle(.secondary) - } - - case .signedIn(let email, let planType): - VStack(alignment: .leading, spacing: 6) { - HStack { - NoticeLabel(chatGPTCodexSignedInLabel(email: email), severity: .success) - Spacer() - Button(String(localized: "Sign Out")) { - Task { await chatGPTCodexService.signOut() } - } - } - if let planType, !planType.isEmpty { - Text(String(format: String(localized: "Plan: %@"), planType)) - .font(.caption) - .foregroundStyle(.secondary) - } - } - } - - if let message = chatGPTCodexService.errorMessage { - NoticeLabel(message, severity: .error) - .font(.caption) - .lineLimit(3) - } - } header: { - Text("Account") - } footer: { - Text("Access uses your ChatGPT subscription (Plus, Pro, Business, or Enterprise) and follows OpenAI's terms. This is an unofficial interface that may change.") - .font(.caption) - .foregroundStyle(.secondary) - } - } - - private var chatGPTCodexSignInRows: some View { - VStack(alignment: .leading, spacing: 8) { - HStack { - Text("Sign in to use your ChatGPT subscription") - .foregroundStyle(.secondary) - Spacer() - Button(String(localized: "Sign in with ChatGPT")) { - Task { await chatGPTCodexService.signIn() } - } - .buttonStyle(.borderedProminent) - } - Button(String(localized: "Import from Codex CLI")) { - Task { await chatGPTCodexService.importFromCodexCLI() } - } - .buttonStyle(.borderless) - .controlSize(.small) - } - } - - private func chatGPTCodexSignedInLabel(email: String) -> String { - email.isEmpty - ? String(localized: "Signed in") - : String(format: String(localized: "Signed in as %@"), email) - } - - @ViewBuilder - private var statusRow: some View { - switch copilotService.status { - case .stopped: - Label("Service stopped", systemImage: "circle") - .foregroundStyle(.secondary) - .font(.caption) - case .starting: - HStack(spacing: 6) { - ProgressView().controlSize(.small) - Text("Starting service…") - .font(.caption) - .foregroundStyle(.secondary) - } - case .running: - EmptyView() - case .error(let message): - NoticeLabel(message, severity: .error) - .font(.caption) - .lineLimit(2) - } - } - - // MARK: - Connection - - @ViewBuilder - private var connectionSection: some View { - if shouldShowConnectionSection { - Section { - if allowsNameField { - TextField(String(localized: "Name"), text: $draft.name) - .accessibilityIdentifier("ai-provider-name") - } - if allowsEndpointField { - TextField( - String(localized: "Base URL"), - text: $draft.endpoint, - prompt: Text(draft.defaultEndpoint) - ) - .accessibilityIdentifier("ai-provider-base-url") - .onChange(of: draft.endpoint) { _ in - scheduleFetchModels() - testResult = nil - } - endpointFootnote - } - } header: { - Text("Connection") - } - } - } - - /// Placeholder text disappears as soon as the field is typed in, so the rule the server's own - /// documentation follows is spelled out beside the field, and the URL it resolves to is shown - /// back rather than left to be inferred. - @ViewBuilder - private var endpointFootnote: some View { - VStack(alignment: .leading, spacing: 2) { - Text("Include the version segment your server uses, such as /v1 or /v4.") - .font(.caption) - .foregroundStyle(.secondary) - if let resolvedChatURL { - Text(resolvedChatURL) - .textSelection(.enabled) - .font(.caption) - .foregroundStyle(.secondary) - } - if resolvedEndpoint?.isPlaintextToRemoteHost == true { - NoticeLabel(cleartextCaution) - .font(.caption) - .lineLimit(2) - } - } - } - - private var modelListBlocker: AIModelListFetchGate.Blocker? { - AIProviderDraftRules.modelListBlocker(descriptor: descriptor, draft: draft, apiKey: apiKey) - } - - /// Ollama, llama.cpp, MLX and a keyless Custom server send no authorization header at all, so - /// naming the key there would warn about something that is not happening. - private var cleartextCaution: String { - guard draft.authStyle.usesAPIKey, - !apiKey.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty - else { - return String(localized: "Requests to this host are sent unencrypted over http.") - } - return String(localized: "Your API key is sent unencrypted over http to this host.") - } - - private var resolvedEndpoint: AIEndpoint? { - AIEndpoint(normalizedDraft.endpoint, style: draft.type.endpointStyle) - } - - private var resolvedChatURL: String? { - let style = draft.type.endpointStyle - guard let url = resolvedEndpoint?.chatURL(model: draft.model, style: style) else { return nil } - return url.absoluteString - } - - private var allowsNameField: Bool { - descriptor?.allowsNameConfiguration == true - } - - private var allowsEndpointField: Bool { - descriptor?.allowsEndpointConfiguration == true - } - - private var shouldShowConnectionSection: Bool { - allowsNameField || allowsEndpointField - } - - // MARK: - Model - - private var descriptor: AIProviderDescriptor? { - AIProviderRegistry.shared.descriptor(for: draft.type.rawValue) - } - - private var curatedModels: [CuratedModel] { - descriptor?.curatedModels(for: draft.preset) ?? [] - } - - private var fetchedModels: [String] { - fetched.map(\.id) - } - - private func reasoning(forModelID id: String) -> AIReasoningSupport { - descriptor?.reasoning( - forModelID: id, - fetched: fetched.first(where: { $0.id == id }), - preset: draft.preset - ) ?? .unsupported - } - - private var reasoningForCurrentModel: AIReasoningSupport { - reasoning(forModelID: draft.model) - } - - private var effortLevelsForCurrentModel: [ReasoningEffort] { - reasoningForCurrentModel.effortLevels - } - - private var showsReasoningPicker: Bool { - guard descriptor?.supportsReasoning == true else { return false } - return !effortLevelsForCurrentModel.isEmpty - } - - private var isCustomModel: Bool { - !curatedModels.contains(where: { $0.id == draft.model }) - && !fetchedModels.contains(draft.model) - } - - private var modelSection: some View { - Section { - modelPicker - if isCustomModel { - TextField(String(localized: "Model ID"), text: typedModelBinding) - .textFieldStyle(.roundedBorder) - } - if showsReasoningPicker { - reasoningPicker - } - modelFetchStatus - } header: { - Text("Model") - } - } - - private var modelPicker: some View { - Picker(String(localized: "Model"), selection: modelSelectionBinding) { - if !curatedModels.isEmpty { - Section { - ForEach(curatedModels) { model in - Text(model.displayName).tag(ModelSelection.curated(model.id)) - } - } - } - let fetchedFiltered = fetchedModels.filter { id in - !curatedModels.contains(where: { $0.id == id }) - } - if !fetchedFiltered.isEmpty { - Section { - ForEach(fetchedFiltered, id: \.self) { id in - Text(id).tag(ModelSelection.fetched(id)) - } - } - } - Text(String(localized: "Other…")).tag(ModelSelection.custom) - } - .pickerStyle(.menu) - } - - private enum ModelSelection: Hashable { - case curated(String) - case fetched(String) - case custom - } - - private var modelSelectionBinding: Binding { - Binding( - get: { - if curatedModels.contains(where: { $0.id == draft.model }) { - return .curated(draft.model) - } - if fetchedModels.contains(draft.model) { - return .fetched(draft.model) - } - return .custom - }, - set: { newValue in - switch newValue { - case .curated(let id), .fetched(let id): - choseOtherModel = false - selectModel(id, picked: true) - case .custom: - choseOtherModel = true - if curatedModels.contains(where: { $0.id == draft.model }) || fetchedModels.contains(draft.model) { - selectModel("", picked: false) - } - } - } - ) - } - - private var typedModelBinding: Binding { - Binding( - get: { draft.model }, - set: { typed in - choseOtherModel = true - selectModel(typed, picked: false) - } - ) - } - - // The model and the effort it allows change together, in one write. - private func selectModel(_ id: String, picked: Bool) { - var next = draft - next.model = id - next.reasoningEffort = picked - ? AIProviderDraftRules.effort( - afterPicking: draft.reasoningEffort, - reasoning: reasoning(forModelID: id), - curated: curatedModels.first(where: { $0.id == id }) - ) - : AIProviderDraftRules.effort(keeping: draft.reasoningEffort, reasoning: reasoning(forModelID: id)) - draft = next - } - - private var reasoningPicker: some View { - Picker(String(localized: "Reasoning"), selection: $draft.reasoningEffort) { - if !reasoningForCurrentModel.isMandatory { - Text(String(localized: "Off")).tag(ReasoningEffort?.none) - } - ForEach(effortLevelsForCurrentModel) { effort in - Text(effort.displayName).tag(Optional(effort)) - } - } - .pickerStyle(.menu) - } - - @ViewBuilder - private var modelFetchStatus: some View { - if isFetchingModels { - HStack(spacing: 6) { - ProgressView().controlSize(.small) - Text(String(localized: "Fetching models…")) - .font(.caption) - .foregroundStyle(.secondary) - } - } - if let modelFetchError { - HStack { - NoticeLabel(modelFetchError, severity: .error) - .font(.caption) - .lineLimit(2) - Spacer() - Button(String(localized: "Reload")) { - fetchModels() - } - .buttonStyle(.borderless) - .controlSize(.small) - } - } - if modelListBlocker == .missingAPIKey { - Text("Enter an API key to load this provider's models.") - .font(.caption) - .foregroundStyle(.secondary) - } - if needsModelChoice { - Text("Pick a model to save this provider.") - .font(.caption) - .foregroundStyle(.secondary) - } - } - - // MARK: - Advanced - - @ViewBuilder - private var advancedSection: some View { - if showsMaxOutputTokens || showsTelemetryToggle { - Section { - if showsMaxOutputTokens { - LabeledContent("Max output tokens") { - TextField("", text: maxOutputTokensBinding) - .frame(width: 100) - .multilineTextAlignment(.trailing) - } - } - if showsTelemetryToggle { - Toggle("Send telemetry to GitHub", isOn: $draft.telemetryEnabled) - } - } header: { - Text("Advanced") - } - } - } - - private var showsMaxOutputTokens: Bool { - descriptor?.allowsMaxOutputTokens == true - } - - private var showsTelemetryToggle: Bool { - descriptor?.showsTelemetryToggle == true - } - - private var maxOutputTokensBinding: Binding { - Binding( - get: { - guard let value = draft.maxOutputTokens else { return "" } - return String(value) - }, - set: { newValue in - let trimmed = newValue.trimmingCharacters(in: .whitespacesAndNewlines) - if trimmed.isEmpty { - draft.maxOutputTokens = nil - } else if let value = Int(trimmed), value > 0 { - draft.maxOutputTokens = value - } - } - ) - } - - // MARK: - Delete - - private func deleteSection(onDelete: @escaping () -> Void) -> some View { - Section { - Button(role: .destructive) { - showRemoveConfirmation = true - } label: { - Label(String(localized: "Remove Provider"), systemImage: "trash") - .frame(maxWidth: .infinity) - } - } - } - - // MARK: - Tasks - - private func cancelTasks() { - modelFetchTask?.cancel() - modelFetchTask = nil - testTask?.cancel() - testTask = nil - } - - private func ensureCopilotRunning() async { - await copilotService.start() - } - - private func copilotSignIn() async { - copilotErrorMessage = nil - do { - try await copilotService.signIn() - } catch { - copilotErrorMessage = error.localizedDescription - } - } - - private func completeCopilotSignIn() async { - copilotErrorMessage = nil - do { - try await copilotService.completeSignIn() - } catch { - copilotErrorMessage = error.localizedDescription - } - } - - private func commitModelList() { - let update = AIProviderDraftRules.catalogUpdate( - listIsCurrent: fetchedListIsCurrent, - listIsEmpty: fetched.isEmpty, - connectionChanged: normalizedDraft.endpoint != savedEndpoint || apiKey != savedAPIKey - ) - switch update { - case .store: - AIModelCatalog.shared.store(providerID: draft.id, models: fetched) - case .remove: - AIModelCatalog.shared.remove(providerID: draft.id) - case .refetch: - AIModelCatalog.shared.remove(providerID: draft.id) - guard descriptor?.fetchesModelList == true else { return } - let providerID = draft.id - let transport = AIProviderFactory.makeUncachedProvider(for: normalizedDraft, apiKey: apiKey) - Task { await AIModelCatalog.shared.refresh(providerID: providerID, using: transport) } - case .keep: - break - } - } - - private func scheduleFetchModels() { - fetchedListIsCurrent = false - modelFetchTask?.cancel() - modelFetchTask = Task { - try? await Task.sleep(nanoseconds: 500_000_000) - guard !Task.isCancelled else { return } - fetchModels() - } - } - - private func fetchModels() { - switch modelListBlocker { - case .notFetchable: - fetched = [] - fetchedListIsCurrent = false - modelFetchError = nil - isFetchingModels = false - selectInitialModel() - return - case .missingEndpoint, .missingAPIKey: - fetched = [] - fetchedListIsCurrent = false - modelFetchError = nil - isFetchingModels = false - return - case nil: - break - } - - let provider = AIProviderFactory.makeUncachedProvider(for: normalizedDraft, apiKey: apiKey) - isFetchingModels = true - modelFetchError = nil - - modelFetchTask?.cancel() - modelFetchTask = Task { - do { - let models = try await provider.fetchAvailableModels() - guard !Task.isCancelled else { return } - fetched = models - fetchedListIsCurrent = true - selectInitialModel() - isFetchingModels = false - } catch { - guard !Task.isCancelled else { return } - /// The list on screen was fetched with the previous key or Base URL, so it does not - /// describe the server that just failed. - fetched = [] - fetchedListIsCurrent = false - modelFetchError = error.localizedDescription - isFetchingModels = false - } - } - } - - private func selectInitialModel() { - guard draft.model.isEmpty, !choseOtherModel, - let initial = AIProviderDraftRules.initialModel(curated: curatedModels, fetched: fetched) - else { return } - selectModel(initial, picked: false) - } - - func testProvider() { - let trimmed = apiKey.trimmingCharacters(in: .whitespacesAndNewlines) - if draft.authStyle == .apiKey, trimmed.isEmpty { - testResult = .failure(String(localized: "API key is required")) - return - } - - let provider = AIProviderFactory.makeUncachedProvider(for: normalizedDraft, apiKey: apiKey) - isTesting = true - testResult = nil - - testTask?.cancel() - testTask = Task { - do { - let success = try await provider.testConnection() - guard !Task.isCancelled else { return } - isTesting = false - testResult = success - ? .success - : .failure(String(localized: "Connection test failed")) - } catch { - guard !Task.isCancelled else { return } - isTesting = false - testResult = .failure(error.localizedDescription) - } - } - } -} diff --git a/apple/TablePro/Views/Settings/AISettingsView.swift b/apple/TablePro/Views/Settings/AISettingsView.swift index 581c4a9d24..b116673348 100644 --- a/apple/TablePro/Views/Settings/AISettingsView.swift +++ b/apple/TablePro/Views/Settings/AISettingsView.swift @@ -1,21 +1,117 @@ -// -// AISettingsView.swift -// TablePro -// - import Combine import SwiftUI +// Shared by the AI root and its provider pages for the window's life: key presence, account checks, the pending removal. +@MainActor +final class AISettingsPaneModel: ObservableObject { + @Published var pendingRemoval: AIProviderConfig? + @Published private(set) var providersWithKey: Set = [] + + private var accountChecks: [AIProviderType: Date] = [:] + private let now: () -> Date + + static let accountCheckInterval: TimeInterval = 60 + + init(now: @escaping () -> Date = Date.init) { + self.now = now + } + + func hasKey(_ providerID: UUID) -> Bool { + providersWithKey.contains(providerID) + } + + func setHasKey(_ hasKey: Bool, for providerID: UUID) { + if hasKey { + providersWithKey.insert(providerID) + } else { + providersWithKey.remove(providerID) + } + } + + // No Keychain read while AI is off. + func refreshKeys(for settings: AISettings) async { + guard settings.enabled else { return } + let ids = settings.providers.filter { $0.authStyle.usesAPIKey }.map(\.id) + let found = await AIProviderKeychain.providersWithKey(ids) + if found != providersWithKey { + providersWithKey = found + } + } + + // A check spawns the claude tool or reads the ChatGPT tokens, so a revisit within a minute reuses the last answer. + func claimAccountChecks(_ types: Set) -> Set { + let current = now() + let due = types.filter { type in + guard let last = accountChecks[type] else { return true } + return current.timeIntervalSince(last) >= Self.accountCheckInterval + } + for type in due { + accountChecks[type] = current + } + return due + } + + func refreshAccounts(_ types: Set) async { + let due = claimAccountChecks(types) + guard !due.isEmpty else { return } + let chatGPT = ChatGPTCodexService.shared + let claudeAgent = ClaudeAgentService.shared + await withTaskGroup(of: Void.self) { group in + if due.contains(.chatgptCodex) { + group.addTask { await chatGPT.refreshAuthState() } + } + if due.contains(.claudeAgent) { + group.addTask { await claudeAgent.performRefresh() } + } + } + } + + func remove(_ provider: AIProviderConfig, from slice: SettingsSlice, navigation: SettingsNavigationModel) { + let id = provider.id + AIKeyStorage.shared.deleteAPIKey(for: id) + AIProviderFactory.invalidateCache(for: id) + AIModelCatalog.shared.remove(providerID: id) + slice.value = slice.value.removingProvider(id) + providersWithKey.remove(id) + navigation.removeRoute(.aiProvider(id)) + } +} + +extension View { + func aiProviderRemovalAlert( + pending: Binding, + onConfirm: @escaping (AIProviderConfig) -> Void + ) -> some View { + alert( + pending.wrappedValue.map { String(format: String(localized: "Remove “%@”?"), $0.displayName) } ?? "", + isPresented: Binding( + get: { pending.wrappedValue != nil }, + set: { if !$0 { pending.wrappedValue = nil } } + ), + presenting: pending.wrappedValue + ) { provider in + Button(String(localized: "Remove"), role: .destructive) { + pending.wrappedValue = nil + onConfirm(provider) + } + Button(String(localized: "Cancel"), role: .cancel) { + pending.wrappedValue = nil + } + } message: { provider in + Text(verbatim: provider.authStyle.usesAPIKey + ? String(localized: "Its settings are removed from every Mac that syncs settings, and its API key is deleted from the Keychain.") + : String(localized: "Its settings are removed from every Mac that syncs settings.")) + } + } +} + struct AISettingsView: View { @Binding var settings: AISettings + @ObservedObject var visit: SettingsPaneVisit - @State private var editingProviderID: UUID? - @State private var addingProvider: AIProviderConfig? - @State private var pendingDeleteID: UUID? - @ObservedObject private var chatGPTCodexService = ChatGPTCodexService.shared - @ObservedObject private var claudeAgentService = ClaudeAgentService.shared - @ObservedObject private var copilotService = CopilotService.shared - @State private var providersWithKey: Set = [] + @EnvironmentObject private var paneModel: AISettingsPaneModel + @State private var addSession: AIProviderAddSession? + @State private var appleIntelligence: AppleIntelligenceAvailability? var body: some View { Form { @@ -23,465 +119,413 @@ struct AISettingsView: View { if settings.enabled { activeProviderSection providersSection - appleIntelligenceSection + if showsAppleIntelligence { + appleIntelligenceSection + } inlineSuggestionsSection agentSection contextSection - CustomSlashCommandsSection(storage: CustomSlashCommandStorage.shared) - privacySection + Section { + SlashCommandsDrillRow(storage: CustomSlashCommandStorage.shared) + } } + privacySection } .formStyle(.grouped) - .task(id: settings.enabled ? settings.providers.map(\.id) : []) { refreshKeyAvailability() } - .task(id: AIProviderAccountProbes.types(toProbe: settings)) { - await refreshAccountStatus(of: AIProviderAccountProbes.types(toProbe: settings)) + .accessibilityElement(children: .contain) + .accessibilityIdentifier("settings-pane-ai") + .task(id: visit.count) { + appleIntelligence = SystemOnDeviceLanguageModel().availability } - .sheet(item: editingProviderBinding) { provider in - AIProviderDetailSheet( - provider: provider, - initialAPIKey: AIKeyStorage.shared.loadAPIKey(for: provider.id) ?? "", - isNew: false, - onSave: { saved, apiKey in - saveProvider(saved, apiKey: apiKey, isNew: false) - editingProviderID = nil - }, - // The sheet already asked; the parent alert is for the context menu only. - onDelete: { - removeProvider(provider.id) - editingProviderID = nil - }, - onCancel: { - editingProviderID = nil - } - ) + .task(id: KeyRefresh(visit: visit.count, enabled: settings.enabled, providerIDs: settings.providers.map(\.id))) { + await paneModel.refreshKeys(for: settings) } - .sheet(item: $addingProvider) { provider in - AIProviderDetailSheet( - provider: provider, - initialAPIKey: "", - isNew: true, - onSave: { saved, apiKey in - saveProvider(saved, apiKey: apiKey, isNew: true) - addingProvider = nil - }, - onDelete: nil, - onCancel: { - addingProvider = nil - } - ) + .task(id: AccountRefresh(visit: visit.count, types: AIProviderAccountProbes.types(toProbe: settings))) { + await paneModel.refreshAccounts(AIProviderAccountProbes.types(toProbe: settings)) } - .alert(deleteAlertTitle, isPresented: deleteAlertBinding) { - Button(String(localized: "Remove"), role: .destructive) { - if let id = pendingDeleteID { - removeProvider(id) - } - pendingDeleteID = nil - } - Button(String(localized: "Cancel"), role: .cancel) { - pendingDeleteID = nil + .sheet(item: $addSession) { session in + AIProviderAddSheet(session: session) { provider, hasKey in + settings = settings.upserting(provider, makeActiveIfNone: true) + paneModel.setHasKey(hasKey, for: provider.id) } - } message: { - Text(String(localized: "The API key will be permanently deleted.")) } } - // MARK: - Enable + private struct KeyRefresh: Equatable { + let visit: Int + let enabled: Bool + let providerIDs: [UUID] + } + + private struct AccountRefresh: Equatable { + let visit: Int + let types: Set + } private var enableSection: some View { Section { - Toggle("Enable AI Features", isOn: $settings.enabled) + Toggle(isOn: $settings.enabled) { + Text("Enable AI features") + Text("Chat, Agent mode, inline suggestions and query actions such as Explain and Optimize.") + } + .accessibilityIdentifier("settings-ai-enabled") } } - // MARK: - Active Provider - private var activeProviderSection: some View { Section { - Picker("Active Provider", selection: $settings.activeProviderID) { + Picker(selection: activeProviderBinding) { Text("None").tag(UUID?.none) ForEach(settings.providers) { provider in Label { - Text(provider.displayName) + Text(verbatim: provider.displayName) } icon: { provider.icon.menuImage() } .labelStyle(.titleAndIcon) .tag(UUID?.some(provider.id)) } + } label: { + Text("Active provider") } .pickerStyle(.menu) .disabled(settings.providers.isEmpty) + .accessibilityIdentifier("settings-ai-active-provider") } } - // MARK: - Providers + // An id whose provider another Mac removed reads as None, the provider that answers. + private var activeProviderBinding: Binding { + let settings = $settings + return Binding( + get: { settings.wrappedValue.activeProvider?.id }, + set: { settings.wrappedValue.activeProviderID = $0 } + ) + } private var providersSection: some View { Section { if settings.providers.isEmpty { - emptyProvidersRow + VStack(alignment: .leading, spacing: 2) { + Text("No providers") + Text("Add one to use chat and Agent mode.") + .font(.subheadline) + .foregroundStyle(.secondary) + } + .accessibilityElement(children: .combine) } else { ForEach(settings.providers) { provider in - Button { - editingProviderID = provider.id - } label: { - providerRow(provider) - } - .buttonStyle(.plain) - .contentShape(Rectangle()) - .contextMenu { - Button(String(localized: "Edit")) { - editingProviderID = provider.id - } - Button(String(localized: "Set as Active")) { - settings.activeProviderID = provider.id - } - .disabled(settings.activeProviderID == provider.id) - Divider() - Button(String(localized: "Remove"), role: .destructive) { - pendingDeleteID = provider.id - } - } + providerLink(provider) } } - addProviderMenu } header: { Text("Providers") + } footer: { + SettingsSectionActions { + AIProviderAddMenuButton { choice in + let registry = AIProviderRegistry.shared + addSession = AIProviderAddSession( + provider: choice.makeProvider { registry.descriptor(for: $0.rawValue) } + ) + } + } } } - private var emptyProvidersRow: some View { - HStack { - Spacer() - Text("No providers configured") - .foregroundStyle(.secondary) - .font(.callout) - Spacer() + private func providerLink(_ provider: AIProviderConfig) -> some View { + let isActive = provider.id == settings.activeProvider?.id + return NavigationLink(value: SettingsRoute.aiProvider(provider.id)) { + AIProviderRow(provider: provider, isActive: isActive, hasKey: paneModel.hasKey(provider.id)) } - .padding(.vertical, 6) - } - - private func providerRow(_ provider: AIProviderConfig) -> some View { - HStack(spacing: 10) { - ZStack { - if provider.id == settings.activeProviderID { - Image(systemName: "checkmark") - .font(.caption.bold()) - .foregroundStyle(Color.accentColor) - .accessibilityLabel(String(localized: "Active")) - } + .contextMenu { + Button(String(localized: "Set as Active")) { + settings.activeProviderID = provider.id } - .frame(width: 14) - - BrandIconView(icon: provider.icon) - .foregroundStyle(.secondary) - .frame(width: 16, height: 16) - .frame(width: 20) - - VStack(alignment: .leading, spacing: 2) { - Text(provider.displayName) - .fontWeight(.regular) - AIProviderStatusLabel(status: status(for: provider), showsReadySymbol: false) - .font(.caption) + .disabled(isActive) + Divider() + Button(String(localized: "Remove…"), role: .destructive) { + paneModel.pendingRemoval = provider } - - Spacer() - - Image(systemName: "chevron.right") - .font(.caption) - .foregroundStyle(.tertiary) - } - .padding(.vertical, 2) - .task { - // Sign-in state lives in the language server, so a configured Copilot row has nothing - // true to show until it runs. - guard provider.type == .copilot else { return } - await copilotService.start() } - } - - private var addProviderMenu: some View { - Menu { - ForEach(orderedAddableTypes, id: \.self) { type in - Button { - addingProvider = makeNewProvider(type: type) - } label: { - Label { - Text(type.displayName) - } icon: { - type.icon.menuImage() - } - .labelStyle(.titleAndIcon) + .accessibilityActions { + if !isActive { + Button(String(localized: "Set as Active")) { + settings.activeProviderID = provider.id } } - ForEach(AIProviderPreset.all) { preset in - Button { - addingProvider = AIProviderConfig(preset: preset) - } label: { - Label { - Text(preset.displayName) - } icon: { - preset.icon.menuImage() - } - .labelStyle(.titleAndIcon) - } - } - Divider() - Button { - addingProvider = makeNewProvider(type: .custom) - } label: { - Label(String(localized: "Add Custom Provider…"), systemImage: AIProviderType.custom.icon.fallbackSystemImage) - .labelStyle(.titleAndIcon) + Button(String(localized: "Remove")) { + paneModel.pendingRemoval = provider } - } label: { - Label(String(localized: "Add Provider…"), systemImage: "plus") } - .menuStyle(.button) - .buttonStyle(.borderless) - .fixedSize() + .accessibilityIdentifier("settings-ai-provider-\(provider.id.uuidString)") } - private var orderedAddableTypes: [AIProviderType] { - AIProviderType.allCases.filter { type in - type != .custom && AIProviderRegistry.shared.descriptor(for: type.rawValue) != nil + private var showsAppleIntelligence: Bool { + if settings.useAppleIntelligence { return true } + switch appleIntelligence { + case nil, .unavailable(.requiresNewerMacOS), .unavailable(.deviceNotEligible): + return false + default: + return true } } - // MARK: - Apple Intelligence - private var appleIntelligenceSection: some View { - let availability = SystemOnDeviceLanguageModel().availability - return Section { - Toggle("Use for inline suggestions and query actions", isOn: $settings.useAppleIntelligence) - .disabled(!availability.isAvailable && !settings.useAppleIntelligence) + Section { + Toggle(isOn: $settings.useAppleIntelligence) { + Text("Use for inline suggestions and query actions") + if let appleIntelligence { + Text(verbatim: appleIntelligence.unavailableExplanation + ?? String(localized: "Runs on this Mac and sends nothing over the network. Chat and Agent mode keep the active provider.")) + } + } + .disabled(appleIntelligence?.isAvailable == false && !settings.useAppleIntelligence) + .accessibilityIdentifier("settings-ai-apple-intelligence") } header: { - Text(AppleIntelligenceAvailability.displayName) - } footer: { - Text(Self.appleIntelligenceFooter(availability)) - .font(.caption) - .foregroundStyle(.secondary) + Text(verbatim: AppleIntelligenceAvailability.displayName) } } - private static func appleIntelligenceFooter(_ availability: AppleIntelligenceAvailability) -> String { - if let unavailable = availability.unavailableExplanation { return unavailable } - return String(localized: "Inline suggestions and Review, Explain, Optimize and Fix run on this Mac and send nothing over the network.") - + " " + String(localized: "The chat and Agent mode keep the active provider.") - } - - // MARK: - Inline Suggestions - private var canSuggestInline: Bool { settings.hasActiveProvider || settings.useAppleIntelligence } private var inlineSuggestionsSection: some View { Section { - Toggle("Enable inline suggestions while typing", isOn: $settings.inlineSuggestionsEnabled) - .disabled(!canSuggestInline) - .help(canSuggestInline - ? "" - : String(localized: "Configure an active provider or turn on Apple Intelligence to enable inline suggestions.")) - Stepper( - String(format: String(localized: "Debounce: %d ms"), settings.inlineSuggestionDebounceMs), - value: $settings.inlineSuggestionDebounceMs, - in: AISettings.inlineSuggestionDebounceRange, - step: 50 + Toggle(isOn: $settings.inlineSuggestionsEnabled) { + Text("Suggest SQL while typing") + if canSuggestInline { + Text("Press Tab to accept, Escape to dismiss.") + } else { + Text("Choose an active provider or turn on Apple Intelligence first.") + } + } + .disabled(!canSuggestInline && !settings.inlineSuggestionsEnabled) + .accessibilityIdentifier("settings-ai-inline") + + SettingsNumberField( + "Delay", + value: debounceBinding, + range: AISettings.inlineSuggestionDebounceRange, + step: 50, + unit: "ms", + identifier: "settings-ai-inline-delay" ) .disabled(!settings.inlineSuggestionsEnabled) } header: { Text("Inline Suggestions") - } footer: { - Text("Inline SQL suggestions appear as you type. Press Tab to accept, Escape to dismiss.") - .font(.caption) - .foregroundStyle(.secondary) } } - // MARK: - Agent + private var debounceBinding: Binding { + let settings = $settings + return Binding( + get: { settings.wrappedValue.clampedInlineSuggestionDebounceMs }, + set: { settings.wrappedValue.inlineSuggestionDebounceMs = $0 } + ) + } private var agentSection: some View { Section { - Toggle("Limit tool calls per reply", isOn: $settings.maxToolRoundtripsEnabled) - Stepper( - String(format: String(localized: "Tool call limit: %d"), settings.maxToolRoundtrips), - value: $settings.maxToolRoundtrips, - in: AISettings.maxToolRoundtripsRange, - step: 5 + Toggle(isOn: $settings.maxToolRoundtripsEnabled) { + Text("Limit tool calls per reply") + Text("Agent mode pauses at the limit so you can continue. A higher limit uses more tokens per reply.") + } + .accessibilityIdentifier("settings-ai-tool-limit-enabled") + + SettingsNumberField( + "Tool call limit", + value: toolLimitBinding, + range: AISettings.maxToolRoundtripsRange, + step: 5, + identifier: "settings-ai-tool-limit" ) .disabled(!settings.maxToolRoundtripsEnabled) } header: { Text("Agent") - } footer: { - Text("Agent mode calls tools in a loop until it finishes or hits this limit, then pauses so you can continue. Raising it costs more tokens per reply.") - .font(.caption) - .foregroundStyle(.secondary) } } - // MARK: - Context + private var toolLimitBinding: Binding { + let settings = $settings + return Binding( + get: { settings.wrappedValue.clampedMaxToolRoundtrips }, + set: { settings.wrappedValue.maxToolRoundtrips = $0 } + ) + } private var contextSection: some View { Section { Toggle("Include database schema", isOn: $settings.includeSchema) + .accessibilityIdentifier("settings-ai-include-schema") + SettingsNumberField( + "Maximum tables", + subtitle: "Used for chat context, {{schema}} commands and Copilot suggestions.", + value: maxTablesBinding, + range: AISettings.maxSchemaTablesRange, + step: 1, + identifier: "settings-ai-max-tables" + ) Toggle("Include current query", isOn: $settings.includeCurrentQuery) + .accessibilityIdentifier("settings-ai-include-query") Toggle("Include query results", isOn: $settings.includeQueryResults) - Stepper( - String(format: String(localized: "Max schema tables: %d"), settings.maxSchemaTables), - value: $settings.maxSchemaTables, - in: 1...100 - ) + .accessibilityIdentifier("settings-ai-include-results") } header: { Text("Context") } } - // MARK: - Privacy + private var maxTablesBinding: Binding { + let settings = $settings + return Binding( + get: { settings.wrappedValue.clampedMaxSchemaTables }, + set: { settings.wrappedValue.maxSchemaTables = $0 } + ) + } + // Shown with AI off too: MCP clients read the same policy. private var privacySection: some View { Section { - Picker("Connection policy", selection: $settings.defaultConnectionPolicy) { + Picker(selection: $settings.defaultConnectionPolicy) { ForEach(AIConnectionPolicy.allCases) { policy in - Text(policy.displayName).tag(policy) + Text(verbatim: policy.displayName).tag(policy) } + } label: { + Text("Default AI policy") + Text("Applies to connections set to Use Default, in AI features and for MCP clients.") } .pickerStyle(.menu) + .accessibilityIdentifier("settings-ai-connection-access") } header: { Text("Privacy") } } +} - // MARK: - Bindings +private struct SlashCommandsDrillRow: View { + @ObservedObject var storage: CustomSlashCommandStorage - private var editingProviderBinding: Binding { - Binding( - get: { - guard let id = editingProviderID else { return nil } - return settings.providers.first(where: { $0.id == id }) - }, - set: { newValue in - editingProviderID = newValue?.id - } + var body: some View { + SettingsDrillRow( + route: SettingsRoute.page(.slashCommands), + title: SettingsPage.slashCommands.title, + value: SettingsFormat.count(storage.commands.count) ) } +} - private var deleteAlertBinding: Binding { - Binding( - get: { pendingDeleteID != nil }, - set: { isPresented in - if !isPresented { - pendingDeleteID = nil - } - } - ) - } +// Each row observes only the service its own status comes from, and starts nothing. +private struct AIProviderRow: View { + let provider: AIProviderConfig + let isActive: Bool + let hasKey: Bool - private var deleteAlertTitle: String { - guard let id = pendingDeleteID, - let provider = settings.providers.first(where: { $0.id == id }) else { - return String(localized: "Remove Provider?") + var body: some View { + HStack(spacing: 10) { + BrandIconView(icon: provider.icon) + .foregroundStyle(.secondary) + .frame(width: 20, height: 20) + .frame(width: 24, height: 24) + VStack(alignment: .leading, spacing: 2) { + Text(verbatim: provider.displayName) + AIProviderRowStatus(provider: provider, hasKey: hasKey) + .font(.subheadline) + } + Spacer(minLength: 8) + if isActive { + Text("Active") + .foregroundStyle(.secondary) + } } - return String(format: String(localized: "Remove %@?"), provider.displayName) - } - - // MARK: - Status - - private func status(for provider: AIProviderConfig) -> AIProviderStatus { - AIProviderStatus.resolve( - provider: provider, - hasAPIKey: providersWithKey.contains(provider.id), - oauthState: oauthState(for: provider.type), - serviceError: serviceError(for: provider.type), - claudeAgent: claudeAgentService.state - ) + .accessibilityElement(children: .combine) } +} - // Copilot's sign-in is known only once its language server answers, which this row starts. A - // server stopped after it answered keeps the state it reported. - private func oauthState(for type: AIProviderType) -> OAuthAuthState? { - if type == .copilot, copilotService.status == .starting { return nil } - return OAuthProviderRegistry.service(for: type)?.oauthState - } +private struct AIProviderRowStatus: View { + let provider: AIProviderConfig + let hasKey: Bool - private func serviceError(for type: AIProviderType) -> String? { - switch type { + var body: some View { + switch provider.type { case .copilot: - if case .error(let message) = copilotService.status { return message } - return copilotService.statusMessage + CopilotRowStatus(provider: provider) case .chatgptCodex: - return chatGPTCodexService.errorMessage + ChatGPTRowStatus(provider: provider) + case .claudeAgent: + ClaudeAgentRowStatus(provider: provider) default: - return nil + AIProviderStatusLabel( + status: AIProviderStatus.resolve( + provider: provider, + hasAPIKey: hasKey, + oauthState: nil, + serviceError: nil, + claudeAgent: .unknown + ), + showsReadySymbol: false + ) } } +} - private func refreshAccountStatus(of types: Set) async { - let chatGPT = chatGPTCodexService - let claudeAgent = claudeAgentService - await withTaskGroup(of: Void.self) { group in - if types.contains(.chatgptCodex) { - group.addTask { await chatGPT.refreshAuthState() } - } - if types.contains(.claudeAgent) { - group.addTask { await claudeAgent.performRefresh() } - } - } +private struct CopilotRowStatus: View { + let provider: AIProviderConfig + @ObservedObject private var copilot = CopilotService.shared + + var body: some View { + AIProviderStatusLabel(status: status, showsReadySymbol: false) } - private func refreshKeyAvailability() { - guard settings.enabled else { return } - var ids: Set = [] - for provider in settings.providers where provider.authStyle.usesAPIKey { - if let key = AIKeyStorage.shared.loadAPIKey(for: provider.id), !key.isEmpty { - ids.insert(provider.id) - } + // The sign-in is known only once the language server answers; a server stopped after that keeps its answer. + private var status: AIProviderStatus { + var serviceError = copilot.statusMessage + if case .error(let message) = copilot.status { + serviceError = message } - providersWithKey = ids + let reported = copilot.hasReportedAuthState && copilot.status != .starting + return AIProviderStatus.resolve( + provider: provider, + hasAPIKey: false, + oauthState: reported ? copilot.oauthState : nil, + serviceError: serviceError, + claudeAgent: .unknown, + serviceStopped: copilot.status == .stopped + ) } +} - // MARK: - Mutations +private struct ChatGPTRowStatus: View { + let provider: AIProviderConfig + @ObservedObject private var service = ChatGPTCodexService.shared - private func makeNewProvider(type: AIProviderType) -> AIProviderConfig { - let descriptor = AIProviderRegistry.shared.descriptor(for: type.rawValue) - return AIProviderConfig( - id: UUID(), - name: "", - type: type, - model: "", - endpoint: type.defaultEndpoint, - maxOutputTokens: nil, - telemetryEnabled: descriptor?.defaultTelemetryEnabled ?? false + var body: some View { + AIProviderStatusLabel( + status: AIProviderStatus.resolve( + provider: provider, + hasAPIKey: false, + oauthState: service.oauthState, + serviceError: service.errorMessage, + claudeAgent: .unknown + ), + showsReadySymbol: false ) } +} - private func saveProvider(_ provider: AIProviderConfig, apiKey: String, isNew: Bool) { - if provider.authStyle.usesAPIKey { - AIKeyStorage.shared.saveAPIKey(apiKey, for: provider.id) - } - - if let index = settings.providers.firstIndex(where: { $0.id == provider.id }) { - settings.providers[index] = provider - } else { - settings.providers.append(provider) - } - - AIProviderFactory.invalidateCache(for: provider.id) - refreshKeyAvailability() - - if isNew, settings.activeProviderID == nil { - settings.activeProviderID = provider.id - } - AppEvents.shared.aiProviderSaved.send(provider.id) - } +private struct ClaudeAgentRowStatus: View { + let provider: AIProviderConfig + @ObservedObject private var service = ClaudeAgentService.shared - private func removeProvider(_ id: UUID) { - AIKeyStorage.shared.deleteAPIKey(for: id) - AIProviderFactory.invalidateCache(for: id) - AIModelCatalog.shared.remove(providerID: id) - settings.providers.removeAll { $0.id == id } - if settings.activeProviderID == id { - settings.activeProviderID = nil - } - refreshKeyAvailability() + var body: some View { + AIProviderStatusLabel( + status: AIProviderStatus.resolve( + provider: provider, + hasAPIKey: false, + oauthState: nil, + serviceError: nil, + claudeAgent: service.state + ), + showsReadySymbol: false + ) } } diff --git a/apple/TablePro/Views/Settings/Account/AccountFeaturesSection.swift b/apple/TablePro/Views/Settings/Account/AccountFeaturesSection.swift index 1f77c0c5bc..3f73a68183 100644 --- a/apple/TablePro/Views/Settings/Account/AccountFeaturesSection.swift +++ b/apple/TablePro/Views/Settings/Account/AccountFeaturesSection.swift @@ -1,32 +1,48 @@ -// -// AccountFeaturesSection.swift -// TablePro -// - import SwiftUI -struct AccountFeaturesSection: View { +internal struct AccountFeaturesPage: View { @ObservedObject var access: FeatureAccess - let offersPurchase: Bool + + private var offersPurchase: Bool { + !access.state.isSignedIn && access.state.entitlement == nil && access.state.legacy == nil + } var body: some View { - Section { - ForEach(ProFeature.allCases, id: \.self) { feature in - AccountFeatureRow(feature: feature, isIncluded: access.isAvailable(feature)) + Form { + Section { + ForEach(ProFeature.allCases, id: \.self) { feature in + AccountFeatureRow(feature: feature, isIncluded: access.isAvailable(feature)) + } } - } header: { - Text("Features") - } footer: { - HStack(spacing: 16) { + + Section { if offersPurchase { - Link("Buy a License", destination: SupportLinks.pricing(.licenseSettings)) - .countsUpgradeClicks(from: .licenseSettings) + LabeledContent { + Link(String(localized: "View Plans…"), destination: SupportLinks.pricing(.licenseSettings)) + .buttonStyle(.bordered) + .fixedSize() + .countsUpgradeClicks(from: .licenseSettings) + .accessibilityIdentifier("account-view-plans") + } label: { + Text("Paid plans") + Text("Compare what each plan includes.") + } } - Link("Learn More About Licensing", destination: SupportLinks.licensingGuide) + LabeledContent { + Link(String(localized: "Learn More…"), destination: SupportLinks.licensingGuide) + .buttonStyle(.bordered) + .fixedSize() + .accessibilityIdentifier("account-licensing-guide") + } label: { + Text("Plans and devices") + Text("How plans, devices and offline files work.") + } } - .font(.callout) } + .formStyle(.grouped) + .accessibilityElement(children: .contain) + .accessibilityIdentifier(SettingsPage.accountFeatures.pageIdentifier) } } @@ -45,12 +61,12 @@ private struct AccountFeatureRow: View { Text(feature.displayName) Text(feature.featureDescription) - .font(.callout) + .font(.subheadline) .foregroundStyle(.secondary) .fixedSize(horizontal: false, vertical: true) } - Spacer() + Spacer(minLength: 12) if isIncluded { Label { @@ -60,13 +76,18 @@ private struct AccountFeatureRow: View { Image(systemName: "checkmark.circle.fill") .foregroundStyle(.green) } + .fixedSize() } else { - Image(systemName: "lock.fill") - .foregroundStyle(.secondary) - .accessibilityLabel(Text(feature.paidPlanRequirement)) + Label { + Text("Not included") + } icon: { + Image(systemName: "lock.fill") + } + .foregroundStyle(.secondary) + .fixedSize() + .accessibilityLabel(Text(feature.paidPlanRequirement)) } } - .padding(.vertical, 2) .accessibilityElement(children: .combine) } } diff --git a/apple/TablePro/Views/Settings/Account/AccountSettingsContent.swift b/apple/TablePro/Views/Settings/Account/AccountSettingsContent.swift index b0d4029775..f94d98fa95 100644 --- a/apple/TablePro/Views/Settings/Account/AccountSettingsContent.swift +++ b/apple/TablePro/Views/Settings/Account/AccountSettingsContent.swift @@ -1,8 +1,3 @@ -// -// AccountSettingsContent.swift -// TablePro -// - import Foundation // What Settings > Account shows for one account state (clients.md, Settings > Account). @@ -81,6 +76,14 @@ internal struct AccountSettingsContent: Equatable { let isExpired: Bool } + enum VerificationState: Equatable { + case verified(at: Date, until: Date) + case offlineFile(until: Date) + case expired(on: Date) + case offlineFileExpired(on: Date) + case notVerified + } + static let expiryWarning: TimeInterval = 3 * 24 * 60 * 60 let identity: Identity @@ -89,6 +92,7 @@ internal struct AccountSettingsContent: Equatable { let plans: [PlanRow] let isFree: Bool let showsDevices: Bool + let showsTeams: Bool let devices: [DeviceRow]? let teams: [TeamRow]? let verification: Verification? @@ -119,6 +123,7 @@ internal struct AccountSettingsContent: Equatable { plans: plans, isFree: showsPlan && !isDeviceLimit && entitlement != nil && plans.isEmpty, showsDevices: state.isSignedIn, + showsTeams: state.isSignedIn, devices: state.isSignedIn ? devices.map { deviceRows($0, machineID: machineID, now: now) } : nil, teams: state.isSignedIn ? profile.map { teamRows($0, configuration: configuration) } : nil, verification: entitlement.map { @@ -134,6 +139,21 @@ internal struct AccountSettingsContent: Equatable { ) } + var verificationState: VerificationState? { + guard let verification else { return canRefresh ? .notVerified : nil } + switch (verification.isOfflineFile, verification.isExpired) { + case (false, false): return .verified(at: verification.verifiedAt, until: verification.validUntil) + case (true, false): return .offlineFile(until: verification.validUntil) + case (false, true): return .expired(on: verification.validUntil) + case (true, true): return .offlineFileExpired(on: verification.validUntil) + } + } + + // A notice with Try Again already runs the check the verification row's Refresh would. + var offersRetry: Bool { + notices.contains { LicensePresentation.action(for: $0) == .retryValidation } + } + // Without GET /v2/me, so a team plan's payment notice offers no billing link here. static func notices(state: AccountState, configuration: AccountConfiguration, now: Date) -> [Notice] { let isDeviceLimit = state.refresh.isDeviceLimit @@ -268,6 +288,12 @@ internal struct AccountSettingsContent: Equatable { // The pane, the gates and Welcome read a state in the same words. extension AccountSettingsContent.Notice { + // A canceling plan is the person's own choice, so it informs rather than warns. + var isInformational: Bool { + if case .canceling = self { return true } + return false + } + var title: String { switch self { case .deviceLimit: diff --git a/apple/TablePro/Views/Settings/Account/AccountSettingsModel.swift b/apple/TablePro/Views/Settings/Account/AccountSettingsModel.swift index 5cbc081119..a43d572399 100644 --- a/apple/TablePro/Views/Settings/Account/AccountSettingsModel.swift +++ b/apple/TablePro/Views/Settings/Account/AccountSettingsModel.swift @@ -1,10 +1,6 @@ -// -// AccountSettingsModel.swift -// TablePro -// - import Combine import Foundation +import TableProHTTP internal struct AccountRemote: Equatable { var value: Value? @@ -19,6 +15,26 @@ internal struct AccountActionFailure: Equatable, Identifiable { var id: String { title + message } } +internal struct AccountSignOutConfirmation: Equatable { + let discardsTeamChanges: Bool + let removesOfflineFile: Bool + + var discardsSomething: Bool { + discardsTeamChanges || removesOfflineFile + } + + var message: String { + var sentences = [String(localized: "Paid features stop on this Mac until you sign in again.")] + if discardsTeamChanges { + sentences.append(String(localized: "Team library changes that were not sent yet are discarded.")) + } + if removesOfflineFile { + sentences.append(String(localized: "The imported offline file is removed.")) + } + return sentences.joined(separator: " ") + } +} + @MainActor internal final class AccountSettingsModel: ObservableObject { enum Activity: Equatable { @@ -30,6 +46,20 @@ internal final class AccountSettingsModel: ObservableObject { case usingKey } + struct Loader { + var profile: @MainActor () async throws(AccountError) -> AccountProfile + var devices: @MainActor () async throws(AccountError) -> [AccountDevice] + + static func live(_ services: AccountServices) -> Loader { + Loader( + profile: { () async throws(AccountError) -> AccountProfile in try await services.fetchProfile() }, + devices: { () async throws(AccountError) -> [AccountDevice] in try await services.fetchDevices() } + ) + } + } + + static let freshness: TimeInterval = 60 + @Published private(set) var profile = AccountRemote() @Published private(set) var devices = AccountRemote<[AccountDevice]>() @Published private(set) var activity: Activity? @@ -40,15 +70,34 @@ internal final class AccountSettingsModel: ObservableObject { // Read once when the sheet opens, not on every render: it comes from the Keychain. @Published private(set) var licenseKeyPrefill: String? @Published var presentsOfflineImporter = false + @Published var pendingRemoval: AccountSettingsContent.DeviceRow? + // Taken when Sign Out… is clicked, so the dialog names what this Mac held at that moment. + @Published private(set) var signOutConfirmation: AccountSignOutConfirmation? let services: AccountServices + private let loader: Loader private let now: () -> Date + private let openURL: @MainActor (URL) -> Void + private let hasUnsentTeamChanges: @MainActor () -> Bool private var stateObserver: AnyCancellable? private var loadedSignedIn: Bool? + // Bumped when the loaded data is dropped, so a load still out for the old account lands nowhere. + private var generation = 0 + private var lastLoad: Date? + private var returnsFromPortal = false - init(services: AccountServices, now: @escaping () -> Date = { Date() }) { + init( + services: AccountServices, + loader: Loader? = nil, + now: @escaping () -> Date = { Date() }, + openURL: @escaping @MainActor (URL) -> Void = { _ = WebPageOpener.open($0, scope: .httpsOrLoopbackHTTP) }, + hasUnsentTeamChanges: @escaping @MainActor () -> Bool = { TeamLibrarySync.shared.hasUnsentChanges } + ) { self.services = services + self.loader = loader ?? .live(services) self.now = now + self.openURL = openURL + self.hasUnsentTeamChanges = hasUnsentTeamChanges stateObserver = services.access.$state .dropFirst() .sink { [weak self] state in @@ -80,6 +129,29 @@ internal final class AccountSettingsModel: ObservableObject { activity != nil } + var confirmsSignOut: Bool { + signOutConfirmation != nil + } + + // Every show of the pane and every return to the window: a portal visit may have changed the account. + func refreshOnVisit() async { + guard returnsFromPortal else { + await reloadIfStale() + return + } + returnsFromPortal = false + await services.checkNow() + await reload() + } + + func reloadIfStale() async { + if services.access.state.isSignedIn == loadedSignedIn, let lastLoad, + now().timeIntervalSince(lastLoad) < Self.freshness { + return + } + await reload() + } + // Keeps what it loaded before when a load fails; a sign-in or sign-out drops it first. func reload() async { let isSignedIn = services.access.state.isSignedIn @@ -88,32 +160,55 @@ internal final class AccountSettingsModel: ObservableObject { loadedSignedIn = isSignedIn } guard isSignedIn else { return } - async let profileLoad: Void = loadProfile() - async let devicesLoad: Void = loadDevices() - _ = await (profileLoad, devicesLoad) + let started = generation + async let profileLoad = loadProfile() + async let devicesLoad = loadDevices() + let (profileLoaded, devicesLoaded) = await (profileLoad, devicesLoad) + guard started == generation, profileLoaded, devicesLoaded else { return } + lastLoad = now() } - func loadProfile() async { - if profile.value == nil { - profile.isLoading = true - } + @discardableResult + func loadProfile() async -> Bool { + let started = generation + profile.isLoading = true do throws(AccountError) { - profile = AccountRemote(value: try await services.fetchProfile()) + let value = try await loader.profile() + guard started == generation else { return false } + profile = AccountRemote(value: value) + return true + } catch .canceled { + if started == generation { + profile.isLoading = false + } + return false } catch { + guard started == generation else { return false } profile.isLoading = false profile.failure = error.friendlyDescription ?? String(localized: "Could not load your teams.") + return false } } - func loadDevices() async { - if devices.value == nil { - devices.isLoading = true - } + @discardableResult + func loadDevices() async -> Bool { + let started = generation + devices.isLoading = true do throws(AccountError) { - devices = AccountRemote(value: try await services.fetchDevices()) + let value = try await loader.devices() + guard started == generation else { return false } + devices = AccountRemote(value: value) + return true + } catch .canceled { + if started == generation { + devices.isLoading = false + } + return false } catch { + guard started == generation else { return false } devices.isLoading = false devices.failure = error.friendlyDescription ?? String(localized: "Could not load your devices.") + return false } } @@ -130,7 +225,19 @@ internal final class AccountSettingsModel: ObservableObject { presentDeviceLimitIfReached() } + func requestSignOut() { + signOutConfirmation = AccountSignOutConfirmation( + discardsTeamChanges: hasUnsentTeamChanges(), + removesOfflineFile: services.access.state.entitlement?.isOffline == true + ) + } + + func cancelSignOut() { + signOutConfirmation = nil + } + func signOut() async { + signOutConfirmation = nil activity = .signingOut defer { activity = nil } await services.signOut() @@ -143,7 +250,14 @@ internal final class AccountSettingsModel: ObservableObject { await reload() } + // The next return to the window checks the account again: billing, devices and teams change in the portal. + func openPortal(_ url: URL) { + returnsFromPortal = true + openURL(url) + } + func removeDevice(_ device: AccountSettingsContent.DeviceRow) async { + pendingRemoval = nil activity = .removing(device.id) defer { activity = nil } do throws(AccountError) { @@ -171,20 +285,30 @@ internal final class AccountSettingsModel: ObservableObject { } } - // Nil when the key signed this Mac in; the message to show beside the key otherwise. + func offlineFilePickerFailed(_ error: any Error) { + actionFailure = AccountActionFailure( + title: String(localized: "Could not import the offline file"), + message: error.localizedDescription + ) + } + + // Nil when the key signed this Mac in or the exchange was canceled; the message to show beside the key otherwise. func useLicenseKey(_ key: String) async -> String? { activity = .usingKey defer { activity = nil } do throws(AccountError) { _ = try await services.useLicenseKey(key) + } catch .canceled { + return nil } catch { return error.licenseKeyDescription ?? String(localized: "Could not use this license key.") } presentsLicenseKey = false presentDeviceLimitIfReached() - // The key may belong to another account than the one signed in before. + // The key may belong to another account than the one signed in before. The sheet closing cancels its own + // task, so the reload runs outside it. forgetLoaded() - await reload() + Task { await reload() } return nil } @@ -200,6 +324,8 @@ internal final class AccountSettingsModel: ObservableObject { } private func forgetLoaded() { + generation += 1 + lastLoad = nil profile = AccountRemote() devices = AccountRemote() } diff --git a/apple/TablePro/Views/Settings/Account/AccountSettingsView.swift b/apple/TablePro/Views/Settings/Account/AccountSettingsView.swift index 51a2de5c4f..f59961f1c7 100644 --- a/apple/TablePro/Views/Settings/Account/AccountSettingsView.swift +++ b/apple/TablePro/Views/Settings/Account/AccountSettingsView.swift @@ -1,412 +1,331 @@ -// -// AccountSettingsView.swift -// TablePro -// - import SwiftUI -import UniformTypeIdentifiers -// Settings > Account (clients.md): Account, Plan, Features, Devices, Teams, Offline. +// Settings > Account (clients.md): identity, Plan, then the Features, Devices, Teams and Offline File pages. internal struct AccountSettingsView: View { - @StateObject private var model: AccountSettingsModel - @Environment(\.openURL) private var openURL - @State private var pendingRemoval: AccountSettingsContent.DeviceRow? - - init(model: @autoclosure @escaping () -> AccountSettingsModel) { - _model = StateObject(wrappedValue: model()) - } + @ObservedObject var model: AccountSettingsModel + let showDevices: () -> Void var body: some View { let content = model.content Form { - AccountIdentitySection(model: model, identity: content.identity) + AccountIdentitySection(model: model, identity: content.identity, canRefresh: content.canRefresh) if content.showsPlan { - planSection(content) - } - - AccountFeaturesSection(access: model.access, offersPurchase: content.identity == .signedOut) - - if content.showsDevices { - devicesSection(content.devices) - } - - teamsSection(content.teams) - - AccountOfflineSection(model: model, content: content) - } - .formStyle(.grouped) - .task { await model.reload() } - .sheet(isPresented: $model.presentsDeviceLimit) { - DeviceLimitSheet(model: DeviceLimitModel(services: model.services)) - } - .sheet(isPresented: $model.presentsLicenseKey) { - LicenseKeySheet( - storedKey: model.licenseKeyPrefill, - signedInEmail: model.access.state.isSignedIn ? model.profile.value?.email ?? model.access.state.entitlement?.email : nil, - isWorking: model.activity == .usingKey - ) { key in - await model.useLicenseKey(key) - } - } - .fileImporter( - isPresented: $model.presentsOfflineImporter, - allowedContentTypes: [UTType(filenameExtension: "jwt") ?? .data], - allowsMultipleSelection: false - ) { result in - if case .success(let urls) = result, let url = urls.first { - Task { await model.importOfflineFile(at: url) } - } - } - .alert( - model.actionFailure?.title ?? "", - isPresented: Binding(get: { model.actionFailure != nil }, set: { if !$0 { model.actionFailure = nil } }), - presenting: model.actionFailure - ) { _ in - Button(String(localized: "OK")) {} - } message: { failure in - Text(failure.message) - } - .confirmationDialog( - pendingRemoval.map { String(format: String(localized: "Remove “%@”?"), $0.name) } ?? "", - isPresented: Binding(get: { pendingRemoval != nil }, set: { if !$0 { pendingRemoval = nil } }), - presenting: pendingRemoval - ) { row in - Button(String(localized: "Remove"), role: .destructive) { - Task { await model.removeDevice(row) } - } - } message: { _ in - Text("TablePro on that device signs out the next time it checks your account. Its paid features keep working until its last check expires.") - } - } - - // MARK: - Plan - - private func planSection(_ content: AccountSettingsContent) -> some View { - Section { - ForEach(content.notices) { notice in - AccountNoticeRow(notice: notice, model: model) - } - - ForEach(content.plans) { plan in - AccountPlanRow(plan: plan) - } - - if content.notices.isEmpty, content.plans.isEmpty, !content.isFree { - AccountLoadingRow(label: String(localized: "Checking your plan")) - } - - if content.isFree { - HStack { - VStack(alignment: .leading, spacing: 2) { - Text("You're on Free") - Text("Paid plans add the features below.") - .font(.callout) - .foregroundStyle(.secondary) - } - - Spacer() - - Button(String(localized: "Upgrade…")) { - Telemetry.shared.upgradeClicked(from: .licenseSettings) - openURL(model.services.configuration.portalBilling) - } - .accessibilityIdentifier("account-upgrade") - } - } - } header: { - Text("Plan") - } - } - - // MARK: - Devices - - private func devicesSection(_ devices: [AccountSettingsContent.DeviceRow]?) -> some View { - Section { - if let devices { - ForEach(devices) { device in - AccountDeviceRow( - device: device, - isRemoving: model.activity == .removing(device.id), - isDisabled: model.isBusy - ) { - pendingRemoval = device - } - } - } else if model.devices.isLoading { - AccountLoadingRow(label: String(localized: "Loading devices")) + AccountPlanSection(model: model, content: content, showDevices: showDevices) } - if let failure = model.devices.failure { - AccountLoadFailureRow(message: failure) { - Task { await model.loadDevices() } - } - } - } header: { - Text("Devices") - } footer: { - Text("A plan works on up to 3 devices at a time. Removing one signs TablePro out there.") - .font(.callout) - .foregroundStyle(.secondary) - } - } - - // MARK: - Teams - - @ViewBuilder - private func teamsSection(_ teams: [AccountSettingsContent.TeamRow]?) -> some View { - let failure = model.access.state.isSignedIn ? model.profile.failure : nil - if teams?.isEmpty == false || failure != nil || (teams == nil && model.profile.isLoading) { Section { - ForEach(teams ?? []) { team in - AccountTeamRow(team: team) + SettingsDrillRow(route: SettingsRoute.page(.accountFeatures), title: SettingsPage.accountFeatures.title) + + if content.showsDevices { + SettingsDrillRow( + route: SettingsRoute.page(.accountDevices), + title: SettingsPage.accountDevices.title, + value: content.devices.map { $0.count.formatted(.number) } + ) } - if teams == nil, model.profile.isLoading { - AccountLoadingRow(label: String(localized: "Loading teams")) + if content.showsTeams { + SettingsDrillRow( + route: SettingsRoute.page(.accountTeams), + title: SettingsPage.accountTeams.title, + value: content.teams.map { $0.isEmpty ? String(localized: "None") : $0.count.formatted(.number) } + ) } - if let failure { - AccountLoadFailureRow(message: failure) { - Task { await model.loadProfile() } - } - } - } header: { - Text("Teams") + SettingsDrillRow(route: SettingsRoute.page(.accountOffline), title: SettingsPage.accountOffline.title) } } + .formStyle(.grouped) + .accessibilityElement(children: .contain) + .accessibilityIdentifier("settings-pane-account") } } -// MARK: - Account - private struct AccountIdentitySection: View { @ObservedObject var model: AccountSettingsModel let identity: AccountSettingsContent.Identity - @Environment(\.openURL) private var openURL + let canRefresh: Bool var body: some View { Section { switch identity { - case .account(let name, let email, let isSignedIn): - signedIn(name: name, email: email, isSignedIn: isSignedIn) + case .account(let name, let email, true): + signedIn(name: name, email: email) + case .account(let name, let email, false): + offlineFile(name: name, email: email) case .licenseKey(let isValid): licenseKey(isValid: isValid) case .signedOut: signedOut } - } header: { - Text("Account") } } @ViewBuilder - private func signedIn(name: String?, email: String?, isSignedIn: Bool) -> some View { - HStack(spacing: 12) { - Image(systemName: "person.crop.circle.fill") - .font(.system(size: 36)) - .foregroundStyle(.secondary) - .accessibilityHidden(true) - - VStack(alignment: .leading, spacing: 2) { - Text(name ?? email ?? String(localized: "Signed in")) - .font(.headline) - .lineLimit(1) - .truncationMode(.tail) - - if name != nil, let email { - Text(email) - .foregroundStyle(.secondary) - .lineLimit(1) - .truncationMode(.middle) - } - - if !isSignedIn { - Text("From an offline file") - .font(.callout) - .foregroundStyle(.secondary) - } - } - .textSelection(.enabled) - - Spacer() - + private func signedIn(name: String?, email: String?) -> some View { + AccountIdentityRow( + systemImage: "person.crop.circle.fill", + tint: .secondary, + title: name ?? email ?? String(localized: "Signed in"), + subtitles: name == nil ? [] : [email].compactMap { $0 }, + fullText: email + ) { if model.activity == .signingOut { ProgressView() .controlSize(.small) .accessibilityLabel(Text("Signing out")) } - } - .padding(.vertical, 2) - .accessibilityElement(children: .combine) - - HStack { - if isSignedIn { - Button(String(localized: "Manage Account…")) { - openURL(model.services.configuration.accountURL) - } - .accessibilityIdentifier("account-manage") - Spacer() + Button(String(localized: "Sign Out…")) { + model.requestSignOut() + } + .disabled(model.isBusy) + .fixedSize() + .accessibilityIdentifier("account-sign-out") + } - Button(String(localized: "Sign Out")) { - Task { await model.signOut() } - } - .disabled(model.isBusy) - .accessibilityIdentifier("account-sign-out") - } else { - signInButton - Spacer() + LabeledContent { + Button(String(localized: "Manage Account…")) { + model.openPortal(model.services.configuration.accountURL) } + .fixedSize() + .accessibilityIdentifier("account-manage") + } label: { + Text("Profile, sign-in methods and billing") } } - // The key exchange signs this Mac in, so a sign-in here would leave the key unexchanged. - private func licenseKey(isValid: Bool) -> some View { - HStack(spacing: 12) { - Image(systemName: isValid ? "checkmark.seal.fill" : "seal") - .font(.largeTitle) - .foregroundStyle(isValid ? Color.green : Color.secondary) - .accessibilityHidden(true) + // A Mac that only holds an offline file has no session, so it can still sign in. + @ViewBuilder + private func offlineFile(name: String?, email: String?) -> some View { + AccountIdentityRow( + systemImage: "person.crop.circle.fill", + tint: .secondary, + title: name ?? email ?? String(localized: "Signed in"), + subtitles: (name == nil ? [] : [email].compactMap { $0 }) + [String(localized: "From an offline file")], + fullText: email + ) { + signInControl + } - VStack(alignment: .leading, spacing: 2) { - Text("License key") - .font(.headline) + signInFailure + } - Text(isValid + // The key exchange signs this Mac in, so a sign-in here would leave the key unexchanged. + private func licenseKey(isValid: Bool) -> some View { + AccountIdentityRow( + systemImage: isValid ? "checkmark.seal.fill" : "seal", + tint: isValid ? .green : .secondary, + title: String(localized: "License key"), + subtitles: [ + isValid ? String(localized: "TablePro signs you in with your license key the next time it reaches the server.") - : String(localized: "Connect to the internet to verify your license.")) - .foregroundStyle(.secondary) - .fixedSize(horizontal: false, vertical: true) + : String(localized: "Connect to the internet to verify your license."), + ], + wrapsSubtitles: true + ) { + if canRefresh { + AccountRefreshControl(model: model) } } - .padding(.vertical, 2) - .accessibilityElement(children: .combine) } @ViewBuilder private var signedOut: some View { - VStack(alignment: .leading, spacing: 4) { + LabeledContent { + signInControl + } label: { Text("Sign in to TablePro") - .font(.headline) - Text("Your account unlocks the features your plan includes on this Mac. Everything else works without an account.") - .foregroundStyle(.secondary) - .fixedSize(horizontal: false, vertical: true) } - .padding(.vertical, 2) - if let failure = model.signInFailure { - Label(failure, systemImage: "exclamationmark.triangle.fill") - .foregroundStyle(.orange) - .fixedSize(horizontal: false, vertical: true) - .accessibilityIdentifier("account-sign-in-error") - } + signInFailure - HStack(spacing: 10) { - signInButton - .buttonStyle(.borderedProminent) + SettingsHelpRow(SignInCopy.codeHint) + } + private var signInControl: some View { + HStack(spacing: 8) { if model.activity == .signingIn { ProgressView() .controlSize(.small) .accessibilityLabel(Text("Signing in")) } - Spacer() + Button(String(localized: "Sign In")) { + Task { + await model.signIn(using: WebAuthenticationSessionAuthenticator()) + } + } + .disabled(model.isBusy) + .fixedSize() + .accessibilityIdentifier("account-sign-in-button") } + } - Text(SignInCopy.codeHint) - .font(.callout) - .foregroundStyle(.secondary) - .fixedSize(horizontal: false, vertical: true) + @ViewBuilder + private var signInFailure: some View { + if let failure = model.signInFailure { + AccountFailureLine(message: failure, identifier: "account-sign-in-error") + } } +} - private var signInButton: some View { - Button(String(localized: "Sign In")) { - Task { - await model.signIn(using: WebAuthenticationSessionAuthenticator()) +private struct AccountIdentityRow: View { + let systemImage: String + let tint: Color + let title: String + let subtitles: [String] + var fullText: String? + var wrapsSubtitles = false + @ViewBuilder let trailing: Trailing + + var body: some View { + HStack(spacing: 10) { + Image(systemName: systemImage) + .resizable() + .scaledToFit() + .frame(width: 32, height: 32) + .foregroundStyle(tint) + .accessibilityHidden(true) + + VStack(alignment: .leading, spacing: 1) { + Text(title) + .lineLimit(1) + .truncationMode(.tail) + + ForEach(subtitles, id: \.self) { subtitle in + if wrapsSubtitles { + Text(subtitle) + .font(.subheadline) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + } else { + Text(subtitle) + .font(.subheadline) + .foregroundStyle(.secondary) + .lineLimit(1) + .truncationMode(.middle) + } + } } + .textSelection(.enabled) + .help(fullText ?? "") + + Spacer(minLength: 12) + + trailing } - .disabled(model.isBusy) - .accessibilityIdentifier("account-sign-in-button") + .accessibilityElement(children: .contain) } } -// MARK: - Offline - -private struct AccountOfflineSection: View { +private struct AccountPlanSection: View { @ObservedObject var model: AccountSettingsModel let content: AccountSettingsContent + let showDevices: () -> Void var body: some View { Section { - if let verification = content.verification { - HStack { - Text(Self.verificationText(verification)) - .fixedSize(horizontal: false, vertical: true) + ForEach(content.notices) { notice in + AccountNoticeRow(notice: notice, model: model, showDevices: showDevices) + } - Spacer() + ForEach(content.plans) { plan in + AccountPlanRow(plan: plan, model: model) + } - refreshButton + if content.isFree { + LabeledContent { + Button(String(localized: "Upgrade…")) { + Telemetry.shared.upgradeClicked(from: .licenseSettings) + model.openPortal(model.services.configuration.portalBilling) + } + .fixedSize() + .accessibilityIdentifier("account-upgrade") + } label: { + Text("You're on Free") + Text("A paid plan adds the features listed under Features.") } + } - // The last check still holds, so no notice above names a Refresh that just failed. - if LicensePresentation.checkFailureMessage(model.access.state.refresh) != nil { - LicenseCheckFailureLine() - } - } else if content.canRefresh { - HStack { - Text("Not verified yet") - .foregroundStyle(.secondary) - Spacer() - refreshButton - } + if content.notices.isEmpty, content.plans.isEmpty, !content.isFree { + AccountLoadingRow(label: String(localized: "Checking your plan")) } - LabeledContent(String(localized: "Machine ID")) { - HStack(spacing: 8) { - Text(verbatim: content.machineID) - .font(.callout.monospaced()) - .lineLimit(1) - .truncationMode(.middle) - .textSelection(.enabled) - .accessibilityIdentifier("account-machine-id") + if let state = content.verificationState { + AccountVerificationRow( + state: state, + model: model, + showsRefresh: content.canRefresh && !content.offersRetry + ) + } - Button(String(localized: "Copy")) { - ClipboardService.shared.writeText(content.machineID) - } - .accessibilityLabel(Text("Copy Machine ID")) - } + // The last check still holds, so no notice above names a Refresh that just failed. + if content.verification != nil, + let failure = LicensePresentation.checkFailureMessage(model.access.state.refresh) { + AccountFailureLine(message: failure) } + } header: { + Text("Plan") + } + } +} - HStack { - Button(String(localized: "Import Offline File…")) { - model.presentsOfflineImporter = true - } - .disabled(model.isBusy) - .accessibilityIdentifier("account-import-offline-file") +private struct AccountNoticeRow: View { + let notice: AccountSettingsContent.Notice + @ObservedObject var model: AccountSettingsModel + let showDevices: () -> Void - Button(String(localized: "Use License Key…")) { - model.presentLicenseKey() - } - .disabled(model.isBusy) - .accessibilityIdentifier("account-use-license-key") + private var severity: NoticeSeverity { + notice.isInformational ? .info : .warning + } + + var body: some View { + HStack(alignment: .firstTextBaseline, spacing: 8) { + Image(systemName: severity.symbolName) + .foregroundStyle(severity.tint) + .frame(width: 16) + .accessibilityHidden(true) - Spacer() + VStack(alignment: .leading, spacing: 3) { + Text(notice.title) + + Text(notice.message) + .font(.subheadline) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) } - } header: { - Text("Offline") - } footer: { - Text("For a Mac that never reaches the internet, create an offline file for this machine ID in your account, then import it here.") - .font(.callout) - .foregroundStyle(.secondary) + + Spacer(minLength: 12) + + action } + .accessibilityElement(children: .contain) + .accessibilityIdentifier("account-notice-\(notice.id)") } @ViewBuilder - private var refreshButton: some View { - if content.canRefresh { + private var action: some View { + switch notice { + case .deviceLimit: + Button(String(localized: "Show Devices"), action: showDevices) + .fixedSize() + .accessibilityIdentifier("account-choose-device") + case .paymentProblem(let plan): + if let billing = plan.billing { + Button(String(localized: "Update Payment Method…")) { model.openPortal(billing) } + .fixedSize() + } + case .canceling: + // The plan's own row has Billing…, where the cancellation is resumed. + EmptyView() + case .expiringSoon(_, true), .expired(_, true): + Button(String(localized: "Import Offline File…")) { model.presentsOfflineImporter = true } + .disabled(model.isBusy) + .fixedSize() + case .expiringSoon, .expired, .verificationFailed: HStack(spacing: 8) { if model.activity == .checking { ProgressView() @@ -414,62 +333,36 @@ private struct AccountOfflineSection: View { .accessibilityLabel(Text("Refreshing")) } - Button(String(localized: "Refresh")) { + Button(String(localized: "Try Again")) { Task { await model.checkNow() } } .disabled(model.isBusy) - .accessibilityIdentifier("account-refresh") + .fixedSize() } } } - - static func verificationText(_ verification: AccountSettingsContent.Verification) -> String { - let until = verification.validUntil.formatted(date: .abbreviated, time: .omitted) - if verification.isExpired { - return verification.isOfflineFile - ? String(format: String(localized: "Offline file expired on %@"), until) - : String(format: String(localized: "Expired on %@"), until) - } - if verification.isOfflineFile { - return String(format: String(localized: "Offline file, valid until %@"), until) - } - return String( - format: String(localized: "Verified %@, valid until %@"), - verification.verifiedAt.formatted(.relative(presentation: .named)), - until - ) - } } -// MARK: - Rows - private struct AccountPlanRow: View { let plan: AccountSettingsContent.PlanRow - @Environment(\.openURL) private var openURL + @ObservedObject var model: AccountSettingsModel var body: some View { - HStack(spacing: 12) { - VStack(alignment: .leading, spacing: 2) { - Text(plan.title) - - Text(plan.owner) - .font(.callout) - .foregroundStyle(.secondary) - .lineLimit(1) - .truncationMode(.tail) - } - - Spacer(minLength: 12) - + SettingsRecordRow(title: plan.title, subtitle: plan.owner) { if let status = plan.status { AccountPlanStatusLabel(status: status) } if let billing = plan.billing { - Button(String(localized: "Billing…")) { openURL(billing) } + Button(String(localized: "Billing…")) { model.openPortal(billing) } + .fixedSize() } } - .accessibilityElement(children: .contain) + .modifier(AccountRowMenu(title: String(localized: "Billing…"), isAvailable: plan.billing != nil) { + if let billing = plan.billing { + model.openPortal(billing) + } + }) } } @@ -477,171 +370,281 @@ private struct AccountPlanStatusLabel: View { let status: AccountSettingsContent.PlanStatus var body: some View { - switch status { - case .paymentProblem: - Label(String(localized: "Payment problem"), systemImage: "exclamationmark.triangle.fill") - .foregroundStyle(.orange) - case .active: - Text("Active") - .foregroundStyle(.secondary) - case .lifetime: - Text("Lifetime") - .foregroundStyle(.secondary) - case .renewsOn(let date): - Text(String(format: String(localized: "Renews on %@"), date.formatted(date: .abbreviated, time: .omitted))) - .foregroundStyle(.secondary) - case .endsOn(let date), .canceling(endsAt: .some(let date)): - Text(String(format: String(localized: "Ends on %@"), date.formatted(date: .abbreviated, time: .omitted))) - .foregroundStyle(.secondary) - case .canceling(endsAt: .none): - Text("Canceling") - .foregroundStyle(.secondary) + Group { + switch status { + case .paymentProblem: + Label { + Text("Payment problem") + } icon: { + Image(systemName: NoticeSeverity.warning.symbolName) + .foregroundStyle(NoticeSeverity.warning.tint) + } + case .active: + Text("Active") + case .lifetime: + Text("Lifetime") + case .renewsOn(let date): + Text(String(format: String(localized: "Renews on %@"), date.formatted(date: .abbreviated, time: .omitted))) + case .endsOn(let date), .canceling(endsAt: .some(let date)): + Text(String(format: String(localized: "Ends on %@"), date.formatted(date: .abbreviated, time: .omitted))) + case .canceling(endsAt: .none): + Text("Canceling") + } } + .foregroundStyle(.secondary) + .lineLimit(1) + .layoutPriority(1) } } -private struct AccountNoticeRow: View { - let notice: AccountSettingsContent.Notice +private struct AccountVerificationRow: View { + let state: AccountSettingsContent.VerificationState @ObservedObject var model: AccountSettingsModel - @Environment(\.openURL) private var openURL + let showsRefresh: Bool var body: some View { - HStack(alignment: .top, spacing: 10) { - Image(systemName: "exclamationmark.triangle.fill") - .foregroundStyle(.orange) - .accessibilityHidden(true) - - VStack(alignment: .leading, spacing: 4) { - Text(notice.title) - .font(.headline) - - Text(notice.message) - .foregroundStyle(.secondary) - .fixedSize(horizontal: false, vertical: true) - - action - .padding(.top, 2) + SettingsRecordRow(title: title, subtitle: subtitle) { + if showsRefresh { + AccountRefreshControl(model: model) } + } + } - Spacer(minLength: 0) + private var title: String { + switch state { + case .verified(let at, _): + String(format: String(localized: "Verified %@"), at.formatted(.relative(presentation: .named))) + case .offlineFile, .offlineFileExpired: + String(localized: "Offline file") + case .expired: + String(localized: "Expired") + case .notVerified: + String(localized: "Not verified yet") } - .padding(.vertical, 2) - .accessibilityElement(children: .contain) - .accessibilityIdentifier("account-notice-\(notice.id)") } - @ViewBuilder - private var action: some View { - switch notice { - case .deviceLimit: - Button(String(localized: "Choose a Device…")) { model.presentsDeviceLimit = true } - .accessibilityIdentifier("account-choose-device") - case .paymentProblem(let plan): - if let billing = plan.billing { - Button(String(localized: "Update Payment Method…")) { openURL(billing) } + private var subtitle: String? { + switch state { + case .verified(_, let until), .offlineFile(let until): + String(format: String(localized: "Valid until %@"), until.formatted(date: .abbreviated, time: .omitted)) + case .expired(let on), .offlineFileExpired(let on): + String(format: String(localized: "Expired on %@"), on.formatted(date: .abbreviated, time: .omitted)) + case .notVerified: + nil + } + } +} + +private struct AccountRefreshControl: View { + @ObservedObject var model: AccountSettingsModel + + var body: some View { + HStack(spacing: 8) { + if model.activity == .checking { + ProgressView() + .controlSize(.small) + .accessibilityLabel(Text("Refreshing")) } - case .canceling: - // The plan's own row has Billing…, where the cancellation is resumed. - EmptyView() - case .expiringSoon(_, true), .expired(_, true): - Button(String(localized: "Import Offline File…")) { model.presentsOfflineImporter = true } - case .expiringSoon, .expired, .verificationFailed: - Button(String(localized: "Try Again")) { + + Button(String(localized: "Refresh")) { Task { await model.checkNow() } } .disabled(model.isBusy) + .fixedSize() + .accessibilityIdentifier("account-refresh") } } } -private struct AccountDeviceRow: View { - let device: AccountSettingsContent.DeviceRow - let isRemoving: Bool - let isDisabled: Bool - let onRemove: () -> Void +internal struct AccountDevicesPage: View { + @ObservedObject var model: AccountSettingsModel var body: some View { - HStack(spacing: 10) { - Image(systemName: device.system.hasPrefix("macOS") ? "laptopcomputer" : "desktopcomputer") - .foregroundStyle(.secondary) - .frame(width: 20) - .accessibilityHidden(true) + let devices = model.content.devices + Form { + Section { + if let devices { + if devices.isEmpty, model.devices.failure == nil { + Text("No devices are signed in.") + .foregroundStyle(.secondary) + } - VStack(alignment: .leading, spacing: 2) { - HStack(spacing: 6) { - Text(device.name) - .lineLimit(1) - .truncationMode(.middle) + ForEach(devices) { device in + AccountDeviceRow( + device: device, + isRemoving: model.activity == .removing(device.id), + isDisabled: model.isBusy + ) { + model.pendingRemoval = device + } + } + } else if model.devices.isLoading { + AccountLoadingRow(label: String(localized: "Loading devices")) + } - if device.isThisMac { - Text("This Mac") - .font(.caption) - .foregroundStyle(.secondary) - .padding(.horizontal, 6) - .padding(.vertical, 1) - .background(Capsule().fill(Color(nsColor: .quaternaryLabelColor))) + if let failure = model.devices.failure { + AccountLoadFailureRow(message: failure, isRetrying: model.devices.isLoading) { + Task { await model.loadDevices() } } } - Text(AccountDeviceText.detail(system: device.system, lastSeenAt: device.lastSeenAt)) - .font(.callout) - .foregroundStyle(.secondary) - .lineLimit(1) + SettingsHelpRow("A plan works on up to 3 devices at a time. Removing one signs TablePro out there.") } + } + .formStyle(.grouped) + .accessibilityElement(children: .contain) + .accessibilityIdentifier(SettingsPage.accountDevices.pageIdentifier) + } +} - Spacer(minLength: 12) +private struct AccountDeviceRow: View { + let device: AccountSettingsContent.DeviceRow + let isRemoving: Bool + let isDisabled: Bool + let onRemove: () -> Void + var body: some View { + SettingsRecordRow( + title: device.name, + subtitle: AccountDeviceText.detail(system: device.system, lastSeenAt: device.lastSeenAt, isThisMac: device.isThisMac) + ) { if let offlineUntil = device.offlineUntil { Text(AccountDeviceText.offlineFile(until: offlineUntil)) - .font(.callout) .foregroundStyle(.secondary) + .lineLimit(1) + .layoutPriority(1) } else if isRemoving { ProgressView() .controlSize(.small) .accessibilityLabel(Text("Removing")) } else if device.canRemove { - Button(String(localized: "Remove"), action: onRemove) + Button(String(localized: "Remove…"), action: onRemove) .disabled(isDisabled) + .fixedSize() .accessibilityLabel(Text(String(format: String(localized: "Remove %@"), device.name))) } } + .modifier(AccountRowMenu( + title: String(localized: "Remove…"), + isAvailable: device.canRemove && !isRemoving, + isDisabled: isDisabled, + action: onRemove + )) + } +} + +internal struct AccountTeamsPage: View { + @ObservedObject var model: AccountSettingsModel + + var body: some View { + let teams = model.content.teams + Form { + Section { + if let teams { + if teams.isEmpty, model.profile.failure == nil { + Text("You are not on a team.") + .foregroundStyle(.secondary) + } + + ForEach(teams) { team in + AccountTeamRow(team: team, model: model) + } + } else if model.profile.isLoading { + AccountLoadingRow(label: String(localized: "Loading teams")) + } + + if let failure = model.profile.failure { + AccountLoadFailureRow(message: failure, isRetrying: model.profile.isLoading) { + Task { await model.loadProfile() } + } + } + } + } + .formStyle(.grouped) .accessibilityElement(children: .contain) + .accessibilityIdentifier(SettingsPage.accountTeams.pageIdentifier) } } private struct AccountTeamRow: View { let team: AccountSettingsContent.TeamRow - @Environment(\.openURL) private var openURL + @ObservedObject var model: AccountSettingsModel + + private var subtitle: String { + let seat = team.hasSeat ? String(localized: "Seat assigned") : String(localized: "No seat") + guard let role = team.role else { return seat } + return String(format: String(localized: "%@ · %@"), role, seat) + } var body: some View { - HStack(spacing: 12) { - VStack(alignment: .leading, spacing: 2) { - Text(team.name) - .lineLimit(1) - .truncationMode(.tail) - .help(team.name) + SettingsRecordRow(title: team.name, subtitle: subtitle) { + Button(String(localized: "Manage…")) { model.openPortal(team.manage) } + .fixedSize() + .accessibilityLabel(Text(String(format: String(localized: "Manage %@"), team.name))) + } + .modifier(AccountRowMenu(title: String(localized: "Manage…")) { + model.openPortal(team.manage) + }) + } +} - if let role = team.role { - Text(role) - .font(.callout) - .foregroundStyle(.secondary) - } - } +internal struct AccountOfflinePage: View { + @ObservedObject var model: AccountSettingsModel - Spacer(minLength: 12) + var body: some View { + let machineID = model.services.machineID + Form { + Section { + LabeledContent(String(localized: "Machine ID")) { + HStack(spacing: 8) { + Text(verbatim: machineID) + .font(.body.monospaced()) + .foregroundStyle(.secondary) + .lineLimit(1) + .truncationMode(.middle) + .textSelection(.enabled) + .frame(maxWidth: 240, alignment: .trailing) + .help(machineID) + .accessibilityIdentifier("account-machine-id") + + Button(String(localized: "Copy")) { + ClipboardService.shared.writeText(machineID) + } + .fixedSize() + .accessibilityLabel(Text("Copy Machine ID")) + } + } - if team.hasSeat { - Label(String(localized: "Seat"), systemImage: "checkmark.circle.fill") - .foregroundStyle(.secondary) - } else { - Text("No seat") - .foregroundStyle(.secondary) + LabeledContent { + Button(String(localized: "Import Offline File…")) { + model.presentsOfflineImporter = true + } + .disabled(model.isBusy) + .fixedSize() + .accessibilityIdentifier("account-import-offline-file") + } label: { + Text("Offline file") + Text("For a Mac that never reaches the internet, create an offline file for this machine ID in your account, then import it here.") + } } - Button(String(localized: "Manage…")) { openURL(team.manage) } - .accessibilityLabel(Text(String(format: String(localized: "Manage %@"), team.name))) + Section { + LabeledContent { + Button(String(localized: "Use License Key…")) { + model.presentLicenseKey() + } + .disabled(model.isBusy) + .fixedSize() + .accessibilityIdentifier("account-use-license-key") + } label: { + Text("License key") + Text("Sign this Mac in with a key from an older version of TablePro.") + } + } } + .formStyle(.grouped) .accessibilityElement(children: .contain) + .accessibilityIdentifier(SettingsPage.accountOffline.pageIdentifier) } } @@ -652,6 +655,7 @@ private struct AccountLoadingRow: View { HStack(spacing: 8) { ProgressView() .controlSize(.small) + .accessibilityHidden(true) Text(label) .foregroundStyle(.secondary) } @@ -661,17 +665,65 @@ private struct AccountLoadingRow: View { private struct AccountLoadFailureRow: View { let message: String + let isRetrying: Bool let onRetry: () -> Void var body: some View { - HStack(spacing: 8) { - Label(message, systemImage: "exclamationmark.triangle.fill") - .foregroundStyle(.secondary) + HStack(alignment: .firstTextBaseline, spacing: 8) { + Image(systemName: NoticeSeverity.warning.symbolName) + .foregroundStyle(NoticeSeverity.warning.tint) + .frame(width: 16) + .accessibilityHidden(true) + + Text(message) .fixedSize(horizontal: false, vertical: true) - Spacer() + Spacer(minLength: 12) + + if isRetrying { + ProgressView() + .controlSize(.small) + .accessibilityLabel(Text("Loading")) + } else { + Button(String(localized: "Try Again"), action: onRetry) + .fixedSize() + } + } + .accessibilityElement(children: .contain) + } +} + +private struct AccountFailureLine: View { + let message: String + var identifier: String? - Button(String(localized: "Try Again"), action: onRetry) + var body: some View { + NoticeLabel(message) + .font(.subheadline) + .accessibilityElement(children: .combine) + .accessibilityIdentifier(identifier ?? "") + } +} + +// A row's one action also sits in its context menu and its accessibility actions. +private struct AccountRowMenu: ViewModifier { + let title: String + var isAvailable = true + var isDisabled = false + let action: () -> Void + + func body(content: Content) -> some View { + if isAvailable { + content + .contextMenu { + Button(title, action: action) + .disabled(isDisabled) + } + .accessibilityAction(named: Text(title)) { + if !isDisabled { action() } + } + } else { + content } } } diff --git a/apple/TablePro/Views/Settings/Account/LicensePresentation.swift b/apple/TablePro/Views/Settings/Account/LicensePresentation.swift index c67dd3969b..03a3cdc590 100644 --- a/apple/TablePro/Views/Settings/Account/LicensePresentation.swift +++ b/apple/TablePro/Views/Settings/Account/LicensePresentation.swift @@ -1,8 +1,3 @@ -// -// LicensePresentation.swift -// TablePro -// - import Foundation internal enum LicenseNoticeAction: Equatable { @@ -11,7 +6,8 @@ internal enum LicenseNoticeAction: Equatable { case upgrade case renew case retryValidation - case openAccountSettings + // nil opens the Account pane itself. + case openAccountSettings(page: SettingsPage?) var title: String { switch self { @@ -60,7 +56,7 @@ internal enum LicensePresentation { return LicenseNotice( title: String(localized: "Your plan is in use on 3 other devices"), message: String(localized: "Remove one in Settings to use your plan on this Mac."), - action: .openAccountSettings + action: .openAccountSettings(page: .accountDevices) ) } return LicenseNotice(title: feature.paidPlanRequirement, message: feature.featureDescription, action: .upgrade) @@ -86,7 +82,7 @@ internal enum LicensePresentation { // plan stays in the pane: the person chose it, and the pane shows the date it ends. static func welcomeLine(state: AccountState, configuration: AccountConfiguration, now: Date) -> LicenseNotice? { let notices = AccountSettingsContent.notices(state: state, configuration: configuration, now: now) - if let first = notices.first(where: { !$0.isCanceling }) { + if let first = notices.first(where: { !$0.isInformational }) { return notice(first) } guard !state.isSignedIn, state.legacy == nil else { return nil } @@ -108,8 +104,12 @@ internal enum LicensePresentation { switch notice { case .expiringSoon(_, false), .expired(_, false), .verificationFailed: return .retryValidation - case .deviceLimit, .paymentProblem, .expiringSoon(_, true), .expired(_, true): - return .openAccountSettings + case .deviceLimit: + return .openAccountSettings(page: .accountDevices) + case .expiringSoon(_, true), .expired(_, true): + return .openAccountSettings(page: .accountOffline) + case .paymentProblem: + return .openAccountSettings(page: nil) case .canceling: return nil } @@ -120,10 +120,3 @@ internal enum LicensePresentation { return error.friendlyDescription } } - -private extension AccountSettingsContent.Notice { - var isCanceling: Bool { - if case .canceling = self { return true } - return false - } -} diff --git a/apple/TablePro/Views/Settings/Appearance/ThemeEditorView.swift b/apple/TablePro/Views/Settings/Appearance/ThemeEditorView.swift index 709db8dc4e..a7dc89f3a8 100644 --- a/apple/TablePro/Views/Settings/Appearance/ThemeEditorView.swift +++ b/apple/TablePro/Views/Settings/Appearance/ThemeEditorView.swift @@ -55,8 +55,6 @@ internal struct ThemeEditorView: View { } } - // MARK: - Sections - private var builtInSection: some View { Section { HStack { @@ -148,8 +146,6 @@ internal struct ThemeEditorView: View { ) } - // MARK: - Alerts - @ViewBuilder private func alertButtons(for alert: ThemeEditorModel.Alert) -> some View { switch alert { @@ -164,15 +160,15 @@ internal struct ThemeEditorView: View { } } -// Observes the settings itself, so a settings change re-renders this footer and not the editor or its preview. +// Observes the value colors slice itself, so a change re-renders this footer and not the editor or its preview. private struct ThemeValuesSectionFooter: View { let contrastNote: String? - @ObservedObject private var settingsManager = AppSettingsManager.shared + @ObservedObject private var valueColors = AppSettingsManager.shared.valueColorsSlice var body: some View { let settingNote = ThemeValueColorsNote.message( for: .values, - colorsValuesByType: settingsManager.valueColors.colorsValuesByType + colorsValuesByType: valueColors.value.colorsValuesByType ) if contrastNote != nil || settingNote != nil { VStack(alignment: .leading, spacing: 4) { @@ -206,7 +202,7 @@ internal extension ThemeEditorModel.Alert { case .changedOnDisk: return String(localized: "It was changed outside TablePro. The editor now shows the newer version.") case .unreadableOnDisk: - return String(localized: "It was changed outside TablePro and no longer loads. Settings > Appearance lists it under Not Loaded with the reason.") + return String(localized: "It was changed outside TablePro and no longer loads. Settings > Appearance > Manage Themes lists it under Couldn't Load with the reason.") case .deletedOnDisk: return String(localized: "The file was removed outside TablePro, possibly on another Mac.") case let .saveFailed(_, reason): diff --git a/apple/TablePro/Views/Settings/Appearance/ThemeLibraryModel.swift b/apple/TablePro/Views/Settings/Appearance/ThemeLibraryModel.swift index 1d12ffda57..b0c73aeee8 100644 --- a/apple/TablePro/Views/Settings/Appearance/ThemeLibraryModel.swift +++ b/apple/TablePro/Views/Settings/Appearance/ThemeLibraryModel.swift @@ -14,12 +14,23 @@ internal enum ThemeLibraryItem: Hashable, Sendable { @MainActor internal protocol ThemeSelectionStore: AnyObject { var themeSelection: AppearanceSettings { get set } + var themeSelectionWillChange: AnyPublisher { get } +} + +extension ThemeSelectionStore { + internal var themeSelectionWillChange: AnyPublisher { + Empty().eraseToAnyPublisher() + } } extension AppSettingsManager: ThemeSelectionStore { internal var themeSelection: AppearanceSettings { - get { appearance } - set { appearance = newValue } + get { appearanceSlice.value } + set { appearanceSlice.value = newValue } + } + + internal var themeSelectionWillChange: AnyPublisher { + appearanceSlice.objectWillChange.eraseToAnyPublisher() } } @@ -63,8 +74,7 @@ internal struct ThemeImportReport: Equatable { internal var imported: [ThemeDefinition] = [] internal var failures: [ThemeImportFailure] = [] - /// A clean import needs no alert: the new row is selected. Anything else is one alert for the - /// whole drop, so ten files never mean ten alerts. + // One alert for a whole drop, and none for a clean one: the new row is selected. internal var alert: ThemeLibraryAlert? { guard !failures.isEmpty else { return nil } let lines = failures.map { @@ -76,16 +86,53 @@ internal struct ThemeImportReport: Equatable { message: only.reason ) } - let title: String - switch imported.count { - case 0: title = String(localized: "No Themes Imported") - case 1: title = String(localized: "Imported 1 theme.") - default: title = String(format: String(localized: "Imported %d themes."), imported.count) - } + let title = imported.isEmpty + ? String(localized: "No Themes Imported") + : String(AttributedString(localized: "Imported ^[\(imported.count) Theme](inflect: true)").characters) return ThemeLibraryAlert(title: title, message: lines.joined(separator: "\n")) } } +internal enum ThemeLibraryAction: Hashable, Sendable { + case edit + case showInEditor + case duplicate + case rename + case export + case use(ThemeAppearance) + case showInFinder + case tryAgain + case moveToTrash + + internal var title: String { + switch self { + case .edit: return String(localized: "Edit…") + case .showInEditor: return String(localized: "Show in Theme Editor") + case .duplicate: return String(localized: "Duplicate") + case .rename: return String(localized: "Rename") + case .export: return String(localized: "Export…") + case .use(.light): return String(localized: "Use for Light Appearance") + case .use(.dark): return String(localized: "Use for Dark Appearance") + case .showInFinder: return String(localized: "Show in Finder") + case .tryAgain: return String(localized: "Try Again") + case .moveToTrash: return String(localized: "Move to Trash") + } + } +} + +internal struct ThemeLibraryMenuEntry: Hashable, Sendable { + internal let action: ThemeLibraryAction + internal let isEnabled: Bool + // A separator goes before it when anything shows above it. + internal let startsGroup: Bool + + internal init(_ action: ThemeLibraryAction, isEnabled: Bool, startsGroup: Bool = false) { + self.action = action + self.isEnabled = isEnabled + self.startsGroup = startsGroup + } +} + internal struct ThemeFileDocument: FileDocument { internal static var readableContentTypes: [UTType] { [.json] } @@ -105,19 +152,22 @@ internal struct ThemeFileDocument: FileDocument { } } -/// Every action of the Appearance pane's theme list. Views call it and show what it publishes; it -/// never reaches the engine, which follows the catalog by itself. An action on a theme whose editor -/// is open goes through that editor, so the window and the list cannot write over each other. +// Never reaches the engine, which follows the catalog itself. An action on a theme whose editor is +// open goes through that editor, so the window and the list cannot write over each other. @MainActor internal final class ThemeLibraryModel: ObservableObject { @Published internal var alert: ThemeLibraryAlert? + // The Settings window sets this. It shows an alert raised while the Manage Themes page is off + // screen, an undo from another page for one, and returns true; false leaves it to the page. + internal var presentOffPage: (@MainActor (ThemeLibraryAlert) -> Bool)? + internal let catalog: ThemeCatalog private let selection: ThemeSelectionStore private let editors: ThemeEditorPresenting private let revealInFinder: @MainActor ([URL]) -> Void private let dragDirectory: URL - private var catalogCancellable: AnyCancellable? + private var cancellables: Set = [] private static let logger = Logger(subsystem: "com.TablePro", category: "ThemeLibrary") @@ -134,13 +184,15 @@ internal final class ThemeLibraryModel: ObservableObject { self.editors = editors self.dragDirectory = dragDirectory self.revealInFinder = revealInFinder - catalogCancellable = catalog.objectWillChange.sink { [weak self] _ in - self?.objectWillChange.send() - } + catalog.objectWillChange + .sink { [weak self] _ in self?.objectWillChange.send() } + .store(in: &cancellables) + // The in-use subtitles follow the slots, which sync and the theme editor also write. + selection.themeSelectionWillChange + .sink { [weak self] _ in self?.objectWillChange.send() } + .store(in: &cancellables) } - // MARK: - Contents - internal var builtInThemes: [ThemeDefinition] { catalog.themes.filter(\.isBuiltIn) } @@ -168,7 +220,12 @@ internal final class ThemeLibraryModel: ObservableObject { return record(for: item) != nil } - /// The slot a theme can still be chosen for, or nil when it is already the choice there. + internal func hasFile(_ item: ThemeLibraryItem?) -> Bool { + if case let .theme(id) = item { return catalog.fileURL(for: id) != nil } + return record(for: item) != nil + } + + // The slot a theme can still be chosen for, or nil when it is already the choice there. internal func availableSlot(for theme: ThemeDefinition) -> ThemeAppearance? { let current = selection.themeSelection switch theme.appearance { @@ -177,6 +234,16 @@ internal final class ThemeLibraryModel: ObservableObject { } } + // The themes the windows draw with, resolved as the pop-ups resolve them. + internal var inUseThemeIds: Set { + let current = selection.themeSelection + let themes = catalog.themes + return [ + ThemeSlotChoice(slot: .light, savedId: current.preferredLightThemeId, themes: themes).selectedId, + ThemeSlotChoice(slot: .dark, savedId: current.preferredDarkThemeId, themes: themes).selectedId, + ] + } + internal static func appearanceLabel(_ appearance: ThemeAppearance) -> String { switch appearance { case .light: return String(localized: "Light") @@ -184,8 +251,40 @@ internal final class ThemeLibraryModel: ObservableObject { } } - // MARK: - Opening and choosing + internal static func rowSubtitle(_ appearance: ThemeAppearance, isInUse: Bool) -> String { + guard isInUse else { return appearanceLabel(appearance) } + switch appearance { + case .light: return String(localized: "Light, in use") + case .dark: return String(localized: "Dark, in use") + } + } + // One list for the context menu, which leaves out a disabled entry, and the pull-down, which dims it. + internal func menuEntries(for item: ThemeLibraryItem?) -> [ThemeLibraryMenuEntry] { + if record(for: item) != nil { + return [ + ThemeLibraryMenuEntry(.showInFinder, isEnabled: true), + ThemeLibraryMenuEntry(.tryAgain, isEnabled: true), + ThemeLibraryMenuEntry(.moveToTrash, isEnabled: true, startsGroup: true), + ] + } + guard let theme = theme(for: item) else { + let actions: [ThemeLibraryAction] = [.edit, .duplicate, .rename, .export, .showInFinder] + return actions.map { ThemeLibraryMenuEntry($0, isEnabled: false) } + + [ThemeLibraryMenuEntry(.moveToTrash, isEnabled: false, startsGroup: true)] + } + return [ + ThemeLibraryMenuEntry(theme.isEditable ? .edit : .showInEditor, isEnabled: true), + ThemeLibraryMenuEntry(.duplicate, isEnabled: true), + ThemeLibraryMenuEntry(.rename, isEnabled: theme.isEditable), + ThemeLibraryMenuEntry(.export, isEnabled: true), + ThemeLibraryMenuEntry(.use(theme.appearance), isEnabled: availableSlot(for: theme) != nil), + ThemeLibraryMenuEntry(.showInFinder, isEnabled: hasFile(item)), + ThemeLibraryMenuEntry(.moveToTrash, isEnabled: theme.isEditable, startsGroup: true), + ] + } + + // A built-in opens read-only, with Duplicate. internal func edit(_ id: String) { guard catalog.theme(id: id) != nil else { return } editors.openEditor(for: id) @@ -201,14 +300,12 @@ internal final class ThemeLibraryModel: ObservableObject { selection.themeSelection = updated } - // MARK: - Creating - @discardableResult internal func duplicate(_ id: String, undoManager: UndoManager?) -> ThemeDefinition? { makeCopy(of: id, actionName: String(localized: "Duplicate"), undoManager: undoManager) } - /// A theme made to be edited, so its editor opens with it. + // A theme made to be edited, so its editor opens with it. @discardableResult internal func createTheme(basedOn id: String, undoManager: UndoManager?) -> ThemeDefinition? { guard let copy = makeCopy(of: id, actionName: String(localized: "New Theme"), undoManager: undoManager) else { @@ -243,15 +340,13 @@ internal final class ThemeLibraryModel: ObservableObject { } registerCreation(of: report.imported.map(\.id), actionName: String(localized: "Import"), undoManager: undoManager) if let alert = report.alert { - self.alert = alert + raise(alert) } return report } - // MARK: - Renaming - - /// The name the rename field starts from: the file's own, not the "Ocean 2" the list shows for - /// the second of two "Ocean" themes, so committing it untouched changes nothing. + // The file's own name, not the "Ocean 2" the list shows for the second of two "Ocean" themes, + // so committing it untouched changes nothing. internal func nameForRenaming(_ id: String) -> String? { catalog.storedTheme(id: id)?.name } @@ -299,15 +394,13 @@ internal final class ThemeLibraryModel: ObservableObject { register(on: undoManager, actionName: String(localized: "Rename")) { model in guard let current = model.catalog.storedTheme(id: id)?.name else { return } if case let .rejected(reason) = model.applyRename(id, to: name) { - model.alert = ThemeLibraryAlert(title: String(localized: "Couldn't Rename the Theme"), message: reason) + model.raise(ThemeLibraryAlert(title: String(localized: "Couldn't Rename the Theme"), message: reason)) return } model.registerRename(id, back: current, undoManager: undoManager) } } - // MARK: - Export - internal func exportDocument(for id: String) -> ThemeFileDocument? { editors.editor(for: id)?.flush() guard let theme = catalog.storedTheme(id: id) else { return nil } @@ -322,12 +415,15 @@ internal final class ThemeLibraryModel: ObservableObject { return cleaned.isEmpty ? theme.id : cleaned } - /// A copy in a folder of its own rather than the theme's file, because Finder may move a dragged - /// file instead of copying it, and a built-in theme has no file. + // A copy, because Finder may move a dragged file rather than copy it, and a built-in has no file. + // One folder per theme, emptied on each drag, so drags never pile up copies. internal func dragExportURL(for id: String) throws -> URL { editors.editor(for: id)?.flush() guard let theme = catalog.storedTheme(id: id) else { throw CocoaError(.fileNoSuchFile) } - let folder = dragDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true) + let folder = dragDirectory.appendingPathComponent(id, isDirectory: true) + if FileManager.default.fileExists(atPath: folder.path) { + try FileManager.default.removeItem(at: folder) + } try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) let url = folder.appendingPathComponent(Self.exportFileName(for: theme) + ".json", isDirectory: false) try ThemeFileFormat.encode(theme).write(to: url, options: .atomic) @@ -348,26 +444,23 @@ internal final class ThemeLibraryModel: ObservableObject { url.standardizedFileURL.path.hasPrefix(dragDirectory.standardizedFileURL.path + "/") } - // MARK: - Finder - internal func revealInFinder(_ item: ThemeLibraryItem?) { if case let .theme(id) = item, let url = catalog.fileURL(for: id) { revealInFinder([url]) } else if let record = record(for: item) { revealInFinder([URL(fileURLWithPath: record.path)]) - } else { - revealInFinder([catalog.themesDirectory]) } } + internal func revealThemesFolder() { + revealInFinder([catalog.themesDirectory]) + } + internal func retryLoading() { catalog.reloadSynchronously() } - // MARK: - Trash - - /// Asked only when the trash changes what the windows draw. Moving a theme nothing uses is undone - /// from the Edit menu, so it needs no alert. + // Asked only when the trash changes what the windows draw; any other trash is undone from the Edit menu. internal func trashConfirmation(for item: ThemeLibraryItem) -> ThemeTrashConfirmation? { guard let theme = theme(for: item), theme.isEditable else { return nil } let current = selection.themeSelection @@ -392,7 +485,7 @@ internal final class ThemeLibraryModel: ObservableObject { } return ThemeTrashConfirmation( item: item, - title: String(format: String(localized: "Delete “%@”?"), theme.name), + title: String(format: String(localized: "Move “%@” to the Trash?"), theme.name), message: message ) } @@ -458,9 +551,7 @@ internal final class ThemeLibraryModel: ObservableObject { } } - // MARK: - Undoing a creation - - /// The way Finder undoes a duplicate: the new file goes to the Trash, and Redo brings it back. + // As Finder undoes a duplicate: the new file goes to the Trash, and Redo brings it back. private func registerCreation(of ids: [String], actionName: String, undoManager: UndoManager?) { guard let undoManager, !ids.isEmpty else { return } register(on: undoManager, actionName: actionName) { model in @@ -497,7 +588,7 @@ internal final class ThemeLibraryModel: ObservableObject { registerCreation(of: ids, actionName: actionName, undoManager: undoManager) } - /// A group of its own, so each action is one undo whether or not the manager groups by event. + // A group of its own, so each action is one undo whether or not the manager groups by event. private func register( on undoManager: UndoManager, actionName: String, @@ -513,8 +604,6 @@ internal final class ThemeLibraryModel: ObservableObject { undoManager.endUndoGrouping() } - // MARK: - Failures - private func perform(_ title: String, _ work: () throws -> Value) -> Value? { do { return try work() @@ -526,13 +615,17 @@ internal final class ThemeLibraryModel: ObservableObject { private func fail(_ title: String, _ error: Error) { Self.logger.error("Theme action failed: \(error.publicLogShape, privacy: .public)") - alert = ThemeLibraryAlert(title: title, message: error.localizedDescription) + raise(ThemeLibraryAlert(title: title, message: error.localizedDescription)) + } + + private func raise(_ alert: ThemeLibraryAlert) { + if presentOffPage?(alert) == true { return } + self.alert = alert } } internal extension AppearanceSettings { - /// A slot that held a theme the user just trashed goes back to its built-in, so the popup does - /// not then report that theme as missing. + // A slot that held a trashed theme goes back to its built-in, so the pop-up does not report it missing. func releasing(themeId: String) -> AppearanceSettings { var updated = self if updated.preferredLightThemeId == themeId { @@ -544,8 +637,7 @@ internal extension AppearanceSettings { return updated } - /// Undo of a trash puts the theme back only into the slots the trash released and nothing has - /// chosen since. + // Undo of a trash refills only the slots the trash released and nothing has chosen since. func reclaiming(themeId: String, from before: AppearanceSettings) -> AppearanceSettings { var updated = self if before.preferredLightThemeId == themeId, updated.preferredLightThemeId == BuiltInThemes.defaultLightId { diff --git a/apple/TablePro/Views/Settings/Appearance/ThemeLibrarySection.swift b/apple/TablePro/Views/Settings/Appearance/ThemeLibrarySection.swift index e5da101404..c771368268 100644 --- a/apple/TablePro/Views/Settings/Appearance/ThemeLibrarySection.swift +++ b/apple/TablePro/Views/Settings/Appearance/ThemeLibrarySection.swift @@ -3,15 +3,9 @@ import SwiftUI import TableProTheme import UniformTypeIdentifiers -/// Every theme on this Mac in one list: the built-ins, the user's own, and the files that did not -/// load. The add and remove pair and the action pull-down sit under it the way macOS puts them under -/// a list. A context menu acts on the row under the pointer, which is not always the selected one. +// A context menu acts on the row under the pointer, which is not always the selected one. internal struct ThemeLibrarySection: View { - @StateObject private var model = ThemeLibraryModel( - catalog: .shared, - selection: AppSettingsManager.shared, - editors: ThemeEditorWindows.shared - ) + @ObservedObject private var model: ThemeLibraryModel @Environment(\.undoManager) private var undoManager @@ -33,80 +27,73 @@ internal struct ThemeLibrarySection: View { // A two-line theme row. The table sizes a row it has not measured at this estimate, and an // accessibility read makes it drop and remeasure off-screen rows, so any other value moves the rows. private static let rowHeight: CGFloat = 42 - /// A grouped Form centers its sections at most this wide (measured on macOS 27), so the list keeps - /// the edges of the sections above it. - private static let formContentWidth: CGFloat = 704 - private static let formMargin: CGFloat = 20 - /// How far a grouped Form indents its section headers from the section's edge. - private static let headerInset: CGFloat = 10 + + internal init(model: ThemeLibraryModel) { + self._model = ObservedObject(wrappedValue: model) + } internal var body: some View { - VStack(alignment: .leading, spacing: 8) { - Text("Themes") - .font(.headline) - .padding(.horizontal, Self.headerInset) - .accessibilityAddTraits(.isHeader) + SettingsFullPageList { list - .alert( - model.alert?.title ?? "", - isPresented: isPresented($model.alert), - presenting: model.alert - ) { _ in - Button(String(localized: "OK")) {} - } message: { alert in - Text(alert.message) - } - .alert( - pendingTrash?.title ?? "", - isPresented: isPresented($pendingTrash), - presenting: pendingTrash - ) { confirmation in - Button(String(localized: "Move to Trash"), role: .destructive) { - trash(confirmation.item) - } - Button(String(localized: "Cancel"), role: .cancel) {} - } message: { confirmation in - Text(confirmation.message) - } - .fileImporter(isPresented: $isImporting, allowedContentTypes: [.json], allowsMultipleSelection: true) { result in - guard case let .success(urls) = result else { return } - importThemes(urls) - } - .fileExporter( - isPresented: isPresented($exporting), - document: exporting?.document, - contentType: .json, - defaultFilename: exporting?.fileName - ) { _ in } + } bar: { + bar + } + .accessibilityElement(children: .contain) + .accessibilityIdentifier(SettingsPage.manageThemes.pageIdentifier) + .alert( + model.alert?.title ?? "", + isPresented: isPresented($model.alert), + presenting: model.alert + ) { _ in + Button(String(localized: "OK")) {} + } message: { alert in + Text(alert.message) + } + .alert( + pendingTrash?.title ?? "", + isPresented: isPresented($pendingTrash), + presenting: pendingTrash + ) { confirmation in + Button(String(localized: "Move to Trash"), role: .destructive) { + trash(confirmation.item) + } + Button(String(localized: "Cancel"), role: .cancel) {} + } message: { confirmation in + Text(confirmation.message) + } + .fileImporter(isPresented: $isImporting, allowedContentTypes: [.json], allowsMultipleSelection: true) { result in + guard case let .success(urls) = result else { return } + importThemes(urls) } - .frame(maxWidth: Self.formContentWidth) - .padding(.horizontal, Self.formMargin) - .padding(.bottom, Self.formMargin) - .frame(maxWidth: .infinity) + .fileExporter( + isPresented: isPresented($exporting), + document: exporting?.document, + contentType: .json, + defaultFilename: exporting?.fileName + ) { _ in } } - // MARK: - List - - /// The user's own themes come first: fourteen built-ins above them would push the rows a person - /// creates, renames and trashes out of sight. + // The user's own themes come first: the built-ins above them would push the rows a person + // creates, renames and trashes out of sight. private var list: some View { - ScrollViewReader { proxy in + let inUse = model.inUseThemeIds + return ScrollViewReader { proxy in List(selection: $selection) { Section(String(localized: "Custom")) { if model.customThemes.isEmpty { - Text("Duplicate a theme or import one to customize colors.") + Text("Click + to add a theme, or drop a TablePro or VS Code theme file here.") .foregroundStyle(.secondary) .accessibilityIdentifier("appearance-themes-custom-empty") } ForEach(model.customThemes) { theme in - themeRow(theme) + themeRow(theme, isInUse: inUse.contains(theme.id)) .tag(ThemeLibraryItem.theme(theme.id)) .id(ThemeLibraryItem.theme(theme.id)) } } if !model.notLoaded.isEmpty { - Section(String(localized: "Not Loaded")) { + Section(String(localized: "Couldn't Load")) { ForEach(model.notLoaded) { record in notLoadedRow(record) .tag(ThemeLibraryItem.notLoaded(path: record.path)) @@ -117,49 +104,57 @@ internal struct ThemeLibrarySection: View { Section(String(localized: "Built-in")) { ForEach(model.builtInThemes) { theme in - themeRow(theme) + themeRow(theme, isInUse: inUse.contains(theme.id)) .tag(ThemeLibraryItem.theme(theme.id)) .id(ThemeLibraryItem.theme(theme.id)) } } } - .listStyle(.bordered(alternatesRowBackgrounds: false)) .environment(\.defaultMinListRowHeight, Self.rowHeight) - .frame(minHeight: Self.minimumListHeight, maxHeight: .infinity) - .accessibilityIdentifier("appearance-themes-list") .contextMenu(forSelectionType: ThemeLibraryItem.self) { items in - rowMenu(for: items.first) + if let item = items.first { + menuItems(for: item, dimsUnavailable: false) + } else { + emptyAreaMenu + } } primaryAction: { items in guard case let .theme(id) = items.first else { return } model.edit(id) } - .onDeleteCommand { requestTrash(selection) } + .onDeleteCommand { + if model.canTrash(selection) { + requestTrash(selection) + } else { + NSSound.beep() + } + } .dropDestination(for: URL.self) { urls, _ in let files = urls.filter(\.isFileURL) guard !files.isEmpty else { return false } importThemes(files) return true } - .safeAreaInset(edge: .bottom, spacing: 0) { - footer - } .onChange(of: selection) { item in guard let item else { return } proxy.scrollTo(item) } + .frame(minHeight: Self.minimumListHeight, maxHeight: .infinity) + .accessibilityElement(children: .contain) + .accessibilityIdentifier("appearance-themes-list") } } @ViewBuilder - private func themeRow(_ theme: ThemeDefinition) -> some View { + private func themeRow(_ theme: ThemeDefinition, isInUse: Bool) -> some View { if renamingId == theme.id { renameField(for: theme) } else { + // No combined element: the UI tests find a row by its name's text. VStack(alignment: .leading, spacing: 1) { Text(theme.name) .lineLimit(1) - Text(ThemeLibraryModel.appearanceLabel(theme.appearance)) - .font(.caption) + Text(ThemeLibraryModel.rowSubtitle(theme.appearance, isInUse: isInUse)) + .font(.subheadline) .foregroundStyle(.secondary) } .padding(.vertical, 2) @@ -181,7 +176,7 @@ internal struct ThemeLibrarySection: View { .accessibilityIdentifier("appearance-theme-rename-field") if let renameError { NoticeLabel(renameError, severity: .error) - .font(.caption) + .font(.subheadline) .accessibilityIdentifier("appearance-theme-rename-error") } } @@ -193,7 +188,7 @@ internal struct ThemeLibrarySection: View { Text(record.fileName) .lineLimit(1) Text(record.reason) - .font(.caption) + .font(.subheadline) .foregroundStyle(.secondary) .lineLimit(3) .fixedSize(horizontal: false, vertical: true) @@ -202,137 +197,104 @@ internal struct ThemeLibrarySection: View { .help(record.reason) } - /// A contextual menu leaves out what does not apply; the pull-down below dims it instead. - @ViewBuilder - private func rowMenu(for item: ThemeLibraryItem?) -> some View { - if let theme = model.theme(for: item) { - if theme.isEditable { - Button(String(localized: "Edit…")) { model.edit(theme.id) } - } - Button(String(localized: "Duplicate")) { duplicate(theme.id) } - if theme.isEditable { - RenameButton() - .renameAction { beginRename(theme) } - } - Button(String(localized: "Export…")) { export(theme.id) } - if let slot = model.availableSlot(for: theme) { - Button(useTitle(for: slot)) { model.use(theme.id, for: slot) } - } - if theme.isEditable { - Button(String(localized: "Show in Finder")) { model.revealInFinder(item) } + private var bar: some View { + SettingsListBar( + addLabel: String(localized: "Add Theme"), + removeLabel: String(localized: "Move to Trash"), + canRemove: model.canTrash(selection), + addIdentifier: "appearance-theme-add", + removeIdentifier: "appearance-theme-remove", + addMenu: { addMenuItems }, + onRemove: { requestTrash(selection) }, + actionsLabel: String(localized: "Theme Actions"), + actionsIdentifier: "appearance-theme-actions", + actions: { + menuItems(for: selection, dimsUnavailable: true) Divider() - Button(String(localized: "Move to Trash")) { requestTrash(item) } + showThemesFolderButton } - } else if let item, model.record(for: item) != nil { - Button(String(localized: "Show in Finder")) { model.revealInFinder(item) } - Button(String(localized: "Try Again")) { model.retryLoading() } - Divider() - Button(String(localized: "Move to Trash")) { requestTrash(item) } - } + ) } - private func useTitle(for slot: ThemeAppearance) -> String { - switch slot { - case .light: return String(localized: "Use for Light Appearance") - case .dark: return String(localized: "Use for Dark Appearance") - } + @ViewBuilder + private var addMenuItems: some View { + newThemeMenu + Divider() + importButton } - // MARK: - Footer - - private var footer: some View { - VStack(spacing: 0) { - Divider() - HStack(spacing: 0) { - ControlGroup { - addMenu - - Button { - requestTrash(selection) - } label: { - Label(String(localized: "Move to Trash"), systemImage: "minus") - .labelStyle(.iconOnly) - } - .help(String(localized: "Move to Trash")) - .accessibilityLabel(String(localized: "Move to Trash")) - .accessibilityIdentifier("appearance-theme-remove") - .disabled(!model.canTrash(selection)) - - actionsMenu - } - .controlGroupStyle(.navigation) - .controlSize(.small) - .fixedSize() - - Spacer() - } - .padding(.horizontal, 4) - .padding(.vertical, 2) - } - .background(.bar) + @ViewBuilder + private var emptyAreaMenu: some View { + newThemeMenu + importButton + Divider() + showThemesFolderButton } - /// An icon-only `Menu` is named only through `.contain` plus a label on the menu itself; a - /// label inside its label closure leaves VoiceOver reading "More", or nothing on CI. - private var addMenu: some View { - Menu { - Menu(String(localized: "New Theme Based On")) { - ForEach(model.builtInThemes) { theme in + private var newThemeMenu: some View { + Menu(String(localized: "New Theme Based On")) { + ForEach(model.builtInThemes) { theme in + Button(theme.name) { createTheme(basedOn: theme.id) } + } + if !model.customThemes.isEmpty { + Divider() + ForEach(model.customThemes) { theme in Button(theme.name) { createTheme(basedOn: theme.id) } } - if !model.customThemes.isEmpty { - Divider() - ForEach(model.customThemes) { theme in - Button(theme.name) { createTheme(basedOn: theme.id) } - } - } } - Divider() - Button(String(localized: "Import…")) { isImporting = true } - } label: { - Label(String(localized: "Add Theme"), systemImage: "plus") - .labelStyle(.iconOnly) } - .menuIndicator(.hidden) - .help(String(localized: "Add Theme")) - .accessibilityElement(children: .contain) - .accessibilityLabel(String(localized: "Add Theme")) - .accessibilityIdentifier("appearance-theme-add") } - private var actionsMenu: some View { - let theme = model.theme(for: selection) - return Menu { - Button(String(localized: "Edit…")) { - if let theme { model.edit(theme.id) } - } - .disabled(theme == nil) - Button(String(localized: "Duplicate")) { - if let theme { duplicate(theme.id) } - } - .disabled(theme == nil) - Button(String(localized: "Rename")) { - if let theme { beginRename(theme) } + private var importButton: some View { + Button(String(localized: "Import…")) { isImporting = true } + } + + private var showThemesFolderButton: some View { + Button(String(localized: "Show Themes Folder in Finder")) { model.revealThemesFolder() } + } + + // The context menu leaves out what does not apply; the pull-down dims it. + private func menuItems(for item: ThemeLibraryItem?, dimsUnavailable: Bool) -> some View { + let entries = model.menuEntries(for: item).filter { dimsUnavailable || $0.isEnabled } + return ForEach(Array(entries.enumerated()), id: \.element.action) { index, entry in + if entry.startsGroup, index > 0 { + Divider() } - .disabled(theme?.isEditable != true) - Button(String(localized: "Export…")) { - if let theme { export(theme.id) } + if entry.action == .rename, !dimsUnavailable { + RenameButton() + .renameAction { perform(.rename, on: item) } + } else { + Button(entry.action.title) { perform(entry.action, on: item) } + .disabled(!entry.isEnabled) } - .disabled(theme == nil) - Divider() - Button(String(localized: "Show in Finder")) { model.revealInFinder(selection) } - } label: { - Label(String(localized: "Theme Actions"), systemImage: "ellipsis.circle") - .labelStyle(.iconOnly) } - .menuIndicator(.hidden) - .help(String(localized: "Theme Actions")) - .accessibilityElement(children: .contain) - .accessibilityLabel(String(localized: "Theme Actions")) - .accessibilityIdentifier("appearance-theme-actions") } - // MARK: - Actions + private func perform(_ action: ThemeLibraryAction, on item: ThemeLibraryItem?) { + switch action { + case .edit, .showInEditor: + guard case let .theme(id) = item else { return } + model.edit(id) + case .duplicate: + guard case let .theme(id) = item else { return } + duplicate(id) + case .rename: + guard let theme = model.theme(for: item) else { return } + beginRename(theme) + case .export: + guard case let .theme(id) = item else { return } + export(id) + case let .use(slot): + guard case let .theme(id) = item else { return } + model.use(id, for: slot) + case .showInFinder: + model.revealInFinder(item) + case .tryAgain: + model.retryLoading() + case .moveToTrash: + requestTrash(item) + } + } private func duplicate(_ id: String) { guard let copy = model.duplicate(id, undoManager: undoManager) else { return } @@ -364,7 +326,7 @@ internal struct ThemeLibrarySection: View { renamingId = theme.id } - /// A taken name keeps the field open with the reason, the way Finder refuses one. + // A taken name keeps the field open with the reason, the way Finder refuses one. private func commitRename(_ id: String) { guard renamingId == id else { return } switch model.rename(id, to: renameText, undoManager: undoManager) { diff --git a/apple/TablePro/Views/Settings/AppearanceSettingsView.swift b/apple/TablePro/Views/Settings/AppearanceSettingsView.swift index 9170061c6a..18b7ed86dc 100644 --- a/apple/TablePro/Views/Settings/AppearanceSettingsView.swift +++ b/apple/TablePro/Views/Settings/AppearanceSettingsView.swift @@ -3,44 +3,36 @@ import TableProTheme internal struct AppearanceSettingsView: View { @Binding internal var settings: AppearanceSettings + @Binding internal var appearanceMode: AppAppearanceMode @ObservedObject private var catalog = ThemeCatalog.shared - @ObservedObject private var settingsManager = AppSettingsManager.shared private static let modes: [AppAppearanceMode] = [.auto, .light, .dark] internal var body: some View { - VStack(spacing: 0) { - settingsForm - ThemeLibrarySection() - } - } - - // A List inside a scrolling grouped Form does not scroll (measured on macOS 27), so the Form - // keeps its own height and the theme list sits below it. - private var settingsForm: some View { Form { Section { - Picker(String(localized: "Appearance"), selection: $settingsManager.appearanceMode) { + Picker(selection: $appearanceMode) { ForEach(Self.modes, id: \.self) { mode in Text(Self.title(for: mode)).tag(mode) } + } label: { + Text("Appearance") + Text("Controls, sidebars and Settings follow this. Applies to this Mac.") } + .pickerStyle(.segmented) .accessibilityIdentifier("appearance-mode-picker") - } footer: { - Text("Applies to this Mac.") } - Section { + Section("Themes") { themePicker(ThemeSlotChoice(slot: .light, savedId: settings.preferredLightThemeId, themes: catalog.themes)) themePicker(ThemeSlotChoice(slot: .dark, savedId: settings.preferredDarkThemeId, themes: catalog.themes)) - } footer: { - Text("Themes color the editor, the data grid, other content views and the window background. Controls, sidebars and Settings follow the system appearance.") + SettingsDrillRow(route: SettingsRoute.page(.manageThemes), title: SettingsPage.manageThemes.title) } } .formStyle(.grouped) - .scrollDisabled(true) - .fixedSize(horizontal: false, vertical: true) + .accessibilityElement(children: .contain) + .accessibilityIdentifier("settings-pane-appearance") } private static func title(for mode: AppAppearanceMode) -> String { @@ -69,11 +61,12 @@ internal struct AppearanceSettingsView: View { .accessibilityIdentifier("appearance-\(choice.slot.rawValue)-theme-note") } } + .pickerStyle(.menu) .accessibilityIdentifier("appearance-\(choice.slot.rawValue)-theme") } - /// The popup shows the theme in use, but only a pick writes the setting: a saved id this Mac - /// cannot resolve stays saved for the Mac that has the theme. + // Shows the theme in use, but only a pick writes: a saved id this Mac cannot resolve stays saved + // for the Mac that has the theme. private func selectionBinding(for choice: ThemeSlotChoice) -> Binding { Binding( get: { choice.selectedId }, @@ -90,6 +83,6 @@ internal struct AppearanceSettingsView: View { } #Preview { - AppearanceSettingsView(settings: .constant(.default)) - .frame(width: 720, height: 560) + AppearanceSettingsView(settings: .constant(.default), appearanceMode: .constant(.auto)) + .frame(width: 520, height: 480) } diff --git a/apple/TablePro/Views/Settings/ClaudeAgentDisclosureSection.swift b/apple/TablePro/Views/Settings/ClaudeAgentDisclosureSection.swift index 919d189762..8da2a7fd1d 100644 --- a/apple/TablePro/Views/Settings/ClaudeAgentDisclosureSection.swift +++ b/apple/TablePro/Views/Settings/ClaudeAgentDisclosureSection.swift @@ -1,8 +1,3 @@ -// -// ClaudeAgentDisclosureSection.swift -// TablePro -// - import SwiftUI struct ClaudeAgentDisclosureSection: View { @@ -10,22 +5,19 @@ struct ClaudeAgentDisclosureSection: View { Section { ForEach(ClaudeAgentDisclosure.notes) { note in Label { - Text(note.text) - .font(.callout) + Text(verbatim: note.text) .foregroundStyle(note.severity == .caution ? Color.primary : Color.secondary) .fixedSize(horizontal: false, vertical: true) } icon: { Image(systemName: note.severity.symbolName) .foregroundStyle(note.severity == .caution ? Color.orange : Color.secondary) + .accessibilityHidden(true) } .accessibilityElement(children: .combine) } + SettingsHelpRow(ClaudeAgentDisclosure.supportedAlternative) } header: { Text("Tradeoffs") - } footer: { - Text(ClaudeAgentDisclosure.supportedAlternative) - .font(.caption) - .foregroundStyle(.secondary) } } } diff --git a/apple/TablePro/Views/Settings/Components/AIProviderStatusLabel.swift b/apple/TablePro/Views/Settings/Components/AIProviderStatusLabel.swift index c3329020ea..9dc796176b 100644 --- a/apple/TablePro/Views/Settings/Components/AIProviderStatusLabel.swift +++ b/apple/TablePro/Views/Settings/Components/AIProviderStatusLabel.swift @@ -1,8 +1,3 @@ -// -// AIProviderStatusLabel.swift -// TablePro -// - import SwiftUI internal struct AIProviderStatusLabel: View { @@ -12,19 +7,21 @@ internal struct AIProviderStatusLabel: View { var body: some View { switch status { case .checking, .signingIn: - HStack(spacing: 6) { - ProgressView() - .controlSize(.small) - Text(status.title) + Label { + Text(verbatim: status.title) .foregroundStyle(.secondary) + } icon: { + ProgressView() + .controlSize(.mini) + .accessibilityHidden(true) } default: if let severity = status.severity { NoticeLabel(status.title, severity: severity) - } else if showsReadySymbol { + } else if showsReadySymbol, status.isReady { NoticeLabel(status.title, severity: .success) } else { - Text(status.title) + Text(verbatim: status.title) .foregroundStyle(.secondary) } } diff --git a/apple/TablePro/Views/Settings/Components/CopyableCodeBlock.swift b/apple/TablePro/Views/Settings/Components/CopyableCodeBlock.swift index 9f9ffb0948..523292ce14 100644 --- a/apple/TablePro/Views/Settings/Components/CopyableCodeBlock.swift +++ b/apple/TablePro/Views/Settings/Components/CopyableCodeBlock.swift @@ -8,7 +8,7 @@ struct CopyableCodeBlock: View { var body: some View { HStack(alignment: .top) { Text(verbatim: displayText ?? text) - .font(.system(.caption, design: .monospaced)) + .font(.system(.callout, design: .monospaced)) .textSelection(.enabled) .padding(8) .frame(maxWidth: .infinity, alignment: .leading) diff --git a/apple/TablePro/Views/Settings/Components/SettingsChoices.swift b/apple/TablePro/Views/Settings/Components/SettingsChoices.swift new file mode 100644 index 0000000000..798a43b822 --- /dev/null +++ b/apple/TablePro/Views/Settings/Components/SettingsChoices.swift @@ -0,0 +1,29 @@ +import SwiftUI + +enum SettingsChoices { + static func options(_ fixed: [Value], including current: Value) -> (fixed: [Value], extra: Value?) { + (fixed, fixed.contains(current) ? nil : current) + } +} + +// A pop-up whose stored value is off its list draws blank, so that value gets its own item after a divider. +struct SettingsChoiceItems: View { + private let fixed: [Value] + private let extra: Value? + private let title: (Value) -> Title + + init(_ values: [Value], including current: Value, @ViewBuilder title: @escaping (Value) -> Title) { + (fixed, extra) = SettingsChoices.options(values, including: current) + self.title = title + } + + var body: some View { + ForEach(fixed, id: \.self) { value in + title(value).tag(value) + } + if let extra { + Divider() + title(extra).tag(extra) + } + } +} diff --git a/apple/TablePro/Views/Settings/Components/SettingsDrillRow.swift b/apple/TablePro/Views/Settings/Components/SettingsDrillRow.swift new file mode 100644 index 0000000000..9f1316355c --- /dev/null +++ b/apple/TablePro/Views/Settings/Components/SettingsDrillRow.swift @@ -0,0 +1,60 @@ +import SwiftUI + +protocol SettingsDrillIdentifying { + var settingsDrillIdentifier: String? { get } +} + +struct SettingsDrillRow: View { + private let route: Route + private let title: Text + private let subtitle: LocalizedStringKey? + private let value: String? + private let identifier: String? + + init( + route: Route, + title: LocalizedStringKey, + value: String? = nil, + subtitle: LocalizedStringKey? = nil, + identifier: String? = nil + ) { + self.init(route: route, titleText: Text(title), value: value, subtitle: subtitle, identifier: identifier) + } + + @_disfavoredOverload + init( + route: Route, + title: Title, + value: String? = nil, + subtitle: LocalizedStringKey? = nil, + identifier: String? = nil + ) { + self.init(route: route, titleText: Text(title), value: value, subtitle: subtitle, identifier: identifier) + } + + private init(route: Route, titleText: Text, value: String?, subtitle: LocalizedStringKey?, identifier: String?) { + self.route = route + self.title = titleText + self.subtitle = subtitle + self.value = value + // Route stays any Hashable for NavigationLink, so the page id comes from a route that adopts the protocol. + self.identifier = identifier ?? (route as? any SettingsDrillIdentifying)?.settingsDrillIdentifier + } + + var body: some View { + NavigationLink(value: route) { + LabeledContent { + if let value { + Text(value) + .foregroundStyle(.secondary) + } + } label: { + title + if let subtitle { + Text(subtitle) + } + } + } + .accessibilityIdentifier(identifier ?? "") + } +} diff --git a/apple/TablePro/Views/Settings/Components/SettingsFormat.swift b/apple/TablePro/Views/Settings/Components/SettingsFormat.swift new file mode 100644 index 0000000000..48369c424d --- /dev/null +++ b/apple/TablePro/Views/Settings/Components/SettingsFormat.swift @@ -0,0 +1,38 @@ +import Foundation + +enum SettingsFormat { + static var ungrouped: IntegerFormatStyle { .number.grouping(.never) } + + static func duration(seconds: Int, locale: Locale = .autoupdatingCurrent) -> String { + Duration.seconds(seconds).formatted( + Duration.UnitsFormatStyle(allowedUnits: [.hours, .minutes, .seconds], width: .wide).locale(locale) + ) + } + + static func count(_ value: Int, locale: Locale = .autoupdatingCurrent) -> String { + value.formatted(.number.locale(locale)) + } + + // Ports and identifiers: "23508", never "23,508" or "23.508". + static func identifier(_ value: Int, locale: Locale = .autoupdatingCurrent) -> String { + value.formatted(ungrouped.locale(locale)) + } + + // Whole years read as "1 year" rather than "365 days". + static func days(_ days: Int, locale: Locale = .autoupdatingCurrent) -> String { + let formatter = DateComponentsFormatter() + formatter.unitsStyle = .full + var calendar = Calendar.autoupdatingCurrent + calendar.locale = locale + formatter.calendar = calendar + let components: DateComponents + if days != 0, days.isMultiple(of: 365) { + formatter.allowedUnits = [.year] + components = DateComponents(year: days / 365) + } else { + formatter.allowedUnits = [.day] + components = DateComponents(day: days) + } + return formatter.string(from: components) ?? count(days, locale: locale) + } +} diff --git a/apple/TablePro/Views/Settings/Components/SettingsFullPageList.swift b/apple/TablePro/Views/Settings/Components/SettingsFullPageList.swift new file mode 100644 index 0000000000..ab753adf2c --- /dev/null +++ b/apple/TablePro/Views/Settings/Components/SettingsFullPageList.swift @@ -0,0 +1,46 @@ +import AppKit +import SwiftUI + +// Not a grouped Form: a List inside one does not scroll. +struct SettingsFullPageList: View { + private static var borderWidth: CGFloat { 1 } + + private let content: Content + private let emptyState: EmptyState + private let bar: Bar + + init( + @ViewBuilder content: () -> Content, + @ViewBuilder emptyState: () -> EmptyState = { EmptyView() }, + @ViewBuilder bar: () -> Bar = { EmptyView() } + ) { + self.content = content() + self.emptyState = emptyState() + self.bar = bar() + } + + var body: some View { + list + .frame(maxHeight: .infinity) + .padding(20) + } + + @ViewBuilder + private var list: some View { + let bordered = content + .listStyle(.bordered(alternatesRowBackgrounds: false)) + .overlay { emptyState } + + if Bar.self == EmptyView.self { + bordered + } else { + // An inset, unlike the .listBar overlay, scrolls the last row clear of the bar. + bordered.safeAreaInset(edge: .bottom, spacing: 0) { + ListBar { bar } + // Rows scroll under the bar, so it needs the list's fill, kept inside the border. + .background(Color(nsColor: .controlBackgroundColor)) + .padding([.horizontal, .bottom], Self.borderWidth) + } + } + } +} diff --git a/apple/TablePro/Views/Settings/Components/SettingsHelpRow.swift b/apple/TablePro/Views/Settings/Components/SettingsHelpRow.swift new file mode 100644 index 0000000000..60477fdced --- /dev/null +++ b/apple/TablePro/Views/Settings/Components/SettingsHelpRow.swift @@ -0,0 +1,22 @@ +import SwiftUI + +struct SettingsHelpRow: View { + private let text: Text + + init(_ text: LocalizedStringKey) { + self.text = Text(text) + } + + @_disfavoredOverload + init(_ text: S) { + self.text = Text(text) + } + + var body: some View { + text + .font(.subheadline) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + .frame(maxWidth: .infinity, alignment: .leading) + } +} diff --git a/apple/TablePro/Views/Settings/Components/SettingsListBar.swift b/apple/TablePro/Views/Settings/Components/SettingsListBar.swift new file mode 100644 index 0000000000..ce3b27fc76 --- /dev/null +++ b/apple/TablePro/Views/Settings/Components/SettingsListBar.swift @@ -0,0 +1,252 @@ +import AppKit +import SwiftUI + +// Only the row: SettingsFullPageList draws the bar's divider and fill inside the list's border. +struct SettingsListBar: View { + private struct AddRemove { + let addLabel: String + let removeLabel: String + let canAdd: Bool + let canRemove: Bool + let addHelp: String? + let removeHelp: String? + let addIdentifier: String? + let removeIdentifier: String? + // nil when + opens the add menu. + let onAdd: (() -> Void)? + let onRemove: () -> Void + } + + private static var slotInset: CGFloat { 8 } + + private let addRemove: AddRemove? + private let addMenu: AddMenu + private let actionsLabel: String + private let actionsIdentifier: String? + private let actions: Actions + private let leading: Leading + private let trailing: Trailing + + private init( + addRemove: AddRemove?, + addMenu: AddMenu, + actionsLabel: String, + actionsIdentifier: String?, + actions: Actions, + leading: Leading, + trailing: Trailing + ) { + self.addRemove = addRemove + self.addMenu = addMenu + self.actionsLabel = actionsLabel + self.actionsIdentifier = actionsIdentifier + self.actions = actions + self.leading = leading + self.trailing = trailing + } + + init( + addLabel: String, + removeLabel: String, + canAdd: Bool = true, + canRemove: Bool = true, + addHelp: String? = nil, + removeHelp: String? = nil, + addIdentifier: String? = nil, + removeIdentifier: String? = nil, + @ViewBuilder addMenu: () -> AddMenu, + onRemove: @escaping () -> Void, + actionsLabel: String = String(localized: "Actions"), + actionsIdentifier: String? = nil, + @ViewBuilder actions: () -> Actions = { EmptyView() }, + @ViewBuilder leading: () -> Leading = { EmptyView() }, + @ViewBuilder trailing: () -> Trailing = { EmptyView() } + ) { + self.init( + addRemove: AddRemove( + addLabel: addLabel, + removeLabel: removeLabel, + canAdd: canAdd, + canRemove: canRemove, + addHelp: addHelp, + removeHelp: removeHelp, + addIdentifier: addIdentifier, + removeIdentifier: removeIdentifier, + onAdd: nil, + onRemove: onRemove + ), + addMenu: addMenu(), + actionsLabel: actionsLabel, + actionsIdentifier: actionsIdentifier, + actions: actions(), + leading: leading(), + trailing: trailing() + ) + } + + var body: some View { + HStack(spacing: 0) { + if let addRemove { + addControl(addRemove) + ListBarSeparator() + ListBarButton( + label: addRemove.removeLabel, + systemImage: "minus", + help: addRemove.removeHelp, + identifier: addRemove.removeIdentifier, + action: addRemove.onRemove + ) + .disabled(!addRemove.canRemove) + } + + if Self.isPresent(Actions.self) { + if addRemove != nil { + ListBarSeparator() + } + SettingsListBarMenu( + label: actionsLabel, + systemImage: "ellipsis.circle", + help: nil, + identifier: actionsIdentifier + ) { + actions + } + } + + if Self.isPresent(Leading.self) { + slot(leading) + } + + Spacer(minLength: 0) + + if Self.isPresent(Trailing.self) { + slot(trailing) + .fixedSize() + } + } + } + + @ViewBuilder + private func addControl(_ addRemove: AddRemove) -> some View { + if let onAdd = addRemove.onAdd { + ListBarButton( + label: addRemove.addLabel, + systemImage: "plus", + help: addRemove.addHelp, + identifier: addRemove.addIdentifier, + action: onAdd + ) + .disabled(!addRemove.canAdd) + } else { + SettingsListBarMenu( + label: addRemove.addLabel, + systemImage: "plus", + help: addRemove.addHelp, + identifier: addRemove.addIdentifier + ) { + addMenu + } + .disabled(!addRemove.canAdd) + } + } + + // A regular push button is taller than the 23pt bar. + private func slot(_ content: some View) -> some View { + content + .font(.subheadline) + .controlSize(.small) + .lineLimit(1) + .padding(.horizontal, Self.slotInset) + } + + private static func isPresent(_: V.Type) -> Bool { + V.self != EmptyView.self + } +} + +extension SettingsListBar where AddMenu == EmptyView { + init( + addLabel: String, + removeLabel: String, + canAdd: Bool = true, + canRemove: Bool = true, + addHelp: String? = nil, + removeHelp: String? = nil, + addIdentifier: String? = nil, + removeIdentifier: String? = nil, + onAdd: @escaping () -> Void, + onRemove: @escaping () -> Void, + actionsLabel: String = String(localized: "Actions"), + actionsIdentifier: String? = nil, + @ViewBuilder actions: () -> Actions = { EmptyView() }, + @ViewBuilder leading: () -> Leading = { EmptyView() }, + @ViewBuilder trailing: () -> Trailing = { EmptyView() } + ) { + self.init( + addRemove: AddRemove( + addLabel: addLabel, + removeLabel: removeLabel, + canAdd: canAdd, + canRemove: canRemove, + addHelp: addHelp, + removeHelp: removeHelp, + addIdentifier: addIdentifier, + removeIdentifier: removeIdentifier, + onAdd: onAdd, + onRemove: onRemove + ), + addMenu: EmptyView(), + actionsLabel: actionsLabel, + actionsIdentifier: actionsIdentifier, + actions: actions(), + leading: leading(), + trailing: trailing() + ) + } +} + +extension SettingsListBar where AddMenu == EmptyView, Actions == EmptyView { + init( + @ViewBuilder leading: () -> Leading = { EmptyView() }, + @ViewBuilder trailing: () -> Trailing = { EmptyView() } + ) { + self.init( + addRemove: nil, + addMenu: EmptyView(), + actionsLabel: "", + actionsIdentifier: nil, + actions: EmptyView(), + leading: leading(), + trailing: trailing() + ) + } +} + +private struct SettingsListBarMenu: View { + let label: String + let systemImage: String + let help: String? + let identifier: String? + @ViewBuilder let items: Items + + var body: some View { + Menu { + items + } label: { + Label(label, systemImage: systemImage) + .labelStyle(.iconOnly) + .font(.system(size: NSFont.smallSystemFontSize)) + .foregroundStyle(.secondary) + .frame(width: ListBarMetrics.buttonWidth, height: ListBarMetrics.contentHeight) + .contentShape(Rectangle()) + } + // Plain, not borderless: a borderless menu is an NSPopUpButton that ignores this label's font, color and frame. + .menuStyle(.button) + .buttonStyle(.plain) + .menuIndicator(.hidden) + .fixedSize() + .help(help ?? label) + .accessibilityLabel(label) + .accessibilityIdentifier(identifier ?? "") + } +} diff --git a/apple/TablePro/Views/Settings/Components/SettingsNumberField.swift b/apple/TablePro/Views/Settings/Components/SettingsNumberField.swift new file mode 100644 index 0000000000..5fa38897c4 --- /dev/null +++ b/apple/TablePro/Views/Settings/Components/SettingsNumberField.swift @@ -0,0 +1,161 @@ +import SwiftUI + +enum SettingsInvalidEntry: Equatable, Sendable { + case clamp + case reject(String) +} + +enum SettingsIntegerInput { + // Foundation's integer parsing reads "1,000" as 1 and "1e3" as 1000, so only a sign and decimal digits pass. + static func parse(_ text: String) -> Int? { + var digits = Substring(text.trimmingCharacters(in: .whitespacesAndNewlines)) + var isNegative = false + if let sign = digits.first, sign == "-" || sign == "\u{2212}" { + isNegative = true + digits = digits.dropFirst() + } + guard !digits.isEmpty else { return nil } + var magnitude = 0 + for character in digits { + guard character.unicodeScalars.count == 1, + let scalar = character.unicodeScalars.first, + scalar.properties.numericType == .decimal, + let digit = character.wholeNumberValue else { return nil } + let (shifted, shiftOverflow) = magnitude.multipliedReportingOverflow(by: 10) + let (sum, addOverflow) = shifted.addingReportingOverflow(digit) + guard !shiftOverflow, !addOverflow else { return nil } + magnitude = sum + } + return isNegative ? -magnitude : magnitude + } + + static func resolve(_ text: String, in range: ClosedRange, invalid: SettingsInvalidEntry) -> SettingsDraftResolution { + guard let number = parse(text) else { + switch invalid { + case .clamp: return .revert + case .reject(let message): return .reject(message) + } + } + if range.contains(number) { return .accept(number) } + switch invalid { + case .clamp: return .accept(min(max(number, range.lowerBound), range.upperBound)) + case .reject(let message): return .reject(message) + } + } +} + +struct SettingsNumberField: View { + private let title: LocalizedStringKey + private let subtitle: LocalizedStringKey? + @Binding private var value: Int + private let range: ClosedRange + private let step: Int? + private let unit: LocalizedStringResource? + private let width: CGFloat + private let invalid: SettingsInvalidEntry + private let identifier: String? + + @State private var draft: SettingsTextDraft + @FocusState private var isFocused: Bool + + init( + _ title: LocalizedStringKey, + subtitle: LocalizedStringKey? = nil, + value: Binding, + range: ClosedRange, + step: Int? = nil, + unit: LocalizedStringResource? = nil, + width: CGFloat = 64, + invalid: SettingsInvalidEntry = .clamp, + identifier: String? = nil + ) { + self.title = title + self.subtitle = subtitle + _value = value + self.range = range + self.step = step + self.unit = unit + self.width = width + self.invalid = invalid + self.identifier = identifier + _draft = State(initialValue: SettingsTextDraft(SettingsFormat.identifier(value.wrappedValue))) + } + + var body: some View { + LabeledContent { + HStack(alignment: .firstTextBaseline, spacing: 6) { + TextField(text: $draft.text, prompt: nil) { Text(title) } + .labelsHidden() + .textFieldStyle(.roundedBorder) + .multilineTextAlignment(.trailing) + .frame(width: width) + .focused($isFocused) + .onSubmit(commit) + .onExitCommand { draft.revert() } + .accessibilityIdentifier(identifier ?? "") + + if let step { + Stepper(value: stepperValue, in: range, step: step) { Text(title) } + .labelsHidden() + .accessibilityValue(Text(verbatim: spokenValue)) + .accessibilityIdentifier(identifier.map { "\($0)-stepper" } ?? "") + } + + if let unit { + Text(unit) + .foregroundStyle(.secondary) + } + } + } label: { + Text(title) + if let error = draft.error { + NoticeLabel(error, severity: .error) + } else if let subtitle { + Text(subtitle) + } + } + .onChange(of: isFocused) { focused in + if !focused { commit() } + } + .onChange(of: draft.text) { _ in + draft.clearError(ifResolvedBy: resolve) + } + .onChange(of: value) { newValue in + draft.resync(to: SettingsFormat.identifier(newValue)) + } + .onAppear { + draft.resync(to: SettingsFormat.identifier(value)) + } + .onDisappear(perform: commit) + } + + private var spokenValue: String { + let number = SettingsFormat.identifier(value) + guard let unit else { return number } + return "\(number) \(String(localized: unit))" + } + + private var stepperValue: Binding { + Binding( + get: { value }, + set: { stepped in + let clamped = min(max(stepped, range.lowerBound), range.upperBound) + if clamped != value { value = clamped } + draft.settle(to: SettingsFormat.identifier(value)) + } + ) + } + + private func resolve(_ text: String) -> SettingsDraftResolution { + SettingsIntegerInput.resolve(text, in: range, invalid: invalid) + } + + private func commit() { + if let committed = draft.commit(to: value, resolve: resolve) { + value = committed + } + if draft.error == nil { + draft.settle(to: SettingsFormat.identifier(value)) + } + } +} diff --git a/apple/TablePro/Views/Settings/Components/SettingsRecordRow.swift b/apple/TablePro/Views/Settings/Components/SettingsRecordRow.swift new file mode 100644 index 0000000000..00e0e48b85 --- /dev/null +++ b/apple/TablePro/Views/Settings/Components/SettingsRecordRow.swift @@ -0,0 +1,137 @@ +import SwiftUI + +struct SettingsRecordRemoval { + let menuTitle: String + let actionName: String + let action: () -> Void + + static func remove(_ action: @escaping () -> Void) -> SettingsRecordRemoval { + SettingsRecordRemoval(menuTitle: String(localized: "Remove…"), actionName: String(localized: "Remove"), action: action) + } + + static func delete(_ action: @escaping () -> Void) -> SettingsRecordRemoval { + SettingsRecordRemoval(menuTitle: String(localized: "Delete…"), actionName: String(localized: "Delete"), action: action) + } +} + +struct SettingsRecordRow: View { + private struct EditActions { + let onEdit: () -> Void + let onDuplicate: (() -> Void)? + let removal: SettingsRecordRemoval? + let identifier: String? + } + + private let title: String + private let subtitle: String? + private let value: String? + private let trailing: Trailing + private var editActions: EditActions? + + init( + title: String, + subtitle: String? = nil, + value: String? = nil, + @ViewBuilder trailing: () -> Trailing = { EmptyView() } + ) { + self.title = title + self.subtitle = subtitle + self.value = value + self.trailing = trailing() + } + + func infoButton( + onEdit: @escaping () -> Void, + onDuplicate: (() -> Void)? = nil, + removal: SettingsRecordRemoval? = nil, + identifier: String? = nil + ) -> SettingsRecordRow { + var row = self + row.editActions = EditActions(onEdit: onEdit, onDuplicate: onDuplicate, removal: removal, identifier: identifier) + return row + } + + var body: some View { + HStack(spacing: 10) { + VStack(alignment: .leading, spacing: 1) { + Text(verbatim: title) + .lineLimit(1) + if let subtitle { + Text(verbatim: subtitle) + .font(.subheadline) + .foregroundStyle(.secondary) + .lineLimit(1) + .truncationMode(.middle) + } + } + .accessibilityElement(children: .combine) + .accessibilityActions { + if let editActions { + Button(String(localized: "Edit"), action: editActions.onEdit) + otherActions(editActions) + } + } + + Spacer(minLength: 8) + + if let value { + Text(verbatim: value) + .foregroundStyle(.secondary) + .monospacedDigit() + } + + trailing + + if let editActions { + Button(action: editActions.onEdit) { + Image(systemName: "info.circle") + .frame(width: 20, height: 20, alignment: .trailing) + .contentShape(Rectangle()) + } + .buttonStyle(.borderless) + .foregroundStyle(.secondary) + .help(String(localized: "Edit")) + .accessibilityLabel(String(format: String(localized: "Edit %@"), title)) + .accessibilityIdentifier(editActions.identifier ?? "") + .accessibilityActions { + otherActions(editActions) + } + } + } + .contentShape(Rectangle()) + .modifier(EditMenu(actions: editActions)) + .accessibilityElement(children: .contain) + } + + // An empty inner context menu would shadow one the caller attaches to the row. + private struct EditMenu: ViewModifier { + let actions: EditActions? + + func body(content: Content) -> some View { + if let actions { + content.contextMenu { + Button(String(localized: "Edit…"), action: actions.onEdit) + if let onDuplicate = actions.onDuplicate { + Button(String(localized: "Duplicate"), action: onDuplicate) + } + if let removal = actions.removal { + Divider() + Button(removal.menuTitle, role: .destructive, action: removal.action) + } + } + } else { + content + } + } + } + + @ViewBuilder + private func otherActions(_ actions: EditActions) -> some View { + if let onDuplicate = actions.onDuplicate { + Button(String(localized: "Duplicate"), action: onDuplicate) + } + if let removal = actions.removal { + Button(removal.actionName, action: removal.action) + } + } +} diff --git a/apple/TablePro/Views/Settings/Components/SettingsSectionActions.swift b/apple/TablePro/Views/Settings/Components/SettingsSectionActions.swift new file mode 100644 index 0000000000..ed619daf1b --- /dev/null +++ b/apple/TablePro/Views/Settings/Components/SettingsSectionActions.swift @@ -0,0 +1,16 @@ +import SwiftUI + +struct SettingsSectionActions: View { + private let content: Content + + init(@ViewBuilder content: () -> Content) { + self.content = content() + } + + var body: some View { + HStack(spacing: 8) { + Spacer(minLength: 0) + content + } + } +} diff --git a/apple/TablePro/Views/Settings/Components/SettingsTextDraft.swift b/apple/TablePro/Views/Settings/Components/SettingsTextDraft.swift new file mode 100644 index 0000000000..ecdf479883 --- /dev/null +++ b/apple/TablePro/Views/Settings/Components/SettingsTextDraft.swift @@ -0,0 +1,68 @@ +import Foundation + +enum SettingsDraftResolution: Equatable { + case accept(Value) + case revert + case reject(String) +} + +// Storage sees a value only through commit: typing never writes, and an untouched draft never overwrites a remote change. +struct SettingsTextDraft: Equatable, Sendable { + var text: String + private(set) var seed: String + private(set) var error: String? + + init(_ seed: String) { + text = seed + self.seed = seed + } + + var isEdited: Bool { text != seed } + + mutating func revert() { + text = seed + error = nil + } + + mutating func resync(to value: String) { + if text == seed { + text = value + error = nil + } + seed = value + } + + mutating func settle(to value: String) { + text = value + seed = value + error = nil + } + + mutating func commit( + to current: Value, + resolve: (String) -> SettingsDraftResolution + ) -> Value? { + guard isEdited else { + error = nil + return nil + } + switch resolve(text) { + case .accept(let value): + error = nil + return value == current ? nil : value + case .revert: + revert() + return nil + case .reject(let message): + error = message + return nil + } + } + + mutating func clearError(ifResolvedBy resolve: (String) -> SettingsDraftResolution) { + guard error != nil else { return } + if case .accept = resolve(text) { + error = nil + } + } +} diff --git a/apple/TablePro/Views/Settings/Components/SettingsTextField.swift b/apple/TablePro/Views/Settings/Components/SettingsTextField.swift new file mode 100644 index 0000000000..fd813d4ac4 --- /dev/null +++ b/apple/TablePro/Views/Settings/Components/SettingsTextField.swift @@ -0,0 +1,65 @@ +import SwiftUI + +struct SettingsTextField: View { + private let title: LocalizedStringKey + private let subtitle: LocalizedStringKey? + @Binding private var text: String + private let prompt: Text? + private let validate: (String) -> String? + private let normalize: (String) -> String + + @State private var draft: SettingsTextDraft + @FocusState private var isFocused: Bool + + init( + _ title: LocalizedStringKey, + subtitle: LocalizedStringKey? = nil, + text: Binding, + prompt: Text? = nil, + validate: @escaping (String) -> String? = { _ in nil }, + normalize: @escaping (String) -> String = { $0 } + ) { + self.title = title + self.subtitle = subtitle + _text = text + self.prompt = prompt + self.validate = validate + self.normalize = normalize + _draft = State(initialValue: SettingsTextDraft(text.wrappedValue)) + } + + var body: some View { + TextField(text: $draft.text, prompt: prompt) { + Text(title) + if let error = validate(draft.text) { + NoticeLabel(error, severity: .error) + } else if let subtitle { + Text(subtitle) + } + } + .focused($isFocused) + .onSubmit(commit) + .onExitCommand { draft.revert() } + .onChange(of: isFocused) { focused in + if !focused { commit() } + } + .onChange(of: text) { newValue in + draft.resync(to: newValue) + } + .onAppear { + draft.resync(to: text) + } + .onDisappear(perform: commit) + } + + private func resolve(_ candidate: String) -> SettingsDraftResolution { + validate(candidate) == nil ? .accept(normalize(candidate)) : .revert + } + + private func commit() { + if let committed = draft.commit(to: text, resolve: resolve) { + text = committed + } + draft.settle(to: text) + } +} diff --git a/apple/TablePro/Views/Settings/ConnectionsSettingsView.swift b/apple/TablePro/Views/Settings/ConnectionsSettingsView.swift new file mode 100644 index 0000000000..6cf0e8eb78 --- /dev/null +++ b/apple/TablePro/Views/Settings/ConnectionsSettingsView.swift @@ -0,0 +1,112 @@ +import SwiftUI +import TableProConnectionLibrary + +struct ConnectionsSettingsView: View { + @Binding var settings: GeneralSettings + private let listPreferences: ConnectionListPreferences + private let recentConnections: RecentConnectionsStore + + init( + settings: Binding, + listPreferences: ConnectionListPreferences = .shared, + recentConnections: RecentConnectionsStore = .shared + ) { + _settings = settings + self.listPreferences = listPreferences + self.recentConnections = recentConnections + } + + var body: some View { + Form { + Section { + Picker(selection: $settings.connectionHealthCheck) { + ForEach(ConnectionHealthCheck.allCases.filter { $0.interval != nil }) { option in + Text(option.title).tag(option) + } + Divider() + Text(ConnectionHealthCheck.onDemand.title).tag(ConnectionHealthCheck.onDemand) + } label: { + Text("Check open connections") + Text( + """ + A small query on each open connection catches a drop early. For a database that sleeps \ + when idle or bills per query, pick Only when used: it checks when you next use the connection. + """ + ) + } + .accessibilityIdentifier("connection-health-check-picker") + + Picker(selection: $settings.queryTimeoutSeconds) { + ForEach(GeneralSettings.queryTimeoutChoices(including: settings.queryTimeoutSeconds), id: \.self) { seconds in + Text(verbatim: GeneralSettings.queryTimeoutTitle(seconds)).tag(seconds) + } + Divider() + Text("No limit").tag(0) + } label: { + Text("Query timeout") + Text( + "Stops longer queries on drivers that support it. A connection's own timeout overrides this. Applies to connections opened after a change." + ) + } + .accessibilityIdentifier("query-timeout-picker") + } + + RecentConnectionsSection(listPreferences: listPreferences, recentConnections: recentConnections) + + ConnectionsPagesSection() + } + .formStyle(.grouped) + .accessibilityElement(children: .contain) + .accessibilityIdentifier("settings-pane-connections") + } +} + +private struct RecentConnectionsSection: View { + @ObservedObject var listPreferences: ConnectionListPreferences + @ObservedObject var recentConnections: RecentConnectionsStore + + var body: some View { + Section { + Toggle(isOn: Binding(get: { listPreferences.showsRecent }, set: { listPreferences.setShowsRecent($0) })) { + Text("Show recent connections") + Text("Adds a Recent section to the welcome window and the connection switcher.") + } + .accessibilityIdentifier("show-recent-connections-toggle") + + // Stays enabled while Recent is hidden: the history also drives the Last Connected sort. + LabeledContent { + Button(String(localized: "Clear Recent")) { + recentConnections.clear() + } + .disabled(recentConnections.ledger.isEmpty) + .accessibilityLabel(Text("Clear Recent Connections")) + .accessibilityIdentifier("clear-recent-connections-button") + } label: { + Text("Connection history") + Text("When you last opened each connection, used by Recent and the Last Connected sort. Stays on this Mac.") + } + } header: { + Text("Recent Connections") + } + } +} + +private struct ConnectionsPagesSection: View { + @EnvironmentObject private var linkedFolders: LinkedFoldersModel + @EnvironmentObject private var trustedLinks: TrustedLinksModel + + var body: some View { + Section { + SettingsDrillRow( + route: SettingsRoute.page(.linkedFolders), + title: SettingsPage.linkedFolders.title, + value: SettingsFormat.count(linkedFolders.folders.count) + ) + SettingsDrillRow( + route: SettingsRoute.page(.trustedLinks), + title: SettingsPage.trustedLinks.title, + value: SettingsFormat.count(trustedLinks.entries.count) + ) + } + } +} diff --git a/apple/TablePro/Views/Settings/CustomSlashCommandsSection.swift b/apple/TablePro/Views/Settings/CustomSlashCommandsSection.swift index 07487a6fac..5bc84ffe18 100644 --- a/apple/TablePro/Views/Settings/CustomSlashCommandsSection.swift +++ b/apple/TablePro/Views/Settings/CustomSlashCommandsSection.swift @@ -1,211 +1,261 @@ -// -// CustomSlashCommandsSection.swift -// TablePro -// - import SwiftUI -struct CustomSlashCommandsSection: View { +struct SlashCommandsPage: View { + private struct Editing: Identifiable { + let command: CustomSlashCommand + let isNew: Bool + + var id: UUID { command.id } + } + @ObservedObject var storage: CustomSlashCommandStorage - @State private var editing: CustomSlashCommand? - @State private var isCreating = false - @State private var saveError: String? + @State private var editing: Editing? @State private var pendingDelete: CustomSlashCommand? var body: some View { - Section { - if storage.commands.isEmpty { - emptyState - } else { - ForEach(storage.commands) { command in - row(for: command) + Form { + Section { + if storage.commands.isEmpty { + VStack(alignment: .leading, spacing: 2) { + Text("No slash commands") + Text("Add one to reuse a prompt in the chat.") + .font(.subheadline) + .foregroundStyle(.secondary) + } + .accessibilityElement(children: .combine) + } else { + ForEach(storage.commands) { command in + row(command) + } } - } - HStack { - Spacer() - Button { - editing = CustomSlashCommand() - isCreating = true - } label: { - Label(String(localized: "Add Command"), systemImage: "plus") + SettingsHelpRow("Type / in the chat to run one. A template can use {{query}}, {{schema}}, {{database}} and {{body}}.") + } footer: { + SettingsSectionActions { + Button("Add Command…") { + editing = Editing(command: CustomSlashCommand(), isNew: true) + } + .accessibilityIdentifier("slash-command-add") } - .controlSize(.small) } - } header: { - Text(String(localized: "Custom Slash Commands")) - } footer: { - Text(String( - localized: "Create your own slash commands. Use {{query}}, {{schema}}, {{database}}, or {{body}} in the template to insert chat context at runtime." - )) - .font(.caption) - .foregroundStyle(.secondary) } - .sheet(item: $editing) { command in + .formStyle(.grouped) + .accessibilityElement(children: .contain) + .accessibilityIdentifier(SettingsPage.slashCommands.pageIdentifier) + .sheet(item: $editing) { editing in CustomSlashCommandEditorSheet( - initial: command, - isCreating: isCreating, - onSave: { updated in - do { - if isCreating { - try storage.add(updated) - } else { - try storage.update(updated) - } - editing = nil - isCreating = false - } catch { - saveError = error.localizedDescription - } - }, - onCancel: { - editing = nil - isCreating = false - } + initial: editing.command, + isCreating: editing.isNew, + isDuplicate: { name in storage.isDuplicate(name, excluding: editing.isNew ? nil : editing.command.id) }, + onSave: { command in save(command, isNew: editing.isNew) }, + onDelete: editing.isNew ? nil : { storage.delete(id: editing.command.id) } ) } - .alert( - String(localized: "Cannot Save Command"), - isPresented: Binding( - get: { saveError != nil }, - set: { if !$0 { saveError = nil } } - ), - presenting: saveError - ) { _ in - Button(String(localized: "OK"), role: .cancel) { saveError = nil } - } message: { message in - Text(message) - } .alert( pendingDelete.map { String(format: String(localized: "Delete “/%@”?"), $0.name) } ?? "", - isPresented: Binding( - get: { pendingDelete != nil }, - set: { if !$0 { pendingDelete = nil } } - ), + isPresented: deleteBinding, presenting: pendingDelete ) { command in Button(String(localized: "Delete"), role: .destructive) { storage.delete(id: command.id) pendingDelete = nil } - Button(String(localized: "Cancel"), role: .cancel) { pendingDelete = nil } + Button(String(localized: "Cancel"), role: .cancel) { + pendingDelete = nil + } } message: { _ in - Text(String(localized: "The command is removed from this Mac and from every Mac that syncs settings. This cannot be undone.")) + Text("The command is removed from this Mac and from every Mac that syncs settings. This cannot be undone.") } } - @ViewBuilder - private var emptyState: some View { - Text(String(localized: "No custom commands yet.")) - .font(.caption) - .foregroundStyle(.secondary) + private func row(_ command: CustomSlashCommand) -> some View { + SettingsRecordRow( + title: "/\(command.name)", + subtitle: command.description.isEmpty ? nil : command.description + ) + .infoButton( + onEdit: { editing = Editing(command: command, isNew: false) }, + removal: .delete { pendingDelete = command }, + identifier: "slash-command-edit-\(command.id.uuidString)" + ) + .accessibilityIdentifier("slash-command-\(command.id.uuidString)") } - @ViewBuilder - private func row(for command: CustomSlashCommand) -> some View { - HStack(alignment: .firstTextBaseline) { - VStack(alignment: .leading, spacing: 2) { - Text("/\(command.name)") - .font(.body) - if !command.description.isEmpty { - Text(command.description) - .font(.caption) - .foregroundStyle(.secondary) - .lineLimit(1) - } - } - Spacer() - Button(String(localized: "Edit")) { - editing = command - isCreating = false - } - .controlSize(.small) - Button(role: .destructive) { - pendingDelete = command - } label: { - Image(systemName: "trash") + private var deleteBinding: Binding { + Binding( + get: { pendingDelete != nil }, + set: { if !$0 { pendingDelete = nil } } + ) + } + + // Returns the error to show in the sheet, or nil once the command is stored. + private func save(_ command: CustomSlashCommand, isNew: Bool) -> String? { + do { + if isNew { + try storage.add(command) + } else { + try storage.update(command) } - .controlSize(.small) - .accessibilityLabel(String(format: String(localized: "Delete /%@"), command.name)) - .help(String(localized: "Delete")) + editing = nil + return nil + } catch { + return error.localizedDescription } } } struct CustomSlashCommandEditorSheet: View { - @State var draft: CustomSlashCommand - let isCreating: Bool - let onSave: (CustomSlashCommand) -> Void - let onCancel: () -> Void + @Environment(\.dismiss) private var dismiss + @State private var draft: CustomSlashCommand + @State private var saveError: String? + @State private var confirmsDelete = false + + private let isCreating: Bool + private let isDuplicate: (String) -> Bool + private let onSave: (CustomSlashCommand) -> String? + private let onDelete: (() -> Void)? init( initial: CustomSlashCommand, isCreating: Bool, - onSave: @escaping (CustomSlashCommand) -> Void, - onCancel: @escaping () -> Void + isDuplicate: @escaping (String) -> Bool, + onSave: @escaping (CustomSlashCommand) -> String?, + onDelete: (() -> Void)? ) { _draft = State(initialValue: initial) self.isCreating = isCreating + self.isDuplicate = isDuplicate self.onSave = onSave - self.onCancel = onCancel + self.onDelete = onDelete + } + + // A leading slash is what the chat types, not part of the name. + static func normalizedName(_ name: String) -> String { + var trimmed = name.trimmingCharacters(in: .whitespacesAndNewlines) + if trimmed.hasPrefix("/") { + trimmed.removeFirst() + } + return trimmed + } + + private var name: String { + Self.normalizedName(draft.name) + } + + private var duplicates: Bool { + !name.isEmpty && isDuplicate(name) + } + + private var canSave: Bool { + var normalized = draft + normalized.name = name + return normalized.isValid && !duplicates } var body: some View { VStack(spacing: 0) { Form { Section { - LabeledContent(String(localized: "Name")) { - TextField("summarize", text: $draft.name) - .textFieldStyle(.roundedBorder) - } - LabeledContent(String(localized: "Description")) { - TextField(String(localized: "Optional one-line description"), text: $draft.description) - .textFieldStyle(.roundedBorder) + TextField(text: $draft.name, prompt: Text(verbatim: "summarize")) { + Text("Name") + nameNotice } - } footer: { - if SlashCommand.isBuiltIn(name: draft.name) { - NoticeLabel(String( - format: String(localized: "/%@ is a built-in command. Typing it runs the built-in; this one runs only from the command menu."), - draft.name.trimmingCharacters(in: .whitespaces).lowercased() - )) - .font(.caption) + .accessibilityIdentifier("slash-command-name") + TextField(text: $draft.description, prompt: Text("Optional")) { + Text("Description") } + .accessibilityIdentifier("slash-command-description") } Section { TextEditor(text: $draft.promptTemplate) .font(.body.monospaced()) .frame(minHeight: 140) - .overlay( - RoundedRectangle(cornerRadius: 4) - .stroke(Color(nsColor: .separatorColor)) - ) - } header: { - Text(String(localized: "Prompt template")) - } footer: { - Text(String(localized: """ + .accessibilityLabel(String(localized: "Prompt template")) + .accessibilityIdentifier("slash-command-template") + SettingsHelpRow( + """ Use {{query}} for the current editor query, {{schema}} for the active schema, \ - {{database}} for the active database name, and {{body}} for any text typed \ - after the command. - """)) - .font(.caption) - .foregroundStyle(.secondary) + {{database}} for the active database name, and {{body}} for any text typed after the command. + """ + ) + } header: { + Text("Prompt Template") } } .formStyle(.grouped) Divider() - HStack { - Spacer() - Button(String(localized: "Cancel"), action: onCancel) - .keyboardShortcut(.cancelAction) + DialogFooter { + if onDelete != nil { + Button(String(localized: "Delete Command…"), role: .destructive) { + confirmsDelete = true + } + .accessibilityIdentifier("slash-command-delete") + } + } actions: { + Button(String(localized: "Cancel"), role: .cancel) { + dismiss() + } + .keyboardShortcut(.cancelAction) Button(isCreating ? String(localized: "Add") : String(localized: "Save")) { - onSave(draft) + save() } .keyboardShortcut(.defaultAction) - .disabled(!draft.isValid) + .disabled(!canSave) + .accessibilityIdentifier("slash-command-save") + } + .padding() + } + .frame(minWidth: 480, minHeight: 400) + .alert( + String(localized: "Couldn't Save the Command"), + isPresented: saveErrorBinding, + presenting: saveError + ) { _ in + Button(String(localized: "OK"), role: .cancel) { + saveError = nil + } + } message: { message in + Text(verbatim: message) + } + .alert( + String(format: String(localized: "Delete “/%@”?"), name), + isPresented: $confirmsDelete + ) { + Button(String(localized: "Delete"), role: .destructive) { + onDelete?() + dismiss() } - .padding(12) + Button(String(localized: "Cancel"), role: .cancel) {} + } message: { + Text("The command is removed from this Mac and from every Mac that syncs settings. This cannot be undone.") + } + } + + @ViewBuilder + private var nameNotice: some View { + if duplicates { + NoticeLabel(String(format: String(localized: "A command named “/%@” already exists."), name)) + } else if SlashCommand.isBuiltIn(name: name) { + NoticeLabel(String( + format: String(localized: "/%@ is a built-in command. Typing it runs the built-in; this one runs only from the command menu."), + name.lowercased() + )) } - .frame(minWidth: 480, minHeight: 360) + } + + private var saveErrorBinding: Binding { + Binding( + get: { saveError != nil }, + set: { if !$0 { saveError = nil } } + ) + } + + private func save() { + var command = draft + command.name = name + command.description = draft.description.trimmingCharacters(in: .whitespacesAndNewlines) + guard command.isValid, !duplicates else { return } + saveError = onSave(command) } } diff --git a/apple/TablePro/Views/Settings/DataResultsSettingsView.swift b/apple/TablePro/Views/Settings/DataResultsSettingsView.swift index bda0adaed7..33d2ddff4a 100644 --- a/apple/TablePro/Views/Settings/DataResultsSettingsView.swift +++ b/apple/TablePro/Views/Settings/DataResultsSettingsView.swift @@ -1,45 +1,29 @@ -// -// DataResultsSettingsView.swift -// TablePro -// - import SwiftUI struct DataResultsSettingsView: View { - @Binding var dataGrid: DataGridSettings - @Binding var valueColors: ValueColorSettings - @Binding var history: HistorySettings - @Binding var editor: EditorSettings - @Binding var typography: TypographySettings + @ObservedObject var dataGrid: SettingsSlice + let valueColors: SettingsSlice + let editor: SettingsSlice + let typography: SettingsSlice + let history: SettingsSlice var body: some View { Form { - TypographySection(domain: .dataGrid, settings: $typography) - - DataGridSection(settings: $dataGrid, valueColors: $valueColors) - - Section("JSON Viewer") { - Picker("Default view:", selection: $editor.jsonViewerPreferredMode) { - Text("Text").tag(JSONViewMode.text) - Text("Tree").tag(JSONViewMode.tree) - } + DataGridSection( + settings: $dataGrid.value, + typography: typography, + valueColors: valueColors, + editor: editor + ) + + Section { + // No value: Keep entries for also bounds query tab versions, so one word would mislead. + SettingsDrillRow(route: SettingsRoute.page(.queryHistory), title: SettingsPage.queryHistory.title) + DataRewindDrillRow(history: history) } - - HistorySection(settings: $history) - - DataRewindSection(settings: $history) } .formStyle(.grouped) + .accessibilityElement(children: .contain) + .accessibilityIdentifier("settings-pane-data") } } - -#Preview { - DataResultsSettingsView( - dataGrid: .constant(.default), - valueColors: .constant(.default), - history: .constant(.default), - editor: .constant(.default), - typography: .constant(.default) - ) - .frame(width: 450, height: 500) -} diff --git a/apple/TablePro/Views/Settings/EditorSettingsView.swift b/apple/TablePro/Views/Settings/EditorSettingsView.swift index 9d9d68da78..98a67c32fc 100644 --- a/apple/TablePro/Views/Settings/EditorSettingsView.swift +++ b/apple/TablePro/Views/Settings/EditorSettingsView.swift @@ -1,62 +1,102 @@ -// -// EditorSettingsView.swift -// TablePro -// - import SwiftUI import TableProAutocomplete struct EditorSettingsView: View { - @Binding var settings: EditorSettings - @Binding var formatter: SQLFormatterSettings - @Binding var typography: TypographySettings + static let tabWidths = [2, 4, 8] + + @ObservedObject var editor: SettingsSlice + @ObservedObject var typography: SettingsSlice var body: some View { Form { - TypographySection(domain: .editor, settings: $typography) - - Section("Display") { - Toggle("Show line numbers", isOn: $settings.showLineNumbers) - Toggle("Highlight current line", isOn: $settings.highlightCurrentLine) - Toggle("Highlight current statement", isOn: $settings.highlightCurrentStatement) - Toggle("Show invisible characters", isOn: $settings.showInvisibleCharacters) - Toggle("Word wrap", isOn: $settings.wordWrap) + Section { + TypographyRows(domain: .editor, typography: $typography.value) + } header: { + Text("Font") } - Section("Gutter") { - Toggle("Code folding", isOn: $settings.codeFoldingEnabled) - Toggle("Run button beside each statement", isOn: $settings.showStatementRunControls) - .disabled(!settings.showLineNumbers) - .help(Text("The run button sits in the gutter, which needs line numbers.")) + Section { + Toggle("Highlight current line", isOn: $editor.value.highlightCurrentLine) + .accessibilityIdentifier("editor-highlight-current-line") + Toggle(isOn: $editor.value.highlightCurrentStatement) { + Text("Highlight current statement") + Text("A faint band behind the statement the cursor is in.") + } + .accessibilityIdentifier("editor-highlight-current-statement") + Toggle("Show invisible characters", isOn: $editor.value.showInvisibleCharacters) + .accessibilityIdentifier("editor-show-invisibles") + Toggle("Word wrap", isOn: $editor.value.wordWrap) + .accessibilityIdentifier("editor-word-wrap") + } header: { + Text("Display") } - Section("Editing") { - Picker("Tab width:", selection: $settings.tabWidth) { - Text("2 spaces").tag(2) - Text("4 spaces").tag(4) - Text("8 spaces").tag(8) - } - Picker("Keyword case:", selection: $settings.keywordCase) { - ForEach(SQLKeywordCase.allCases, id: \.self) { keywordCase in - Text(keywordCase.displayName).tag(keywordCase) - } + Section { + Toggle("Show line numbers", isOn: $editor.value.showLineNumbers) + .accessibilityIdentifier("editor-line-numbers") + Toggle(isOn: $editor.value.showStatementRunControls) { + Text("Run button beside each statement") + Text("Needs line numbers.") } - Toggle("Query parameters (:name syntax)", isOn: $settings.queryParametersEnabled) - Picker("Key bindings:", selection: $settings.keyBindings) { + .disabled(!editor.value.showLineNumbers) + .accessibilityIdentifier("editor-run-buttons") + Toggle("Code folding", isOn: $editor.value.codeFoldingEnabled) + .accessibilityIdentifier("editor-code-folding") + } header: { + Text("Gutter") + } + + Section { + Picker("Key bindings", selection: $editor.value.keyBindings) { Text("Standard").tag(EditorKeyBindings.standard) Text(verbatim: "Vim").tag(EditorKeyBindings.vim) Text(verbatim: "Emacs").tag(EditorKeyBindings.emacs) } + .pickerStyle(.menu) .accessibilityIdentifier("key-bindings-picker") + + Picker("Tab width", selection: Self.tabWidthBinding($editor.value)) { + SettingsChoiceItems(Self.tabWidths, including: editor.value.clampedTabWidth) { width in + Text("^[\(width) space](inflect: true)") + } + } + .accessibilityIdentifier("editor-tab-width") + + Picker(selection: $editor.value.keywordCase) { + Text(SQLKeywordCase.matchTypedElseUpper.displayName).tag(SQLKeywordCase.matchTypedElseUpper) + Text(SQLKeywordCase.matchTypedElseLower.displayName).tag(SQLKeywordCase.matchTypedElseLower) + Divider() + Text(SQLKeywordCase.upper.displayName).tag(SQLKeywordCase.upper) + Text(SQLKeywordCase.lower.displayName).tag(SQLKeywordCase.lower) + } label: { + Text("Keyword case") + Text("The case completions use. UPPERCASE and lowercase also change keywords as you type.") + } + .accessibilityIdentifier("editor-keyword-case") + + Toggle(isOn: $editor.value.queryParametersEnabled) { + Text("Query parameters") + Text("Asks for a value for each :name placeholder before the query runs.") + } + .accessibilityIdentifier("editor-query-parameters") + } header: { + Text("Editing") } - FormatterSection(settings: $formatter, editor: settings) + Section { + SettingsDrillRow(route: SettingsRoute.page(.sqlFormatting), title: SettingsPage.sqlFormatting.title) + } } .formStyle(.grouped) + .accessibilityElement(children: .contain) + .accessibilityIdentifier("settings-pane-editor") } -} -#Preview { - EditorSettingsView(settings: .constant(.default), formatter: .constant(.default), typography: .constant(.default)) - .frame(width: 450, height: 500) + // Shows the width the editor uses; a pick writes the stored field. + static func tabWidthBinding(_ editor: Binding) -> Binding { + Binding( + get: { editor.wrappedValue.clampedTabWidth }, + set: { editor.wrappedValue.tabWidth = $0 } + ) + } } diff --git a/apple/TablePro/Views/Settings/Entries/AISettingsEntry.swift b/apple/TablePro/Views/Settings/Entries/AISettingsEntry.swift new file mode 100644 index 0000000000..4984b2364a --- /dev/null +++ b/apple/TablePro/Views/Settings/Entries/AISettingsEntry.swift @@ -0,0 +1,55 @@ +import SwiftUI + +internal struct AISettingsEntry: View { + internal let context: SettingsPaneContext + @ObservedObject private var ai: SettingsSlice + + internal init(context: SettingsPaneContext) { + self.context = context + self._ai = ObservedObject(wrappedValue: context.settings.aiSlice) + } + + internal var body: some View { + AISettingsView(settings: $ai.value, visit: context.visit) + } +} + +internal struct AISettingsPageEntry: View { + internal let route: SettingsRoute + internal let context: SettingsPaneContext + + internal init(route: SettingsRoute, context: SettingsPaneContext) { + self.route = route + self.context = context + } + + // A route of another pane never reaches this stack. + internal var body: some View { + switch route { + case .page(.slashCommands): + SlashCommandsPage(storage: CustomSlashCommandStorage.shared) + case .aiProvider(let id): + AIProviderPage(providerID: id, slice: context.settings.aiSlice) + default: + EmptyView() + } + } +} + +// Root and provider pages share the removal alert and the pane model, so both live on the stack. +internal struct AIStackPresentations: ViewModifier { + internal let context: SettingsPaneContext + @StateObject private var paneModel = AISettingsPaneModel() + + internal init(context: SettingsPaneContext) { + self.context = context + } + + internal func body(content: Content) -> some View { + content + .environmentObject(paneModel) + .aiProviderRemovalAlert(pending: $paneModel.pendingRemoval) { provider in + paneModel.remove(provider, from: context.settings.aiSlice, navigation: context.navigation) + } + } +} diff --git a/apple/TablePro/Views/Settings/Entries/AccountSettingsEntry.swift b/apple/TablePro/Views/Settings/Entries/AccountSettingsEntry.swift new file mode 100644 index 0000000000..42102627d1 --- /dev/null +++ b/apple/TablePro/Views/Settings/Entries/AccountSettingsEntry.swift @@ -0,0 +1,127 @@ +import SwiftUI +import UniformTypeIdentifiers + +internal struct AccountSettingsEntry: View { + internal let context: SettingsPaneContext + + internal var body: some View { + AccountSettingsView(model: context.models.account) { [context] in + context.navigation.push(.page(.accountDevices), in: .account) + } + } +} + +internal struct AccountSettingsPageEntry: View { + internal let route: SettingsRoute + internal let context: SettingsPaneContext + + internal var body: some View { + switch route { + case .page(.accountFeatures): + AccountFeaturesPage(access: context.models.account.access) + case .page(.accountDevices): + AccountDevicesPage(model: context.models.account) + case .page(.accountTeams): + AccountTeamsPage(model: context.models.account) + case .page(.accountOffline): + AccountOfflinePage(model: context.models.account) + default: + EmptyView() + } + } +} + +// The root and every page share the model's sheets, dialogs and file panel, so they hang off the pane's stack. +internal struct AccountStackPresentations: ViewModifier { + internal let context: SettingsPaneContext + + internal func body(content: Content) -> some View { + content.modifier(AccountPresentations(model: context.models.account, visit: context.visit, context: context)) + } +} + +private struct AccountPresentations: ViewModifier { + private static let offlineFileTypes = [UTType(filenameExtension: "jwt") ?? .data] + private static let signedInPages: [SettingsRoute] = [.page(.accountDevices), .page(.accountTeams)] + + @ObservedObject var model: AccountSettingsModel + @ObservedObject var visit: SettingsPaneVisit + let context: SettingsPaneContext + + func body(content: Content) -> some View { + content + .task(id: visit.count) { + await model.refreshOnVisit() + } + .onChange(of: model.access.state.isSignedIn) { isSignedIn in + guard !isSignedIn else { return } + for route in Self.signedInPages where context.path.routes.contains(route) { + context.navigation.removeRoute(route) + } + } + .sheet(isPresented: $model.presentsDeviceLimit) { + DeviceLimitSheet(model: DeviceLimitModel(services: model.services)) + } + .sheet(isPresented: $model.presentsLicenseKey) { + LicenseKeySheet( + storedKey: model.licenseKeyPrefill, + signedInEmail: signedInEmail, + isWorking: model.activity == .usingKey + ) { key in + await model.useLicenseKey(key) + } + } + .fileImporter( + isPresented: $model.presentsOfflineImporter, + allowedContentTypes: Self.offlineFileTypes, + allowsMultipleSelection: false + ) { result in + switch result { + case .success(let urls): + if let url = urls.first { + Task { await model.importOfflineFile(at: url) } + } + case .failure(let error): + model.offlineFilePickerFailed(error) + } + } + .alert( + model.actionFailure?.title ?? "", + isPresented: Binding(get: { model.actionFailure != nil }, set: { if !$0 { model.actionFailure = nil } }), + presenting: model.actionFailure + ) { _ in + Button(String(localized: "OK")) {} + } message: { failure in + Text(failure.message) + } + .alert( + model.pendingRemoval.map { String(format: String(localized: "Remove “%@”?"), $0.name) } ?? "", + isPresented: Binding(get: { model.pendingRemoval != nil }, set: { if !$0 { model.pendingRemoval = nil } }), + presenting: model.pendingRemoval + ) { device in + Button(String(localized: "Remove"), role: .destructive) { + Task { await model.removeDevice(device) } + } + Button(String(localized: "Cancel"), role: .cancel) {} + } message: { _ in + Text("TablePro on that device signs out the next time it checks your account. Its paid features keep working until its last check expires.") + } + .alert( + String(localized: "Sign out of TablePro on this Mac?"), + isPresented: Binding(get: { model.confirmsSignOut }, set: { if !$0 { model.cancelSignOut() } }), + presenting: model.signOutConfirmation + ) { confirmation in + Button(String(localized: "Sign Out"), role: confirmation.discardsSomething ? .destructive : nil) { + Task { await model.signOut() } + } + Button(String(localized: "Cancel"), role: .cancel) {} + } message: { confirmation in + Text(confirmation.message) + } + } + + private var signedInEmail: String? { + guard model.access.state.isSignedIn else { return nil } + return model.profile.value?.email ?? model.access.state.entitlement?.email + } +} diff --git a/apple/TablePro/Views/Settings/Entries/AppearanceSettingsEntry.swift b/apple/TablePro/Views/Settings/Entries/AppearanceSettingsEntry.swift new file mode 100644 index 0000000000..b7a89eebcb --- /dev/null +++ b/apple/TablePro/Views/Settings/Entries/AppearanceSettingsEntry.swift @@ -0,0 +1,51 @@ +import SwiftUI + +internal struct AppearanceSettingsEntry: View { + internal let context: SettingsPaneContext + @ObservedObject private var appearance: SettingsSlice + @ObservedObject private var appearanceMode: SettingsSlice + + internal init(context: SettingsPaneContext) { + self.context = context + self._appearance = ObservedObject(wrappedValue: context.settings.appearanceSlice) + self._appearanceMode = ObservedObject(wrappedValue: context.settings.appearanceModeSlice) + } + + internal var body: some View { + AppearanceSettingsView(settings: $appearance.value, appearanceMode: $appearanceMode.value) + } +} + +internal struct AppearanceSettingsPageEntry: View { + internal let route: SettingsRoute + internal let context: SettingsPaneContext + + internal var body: some View { + switch route { + case .page(.manageThemes): + ThemeLibrarySection(model: context.models.themeLibrary) + default: + EmptyView() + } + } +} + +internal struct AppearanceStackPresentations: ViewModifier { + internal let context: SettingsPaneContext + + internal func body(content: Content) -> some View { + content + .onAppear { + Self.routeOffPageAlerts(of: context.models.themeLibrary, to: context) + } + } + + // A theme undo from the root page or another pane fails with no Manage Themes page to show it. + internal static func routeOffPageAlerts(of model: ThemeLibraryModel, to context: SettingsPaneContext) { + model.presentOffPage = { [weak context] alert in + guard let context, context.path.routes.last != .page(.manageThemes) else { return false } + context.presentError(title: alert.title, message: alert.message) + return true + } + } +} diff --git a/apple/TablePro/Views/Settings/Entries/ConnectionsSettingsEntry.swift b/apple/TablePro/Views/Settings/Entries/ConnectionsSettingsEntry.swift new file mode 100644 index 0000000000..4b84bfa786 --- /dev/null +++ b/apple/TablePro/Views/Settings/Entries/ConnectionsSettingsEntry.swift @@ -0,0 +1,55 @@ +import SwiftUI + +internal struct ConnectionsSettingsEntry: View { + internal let context: SettingsPaneContext + @ObservedObject private var general: SettingsSlice + + internal init(context: SettingsPaneContext) { + self.context = context + self._general = ObservedObject(wrappedValue: context.settings.generalSlice) + } + + internal var body: some View { + ConnectionsSettingsView(settings: $general.value) + } +} + +internal struct ConnectionsSettingsPageEntry: View { + internal let route: SettingsRoute + internal let context: SettingsPaneContext + + internal var body: some View { + switch route { + case .page(.linkedFolders): + LinkedFoldersPage() + case .page(.trustedLinks): + TrustedLinksPage() + default: + // The model never pushes a route of another pane onto this stack. + EmptyView() + } + } +} + +// The root's counts and both pages read one pair of models, alive as long as the pane host. +internal struct ConnectionsStackPresentations: ViewModifier { + internal let context: SettingsPaneContext + @ObservedObject private var visit: SettingsPaneVisit + @StateObject private var linkedFolders = LinkedFoldersModel() + @StateObject private var trustedLinks = TrustedLinksModel() + + internal init(context: SettingsPaneContext) { + self.context = context + self._visit = ObservedObject(wrappedValue: context.visit) + } + + internal func body(content: Content) -> some View { + content + .environmentObject(linkedFolders) + .environmentObject(trustedLinks) + .task(id: visit.count) { + linkedFolders.reload() + trustedLinks.refresh() + } + } +} diff --git a/apple/TablePro/Views/Settings/Entries/DataSettingsEntry.swift b/apple/TablePro/Views/Settings/Entries/DataSettingsEntry.swift new file mode 100644 index 0000000000..5b561f1c56 --- /dev/null +++ b/apple/TablePro/Views/Settings/Entries/DataSettingsEntry.swift @@ -0,0 +1,39 @@ +import SwiftUI + +internal struct DataSettingsEntry: View { + internal let context: SettingsPaneContext + + internal var body: some View { + DataResultsSettingsView( + dataGrid: context.settings.dataGridSlice, + valueColors: context.settings.valueColorsSlice, + editor: context.settings.editorSlice, + typography: context.settings.typographySlice, + history: context.settings.historySlice + ) + } +} + +internal struct DataSettingsPageEntry: View { + internal let route: SettingsRoute + internal let context: SettingsPaneContext + + internal var body: some View { + switch route { + case .page(.queryHistory): + QueryHistorySettingsPage(history: context.settings.historySlice, context: context) + case .page(.dataRewind): + DataRewindPage(history: context.settings.historySlice, context: context) + default: + EmptyView() + } + } +} + +internal struct DataStackPresentations: ViewModifier { + internal let context: SettingsPaneContext + + internal func body(content: Content) -> some View { + content + } +} diff --git a/apple/TablePro/Views/Settings/Entries/EditorSettingsEntry.swift b/apple/TablePro/Views/Settings/Entries/EditorSettingsEntry.swift new file mode 100644 index 0000000000..0fab034a47 --- /dev/null +++ b/apple/TablePro/Views/Settings/Entries/EditorSettingsEntry.swift @@ -0,0 +1,44 @@ +import Combine +import SwiftUI + +internal struct EditorSettingsEntry: View { + internal let context: SettingsPaneContext + + internal var body: some View { + EditorSettingsView(editor: context.settings.editorSlice, typography: context.settings.typographySlice) + } +} + +internal struct EditorSettingsPageEntry: View { + internal let route: SettingsRoute + internal let context: SettingsPaneContext + + internal var body: some View { + switch route { + case .page(.sqlFormatting): + SQLFormattingPageHost(formatter: context.settings.formatterSlice, editor: context.settings.editorSlice) + default: + EmptyView() + } + } +} + +internal struct EditorStackPresentations: ViewModifier { + internal let context: SettingsPaneContext + + internal func body(content: Content) -> some View { + content + } +} + +// Follows only the editor font, so a theme change elsewhere never re-renders the page. +private struct SQLFormattingPageHost: View { + @ObservedObject var formatter: SettingsSlice + @ObservedObject var editor: SettingsSlice + @State private var font = ThemeEngine.shared.editorFonts.font + + var body: some View { + SQLFormattingPage(settings: $formatter.value, editor: editor.value, font: font) + .onReceive(ThemeEngine.shared.$editorFonts.map(\.font).removeDuplicates()) { font = $0 } + } +} diff --git a/apple/TablePro/Views/Settings/Entries/ExtensionsSettingsEntry.swift b/apple/TablePro/Views/Settings/Entries/ExtensionsSettingsEntry.swift new file mode 100644 index 0000000000..82f8a5c6b0 --- /dev/null +++ b/apple/TablePro/Views/Settings/Entries/ExtensionsSettingsEntry.swift @@ -0,0 +1,48 @@ +import SwiftUI + +internal struct ExtensionsSettingsEntry: View { + internal let context: SettingsPaneContext + + internal var body: some View { + InstalledPluginsView(context: context) + } +} + +internal struct ExtensionsSettingsPageEntry: View { + internal let route: SettingsRoute + internal let context: SettingsPaneContext + @EnvironmentObject private var model: ExtensionsPaneModel + + internal var body: some View { + switch model.page(for: route) { + case .plugin(let entry, let isStaged): + PluginDetailPage(entry: entry, isStaged: isStaged, context: context) + case .rejected(let row): + RejectedPluginDetailPage(row: row, context: context, tracker: model.manager.installTracker) + case .unavailable: + UnavailableStateView( + String(localized: "Plugin Not Available"), + systemImage: "puzzlepiece.extension", + description: Text("It was removed or replaced.") + ) + .accessibilityElement(children: .contain) + .accessibilityIdentifier("extensions-plugin-unavailable") + } + } +} + +// The model sits above the stack, so the root and every pushed page share one view of the plugin manager. +internal struct ExtensionsStackPresentations: ViewModifier { + internal let context: SettingsPaneContext + @StateObject private var model: ExtensionsPaneModel + + internal init(context: SettingsPaneContext) { + self.context = context + _model = StateObject(wrappedValue: ExtensionsPaneModel(registryClient: context.registryClient)) + } + + internal func body(content: Content) -> some View { + content + .environmentObject(model) + } +} diff --git a/apple/TablePro/Views/Settings/Entries/GeneralSettingsEntry.swift b/apple/TablePro/Views/Settings/Entries/GeneralSettingsEntry.swift new file mode 100644 index 0000000000..0f7367dad6 --- /dev/null +++ b/apple/TablePro/Views/Settings/Entries/GeneralSettingsEntry.swift @@ -0,0 +1,34 @@ +import SwiftUI + +internal struct GeneralSettingsEntry: View { + internal let context: SettingsPaneContext + + internal var body: some View { + let settings = context.settings + GeneralSettingsView(settings: settings.generalSlice, onResetAll: { settings.resetToDefaults() }) + } +} + +internal struct GeneralSettingsPageEntry: View { + internal let route: SettingsRoute + internal let context: SettingsPaneContext + + internal var body: some View { + switch route { + case .page(.softwareUpdate): + SoftwareUpdatePage(updater: .shared, updates: .shared) + case .page(.commandLineTool): + CommandLineToolPage(visit: context.visit) + default: + EmptyView() + } + } +} + +internal struct GeneralStackPresentations: ViewModifier { + internal let context: SettingsPaneContext + + internal func body(content: Content) -> some View { + content + } +} diff --git a/apple/TablePro/Views/Settings/Entries/KeyboardSettingsEntry.swift b/apple/TablePro/Views/Settings/Entries/KeyboardSettingsEntry.swift new file mode 100644 index 0000000000..2b1d16eaa2 --- /dev/null +++ b/apple/TablePro/Views/Settings/Entries/KeyboardSettingsEntry.swift @@ -0,0 +1,34 @@ +import SwiftUI + +internal struct KeyboardSettingsEntry: View { + internal let context: SettingsPaneContext + + internal init(context: SettingsPaneContext) { + self.context = context + } + + // Never nil: SettingsPaneContext.filtersItsList(.keyboard) is true. + internal var body: some View { + if let filter = context.filter { + KeyboardSettingsView(keyboard: context.settings.keyboardSlice, filter: filter) + } + } +} + +// Keyboard has no pages, and the navigation model never pushes another pane's route here. +internal struct KeyboardSettingsPageEntry: View { + internal let route: SettingsRoute + internal let context: SettingsPaneContext + + internal var body: some View { + EmptyView() + } +} + +internal struct KeyboardStackPresentations: ViewModifier { + internal let context: SettingsPaneContext + + internal func body(content: Content) -> some View { + content + } +} diff --git a/apple/TablePro/Views/Settings/Entries/MCPSettingsEntry.swift b/apple/TablePro/Views/Settings/Entries/MCPSettingsEntry.swift new file mode 100644 index 0000000000..bcc25c6932 --- /dev/null +++ b/apple/TablePro/Views/Settings/Entries/MCPSettingsEntry.swift @@ -0,0 +1,81 @@ +import SwiftUI + +internal struct MCPSettingsEntry: View { + internal let context: SettingsPaneContext + @ObservedObject private var mcp: SettingsSlice + @EnvironmentObject private var model: MCPSettingsModel + + internal init(context: SettingsPaneContext) { + self.context = context + self._mcp = ObservedObject(wrappedValue: context.settings.mcpSlice) + } + + internal var body: some View { + MCPSettingsView(settings: $mcp.value, model: model) { + context.navigation.open(.root(.ai), recordsHistory: true) + } + } +} + +internal struct MCPSettingsPageEntry: View { + internal let route: SettingsRoute + internal let context: SettingsPaneContext + @EnvironmentObject private var model: MCPSettingsModel + + internal var body: some View { + switch route { + case .page(.mcpApprovals): + MCPApprovalsPage(context: context, model: model) + case .page(.mcpTokens): + MCPTokenListView(model: model) { + context.settings.mcpSlice.value.port + } + default: + EmptyView() + } + } +} + +// The approval mode lives in the MCP slice, so only this page observes it. +private struct MCPApprovalsPage: View { + @ObservedObject private var mcp: SettingsSlice + @ObservedObject var model: MCPSettingsModel + + init(context: SettingsPaneContext, model: MCPSettingsModel) { + self._mcp = ObservedObject(wrappedValue: context.settings.mcpSlice) + self.model = model + } + + var body: some View { + MCPGrantListView(model: model, approval: mcp.value.connectionApproval) + } +} + +// The model sits on the stack, so the root and both pages share one load and keep it across pushes. +internal struct MCPStackPresentations: ViewModifier { + internal let context: SettingsPaneContext + @StateObject private var model = MCPSettingsModel() + + internal init(context: SettingsPaneContext) { + self.context = context + } + + internal func body(content: Content) -> some View { + content + .environmentObject(model) + .modifier(MCPVisitRefresh(visit: context.visit, model: model)) + } +} + +private struct MCPVisitRefresh: ViewModifier { + @ObservedObject var visit: SettingsPaneVisit + let model: MCPSettingsModel + + func body(content: Content) -> some View { + content + .task(id: visit.count) { + model.activate() + await model.refresh() + } + } +} diff --git a/apple/TablePro/Views/Settings/Entries/NotificationsSettingsEntry.swift b/apple/TablePro/Views/Settings/Entries/NotificationsSettingsEntry.swift new file mode 100644 index 0000000000..e32848c91a --- /dev/null +++ b/apple/TablePro/Views/Settings/Entries/NotificationsSettingsEntry.swift @@ -0,0 +1,33 @@ +import SwiftUI + +internal struct NotificationsSettingsEntry: View { + internal let context: SettingsPaneContext + @ObservedObject private var notifications: SettingsSlice + + internal init(context: SettingsPaneContext) { + self.context = context + self._notifications = ObservedObject(wrappedValue: context.settings.notificationsSlice) + } + + internal var body: some View { + NotificationsSettingsView(settings: $notifications.value, visit: context.visit) + } +} + +// Notifications has no pages, and the navigation model never pushes another pane's route here. +internal struct NotificationsSettingsPageEntry: View { + internal let route: SettingsRoute + internal let context: SettingsPaneContext + + internal var body: some View { + EmptyView() + } +} + +internal struct NotificationsStackPresentations: ViewModifier { + internal let context: SettingsPaneContext + + internal func body(content: Content) -> some View { + content + } +} diff --git a/apple/TablePro/Views/Settings/Entries/ProfilesSettingsEntry.swift b/apple/TablePro/Views/Settings/Entries/ProfilesSettingsEntry.swift new file mode 100644 index 0000000000..a5edee6c32 --- /dev/null +++ b/apple/TablePro/Views/Settings/Entries/ProfilesSettingsEntry.swift @@ -0,0 +1,35 @@ +import SwiftUI + +internal struct ProfilesSettingsEntry: View { + internal let context: SettingsPaneContext + @ObservedObject private var visit: SettingsPaneVisit + @StateObject private var model = ProfilesSettingsModel() + + internal init(context: SettingsPaneContext) { + self.context = context + self._visit = ObservedObject(wrappedValue: context.visit) + } + + internal var body: some View { + ProfilesSettingsView(model: model, presentError: context.presentError) + .task(id: visit.count) { model.refresh() } + } +} + +// Profiles owns no SettingsPage: its editors are sheets, so no route reaches this. +internal struct ProfilesSettingsPageEntry: View { + internal let route: SettingsRoute + internal let context: SettingsPaneContext + + internal var body: some View { + EmptyView() + } +} + +internal struct ProfilesStackPresentations: ViewModifier { + internal let context: SettingsPaneContext + + internal func body(content: Content) -> some View { + content + } +} diff --git a/apple/TablePro/Views/Settings/Entries/SidebarTabsSettingsEntry.swift b/apple/TablePro/Views/Settings/Entries/SidebarTabsSettingsEntry.swift new file mode 100644 index 0000000000..1fa5a03445 --- /dev/null +++ b/apple/TablePro/Views/Settings/Entries/SidebarTabsSettingsEntry.swift @@ -0,0 +1,35 @@ +import SwiftUI + +internal struct SidebarTabsSettingsEntry: View { + internal let context: SettingsPaneContext + @ObservedObject private var general: SettingsSlice + @ObservedObject private var tabs: SettingsSlice + + internal init(context: SettingsPaneContext) { + self.context = context + self._general = ObservedObject(wrappedValue: context.settings.generalSlice) + self._tabs = ObservedObject(wrappedValue: context.settings.tabsSlice) + } + + internal var body: some View { + SidebarTabsSettingsView(settings: $general.value, tabSettings: $tabs.value) + } +} + +// No SettingsPage has Sidebar & Tabs as its parent, so nothing reaches this. +internal struct SidebarTabsSettingsPageEntry: View { + internal let route: SettingsRoute + internal let context: SettingsPaneContext + + internal var body: some View { + EmptyView() + } +} + +internal struct SidebarTabsStackPresentations: ViewModifier { + internal let context: SettingsPaneContext + + internal func body(content: Content) -> some View { + content + } +} diff --git a/apple/TablePro/Views/Settings/Entries/SyncSettingsEntry.swift b/apple/TablePro/Views/Settings/Entries/SyncSettingsEntry.swift new file mode 100644 index 0000000000..b486807b93 --- /dev/null +++ b/apple/TablePro/Views/Settings/Entries/SyncSettingsEntry.swift @@ -0,0 +1,33 @@ +import SwiftUI + +internal struct SyncSettingsEntry: View { + internal let context: SettingsPaneContext + @ObservedObject private var sync: SettingsSlice + + internal init(context: SettingsPaneContext) { + self.context = context + self._sync = ObservedObject(wrappedValue: context.settings.syncSlice) + } + + internal var body: some View { + SyncSettingsView(settings: $sync.value) + } +} + +// iCloud Sync has no pages since What Syncs moved inline, so nothing reaches this. +internal struct SyncSettingsPageEntry: View { + internal let route: SettingsRoute + internal let context: SettingsPaneContext + + internal var body: some View { + EmptyView() + } +} + +internal struct SyncStackPresentations: ViewModifier { + internal let context: SettingsPaneContext + + internal func body(content: Content) -> some View { + content + } +} diff --git a/apple/TablePro/Views/Settings/GeneralSettingsView.swift b/apple/TablePro/Views/Settings/GeneralSettingsView.swift index 4647f9378d..a519169a11 100644 --- a/apple/TablePro/Views/Settings/GeneralSettingsView.swift +++ b/apple/TablePro/Views/Settings/GeneralSettingsView.swift @@ -1,161 +1,100 @@ -import AppKit import SwiftUI struct GeneralSettingsView: View { - @Binding var settings: GeneralSettings - @Binding var tabSettings: TabSettings - @ObservedObject var updater: SoftwareUpdater - var onResetAll: () -> Void + @ObservedObject var settings: SettingsSlice + let onResetAll: () -> Void - @State private var initialLanguage: AppLanguage? @State private var showResetConfirmation = false - @AppStorage(SidebarPersistenceKey.defaultLayout, store: AppStorageEnvironment.shared.defaults) private var defaultSidebarLayout: SidebarLayout = .flat - - private static let standardTimeouts = [10, 20, 30, 40, 50, 60, 90, 120, 180, 300, 600] - - private var queryTimeoutOptions: [Int] { - let current = settings.queryTimeoutSeconds - if current > 0, !Self.standardTimeouts.contains(current) { - return (Self.standardTimeouts + [current]).sorted() - } - return Self.standardTimeouts - } var body: some View { Form { - Picker("Language:", selection: $settings.language) { - ForEach(AppLanguage.allCases) { lang in - Text(lang.displayName).tag(lang) - } - } - - if let initial = initialLanguage, settings.language != initial { - LabeledContent { - Button(String(localized: "Relaunch")) { - UpdateCenter.shared.relaunch() + Section { + Picker("Language", selection: $settings.value.language) { + ForEach(AppLanguage.allCases) { language in + Text(language.displayName).tag(language) } - .accessibilityIdentifier("language-relaunch-button") - } label: { - Text("Relaunch TablePro to finish switching languages.") - .font(.caption) - .foregroundStyle(.secondary) } - } - - Picker("When TablePro starts:", selection: $settings.startupBehavior) { - ForEach(StartupBehavior.allCases) { behavior in - Text(behavior.displayName).tag(behavior) - } - } - - Section("Tabs") { - Toggle("Enable preview tabs", isOn: $tabSettings.enablePreviewTabs) - .help("Single-clicking a table opens a temporary tab that gets replaced on next click.") - } - - Section("Sidebar") { - Toggle("Show connections", isOn: $settings.showWorkspaceRail) - .help("Adds a narrow strip on the window's leading edge listing every connection and database you have open, so one click switches to it.") - - Toggle("Show recent tables", isOn: $settings.showRecentTables) - .help("Adds a Recent section at the top of the Tables sidebar with the last tables you opened per connection and database.") - - Toggle("Show object icons", isOn: $settings.showObjectIcons) - .help("Shows a type icon before each object name in the sidebar. Turn it off for a plain list of names.") - - Toggle("Show object comments", isOn: $settings.showObjectComments) - .help("Shows database object comments next to tables in the sidebar and in grid column headers.") - - Toggle("Show system databases and schemas", isOn: $settings.showSystemContainers) - .accessibilityIdentifier("show-system-containers-toggle") - .help(String(localized: """ - Lists system databases such as mysql and information_schema, and system schemas, \ - in the sidebar tree and the database filter. Switchers always list them. - """)) - - Toggle("Show partitions", isOn: $settings.showPartitions) - .accessibilityIdentifier("show-partitions-toggle") - .help(String(localized: """ - Lists a partitioned table's partitions under it in the sidebar, with how many \ - it holds. Turn it off to keep partitioned tables as single rows. - """)) - - Picker("Row size:", selection: $settings.sidebarRowSize) { - ForEach(SidebarRowSizePreference.allCases, id: \.self) { size in - Text(size.title).tag(size) + .accessibilityIdentifier("general-language-picker") + + if settings.value.language != LanguageLaunchState.language { + LabeledContent { + Button(String(localized: "Relaunch")) { + UpdateCenter.shared.relaunch() + } + .accessibilityIdentifier("language-relaunch-button") + } label: { + Text("Relaunch TablePro to finish switching languages.") } } - .help(String(localized: """ - Match System follows Sidebar icon size in System Settings > Appearance. \ - Choose a size to fit more objects on screen than the rest of the system shows. - """)) - - Picker("Default layout for new connections:", selection: $defaultSidebarLayout) { - Text("List").tag(SidebarLayout.flat) - Text("Tree").tag(SidebarLayout.tree) - } - .help(String(localized: "Layout for new connections on servers that support a database tree. Switch the current connection from the View menu.")) - } - - ConnectionsSettingsSection(healthCheck: $settings.connectionHealthCheck) - Section("Query Execution") { - Picker("Query timeout:", selection: $settings.queryTimeoutSeconds) { - Text("No limit").tag(0) - ForEach(queryTimeoutOptions, id: \.self) { seconds in - Text("\(seconds) seconds").tag(seconds) + Picker("When TablePro starts", selection: $settings.value.startupBehavior) { + ForEach(StartupBehavior.allCases) { behavior in + Text(behavior.displayName).tag(behavior) } } - .help(String(localized: "Maximum time to wait for a query to complete. Set to 0 for no limit. Applied to new connections.")) + .accessibilityIdentifier("general-startup-picker") } - CommandLineToolSection() - - LinkedFoldersSection() - - TrustedExternalConnectionsSection() - - SoftwareUpdateSection(updater: updater, updates: .shared) + Section { + SoftwareUpdateDrillRow() + SettingsDrillRow(route: SettingsRoute.page(.commandLineTool), title: SettingsPage.commandLineTool.title) + } Section { - Toggle("Share usage data", isOn: $settings.shareAnalytics) + Toggle(isOn: $settings.value.shareAnalytics) { + Text("Share usage data") + Text( + """ + Sent to PostHog: app and macOS versions, Mac model, screen size, architecture, language, time zone, \ + database types, connection count, first connection and query, plan prompts, sign-in and sign-out, \ + and your account ID once you sign in. Never hostnames, credentials, queries, or rows. + """ + ) + } + .accessibilityIdentifier("general-share-usage-toggle") } header: { Text("Privacy") - } footer: { - Text( - """ - Sent to PostHog: app and macOS versions, Mac model, screen size, architecture, language, time zone, \ - database types, connection count, first connection and query, plan prompts, sign-in and sign-out, \ - and your account ID once you sign in. Never hostnames, credentials, queries, or rows. - """ - ) } Section { - Button(String(localized: "Reset All Settings to Defaults"), role: .destructive) { - showResetConfirmation = true + LabeledContent { + Button(String(localized: "Reset…"), role: .destructive) { + showResetConfirmation = true + } + .accessibilityLabel(String(localized: "Reset All Settings…")) + .accessibilityIdentifier("general-reset-all-button") + } label: { + Text("Reset all settings") + Text("Returns every section to its defaults.") } } } .formStyle(.grouped) - .alert(String(localized: "Reset All Settings"), isPresented: $showResetConfirmation) { + .accessibilityElement(children: .contain) + .accessibilityIdentifier("settings-pane-general") + .alert(String(localized: "Reset all settings?"), isPresented: $showResetConfirmation) { Button(String(localized: "Reset"), role: .destructive) { onResetAll() } Button(String(localized: "Cancel"), role: .cancel) {} } message: { - Text("This will reset all settings across every section to their default values. AI providers, their API keys and Enable AI Features are kept.") - } - .onAppear { - if initialLanguage == nil { initialLanguage = settings.language } + Text( + """ + Every section returns to its default values. AI providers and their API keys, Enable AI features, \ + Share usage data, linked folders, trusted links, connections and history are kept. + """ + ) } } } -#Preview { - GeneralSettingsView( - settings: .constant(.default), - tabSettings: .constant(.default), - updater: SoftwareUpdater.shared, - onResetAll: {} - ) - .frame(width: 450, height: 500) +// Only this row re-renders when the update status changes. +private struct SoftwareUpdateDrillRow: View { + @ObservedObject private var updates = UpdateCenter.shared + + var body: some View { + SettingsDrillRow( + route: SettingsRoute.page(.softwareUpdate), + title: SettingsPage.softwareUpdate.title, + value: updates.status.indicatorTitle + ) + } } diff --git a/apple/TablePro/Views/Settings/KeyboardSettingsView.swift b/apple/TablePro/Views/Settings/KeyboardSettingsView.swift index 499c040a9d..099bc9dd36 100644 --- a/apple/TablePro/Views/Settings/KeyboardSettingsView.swift +++ b/apple/TablePro/Views/Settings/KeyboardSettingsView.swift @@ -1,231 +1,215 @@ -// -// KeyboardSettingsView.swift -// TablePro -// -// Settings view for customizing keyboard shortcuts. -// - import AppKit import SwiftUI -/// Settings view for keyboard shortcut customization +// A List, not a grouped Form: a Form builds all 126 rows on first show, a List only the visible ones. struct KeyboardSettingsView: View { - @Binding var settings: KeyboardSettings - + @ObservedObject private var keyboard: SettingsSlice + @ObservedObject private var filter: SettingsPaneFilter @ObservedObject private var modules = AppModuleSettings.shared - @State private var searchText = "" - @State private var conflictAlert: ConflictAlertState? - @State private var systemReservedAlert: ShortcutAction? - @State private var reservedAlert: ReservedAlertState? - @State private var needsModifierAlert: ShortcutAction? - @State private var confirmsReset = false - - private var content: some View { - VStack(spacing: 0) { - NativeSearchField( - text: $searchText, - placeholder: String(localized: "Search shortcuts…") - ) - .padding(.horizontal, 20) - .padding(.top, 16) - .padding(.bottom, 8) - - Form { - ForEach(ShortcutCategory.allCases) { category in - let actions = filteredActions(for: category) - if !actions.isEmpty { - Section(category.displayName) { - ForEach(actions) { action in - shortcutRow(for: action) - } - } - } - } + @StateObject private var session: ShortcutRecordingSession + @State private var selection: ShortcutAction? + @State private var confirmsRestore = false + + init(keyboard: SettingsSlice, filter: SettingsPaneFilter) { + _keyboard = ObservedObject(wrappedValue: keyboard) + _filter = ObservedObject(wrappedValue: filter) + _session = StateObject(wrappedValue: ShortcutRecordingSession(keyboard: keyboard)) + } - Section { - HStack { - Spacer() - Button(String(localized: "Reset to Defaults")) { - confirmsReset = true + var body: some View { + let settings = keyboard.value + let sections = ShortcutAction.settingsSections( + matching: filter.query, + in: settings, + enabledModules: modules.enabledModules + ) + SettingsFullPageList { + List(selection: $selection) { + ForEach(sections) { section in + Section(section.category.displayName) { + ForEach(section.actions, id: \.self) { action in + row(for: action, in: settings) } - .disabled(settings.shortcuts.isEmpty) } } } - .formStyle(.grouped) - } - } - - var body: some View { - content - .alert(String(localized: "Reset All Shortcuts?"), isPresented: $confirmsReset) { - Button(String(localized: "Reset"), role: .destructive) { - settings = .default - } - Button(String(localized: "Cancel"), role: .cancel) {} - } message: { - Text(String(localized: "Every custom shortcut goes back to its default.")) - } - .alert( - String(localized: "Shortcut Conflict"), - isPresented: Binding( - get: { conflictAlert != nil }, - set: { if !$0 { conflictAlert = nil } } - ) - ) { - Button(String(localized: "Cancel"), role: .cancel) { - conflictAlert = nil - } - Button(String(localized: "Reassign")) { - if let state = conflictAlert { - if settings.isCustomized(state.conflictingAction) { - settings.clearShortcut(for: state.conflictingAction) - } - settings.setShortcut(state.combo, for: state.action) + .contextMenu(forSelectionType: ShortcutAction.self) { actions in + if let action = actions.first { + rowMenu(for: action, in: settings) + } + } primaryAction: { actions in + if let action = actions.first { + session.begin(action) } - conflictAlert = nil } - } message: { - if let state = conflictAlert { - Text( - String( - format: String(localized: "%@ is already used by \"%@\" in %@. Reassigning removes it from that action."), - state.combo.displayString, - state.conflictingAction.displayName, - state.conflictingAction.category.displayName - ) - ) + } emptyState: { + if sections.isEmpty { + UnavailableStateView.search(text: filter.query) } - } - .alert( - String(localized: "System Reserved Shortcut"), - isPresented: Binding( - get: { systemReservedAlert != nil }, - set: { if !$0 { systemReservedAlert = nil } } - ) - ) { - Button(String(localized: "OK"), role: .cancel) { - systemReservedAlert = nil + } bar: { + SettingsListBar { + Text(Self.summary(customized: settings.customizedCount)) + .foregroundStyle(.secondary) + } trailing: { + Button(String(localized: "Restore Defaults…")) { + confirmsRestore = true + } + .disabled(settings.shortcuts.isEmpty) + .accessibilityIdentifier("shortcut-restore-defaults") } - } message: { - Text(String(localized: "This shortcut is reserved by macOS and cannot be assigned.")) } + .accessibilityElement(children: .contain) + .accessibilityIdentifier("settings-pane-keyboard") .alert( - String(localized: "Reserved Shortcut"), + session.reassignment?.title ?? "", isPresented: Binding( - get: { reservedAlert != nil }, - set: { if !$0 { reservedAlert = nil } } - ) - ) { - Button(String(localized: "OK"), role: .cancel) { - reservedAlert = nil - } - } message: { - if let state = reservedAlert { - Text( - String( - format: String(localized: "This shortcut is reserved for \"%@\" and cannot be assigned."), - state.name - ) - ) + get: { session.reassignment != nil }, + set: { if !$0 { session.dismissReassignment() } } + ), + presenting: session.reassignment + ) { request in + Button(String(localized: "Reassign")) { + session.confirm(request) } + Button(String(localized: "Cancel"), role: .cancel) {} + } message: { request in + Text(request.message) } - .alert( - String(localized: "Modifier Key Required"), - isPresented: Binding( - get: { needsModifierAlert != nil }, - set: { if !$0 { needsModifierAlert = nil } } - ) - ) { - Button(String(localized: "OK"), role: .cancel) { - needsModifierAlert = nil + .alert(String(localized: "Restore Default Shortcuts?"), isPresented: $confirmsRestore) { + Button(String(localized: "Restore Defaults"), role: .destructive) { + keyboard.value = .default } + Button(String(localized: "Cancel"), role: .cancel) {} } message: { - Text(String(localized: "This action needs ⌘ or ⌃. Option and Shift can join them, but cannot hold a shortcut on their own.")) + Text(String(localized: "Every shortcut you changed goes back to its default.")) } - .onAppear { - SystemHotkeyChecker.shared.reload() + .onDisappear { + session.reset() } } - // MARK: - Shortcut Row + private func row(for action: ShortcutAction, in settings: KeyboardSettings) -> some View { + let isArmed = session.recording == action + return ShortcutRow( + action: action, + key: settings.boundKey(for: action), + isCustomized: settings.isCustomized(action), + claimant: settings.defaultClaimant(for: action), + refusal: session.feedback?.action == action ? session.feedback?.message : nil, + isArmed: isArmed, + heldModifiers: isArmed ? session.heldModifiers : [], + keyboard: keyboard, + session: session + ) + } @ViewBuilder - private func shortcutRow(for action: ShortcutAction) -> some View { - HStack(spacing: 8) { - Text(action.displayName) - .frame(maxWidth: .infinity, alignment: .leading) + private func rowMenu(for action: ShortcutAction, in settings: KeyboardSettings) -> some View { + Button(String(localized: "Record Shortcut")) { + session.begin(action) + } + Button(String(localized: "Remove Shortcut")) { + keyboard.value = keyboard.value.clearing(action) + } + .disabled(settings.boundKey(for: action) == nil) + Button(String(localized: "Reset to Default")) { + keyboard.value = keyboard.value.resetting(action) + } + .disabled(!settings.isCustomized(action)) + } + + static func summary(customized count: Int) -> String { + count == 0 + ? String(localized: "No custom shortcuts") + : String(format: String(localized: "%lld customized"), count) + } +} + +// Plain values only, so arming or a refusal re-renders just the rows it touches. +private struct ShortcutRow: View { + let action: ShortcutAction + let key: BoundKey? + let isCustomized: Bool + let claimant: ShortcutAction? + let refusal: String? + let isArmed: Bool + let heldModifiers: NSEvent.ModifierFlags + let keyboard: SettingsSlice + let session: ShortcutRecordingSession - if settings.isCustomized(action) { - Button { - settings.resetToDefault(for: action) - } label: { - Image(systemName: "arrow.uturn.backward") + var body: some View { + HStack(alignment: .firstTextBaseline, spacing: 12) { + VStack(alignment: .leading, spacing: 2) { + Text(action.displayName) + note + } + Spacer(minLength: 12) + if isCustomized { + resetButton + } + ShortcutRecorderField( + action: action, + key: key, + isArmed: isArmed, + heldModifiers: heldModifiers, + session: session + ) + .fixedSize() + } + .accessibilityElement(children: .contain) + .accessibilityActions { + Button(String(localized: "Record Shortcut")) { + session.begin(action) + } + if key != nil { + Button(String(localized: "Remove Shortcut")) { + keyboard.value = keyboard.value.clearing(action) } - .buttonStyle(.borderless) - .controlSize(.small) - .help(String(localized: "Reset to default")) - .accessibilityLabel(String(localized: "Reset to default")) } - - ShortcutRecorderView( - combo: Binding( - get: { settings.shortcut(for: action) }, - set: { _ in } - ), - onRecord: { newCombo in - handleRecord(newCombo, for: action) - }, - onClear: { - settings.clearShortcut(for: action) - }, - onUnusableModifiers: { - needsModifierAlert = action + if isCustomized { + Button(String(localized: "Reset to Default")) { + keyboard.value = keyboard.value.resetting(action) } - ) - .frame(width: 160, height: 24) + } } } - // MARK: - Helpers - - private func filteredActions(for category: ShortcutCategory) -> [ShortcutAction] { - let categoryActions = ShortcutAction.settingsRows(in: category, enabledModules: modules.enabledModules) - if searchText.isEmpty { - return categoryActions + @ViewBuilder private var note: some View { + if let refusal { + // One Text, not a NoticeLabel: a Label moves the row separator to its title, past the glyph. + (Text(Image(systemName: NoticeSeverity.warning.symbolName)).foregroundColor(NoticeSeverity.warning.tint) + + Text(verbatim: " " + refusal)) + .font(.subheadline) + .foregroundStyle(.secondary) + } else if let claimant, let fallback = KeyboardSettings.defaultShortcuts[action] { + Text(String( + format: String(localized: "Default %@ is used by “%@”."), + fallback.displayString, + claimant.displayName + )) + .font(.subheadline) + .foregroundStyle(.secondary) } - let query = searchText.lowercased() - return categoryActions.filter { $0.displayName.lowercased().contains(query) } } - private func handleRecord(_ key: BoundKey, for action: ShortcutAction) { - if !key.hasModifier, !action.allowsBareKey, !key.isFunctionKey { - needsModifierAlert = action - return + private var resetButton: some View { + Button { + keyboard.value = keyboard.value.resetting(action) + } label: { + Image(systemName: "arrow.uturn.backward") + .frame(minWidth: 20, minHeight: 20) + .contentShape(Rectangle()) } + .buttonStyle(.borderless) + .help(resetHelp) + .accessibilityLabel(String(format: String(localized: "Reset %@ to default"), action.displayName)) + .accessibilityIdentifier("shortcut-reset-\(action.rawValue)") + } - switch ShortcutConflictResolver.resolve(key, for: action, in: settings) { - case .none: - settings.setShortcut(key, for: action) - case .systemReserved: - systemReservedAlert = action - case .reserved(let name): - reservedAlert = ReservedAlertState(action: action, name: name) - case .otherAction(let other): - conflictAlert = ConflictAlertState(action: action, conflictingAction: other, combo: key) + private var resetHelp: String { + guard let fallback = KeyboardSettings.defaultShortcuts[action] else { + return String(localized: "Reset to None") } + return String(format: String(localized: "Reset to %@"), fallback.displayString) } } - -// MARK: - Alert State - -private struct ConflictAlertState { - let action: ShortcutAction - let conflictingAction: ShortcutAction - let combo: BoundKey -} - -private struct ReservedAlertState { - let action: ShortcutAction - let name: String -} diff --git a/apple/TablePro/Views/Settings/LinkedFoldersSection.swift b/apple/TablePro/Views/Settings/LinkedFoldersSection.swift index 571b702a52..4ce5300a13 100644 --- a/apple/TablePro/Views/Settings/LinkedFoldersSection.swift +++ b/apple/TablePro/Views/Settings/LinkedFoldersSection.swift @@ -1,173 +1,228 @@ -// -// LinkedFoldersSection.swift -// TablePro -// -// Settings section for managing linked folders. -// Linked folders are watched for .tablepro connection files. -// - import AppKit +import Combine import SwiftUI import TableProImport +import UniformTypeIdentifiers + +@MainActor +internal final class LinkedFoldersModel: ObservableObject { + @Published internal private(set) var folders: [LinkedFolder] + + private let storage: LinkedFolderStorage + private let reloadWatcher: @MainActor () -> Void + private var updates: AnyCancellable? + + internal init( + storage: LinkedFolderStorage = .shared, + updates: AnyPublisher = AppEvents.shared.linkedFoldersDidUpdate.eraseToAnyPublisher(), + reloadWatcher: @escaping @MainActor () -> Void = { LinkedFolderWatcher.shared.reload() } + ) { + self.storage = storage + self.reloadWatcher = reloadWatcher + folders = storage.loadFolders() + // A folder added or removed anywhere else would otherwise leave the list as it was at load. + self.updates = updates.sink { [weak self] _ in + self?.reload() + } + } -struct LinkedFoldersSection: View { - static var title: String { String(localized: "Linked Folders") } + internal func reload() { + apply(storage.loadFolders()) + } + + internal func add(_ url: URL) { + let path = PathPortability.contractHome(url.path) + let current = storage.loadFolders() + guard !current.contains(where: { $0.path == path }) else { + apply(current) + return + } + storage.addFolder(LinkedFolder(path: path)) + apply(storage.loadFolders()) + reloadWatcher() + } + + internal func remove(_ folder: LinkedFolder) { + storage.removeFolder(folder) + apply(storage.loadFolders()) + reloadWatcher() + } + + internal func setEnabled(_ isEnabled: Bool, for folder: LinkedFolder) { + var current = storage.loadFolders() + guard let index = current.firstIndex(where: { $0.id == folder.id }), + current[index].isEnabled != isEnabled else { return } + current[index].isEnabled = isEnabled + storage.saveFolders(current) + apply(current) + reloadWatcher() + } + + private func apply(_ loaded: [LinkedFolder]) { + guard loaded != folders else { return } + folders = loaded + } +} +internal struct LinkedFoldersPage: View { + @EnvironmentObject private var model: LinkedFoldersModel @ObservedObject private var featureAccess = FeatureAccess.shared @ObservedObject private var watcher = LinkedFolderWatcher.shared - @State private var folders: [LinkedFolder] = LinkedFolderStorage.shared.loadFolders() + @State private var isAddingFolder = false private var isLicensed: Bool { featureAccess.isAvailable(.linkedFolders) } - var body: some View { - Section { - if !isLicensed { - LicenseGateRow(feature: .linkedFolders) - } + internal var body: some View { + Form { + Section { + if !isLicensed { + LicenseGateRow(feature: .linkedFolders) + } - if folders.isEmpty { - Text("No linked folders. Add a folder to watch for shared connection files.") - .font(.caption) - .foregroundStyle(.secondary) - } else { - ForEach(folders) { folder in - folderRow(folder) + if model.folders.isEmpty { + Text("No linked folders") + .foregroundStyle(.secondary) + } else { + ForEach(model.folders) { folder in + LinkedFolderRow( + folder: folder, + status: folder.isEnabled ? watcher.folderStatuses[folder.id] : nil, + canTurnOn: isLicensed, + model: model + ) + } } - } - Button { - addFolder() - } label: { - Label("Add Folder…", systemImage: "plus") + SettingsHelpRow( + "TablePro reads .tablepro files saved without a passphrase from these folders. Their connections appear read only in the sidebar." + ) + } footer: { + SettingsSectionActions { + Button(String(localized: "Add Folder…")) { + isAddingFolder = true + } + .disabled(!isLicensed) + .accessibilityIdentifier("linked-folders-add-button") + } } - .disabled(!isLicensed) - } header: { - Text(Self.title) - } footer: { - Text("Watched folders are scanned for .tablepro files without a passphrase. Connections appear read only in the sidebar.") - .font(.caption) - .foregroundStyle(.secondary) } - /// The list is seeded once at init, so without this a folder added or removed anywhere else - /// leaves this pane showing the set as it stood when the window was first built. - .onReceive(AppEvents.shared.linkedFoldersDidUpdate) { _ in - folders = LinkedFolderStorage.shared.loadFolders() + .formStyle(.grouped) + .fileImporter(isPresented: $isAddingFolder, allowedContentTypes: [.folder]) { result in + if case .success(let url) = result { + model.add(url) + } } + .modifier(LinkedFolderDialogMessage()) + .accessibilityElement(children: .contain) + .accessibilityIdentifier(SettingsPage.linkedFolders.pageIdentifier) } +} - // MARK: - Folder Row +private struct LinkedFolderRow: View { + let folder: LinkedFolder + let status: LinkedFolderStatus? + let canTurnOn: Bool + let model: LinkedFoldersModel - private func folderRow(_ folder: LinkedFolder) -> some View { - HStack(spacing: 8) { - Toggle(isOn: Binding( - get: { folder.isEnabled }, - set: { newValue in - guard let index = folders.firstIndex(where: { $0.id == folder.id }) else { return } - folders[index].isEnabled = newValue - LinkedFolderStorage.shared.saveFolders(folders) - LinkedFolderWatcher.shared.reload() + var body: some View { + LabeledContent { + HStack(spacing: 8) { + Toggle(isOn: Binding(get: { folder.isEnabled }, set: { model.setEnabled($0, for: folder) })) { + Text(verbatim: folder.name) + } + .toggleStyle(.switch) + .labelsHidden() + // A folder already on can always be turned off, licensed or not. + .disabled(!canTurnOn && !folder.isEnabled) + .accessibilityLabel(String(format: String(localized: "Watch %@"), folder.name)) + + Menu { + actions + } label: { + Image(systemName: "ellipsis.circle") } - )) { - EmptyView() + .menuStyle(.button) + .buttonStyle(.borderless) + .menuIndicator(.hidden) + .fixedSize() + .help(String(localized: "Actions")) + .accessibilityLabel(String(format: String(localized: "Actions for %@"), folder.name)) } - .toggleStyle(.switch) - .controlSize(.mini) - .labelsHidden() - .accessibilityLabel(folder.name) - + } label: { VStack(alignment: .leading, spacing: 1) { - Text(folder.name) - .font(.body) + Text(verbatim: folder.name) .lineLimit(1) - - Text(folder.path) - .font(.caption) + Text(verbatim: folder.path) + .font(.subheadline) .foregroundStyle(.secondary) .lineLimit(1) .truncationMode(.middle) - - if folder.isEnabled, let status = watcher.folderStatuses[folder.id] { - statusLines(status) + .help(folder.path) + if let status { + LinkedFolderStatusLines(status: status) + .font(.subheadline) } } .accessibilityElement(children: .combine) - - Spacer() - - Button(role: .destructive) { - removeFolder(folder) - } label: { - Image(systemName: "trash") - .frame(width: 24, height: 24) - .foregroundStyle(.secondary) + .accessibilityActions { + Button(String(localized: "Show in Finder"), action: showInFinder) + Button(String(localized: "Remove"), action: remove) } - .buttonStyle(.plain) - .help(String(localized: "Remove Folder")) - .accessibilityLabel(String(localized: "Remove folder")) } + .contextMenu { + actions + } + .accessibilityElement(children: .contain) + .accessibilityIdentifier("linked-folder-row-\(folder.id.uuidString)") } - @ViewBuilder - private func statusLines(_ status: LinkedFolderStatus) -> some View { + @ViewBuilder private var actions: some View { + Button(String(localized: "Show in Finder"), action: showInFinder) + Divider() + Button(String(localized: "Remove"), role: .destructive, action: remove) + } + + private func remove() { + model.remove(folder) + } + + private func showInFinder() { + NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: folder.expandedPath)]) + } +} + +private struct LinkedFolderStatusLines: View { + let status: LinkedFolderStatus + + var body: some View { switch status.contents { case .missing: - warning(String(localized: "Folder not found")) + NoticeLabel(String(localized: "Folder not found")) case .unreadable: - warning(String(localized: "Can't read this folder")) + NoticeLabel(String(localized: "Can't read this folder")) case .connections(let count, let unreadableFiles): - Text(LinkedFolderStatusCopy.connections(count)) - .font(.caption) + Text(verbatim: LinkedFolderStatusCopy.connections(count)) .foregroundStyle(.secondary) if unreadableFiles > 0 { - warning(LinkedFolderStatusCopy.unreadableFiles(unreadableFiles)) + NoticeLabel(LinkedFolderStatusCopy.unreadableFiles(unreadableFiles)) } if !status.isWatched { - warning(String(localized: "Not watching this folder for changes")) + NoticeLabel(String(localized: "Not watching this folder for changes")) } } } +} - private func warning(_ message: String) -> some View { - Label { - Text(message) - .foregroundStyle(.secondary) - } icon: { - Image(systemName: "exclamationmark.triangle.fill") - .foregroundStyle(.orange) - } - .font(.caption) - } - - // MARK: - Actions - - private func addFolder() { - let panel = NSOpenPanel() - panel.canChooseFiles = false - panel.canChooseDirectories = true - panel.allowsMultipleSelection = false - panel.message = String(localized: "Choose a folder to watch for .tablepro connection files") - - guard let window = NSApp.keyWindow else { return } - panel.beginSheetModal(for: window) { response in - guard response == .OK, let url = panel.url else { return } - let path = PathPortability.contractHome(url.path) - - guard !self.folders.contains(where: { $0.path == path }) else { return } - - let folder = LinkedFolder(path: path) - LinkedFolderStorage.shared.addFolder(folder) - self.folders = LinkedFolderStorage.shared.loadFolders() - LinkedFolderWatcher.shared.reload() +private struct LinkedFolderDialogMessage: ViewModifier { + func body(content: Content) -> some View { + if #available(macOS 14.0, *) { + content.fileDialogMessage(Text("Choose a folder to watch for .tablepro connection files")) + } else { + content } } - - private func removeFolder(_ folder: LinkedFolder) { - LinkedFolderStorage.shared.removeFolder(folder) - folders = LinkedFolderStorage.shared.loadFolders() - LinkedFolderWatcher.shared.reload() - } } // Explicit singular and plural keys: see OperationCompletionCopy for why not inflection. diff --git a/apple/TablePro/Views/Settings/MCPSettingsView.swift b/apple/TablePro/Views/Settings/MCPSettingsView.swift index 5a0ccf2f2f..81ae132f6e 100644 --- a/apple/TablePro/Views/Settings/MCPSettingsView.swift +++ b/apple/TablePro/Views/Settings/MCPSettingsView.swift @@ -1,18 +1,188 @@ +import Combine import SwiftUI +import TableProMCP + +// One per Settings window, shared by the pane root and its pages, so a push or a pane switch keeps the rows. +@MainActor +final class MCPSettingsModel: ObservableObject { + @Published private(set) var tokenStore: MCPTokenStore? + @Published private(set) var tokens: [MCPAuthToken] = [] + @Published private(set) var hasLoadedTokens = false + @Published private(set) var grants: [MCPConnectionGrant] = [] + @Published private(set) var hasLoadedGrants = false + @Published private(set) var connectionNames: [UUID: String] = [:] + @Published private(set) var tokenNames: [UUID: String] = [:] + + private let manager: MCPServerManager + private var storeSubscription: AnyCancellable? + private var tokenTask: Task? + private var grantTask: Task? + private var tokenGeneration = 0 + private var grantGeneration = 0 + + init(manager: MCPServerManager) { + self.manager = manager + } + + convenience init() { + self.init(manager: .shared) + } + + deinit { + tokenTask?.cancel() + grantTask?.cancel() + } + + var activeTokenCount: Int { + tokens.filter { $0.isEffectivelyActive }.count + } + + func activate() { + guard storeSubscription == nil else { return } + let grantChanges = manager.grantChanges.changes() + grantTask = Task { [weak self] in + for await _ in grantChanges { + await self?.reloadGrants() + } + } + storeSubscription = manager.$tokenStore + .removeDuplicates { $0 === $1 } + .sink { [weak self] store in self?.adopt(store) } + } + + func refresh() async { + await reloadTokens() + await reloadGrants() + } + + func reloadTokens() async { + tokenGeneration += 1 + let generation = tokenGeneration + guard let store = tokenStore else { return } + let listed = await store.list() + guard generation == tokenGeneration, store === tokenStore else { return } + tokens = listed.filter(\.isUserManaged) + hasLoadedTokens = true + } + + func reloadGrants() async { + grantGeneration += 1 + let generation = grantGeneration + let loaded = await manager.connectionGrants() + let named = await tokenStore?.list() ?? [] + guard generation == grantGeneration else { return } + grants = loaded.sorted { $0.grantedAt > $1.grantedAt } + tokenNames = Dictionary(named.map { ($0.id, $0.name) }, uniquingKeysWith: { first, _ in first }) + connectionNames = Dictionary( + ConnectionStorage.shared.loadConnections().map { ($0.id, $0.name) }, + uniquingKeysWith: { first, _ in first } + ) + hasLoadedGrants = true + } + + func forgetGrant(_ grant: MCPConnectionGrant) async { + await manager.forgetGrant(subject: grant.subject, connectionId: grant.connectionId) + await reloadGrants() + } + + func forgetEveryGrant() async { + await manager.forgetEveryGrant() + await reloadGrants() + } + + func generate(_ request: MCPTokenRequest, configuredPort: Int) async -> Result { + guard let store = tokenStore else { + return .failure(MCPTokenCreateFailure( + message: String(localized: "The MCP server is not running, so TablePro cannot save a token now. Start the server, then try again."), + endsSheet: true + )) + } + let access: ConnectionAccess = request.connectionIds.map { .limited($0) } ?? .all + do { + let result = try await store.generate( + name: request.name, + permissions: request.permissions, + connectionAccess: access, + expiresAt: request.expiresAt, + isBridgeCredential: false, + isClaudeAgentCredential: false, + extraScopes: [] + ) + await reloadTokens() + let port = manager.listeningPort ?? configuredPort + return .success(MCPTokenReveal( + plaintext: result.plaintext, + setup: MCPHTTPClientSetup(port: port), + port: port, + configuredPort: configuredPort + )) + } catch { + return .failure(MCPTokenCreateFailure(message: Self.generateFailureMessage(error), endsSheet: false)) + } + } + + func revoke(_ ids: Set) async -> MCPTokenAlert? { + guard tokenStore != nil else { return .serverNotRunning } + var allSaved = true + for id in ids { + let saved = await manager.revokeToken(id: id) + allSaved = allSaved && saved + } + await reloadTokens() + return allSaved ? nil : .revocationNotSaved + } + + func delete(_ ids: Set) async -> MCPTokenAlert? { + guard let store = tokenStore else { return .serverNotRunning } + var allSaved = true + for id in ids { + let saved = await store.delete(tokenId: id) + allSaved = allSaved && saved + } + await reloadTokens() + return allSaved ? nil : .deletionNotSaved + } + + private func adopt(_ store: MCPTokenStore?) { + tokenStore = store + tokenTask?.cancel() + tokenTask = nil + guard let store else { return } + let changes = store.membershipChanges.changes() + tokenTask = Task { [weak self] in + await self?.reloadTokens() + await self?.reloadGrants() + for await _ in changes { + await self?.reloadTokens() + await self?.reloadGrants() + } + } + } + + private static func generateFailureMessage(_ error: Error) -> String { + switch error as? MCPTokenStoreError { + case .storedTokensUnreadable?: + String(localized: "TablePro could not read the tokens saved in the Keychain, so it will not save a new one over them. Restart TablePro and try again.") + case .randomGenerationFailed?: + String(localized: "macOS could not generate a secure token. Try again.") + case .keychainUnavailable?, .notSaved?, nil: + String(localized: "TablePro could not save the token to the Keychain, so it was not created. Try again.") + } + } +} struct MCPSettingsView: View { @Binding var settings: MCPSettings + @ObservedObject var model: MCPSettingsModel + let onChangeAIPolicy: () -> Void var body: some View { Form { - MCPSection(settings: $settings) + MCPSection(settings: $settings, model: model, onChangeAIPolicy: onChangeAIPolicy) MCPOutsideServersSection() } .formStyle(.grouped) + .accessibilityElement(children: .contain) + .accessibilityIdentifier("settings-pane-mcp") } } - -#Preview { - MCPSettingsView(settings: .constant(.default)) - .frame(width: 520, height: 540) -} diff --git a/apple/TablePro/Views/Settings/NotificationsSettingsView.swift b/apple/TablePro/Views/Settings/NotificationsSettingsView.swift index 7517f80564..301d5b878a 100644 --- a/apple/TablePro/Views/Settings/NotificationsSettingsView.swift +++ b/apple/TablePro/Views/Settings/NotificationsSettingsView.swift @@ -1,60 +1,77 @@ -// -// NotificationsSettingsView.swift -// TablePro -// - import AppKit import SwiftUI import UserNotifications struct NotificationsSettingsView: View { @Binding var settings: NotificationSettings + @ObservedObject var visit: SettingsPaneVisit @StateObject private var permission = NotificationPermissionMonitor() var body: some View { Form { - Section { - Toggle("Notify when long-running work finishes", isOn: $settings.isEnabled) - .accessibilityIdentifier("notifications-enabled-toggle") - - Picker("Only after", selection: $settings.thresholdSeconds) { - ForEach(Self.thresholdChoices, id: \.self) { seconds in - Text(Self.thresholdLabel(seconds)).tag(seconds) - } + if settings.isEnabled, permission.status == .denied { + Section { + permissionRow } - .disabled(!settings.isEnabled) - } header: { - Text("Notifications") - } footer: { - Text("TablePro only notifies when the result is not already on screen.") - .font(.caption) - .foregroundStyle(.secondary) } - if permission.status == .denied { - Section { - HStack(spacing: 8) { - NoticeLabel(String(localized: "Notifications are turned off for TablePro in System Settings.")) - Spacer() - Button("Open System Settings", action: Self.openSystemSettings) + Section { + Toggle(isOn: $settings.isEnabled) { + Text("Show notifications") + Text( + "When long-running work finishes out of sight, an agent needs your answer or its reply fails, or an extension can't load or update." + ) + } + .accessibilityIdentifier("notifications-enabled-toggle") + + Picker(selection: threshold) { + ForEach(settings.thresholdOptions, id: \.self) { seconds in + Text(verbatim: SettingsFormat.duration(seconds: seconds)).tag(seconds) } + } label: { + Text("Treat work as long-running after") + Text( + "When work this long finishes out of sight, its tab is marked and, with notifications on, a notification shows." + ) } + .pickerStyle(.menu) + .accessibilityIdentifier("notifications-threshold-picker") } } .formStyle(.grouped) - .task { + .accessibilityElement(children: .contain) + .accessibilityIdentifier("settings-pane-notifications") + .task(id: visit.count) { await permission.refresh() } } - private static let thresholdChoices = [5, 10, 20, 30, 60, 120, 300, 600] - - private static func thresholdLabel(_ seconds: Int) -> String { - guard seconds >= 60 else { - return String(format: String(localized: "%lld seconds"), seconds) + private var permissionRow: some View { + LabeledContent { + Button("Open System Settings", action: Self.openSystemSettings) + .accessibilityIdentifier("notifications-open-system-settings") + } label: { + Label { + Text("Notifications are off in System Settings") + Text("TablePro can't show any notification until you allow it there.") + } icon: { + Image(systemName: NoticeSeverity.warning.symbolName) + .foregroundStyle(NoticeSeverity.warning.tint) + .accessibilityHidden(true) + } } - return String(format: String(localized: "%lld minutes"), seconds / 60) + .accessibilityElement(children: .contain) + .accessibilityIdentifier("notifications-permission-row") + } + + // A stored value outside the allowed range shows the value that applies instead of a blank pop-up. + private var threshold: Binding { + let settings = $settings + return Binding( + get: { settings.wrappedValue.validatedThresholdSeconds }, + set: { settings.wrappedValue.thresholdSeconds = $0 } + ) } private static func openSystemSettings() { diff --git a/apple/TablePro/Views/Settings/Plugins/ExtensionsPaneModel.swift b/apple/TablePro/Views/Settings/Plugins/ExtensionsPaneModel.swift new file mode 100644 index 0000000000..d78c5f4459 --- /dev/null +++ b/apple/TablePro/Views/Settings/Plugins/ExtensionsPaneModel.swift @@ -0,0 +1,503 @@ +import AppKit +import Combine +import Foundation +import os +import TableProPluginKit + +internal enum ExtensionsPluginGroup: CaseIterable, Hashable, Sendable { + case drivers + case exports + case imports + case other + + // The first capability decides; none, or one this build does not know, lands in Other. + internal init(capabilities: [PluginCapability]) { + switch capabilities.first { + case .databaseDriver: self = .drivers + case .exportFormat: self = .exports + case .importFormat: self = .imports + default: self = .other + } + } + + internal var title: String { + switch self { + case .drivers: String(localized: "Database Drivers") + case .exports: String(localized: "Export Formats") + case .imports: String(localized: "Import Formats") + case .other: String(localized: "Other") + } + } +} + +internal struct ExtensionsPluginRow: Equatable, Identifiable, Sendable { + let id: String + let url: URL + let name: String + let iconName: String + let isBuiltIn: Bool + let version: String + let typeIds: [String] + let formatIds: [String] + let group: ExtensionsPluginGroup + let isStaged: Bool + + var isDriver: Bool { !typeIds.isEmpty } +} + +internal struct ExtensionsPluginSection: Equatable, Identifiable, Sendable { + let group: ExtensionsPluginGroup + let rows: [ExtensionsPluginRow] + + var id: ExtensionsPluginGroup { group } +} + +internal enum ExtensionsRejectedAction: Equatable, Sendable { + case update(registryId: String) + case appUpdate + case retry + case noAction +} + +internal struct ExtensionsRejectedRow: Equatable, Identifiable, Sendable { + let url: URL + let name: String + let iconName: String + let reason: String + let caption: String + let severity: NoticeSeverity + let action: ExtensionsRejectedAction + let canRemove: Bool + let bundleId: String? + // The tracker keys a repair by the registry id, so the row finds its own download. + let trackerId: String? + + var id: URL { url } +} + +internal enum ExtensionsRelaunchReason: Equatable, Sendable { + case removed + case updates + + var text: String { + switch self { + case .removed: String(localized: "Removed plugins stay loaded until TablePro relaunches.") + case .updates: String(localized: "Plugin updates install when TablePro relaunches.") + } + } +} + +internal enum ExtensionsPluginStatus: Equatable, Sendable { + case downloading + case installing + case failed + case staged + case builtIn + case version(String) + + init(phase: PluginInstallTracker.Phase?, isStaged: Bool, isBuiltIn: Bool, version: String) { + switch phase { + case .downloading?: self = .downloading + case .installing?: self = .installing + case .failed?: self = .failed + case .completed?, nil: + if isStaged { + self = .staged + } else if isBuiltIn { + self = .builtIn + } else { + self = .version(version) + } + } + } + + var text: String { + switch self { + case .downloading: String(localized: "Downloading update…") + case .installing: String(localized: "Installing update…") + case .failed: String(localized: "Update failed") + case .staged: String(localized: "Updates when TablePro relaunches") + case .builtIn: String(localized: "Built-in") + case .version(let version): String(format: String(localized: "Version %@"), version) + } + } +} + +internal enum ExtensionsPageStatus: Equatable, Sendable { + case running(PluginInstallTracker.Phase) + case failed(String) + case staged + + init?(phase: PluginInstallTracker.Phase?, isStaged: Bool) { + switch phase { + case .downloading?, .installing?: + guard let phase else { return nil } + self = .running(phase) + case .failed(let reason)?: + self = .failed(reason) + case .completed?, nil: + guard isStaged else { return nil } + self = .staged + } + } +} + +internal struct ExtensionsFilteredContent: Equatable { + let groups: [ExtensionsPluginSection] + let rejected: [ExtensionsRejectedRow] + let modules: [AppModule] + let isFiltering: Bool + + var isEmpty: Bool { groups.isEmpty && rejected.isEmpty && modules.isEmpty } +} + +internal struct ExtensionsSnapshot: Equatable, Sendable { + var groups: [ExtensionsPluginSection] = [] + var rejected: [ExtensionsRejectedRow] = [] + var relaunch: ExtensionsRelaunchReason? + + var rows: [ExtensionsPluginRow] { groups.flatMap(\.rows) } + + // Tracker entries a row already shows; any other running or failed entry gets an activity row. + var trackedIds: Set { + Set(rows.map(\.id)).union(rejected.compactMap(\.trackerId)).union(rejected.compactMap(\.bundleId)) + } + + func filtered(_ query: String, modules: [AppModule] = AppModule.allCases) -> ExtensionsFilteredContent { + let needle = query.trimmingCharacters(in: .whitespacesAndNewlines) + guard !needle.isEmpty else { + return ExtensionsFilteredContent(groups: groups, rejected: rejected, modules: modules, isFiltering: false) + } + let matches: (String) -> Bool = { $0.localizedStandardContains(needle) } + let filteredGroups = groups.compactMap { section -> ExtensionsPluginSection? in + let rows = matches(section.group.title) ? section.rows : section.rows.filter { row in + matches(row.name) || row.typeIds.contains(where: matches) || row.formatIds.contains(where: matches) + } + return rows.isEmpty ? nil : ExtensionsPluginSection(group: section.group, rows: rows) + } + return ExtensionsFilteredContent( + groups: filteredGroups, + rejected: rejected.filter { matches($0.name) || matches($0.caption) }, + modules: modules.filter { matches($0.title) || matches($0.summary) }, + isFiltering: true + ) + } + + static func activities( + in entries: [String: PluginInstallTracker.Entry], + excluding trackedIds: Set + ) -> [PluginInstallTracker.Entry] { + entries.values + .filter { entry in + guard !trackedIds.contains(entry.pluginId) else { return false } + if case .completed = entry.phase { return false } + return true + } + .sorted { $0.order < $1.order } + } +} + +internal enum ExtensionsPage { + case plugin(PluginEntry, isStaged: Bool) + case rejected(ExtensionsRejectedRow) + case unavailable +} + +// Owns the pane's view of the plugin manager for the window's lifetime, shared by the root and its pages. +@MainActor +internal final class ExtensionsPaneModel: ObservableObject { + private static let logger = Logger(subsystem: "com.TablePro", category: "ExtensionsPane") + + @Published private(set) var snapshot = ExtensionsSnapshot() + @Published private(set) var retrying: Set = [] + @Published private(set) var retryFailures: Set = [] + + let manager: PluginManager + let registryClient: RegistryClient + private(set) var plugins: [PluginEntry] = [] + private(set) var stagedPluginIds: Set = [] + private var subscription: AnyCancellable? + + init(manager: PluginManager = .shared, registryClient: RegistryClient) { + self.manager = manager + self.registryClient = registryClient + // @Published sends the new value before storing it, so the inputs come from the publishers, never the manager. + subscription = manager.$plugins + .combineLatest(manager.$rejectedPlugins, manager.$needsRestart, manager.$stagedPluginIds) + .combineLatest(registryClient.$manifest) + .sink { [weak self] inputs, manifest in + MainActor.assumeIsolated { + self?.apply( + plugins: inputs.0, + rejected: inputs.1, + needsRestart: inputs.2, + staged: inputs.3, + manifest: manifest + ) + } + } + } + + private func apply( + plugins: [PluginEntry], + rejected: [RejectedPlugin], + needsRestart: Bool, + staged: Set, + manifest: RegistryManifest? + ) { + self.plugins = plugins + stagedPluginIds = staged + let next = Self.makeSnapshot( + plugins: plugins, + rejected: rejected, + needsRestart: needsRestart, + staged: staged, + manifest: manifest, + isUpdatingEnabled: manager.isUpdatingEnabled, + canRemove: { [manager] in manager.canRemoveRejectedPlugin($0) } + ) + if next != snapshot { + snapshot = next + } + } + + static func makeSnapshot( + plugins: [PluginEntry], + rejected: [RejectedPlugin], + needsRestart: Bool, + staged: Set, + manifest: RegistryManifest?, + isUpdatingEnabled: Bool, + canRemove: (RejectedPlugin) -> Bool + ) -> ExtensionsSnapshot { + let rejectedURLs = Set(rejected.map(\.url)) + let rows = plugins + .filter { !rejectedURLs.contains($0.url) } + .map { row(for: $0, isStaged: staged.contains($0.id)) } + let groups = ExtensionsPluginGroup.allCases.compactMap { group -> ExtensionsPluginSection? in + let members = rows + .filter { $0.group == group } + .sorted { $0.name.localizedStandardCompare($1.name) == .orderedAscending } + return members.isEmpty ? nil : ExtensionsPluginSection(group: group, rows: members) + } + let rejectedRows = rejected + .map { rejectedRow(for: $0, manifest: manifest, isUpdatingEnabled: isUpdatingEnabled, canRemove: canRemove($0)) } + .sorted { $0.name.localizedStandardCompare($1.name) == .orderedAscending } + let relaunch: ExtensionsRelaunchReason? + if needsRestart { + relaunch = .removed + } else if !staged.isEmpty { + relaunch = .updates + } else { + relaunch = nil + } + return ExtensionsSnapshot(groups: groups, rejected: rejectedRows, relaunch: relaunch) + } + + private static func row(for entry: PluginEntry, isStaged: Bool) -> ExtensionsPluginRow { + ExtensionsPluginRow( + id: entry.id, + url: entry.url, + name: entry.name, + iconName: entry.pluginIconName, + isBuiltIn: entry.source == .builtIn, + version: entry.version, + typeIds: (entry.databaseTypeId.map { [$0] } ?? []) + entry.additionalTypeIds, + formatIds: [entry.exportFormatId, entry.importFormatId].compactMap { $0 }, + group: ExtensionsPluginGroup(capabilities: entry.capabilities), + isStaged: isStaged + ) + } + + private static func rejectedRow( + for plugin: RejectedPlugin, + manifest: RegistryManifest?, + isUpdatingEnabled: Bool, + canRemove: Bool + ) -> ExtensionsRejectedRow { + let action = PluginManager.rejectedAction( + registryPlugin: PluginManager.registryPlugin(for: plugin, in: manifest), + manifestLoaded: manifest != nil, + kits: PluginManager.compatibleKits + ) + let status = RejectedPluginStatus(action: action) + let rowAction: ExtensionsRejectedAction + switch action { + case .updateAvailable(let registryPlugin): rowAction = .update(registryId: registryPlugin.id) + case .requiresAppUpdate: rowAction = .appUpdate + case .awaitingCompatibleBuild: rowAction = isUpdatingEnabled ? .retry : .noAction + case .notInRegistry: rowAction = .noAction + } + let resolvedId = manifest.flatMap { PluginManager.resolveRegistryId(for: plugin, in: $0) } + return ExtensionsRejectedRow( + url: plugin.url, + name: plugin.name, + iconName: PluginManager.iconName(forPrimaryTypeId: plugin.providedDatabaseTypeIds.first), + reason: plugin.reason, + caption: status.caption, + severity: status.severity, + action: rowAction, + canRemove: canRemove, + bundleId: plugin.bundleId, + trackerId: resolvedId ?? plugin.registryId ?? plugin.bundleId + ) + } + + // A plugin row whose bundle could not load shows that page; a rejected route whose bundle has since loaded shows it. + func page(for route: SettingsRoute) -> ExtensionsPage { + switch route { + case .plugin(let id): + guard let entry = plugins.first(where: { $0.id == id }) else { return .unavailable } + if let row = snapshot.rejected.first(where: { $0.url == entry.url }) { return .rejected(row) } + return .plugin(entry, isStaged: stagedPluginIds.contains(id)) + case .rejectedPlugin(let url): + if let row = snapshot.rejected.first(where: { $0.url == url }) { return .rejected(row) } + if let entry = plugins.first(where: { $0.url == url }) { + return .plugin(entry, isStaged: stagedPluginIds.contains(entry.id)) + } + return .unavailable + case .page, .aiProvider: + return .unavailable + } + } + + // Waits for the list, so a request made before it loaded still finds its plugin. + func revealPending(in context: SettingsPaneContext) async { + guard context.navigation.pendingPluginReveal != nil else { return } + await manager.waitForInitialLoad() + guard !Task.isCancelled, let request = context.navigation.consumePluginReveal() else { return } + guard context.isCurrent, context.navigation.location.routes.isEmpty, + let target = PluginListSelection.revealTarget( + pluginId: request.pluginId, + loadedIds: manager.plugins.map(\.id), + rejected: manager.rejectedPlugins + ) else { return } + context.filter?.query = "" + context.navigation.push(target.route, in: context.pane) + } + + nonisolated static func installableFiles(_ urls: [URL]) -> [URL] { + urls.filter { url in + url.isFileURL && ["zip", "tableplugin"].contains(url.pathExtension.lowercased()) + } + } + + // Returns false when no file is a plugin, so a drop of anything else is refused. + @discardableResult + func install(_ urls: [URL], context: SettingsPaneContext) -> Bool { + let files = Self.installableFiles(urls) + guard !files.isEmpty else { return false } + Task { await installFiles(files, context: context) } + return true + } + + private func installFiles(_ files: [URL], context: SettingsPaneContext) async { + var installed: [PluginEntry] = [] + for url in files { + do { + installed.append(try await manager.installPlugin(from: url)) + } catch { + Self.logger.info("A plugin file did not install: \(error.localizedDescription)") + } + } + // Several files, or a user who moved on, stay where they are. + guard files.count == 1, let entry = installed.first, context.navigation.location.routes.isEmpty else { return } + context.navigation.push(.plugin(id: entry.id), in: context.pane) + } + + func retryInstall(_ entry: PluginInstallTracker.Entry, context: SettingsPaneContext, replacing route: SettingsRoute? = nil) { + switch entry.retry { + case .registry(let registryPlugin): + update(registryPlugin, context: context, replacing: route) + case .file(let url): + install([url], context: context) + case nil: + break + } + } + + func registryPlugin(id: String) -> RegistryPlugin? { + registryClient.manifest?.plugins.first { $0.id == id } + } + + // A rejected plugin that installed is a loaded one now, so its page takes the loaded route. + func update(_ registryPlugin: RegistryPlugin, context: SettingsPaneContext, replacing route: SettingsRoute? = nil) { + Task { + let result = await manager.performRegistryUpdate(registryPlugin) + guard case .succeeded(let entry) = result, let route else { return } + Self.replace(route, with: .plugin(id: entry.id), in: context) + } + } + + func retryRejected(_ url: URL) { + guard !retrying.contains(url) else { return } + retrying.insert(url) + retryFailures.remove(url) + Task { + let reached = await manager.retryRejectedPluginRepairs(registryClient: registryClient) + retrying.remove(url) + if !reached { + retryFailures.insert(url) + } + } + } + + func uninstall(_ row: ExtensionsPluginRow, context: SettingsPaneContext) { + uninstall(id: row.id, name: row.name, isDriver: row.isDriver, context: context) + } + + func uninstall(id: String, name: String, isDriver: Bool, context: SettingsPaneContext) { + Task { + var message = String(localized: "The plugin moves to the Trash and its settings are deleted. It stays loaded until TablePro relaunches.") + if isDriver { + message += " " + String(localized: "Saved connections that use it stay in your library.") + } + let confirmed = await AlertHelper.confirmDestructive( + title: String(format: String(localized: "Uninstall “%@”?"), name), + message: message, + confirmButton: String(localized: "Uninstall"), + cancelButton: String(localized: "Cancel") + ) + guard confirmed else { return } + do { + try await manager.uninstallPlugin(id: id) { try FileManager.default.trashItem(at: $0, resultingItemURL: nil) } + } catch { + context.presentError(title: String(localized: "Couldn't Uninstall"), message: error.localizedDescription) + return + } + context.navigation.removeRoute(.plugin(id: id)) + } + } + + func moveToTrash(_ url: URL, context: SettingsPaneContext) { + guard let plugin = manager.rejectedPlugins.first(where: { $0.url == url }) else { return } + Task { + let confirmed = await AlertHelper.confirmDestructive( + title: String(format: String(localized: "Move “%@” to the Trash?"), plugin.name), + message: String(localized: "The plugin can't be loaded. You can put it back from the Trash."), + confirmButton: String(localized: "Move to Trash"), + cancelButton: String(localized: "Cancel") + ) + guard confirmed else { return } + do { + try manager.removeRejectedPlugin(plugin) + } catch { + context.presentError(title: String(localized: "Couldn't Move to Trash"), message: error.localizedDescription) + return + } + context.navigation.removeRoute(.rejectedPlugin(url)) + } + } + + func showInFinder(_ url: URL) { + NSWorkspace.shared.activateFileViewerSelecting([url]) + } + + private static func replace(_ old: SettingsRoute, with new: SettingsRoute, in context: SettingsPaneContext) { + let wasShown = context.isCurrent && context.navigation.location.routes.last == old + context.navigation.removeRoute(old) + if wasShown { + context.navigation.push(new, in: context.pane) + } + } +} diff --git a/apple/TablePro/Views/Settings/Plugins/InstalledPluginsView.swift b/apple/TablePro/Views/Settings/Plugins/InstalledPluginsView.swift index a2e78f03f2..f7df092897 100644 --- a/apple/TablePro/Views/Settings/Plugins/InstalledPluginsView.swift +++ b/apple/TablePro/Views/Settings/Plugins/InstalledPluginsView.swift @@ -1,685 +1,350 @@ import AppKit import SwiftUI -import TableProPluginKit import UniformTypeIdentifiers +// The Extensions pane root. The toolbar filter narrows it; the pages are their own views in the pane's stack. struct InstalledPluginsView: View { - @ObservedObject private var pluginManager = PluginManager.shared - @ObservedObject private var registryClient: RegistryClient - // Install progress lives in the tracker, which the plugin manager does not republish. - @ObservedObject private var installTracker = PluginInstallTracker.shared - @ObservedObject private var navigation = PluginsSettingsNavigation.shared - @ObservedObject private var modules = AppModuleSettings.shared - @ObservedObject private var updates = UpdateCenter.shared - - @State private var selection: PluginListSelection? - @State private var searchText = "" - @State private var showErrorAlert = false - @State private var errorAlertTitle = "" - @State private var errorAlertMessage = "" - @State private var isRetryingRejected = false - - init(registryClient: RegistryClient = .shared) { - self.registryClient = registryClient - } - - private var filteredPlugins: [PluginEntry] { - if searchText.isEmpty { return pluginManager.plugins } - return pluginManager.plugins.filter { $0.name.localizedCaseInsensitiveContains(searchText) } - } - - private var filteredModules: [AppModule] { - AppModule.allCases.filter { $0.matches(filter: searchText) } - } - - private var filteredRejected: [RejectedPlugin] { - if searchText.isEmpty { return pluginManager.rejectedPlugins } - return pluginManager.rejectedPlugins.filter { $0.name.localizedCaseInsensitiveContains(searchText) } + private static let importTypes: [UTType] = [.zip] + (UTType("com.tablepro.plugin").map { [$0] } ?? []) + + private let context: SettingsPaneContext + @EnvironmentObject private var model: ExtensionsPaneModel + @ObservedObject private var filter: SettingsPaneFilter + @ObservedObject private var reveal: SettingsPluginReveal + @ObservedObject private var visit: SettingsPaneVisit + @State private var isDropTargeted = false + @State private var isImporting = false + + init(context: SettingsPaneContext) { + self.context = context + _filter = ObservedObject(wrappedValue: context.filter ?? SettingsPaneFilter()) + _reveal = ObservedObject(wrappedValue: context.navigation.pluginReveal) + _visit = ObservedObject(wrappedValue: context.visit) } var body: some View { - HSplitView { - pluginList - .frame(minWidth: 200, idealWidth: 240, maxWidth: 280) - - detailPane - .frame(minWidth: 340) + let content = model.snapshot.filtered(filter.query) + Group { + if content.isFiltering && content.isEmpty { + UnavailableStateView.search(text: filter.query) + .accessibilityElement(children: .contain) + .accessibilityIdentifier("extensions-no-results") + } else { + form(content) + } } - .task { - await registryClient.fetch(policy: .ifStale) + .task(id: visit.count) { + _ = await model.registryClient.fetch(policy: .ifStale) } - .onDrop(of: [.fileURL], isTargeted: nil) { providers in - guard let provider = providers.first, - provider.hasItemConformingToTypeIdentifier(UTType.fileURL.identifier) else { - return false - } - provider.loadItem(forTypeIdentifier: UTType.fileURL.identifier) { data, _ in - guard let data = data as? Data, - let url = URL(dataRepresentation: data, relativeTo: nil) else { return } - let ext = url.pathExtension.lowercased() - guard ext == "zip" || ext == "tableplugin" else { return } - Task { @MainActor in - installPlugin(from: url) - } - } - return true + .task(id: reveal.pending?.id) { + await model.revealPending(in: context) } - .alert(errorAlertTitle, isPresented: $showErrorAlert) { - Button("OK") {} - } message: { - Text(errorAlertMessage) + .dropDestination(for: URL.self) { urls, _ in + model.install(urls, context: context) + } isTargeted: { isTargeted in + isDropTargeted = isTargeted } - } - - // MARK: - Relaunch Row - - // Untagged, so it never takes the selection; the list is where the pending removal is. - private var relaunchRow: some View { - HStack(spacing: 8) { - Label { - Text("Relaunch to finish removing plugins.") - .lineLimit(2) - } icon: { - Image(systemName: "arrow.clockwise") - .foregroundStyle(.secondary) - } - Spacer(minLength: 4) - Button(String(localized: "Relaunch")) { updates.relaunch() } - .controlSize(.small) - .accessibilityIdentifier("plugins-relaunch-button") + .overlay { dropHighlight } + .fileImporter(isPresented: $isImporting, allowedContentTypes: Self.importTypes, allowsMultipleSelection: true) { result in + guard case .success(let urls) = result else { return } + model.install(urls, context: context) } - .padding(.vertical, 2) } - // MARK: - Rejected Plugins - - private func rejectedRow(_ plugin: RejectedPlugin) -> some View { - let status = RejectedPluginStatus(action: pluginManager.rejectedAction(for: plugin)) - return HStack(spacing: 8) { - PluginIconView(name: PluginManager.iconName(forPrimaryTypeId: plugin.providedDatabaseTypeIds.first)) - .font(.title3) - .frame(width: 24, height: 24) - .foregroundStyle(.tertiary) + private func form(_ content: ExtensionsFilteredContent) -> some View { + Form { + ExtensionsAttentionSection(snapshot: model.snapshot, context: context, tracker: model.manager.installTracker) - VStack(alignment: .leading, spacing: 2) { - Text(plugin.name) - .lineLimit(1) - Text(status.caption) - .font(.caption) - .foregroundStyle(.secondary) - .lineLimit(1) + if !content.rejected.isEmpty { + Section(String(localized: "Couldn't Load")) { + ForEach(content.rejected) { row in + ExtensionsRejectedRowView(row: row, context: context, tracker: model.manager.installTracker) + } + } } - Spacer() - - Image(systemName: status.severity.symbolName) - .selectionAwareTint(status.severity.tint) - .accessibilityHidden(true) - } - .padding(.vertical, 2) - .accessibilityElement(children: .combine) - } - - private func rejectedDetail(_ plugin: RejectedPlugin) -> some View { - let action = pluginManager.rejectedAction(for: plugin) - let status = RejectedPluginStatus(action: action) - return ScrollView { - VStack(alignment: .leading, spacing: 16) { - Text(plugin.name) - .font(.title3.weight(.semibold)) - - NoticeLabel(plugin.reason, severity: status.severity) - .font(.callout) - - if let bundleId = plugin.bundleId { - Divider() - Grid(alignment: .leading, horizontalSpacing: 16, verticalSpacing: 10) { - GridRow { - Text("Bundle ID") - .foregroundStyle(.secondary) - Text(bundleId) - .textSelection(.enabled) - } + if !content.modules.isEmpty { + Section(String(localized: "Modules")) { + ForEach(content.modules, id: \.self) { module in + ModuleToggleRow(module: module) } - .font(.callout) } + } - Divider() - - HStack(spacing: 8) { - rejectedActionControl(for: plugin, action: action) - if pluginManager.canRemoveRejectedPlugin(plugin) { - Button(String(localized: "Remove")) { - removeRejectedPlugin(plugin) - } - .accessibilityLabel(String(format: String(localized: "Remove %@"), plugin.name)) + ForEach(content.groups) { section in + Section(section.group.title) { + ForEach(section.rows) { row in + ExtensionsPluginRowView(row: row, context: context, tracker: model.manager.installTracker) } } } - .padding(20) - .frame(maxWidth: .infinity, alignment: .leading) - } - } - @ViewBuilder - private func rejectedActionControl(for plugin: RejectedPlugin, action: RejectedPluginAction) -> some View { - switch action { - case .updateAvailable(let registryPlugin): - Button(String(localized: "Update Now")) { - updatePlugin(registryPlugin) - } - .disabled(pluginManager.isInstalling) - .accessibilityLabel(String(format: String(localized: "Update %@"), plugin.name)) - case .requiresAppUpdate: - Button(updates.status.appUpdateTitle) { - updates.performAppUpdateAction() - } - .disabled(!updates.isAppUpdateActionEnabled) - .help(String(localized: "A newer TablePro is required to load this plugin.")) - case .awaitingCompatibleBuild: - if pluginManager.isUpdatingEnabled { - if isRetryingRejected { - ProgressView() - .controlSize(.small) - } else { - Button(String(localized: "Try Again")) { - retryRejectedPlugins() + // System Settings puts Add below its list. + if !content.isFiltering { + Section { + LabeledContent { + Button(String(localized: "Install from File…")) { + isImporting = true + } + .accessibilityIdentifier("extensions-install-from-file") + } label: { + Text("Install a plugin") + Text("Choose a .tableplugin bundle or a .zip archive, or drop one on this window.") } } } - case .notInRegistry: - EmptyView() - } - } - - private func retryRejectedPlugins() { - isRetryingRejected = true - Task { - defer { isRetryingRejected = false } - await pluginManager.retryRejectedPluginRepairs(registryClient: registryClient) } + .formStyle(.grouped) + .accessibilityElement(children: .contain) + .accessibilityIdentifier("settings-pane-plugins") } - private func removeRejectedPlugin(_ plugin: RejectedPlugin) { - Task { - let confirmed = await AlertHelper.confirmDestructive( - title: String(format: String(localized: "Move “%@” to the Trash?"), plugin.name), - message: String(localized: "The plugin can't be loaded. You can put it back from the Trash."), - confirmButton: String(localized: "Move to Trash"), - cancelButton: String(localized: "Cancel") - ) - guard confirmed else { return } - do { - try pluginManager.removeRejectedPlugin(plugin) - } catch { - errorAlertTitle = String(localized: "Remove Failed") - errorAlertMessage = error.localizedDescription - showErrorAlert = true - return - } - if selection == .rejected(plugin.url) { selection = nil } + @ViewBuilder private var dropHighlight: some View { + if isDropTargeted { + RoundedRectangle(cornerRadius: 12) + .strokeBorder(.tint, lineWidth: 2) + .padding(8) + .allowsHitTesting(false) + .accessibilityHidden(true) } } +} - // MARK: - Plugin List - - private var pluginList: some View { - VStack(spacing: 0) { - NativeSearchField(text: $searchText, placeholder: String(localized: "Filter…")) - .padding(.horizontal, 8) - .padding(.vertical, 6) +// Unfiltered: a relaunch or an install in progress matters whatever the query. +private struct ExtensionsAttentionSection: View { + let snapshot: ExtensionsSnapshot + let context: SettingsPaneContext + @ObservedObject var tracker: PluginInstallTracker + @EnvironmentObject private var model: ExtensionsPaneModel - ScrollViewReader { proxy in - List(selection: $selection) { - if pluginManager.needsRestart { - Section { - relaunchRow - } - } - if !filteredModules.isEmpty { - // Untagged, so a module row toggles but never takes the plugin selection. - Section(String(localized: "Modules")) { - ForEach(filteredModules, id: \.self) { module in - ModuleToggleRow(module: module, settings: modules) - } - } - } - if !filteredRejected.isEmpty { - Section(String(localized: "Couldn't Load")) { - ForEach(filteredRejected, id: \.url) { plugin in - rejectedRow(plugin) - .tag(PluginListSelection.rejected(plugin.url)) - .id(PluginListSelection.rejected(plugin.url)) - } - } - } - Section(String(localized: "Plugins")) { - ForEach(filteredPlugins) { plugin in - pluginRow(plugin) - .tag(PluginListSelection.plugin(plugin.id)) - .id(PluginListSelection.plugin(plugin.id)) + var body: some View { + let activities = ExtensionsSnapshot.activities(in: tracker.entries, excluding: snapshot.trackedIds) + if snapshot.relaunch != nil || !activities.isEmpty { + Section { + if let relaunch = snapshot.relaunch { + LabeledContent { + Button(String(localized: "Relaunch")) { + UpdateCenter.shared.relaunch() } + .accessibilityIdentifier("plugins-relaunch-button") + } label: { + Text("Relaunch TablePro to finish") + Text(verbatim: relaunch.text) } } - .listStyle(.inset) - .safeAreaInset(edge: .bottom, spacing: 0) { - listBottomBar + ForEach(activities) { entry in + activityRow(entry) } - .onAppear { revealRequestedPlugin() } - .onChange(of: navigation.pendingRequest) { _ in - revealRequestedPlugin() - } - .onChange(of: selection) { selection in - guard let selection else { return } - proxy.scrollTo(selection) - } - } - } - .onChange(of: searchText) { _ in - switch selection { - case .plugin(let id) where !filteredPlugins.contains(where: { $0.id == id }): - selection = nil - case .rejected(let url) where !filteredRejected.contains(where: { $0.url == url }): - selection = nil - default: - break } } } - private var listBottomBar: some View { - VStack(alignment: .leading, spacing: 0) { - if let install = bottomBarInstall { - bottomBarStatus(install) - .padding(.horizontal, 10) - .padding(.top, 8) - } - listBottomButtons - } - } - - // A running install first; then a failure with no plugin row to show it. - private var bottomBarInstall: PluginInstallTracker.Entry? { - if let running = installTracker.runningEntries.first { - return running - } - return installTracker.failedEntries.last { install in - !pluginManager.plugins.contains { $0.id == install.pluginId } - } - } - @ViewBuilder - private func bottomBarStatus(_ install: PluginInstallTracker.Entry) -> some View { - switch install.phase { + private func activityRow(_ entry: PluginInstallTracker.Entry) -> some View { + switch entry.phase { case .downloading, .installing: - let title = String(format: String(localized: "Installing %@…"), install.displayName) - VStack(alignment: .leading, spacing: 4) { - HStack(spacing: 6) { - Text(title) - .font(.callout) - .foregroundStyle(.secondary) - .lineLimit(1) - .truncationMode(.middle) - Spacer(minLength: 4) - Button(String(localized: "Cancel")) { - installTracker.cancel(pluginId: install.pluginId) - } - .controlSize(.small) - .disabled(install.phase == .installing) - .accessibilityLabel(String(format: String(localized: "Cancel installing %@"), install.displayName)) + let title = String(format: String(localized: "Installing %@…"), entry.displayName) + LabeledContent { + Button(String(localized: "Cancel")) { + tracker.cancel(pluginId: entry.pluginId) } - installProgress(install.phase) - .accessibilityLabel(Text(title)) + .disabled(entry.phase == .installing) + .accessibilityLabel(String(format: String(localized: "Cancel installing %@"), entry.displayName)) + } label: { + Text(verbatim: title) + ExtensionsInstallProgress(phase: entry.phase) + .accessibilityLabel(Text(verbatim: title)) } case .failed(let reason): - VStack(alignment: .leading, spacing: 4) { - Text(String(format: String(localized: "%@ could not be installed"), install.displayName)) - .font(.callout) - .lineLimit(1) - .truncationMode(.middle) - installFailure(install, reason: reason) + LabeledContent { + HStack(spacing: 8) { + if entry.retry != nil { + Button(String(localized: "Try Again")) { + model.retryInstall(entry, context: context) + } + .accessibilityLabel(String(format: String(localized: "Try installing %@ again"), entry.displayName)) + } + Button(String(localized: "Dismiss")) { + tracker.cancel(pluginId: entry.pluginId) + } + } + } label: { + Text(verbatim: String(format: String(localized: "%@ could not be installed"), entry.displayName)) + Text(verbatim: reason) } case .completed: EmptyView() } } +} - @ViewBuilder - private func installProgress(_ phase: PluginInstallTracker.Phase) -> some View { - if case .downloading(let fraction?) = phase { - ProgressView(value: fraction) - .controlSize(.small) - } else { - ProgressView() - .progressViewStyle(.linear) - .controlSize(.small) - } - } +private struct ExtensionsRejectedRowView: View { + let row: ExtensionsRejectedRow + let context: SettingsPaneContext + @ObservedObject var tracker: PluginInstallTracker + @EnvironmentObject private var model: ExtensionsPaneModel - private func installFailure(_ install: PluginInstallTracker.Entry, reason: String) -> some View { - VStack(alignment: .leading, spacing: 4) { - HStack(alignment: .firstTextBaseline, spacing: 4) { - Image(systemName: "exclamationmark.triangle.fill") - .symbolRenderingMode(.multicolor) - .accessibilityHidden(true) - Text(reason) + var body: some View { + NavigationLink(value: SettingsRoute.rejectedPlugin(row.url)) { + HStack(spacing: 10) { + PluginIconView(name: row.iconName, size: 20) .foregroundStyle(.secondary) - .lineLimit(3) - .help(reason) - } - .font(.caption) - .accessibilityElement(children: .combine) - - HStack(spacing: 6) { - if install.retry != nil { - Button(String(localized: "Try Again")) { - retryInstall(install) - } - .accessibilityLabel(String(format: String(localized: "Try installing %@ again"), install.displayName)) - } - Button(String(localized: "Dismiss")) { - installTracker.cancel(pluginId: install.pluginId) + VStack(alignment: .leading, spacing: 2) { + Text(verbatim: row.name) + .lineLimit(1) + Text(verbatim: caption) + .font(.subheadline) + .foregroundStyle(.secondary) + .lineLimit(1) } + Spacer(minLength: 8) + Image(systemName: row.severity.symbolName) + .selectionAwareTint(row.severity.tint) + .accessibilityHidden(true) } - .controlSize(.small) } - } - - private var listBottomButtons: some View { - HStack(spacing: 4) { - Button { - installFromFile() - } label: { - Image(systemName: "plus") - .frame(width: 24, height: 20) - } - .buttonStyle(.borderless) - .disabled(pluginManager.isInstalling) - .accessibilityLabel(String(localized: "Install plugin from file")) - - Button { - if let plugin = selectedPlugin { - uninstallPlugin(plugin) + .contextMenu { + if row.canRemove { + Button(String(localized: "Move to Trash…")) { + model.moveToTrash(row.url, context: context) } - } label: { - Image(systemName: "minus") - .frame(width: 24, height: 20) } - .buttonStyle(.borderless) - .disabled(selectedPlugin == nil || selectedPlugin?.source == .builtIn) - .accessibilityLabel( - selectedPlugin.map { String(format: String(localized: "Uninstall %@"), $0.name) } - ?? String(localized: "Uninstall plugin") - ) - - Spacer() + Button(String(localized: "Show in Finder")) { + model.showInFinder(row.url) + } + } + .modifier(ExtensionsOptionalAction(name: row.canRemove ? String(localized: "Move to Trash") : nil) { + model.moveToTrash(row.url, context: context) + }) + .accessibilityAction(named: Text("Show in Finder")) { + model.showInFinder(row.url) } - .padding(.horizontal, 8) - .padding(.vertical, 6) + .accessibilityIdentifier("extensions-rejected-row-\(row.url.lastPathComponent)") } - // MARK: - Plugin Row - - @ViewBuilder - private func pluginRow(_ plugin: PluginEntry) -> some View { - HStack(spacing: 8) { - PluginIconView(name: plugin.pluginIconName) - .font(.title3) - .frame(width: 24, height: 24) - .foregroundStyle(.secondary) - - VStack(alignment: .leading, spacing: 2) { - Text(plugin.name) - .lineLimit(1) - - HStack(spacing: 8) { - Text("v\(plugin.version)") - if let capability = plugin.capabilities.first { - Text(capability.displayName) - } - } - .font(.caption) - .foregroundStyle(.secondary) - - if let install = installTracker.entries[plugin.id] { - pluginRowInstallCaption(install) - } else if pluginManager.stagedPluginIds.contains(plugin.id) { - Text("Updates when TablePro relaunches") - .font(.caption) - .foregroundStyle(.secondary) - } - } - - Spacer() - - Text(plugin.source == .builtIn ? String(localized: "Built-in") : String(localized: "User")) - .font(.caption2) - .foregroundStyle(.secondary) + private var caption: String { + switch row.trackerId.flatMap({ tracker.entries[$0]?.phase }) { + case .downloading?: String(localized: "Downloading update…") + case .installing?: String(localized: "Installing update…") + default: row.caption } - .padding(.vertical, 2) } +} - @ViewBuilder - private func pluginRowInstallCaption(_ install: PluginInstallTracker.Entry) -> some View { - switch install.phase { - case .downloading: - Text("Downloading update…") - .font(.caption) - .foregroundStyle(.secondary) - case .installing: - Text("Installing update…") - .font(.caption) - .foregroundStyle(.secondary) - case .completed: - if pluginManager.stagedPluginIds.contains(install.pluginId) { - Text("Updates when TablePro relaunches") - .font(.caption) +private struct ExtensionsPluginRowView: View { + let row: ExtensionsPluginRow + let context: SettingsPaneContext + @ObservedObject var tracker: PluginInstallTracker + @EnvironmentObject private var model: ExtensionsPaneModel + + var body: some View { + let install = tracker.entries[row.id] + NavigationLink(value: SettingsRoute.plugin(id: row.id)) { + HStack(spacing: 10) { + PluginIconView(name: row.iconName, size: 20) .foregroundStyle(.secondary) + VStack(alignment: .leading, spacing: 2) { + Text(verbatim: row.name) + .lineLimit(1) + ExtensionsPluginStatusLine( + status: ExtensionsPluginStatus( + phase: install?.phase, + isStaged: row.isStaged, + isBuiltIn: row.isBuiltIn, + version: row.version + ) + ) + } } - case .failed(let reason): - installFailure(install, reason: reason) } - } - - // MARK: - Detail Pane - - private var selectedPlugin: PluginEntry? { - guard case .plugin(let id) = selection else { return nil } - return pluginManager.plugins.first { $0.id == id } - } - - private var selectedRejected: RejectedPlugin? { - guard case .rejected(let url) = selection else { return nil } - return pluginManager.rejectedPlugins.first { $0.url == url } + .contextMenu { menu(install) } + .modifier(ExtensionsOptionalAction(name: row.isBuiltIn ? nil : String(localized: "Uninstall")) { + model.uninstall(row, context: context) + }) + .modifier(ExtensionsOptionalAction(name: row.isBuiltIn ? nil : String(localized: "Show in Finder")) { + model.showInFinder(row.url) + }) + .accessibilityIdentifier("extensions-plugin-row-\(row.id)") } @ViewBuilder - private var detailPane: some View { - if let rejected = selectedRejected { - rejectedDetail(rejected) - } else if let selected = selectedPlugin { - ScrollView { - VStack(alignment: .leading, spacing: 16) { - Text(selected.name) - .font(.title3.weight(.semibold)) - - Text("v\(selected.version), \(selected.source == .builtIn ? String(localized: "Built-in") : String(localized: "User-installed"))") - .font(.subheadline) - .foregroundStyle(.secondary) - - if !selected.pluginDescription.isEmpty { - Text(selected.pluginDescription) - .font(.callout) - .foregroundStyle(.secondary) - } - - Divider() - - Grid(alignment: .leading, horizontalSpacing: 16, verticalSpacing: 10) { - GridRow { - Text("Bundle ID") - .foregroundStyle(.secondary) - .gridColumnAlignment(.leading) - Text(selected.id) - .textSelection(.enabled) - .gridColumnAlignment(.leading) - } - - if !selected.capabilities.isEmpty { - GridRow { - Text("Capabilities") - .foregroundStyle(.secondary) - Text(selected.capabilities.map(\.displayName).joined(separator: ", ")) - } - } - - if let typeId = selected.databaseTypeId { - GridRow { - Text("Database Type") - .foregroundStyle(.secondary) - Text(typeId) - } - - if !selected.additionalTypeIds.isEmpty { - GridRow { - Text("Also handles") - .foregroundStyle(.secondary) - Text(selected.additionalTypeIds.joined(separator: ", ")) - } - } - - if let port = selected.defaultPort { - GridRow { - Text("Default Port") - .foregroundStyle(.secondary) - Text(verbatim: "\(port)") - } - } - } - } - .font(.callout) - - if let settable = pluginManager.pluginInstances[selected.id] as? any SettablePluginDiscoverable, - let pluginSettings = settable.settingsView() { - Divider() - pluginSettings - } - - if selected.source == .userInstalled { - Divider() - Button("Uninstall", role: .destructive) { - uninstallPlugin(selected) - } + private func menu(_ install: PluginInstallTracker.Entry?) -> some View { + if let install { + switch install.phase { + case .downloading, .installing: + Button(String(localized: "Cancel Update")) { + tracker.cancel(pluginId: row.id) + } + .disabled(install.phase == .installing) + case .failed: + if install.retry != nil { + Button(String(localized: "Try Again")) { + model.retryInstall(install, context: context) } } - .padding(20) - .frame(maxWidth: .infinity, alignment: .leading) - } - } else { - VStack(spacing: 8) { - Image(systemName: "puzzlepiece.extension") - .font(.title) - .foregroundStyle(.tertiary) - Text("Select a plugin to view details") - .font(.headline) - .foregroundStyle(.secondary) + Button(String(localized: "Dismiss")) { + tracker.cancel(pluginId: row.id) + } + case .completed: + EmptyView() } - .frame(maxWidth: .infinity, maxHeight: .infinity) - } - } - - // A failure shows on the plugin's row or in the list's bottom bar, from the tracker. - private func updatePlugin(_ registryPlugin: RegistryPlugin) { - Task { - _ = await pluginManager.performRegistryUpdate(registryPlugin) } - } - - private func retryInstall(_ install: PluginInstallTracker.Entry) { - switch install.retry { - case .registry(let registryPlugin): - updatePlugin(registryPlugin) - case .file(let url): - installPlugin(from: url) - case nil: - break + if !row.isBuiltIn { + if install.map({ $0.phase != .completed }) == true { + Divider() + } + Button(String(localized: "Uninstall…")) { + model.uninstall(row, context: context) + } + Button(String(localized: "Show in Finder")) { + model.showInFinder(row.url) + } } } +} - // MARK: - Actions - - private func revealRequestedPlugin() { - guard let request = navigation.consumePendingRequest(), - let target = PluginListSelection.revealTarget( - pluginId: request.pluginId, - loadedIds: pluginManager.plugins.map(\.id), - rejected: pluginManager.rejectedPlugins - ) else { return } - searchText = "" - selection = target - } - - private func installFromFile() { - let panel = NSOpenPanel() - panel.title = String(localized: "Select Plugin") - panel.allowedContentTypes = [.zip] + (UTType("com.tablepro.plugin").map { [$0] } ?? []) - panel.allowsMultipleSelection = false - panel.canChooseDirectories = false - panel.treatsFilePackagesAsDirectories = false - - guard let window = NSApp.keyWindow else { return } - panel.beginSheetModal(for: window) { response in - guard response == .OK, let url = panel.url else { return } - self.installPlugin(from: url) - } - } +struct ExtensionsPluginStatusLine: View { + let status: ExtensionsPluginStatus - // A failure shows in the list's bottom bar, from the tracker. - private func installPlugin(from url: URL) { - Task { - guard let entry = try? await pluginManager.installPlugin(from: url) else { return } - selection = .plugin(entry.id) + var body: some View { + Group { + if status == .failed { + NoticeLabel(status.text, severity: .warning) + } else { + Text(verbatim: status.text) + .foregroundStyle(.secondary) + } } + .font(.subheadline) + .lineLimit(1) } +} - private func uninstallPlugin(_ plugin: PluginEntry) { - Task { - let confirmed = await AlertHelper.confirmDestructive( - title: String(localized: "Uninstall Plugin?"), - message: String(format: String(localized: "\"%@\" will be removed from your system. This action cannot be undone."), plugin.name), - confirmButton: String(localized: "Uninstall"), - cancelButton: String(localized: "Cancel") - ) - - guard confirmed else { return } +struct ExtensionsInstallProgress: View { + let phase: PluginInstallTracker.Phase - do { - try await pluginManager.uninstallPlugin(id: plugin.id) - selection = nil - } catch { - errorAlertTitle = String(localized: "Uninstall Failed") - errorAlertMessage = error.localizedDescription - showErrorAlert = true - } + var body: some View { + if case .downloading(let fraction?) = phase { + ProgressView(value: fraction) + .controlSize(.small) + } else { + ProgressView() + .progressViewStyle(.linear) + .controlSize(.small) } } } -// MARK: - PluginCapability Display Names +// VoiceOver gets every row action the context menu offers. +struct ExtensionsOptionalAction: ViewModifier { + let name: String? + let action: () -> Void -private extension PluginCapability { - var displayName: String { - switch self { - case .databaseDriver: String(localized: "Database Driver") - case .exportFormat: String(localized: "Export Format") - case .importFormat: String(localized: "Import Format") - case .documentInspector: String(localized: "Document Inspector") - @unknown default: String(localized: "Unknown") + @ViewBuilder + func body(content: Content) -> some View { + if let name { + content.accessibilityAction(named: Text(verbatim: name), action) + } else { + content } } } - -#Preview { - InstalledPluginsView() - .frame(width: 650, height: 500) -} diff --git a/apple/TablePro/Views/Settings/Plugins/ModuleToggleRow.swift b/apple/TablePro/Views/Settings/Plugins/ModuleToggleRow.swift index eb94ca5d06..e4275ee2fd 100644 --- a/apple/TablePro/Views/Settings/Plugins/ModuleToggleRow.swift +++ b/apple/TablePro/Views/Settings/Plugins/ModuleToggleRow.swift @@ -1,33 +1,23 @@ import SwiftUI -// A checkbox per module, the way Safari lists its extensions; this click is the only way a module turns on. +// This switch is the only way a module turns on (apple/AGENTS.md, Scope), and only module rows observe the settings. struct ModuleToggleRow: View { let module: AppModule - @ObservedObject var settings: AppModuleSettings + @ObservedObject private var settings: AppModuleSettings + + init(module: AppModule, settings: AppModuleSettings = .shared) { + self.module = module + self.settings = settings + } var body: some View { Toggle(isOn: Binding( get: { settings.isEnabled(module) }, set: { AppModuleActivation.setEnabled($0, for: module, settings: settings) } )) { - VStack(alignment: .leading, spacing: 2) { - Text(module.title) - Text(module.summary) - .font(.caption) - .foregroundStyle(.secondary) - .fixedSize(horizontal: false, vertical: true) - } + Text(verbatim: module.title) + Text(verbatim: module.summary) } - .toggleStyle(.checkbox) - .padding(.vertical, 2) .accessibilityIdentifier("module-toggle-\(module.rawValue)") } } - -extension AppModule { - func matches(filter: String) -> Bool { - filter.isEmpty - || title.localizedCaseInsensitiveContains(filter) - || summary.localizedCaseInsensitiveContains(filter) - } -} diff --git a/apple/TablePro/Views/Settings/Plugins/PluginDetailPage.swift b/apple/TablePro/Views/Settings/Plugins/PluginDetailPage.swift new file mode 100644 index 0000000000..d826e546ac --- /dev/null +++ b/apple/TablePro/Views/Settings/Plugins/PluginDetailPage.swift @@ -0,0 +1,211 @@ +import SwiftUI +import TableProPluginKit + +struct PluginDetailPage: View { + let entry: PluginEntry + let isStaged: Bool + let context: SettingsPaneContext + @EnvironmentObject private var model: ExtensionsPaneModel + @State private var loaded: PluginLoadedInstance? + + var body: some View { + Form { + Section { + PluginHeaderCard(iconName: entry.pluginIconName, name: entry.name, detail: headerDetail) + } + + PluginStatusSection( + trackerId: entry.id, + displayName: entry.name, + isStaged: isStaged, + route: .plugin(id: entry.id), + context: context, + tracker: model.manager.installTracker + ) + + Section(String(localized: "Details")) { + LabeledContent(String(localized: "Version"), value: entry.version) + LabeledContent( + String(localized: "Source"), + value: entry.source == .builtIn ? String(localized: "Built-in") : String(localized: "User-installed") + ) + if !entry.capabilities.isEmpty { + LabeledContent(String(localized: "Capabilities"), value: capabilityNames) + } + if let typeId = entry.databaseTypeId { + LabeledContent(String(localized: "Database type"), value: typeId) + if !entry.additionalTypeIds.isEmpty { + LabeledContent(String(localized: "Also handles"), value: entry.additionalTypeIds.joined(separator: ", ")) + } + if let port = entry.defaultPort { + LabeledContent(String(localized: "Default port"), value: String(port)) + } + } + LabeledContent(String(localized: "Bundle ID")) { + Text(verbatim: entry.id) + .textSelection(.enabled) + } + } + + if let loaded, let settable = loaded.settable, let options = settable.settingsView() { + Section(optionsTitle) { + options + .frame(maxWidth: .infinity, alignment: .leading) + } + } + + if entry.source == .userInstalled { + Section { + LabeledContent { + Button(String(localized: "Uninstall…"), role: .destructive) { + model.uninstall(id: entry.id, name: entry.name, isDriver: entry.databaseTypeId != nil, context: context) + } + .accessibilityLabel(String(format: String(localized: "Uninstall %@"), entry.name)) + .accessibilityIdentifier("extensions-plugin-uninstall") + } label: { + Text("Uninstall this plugin") + Text("The plugin moves to the Trash and its settings are deleted.") + } + } + } + } + .formStyle(.grouped) + .accessibilityElement(children: .contain) + .accessibilityIdentifier("settings-page-plugin") + .task(id: entry.id) { + loaded = await PluginLoadedInstance.load(entry, manager: model.manager) + } + } + + private var capabilityNames: String { + entry.capabilities.map(\.settingsDisplayName).joined(separator: ", ") + } + + private var headerDetail: String { + let description = loaded?.description ?? entry.pluginDescription + return description.isEmpty ? capabilityNames : description + } + + private var optionsTitle: String { + if entry.exportFormatId != nil { return String(localized: "Export Options") } + if entry.importFormatId != nil { return String(localized: "Import Options") } + return String(localized: "Options") + } +} + +// A format's code loads off the main actor first, so opening its page never holds the window on a signature check. +struct PluginLoadedInstance { + let description: String + let settable: (any SettablePluginDiscoverable)? + + @MainActor + static func load(_ entry: PluginEntry, manager: PluginManager) async -> PluginLoadedInstance? { + if let formatId = entry.exportFormatId { + await manager.loadLazyExportExecutable(formatId: formatId) + _ = manager.exportPlugin(forFormat: formatId) + } else if let formatId = entry.importFormatId { + await manager.loadLazyImportExecutable(formatId: formatId) + _ = manager.importPlugin(forFormat: formatId) + } + // A driver's code is never loaded just to show its page. + guard let instance = manager.pluginInstances[entry.id] else { return nil } + return PluginLoadedInstance( + description: type(of: instance).pluginDescription, + settable: instance as? any SettablePluginDiscoverable + ) + } +} + +struct PluginHeaderCard: View { + let iconName: String + let name: String + let detail: String + + var body: some View { + HStack(spacing: 12) { + PluginIconView(name: iconName, size: 32) + .foregroundStyle(.secondary) + VStack(alignment: .leading, spacing: 2) { + Text(verbatim: name) + .font(.headline) + if !detail.isEmpty { + Text(verbatim: detail) + .font(.subheadline) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + } + } + Spacer(minLength: 0) + } + .accessibilityElement(children: .combine) + } +} + +// Shown only while the tracker has this plugin or an update waits for a relaunch. +struct PluginStatusSection: View { + let trackerId: String? + let displayName: String + let isStaged: Bool + let route: SettingsRoute + let context: SettingsPaneContext + @ObservedObject var tracker: PluginInstallTracker + @EnvironmentObject private var model: ExtensionsPaneModel + + var body: some View { + let install = trackerId.flatMap { tracker.entries[$0] } + if let status = ExtensionsPageStatus(phase: install?.phase, isStaged: isStaged) { + Section { + switch status { + case .running(let phase): + LabeledContent { + Button(String(localized: "Cancel")) { + if let trackerId { tracker.cancel(pluginId: trackerId) } + } + .disabled(phase == .installing) + .accessibilityLabel(String(format: String(localized: "Cancel installing %@"), displayName)) + } label: { + Text(verbatim: ExtensionsPluginStatus(phase: phase, isStaged: false, isBuiltIn: false, version: "").text) + ExtensionsInstallProgress(phase: phase) + .accessibilityLabel(Text(verbatim: String(format: String(localized: "Installing %@…"), displayName))) + } + case .failed(let reason): + LabeledContent { + HStack(spacing: 8) { + if let install, install.retry != nil { + Button(String(localized: "Try Again")) { + model.retryInstall(install, context: context, replacing: route) + } + .accessibilityLabel(String(format: String(localized: "Try installing %@ again"), displayName)) + } + Button(String(localized: "Dismiss")) { + if let trackerId { tracker.cancel(pluginId: trackerId) } + } + } + } label: { + NoticeLabel(reason, severity: .error) + } + case .staged: + LabeledContent { + Button(String(localized: "Relaunch")) { + UpdateCenter.shared.relaunch() + } + } label: { + Text("Updates when TablePro relaunches") + } + } + } + } + } +} + +extension PluginCapability { + var settingsDisplayName: String { + switch self { + case .databaseDriver: String(localized: "Database Driver") + case .exportFormat: String(localized: "Export Format") + case .importFormat: String(localized: "Import Format") + case .documentInspector: String(localized: "Document Inspector") + @unknown default: String(localized: "Unknown") + } + } +} diff --git a/apple/TablePro/Views/Settings/Plugins/PluginIconView.swift b/apple/TablePro/Views/Settings/Plugins/PluginIconView.swift index a56b020fa2..91685ceccd 100644 --- a/apple/TablePro/Views/Settings/Plugins/PluginIconView.swift +++ b/apple/TablePro/Views/Settings/Plugins/PluginIconView.swift @@ -1,21 +1,39 @@ -// -// PluginIconView.swift -// TablePro - import AppKit import SwiftUI struct PluginIconView: View { let name: String + var size: CGFloat = 20 var body: some View { - if NSImage(systemSymbolName: name, accessibilityDescription: nil) != nil { + icon + .frame(width: size + 4, height: size + 4) + .accessibilityHidden(true) + } + + @ViewBuilder private var icon: some View { + if PluginIconKind.isSymbol(name) { Image(systemName: name) + .font(.system(size: size * 0.8)) } else { Image(name) .renderingMode(.template) .resizable() .scaledToFit() + .frame(width: size, height: size) } } } + +// A symbol lookup costs tens of microseconds, and every row asks on each render. +@MainActor +private enum PluginIconKind { + private static var symbols: [String: Bool] = [:] + + static func isSymbol(_ name: String) -> Bool { + if let known = symbols[name] { return known } + let isSymbol = NSImage(systemSymbolName: name, accessibilityDescription: nil) != nil + symbols[name] = isSymbol + return isSymbol + } +} diff --git a/apple/TablePro/Views/Settings/Plugins/PluginListSelection.swift b/apple/TablePro/Views/Settings/Plugins/PluginListSelection.swift index 56ca05867d..7d8984ebef 100644 --- a/apple/TablePro/Views/Settings/Plugins/PluginListSelection.swift +++ b/apple/TablePro/Views/Settings/Plugins/PluginListSelection.swift @@ -1,8 +1,3 @@ -// -// PluginListSelection.swift -// TablePro -// - import Foundation // A rejected bundle can carry the id of a loaded plugin, so rejected rows are told apart by URL. @@ -27,6 +22,13 @@ internal enum PluginListSelection: Hashable { let first = rejected.first(where: \.isOutdated) ?? rejected.first return first.map { .rejected($0.url) } } + + internal var route: SettingsRoute { + switch self { + case .plugin(let id): .plugin(id: id) + case .rejected(let url): .rejectedPlugin(url) + } + } } internal struct RejectedPluginStatus: Equatable { diff --git a/apple/TablePro/Views/Settings/Plugins/PluginsSettingsNavigation.swift b/apple/TablePro/Views/Settings/Plugins/PluginsSettingsNavigation.swift deleted file mode 100644 index 1d9bf2a889..0000000000 --- a/apple/TablePro/Views/Settings/Plugins/PluginsSettingsNavigation.swift +++ /dev/null @@ -1,31 +0,0 @@ -// -// PluginsSettingsNavigation.swift -// TablePro -// - -import Combine -import Foundation - -@MainActor -internal final class PluginsSettingsNavigation: ObservableObject { - internal struct Request: Equatable { - let id: UUID - let pluginId: String? - } - - internal static let shared = PluginsSettingsNavigation() - - @Published internal private(set) var pendingRequest: Request? - - internal init() {} - - internal func reveal(pluginId: String?) { - pendingRequest = Request(id: UUID(), pluginId: pluginId) - } - - internal func consumePendingRequest() -> Request? { - let request = pendingRequest - pendingRequest = nil - return request - } -} diff --git a/apple/TablePro/Views/Settings/Plugins/RejectedPluginDetailPage.swift b/apple/TablePro/Views/Settings/Plugins/RejectedPluginDetailPage.swift new file mode 100644 index 0000000000..3cce81bf9c --- /dev/null +++ b/apple/TablePro/Views/Settings/Plugins/RejectedPluginDetailPage.swift @@ -0,0 +1,129 @@ +import AppKit +import SwiftUI + +struct RejectedPluginDetailPage: View { + let row: ExtensionsRejectedRow + let context: SettingsPaneContext + @ObservedObject var tracker: PluginInstallTracker + @ObservedObject private var updates = UpdateCenter.shared + @EnvironmentObject private var model: ExtensionsPaneModel + + var body: some View { + Form { + Section { + PluginHeaderCard(iconName: row.iconName, name: row.name, detail: caption) + } + + Section { + LabeledContent { + actionControl + } label: { + NoticeLabel(row.reason, severity: row.severity) + } + if model.retryFailures.contains(row.url) { + NoticeLabel( + String(localized: "TablePro couldn't reach the plugin registry to update this plugin. Check your connection and try again."), + severity: .warning + ) + } + } + + PluginStatusSection( + trackerId: row.trackerId, + displayName: row.name, + isStaged: false, + route: .rejectedPlugin(row.url), + context: context, + tracker: tracker + ) + + Section(String(localized: "Details")) { + if let bundleId = row.bundleId { + LabeledContent(String(localized: "Bundle ID")) { + Text(verbatim: bundleId) + .textSelection(.enabled) + } + } + LabeledContent { + Button { + model.showInFinder(row.url) + } label: { + Image(systemName: "arrow.forward") + } + .buttonStyle(.borderless) + .help(String(localized: "Show in Finder")) + .accessibilityLabel(String(localized: "Show in Finder")) + } label: { + Text("Location") + Text(verbatim: location) + .lineLimit(1) + .truncationMode(.middle) + .help(location) + } + } + + if row.canRemove { + Section { + LabeledContent { + Button(String(localized: "Move to Trash…")) { + model.moveToTrash(row.url, context: context) + } + .accessibilityLabel(String(format: String(localized: "Move %@ to the Trash"), row.name)) + } label: { + Text("Remove this plugin") + Text("You can put it back from the Trash.") + } + } + } + } + .formStyle(.grouped) + .accessibilityElement(children: .contain) + .accessibilityIdentifier("settings-page-rejected-plugin") + } + + private var location: String { + (row.url.path as NSString).abbreviatingWithTildeInPath + } + + private var isOwnInstallRunning: Bool { + row.trackerId.flatMap { tracker.entries[$0]?.phase.isRunning } ?? false + } + + private var caption: String { + switch row.trackerId.flatMap({ tracker.entries[$0]?.phase }) { + case .downloading?: String(localized: "Downloading update…") + case .installing?: String(localized: "Installing update…") + default: row.caption + } + } + + @ViewBuilder private var actionControl: some View { + switch row.action { + case .update(let registryId): + Button(String(localized: "Update Now")) { + guard let registryPlugin = model.registryPlugin(id: registryId) else { return } + model.update(registryPlugin, context: context, replacing: .rejectedPlugin(row.url)) + } + .disabled(isOwnInstallRunning) + .accessibilityLabel(String(format: String(localized: "Update %@"), row.name)) + case .appUpdate: + Button(updates.status.appUpdateTitle) { + updates.performAppUpdateAction() + } + .disabled(!updates.isAppUpdateActionEnabled) + .help(String(localized: "A newer TablePro is required to load this plugin.")) + case .retry: + if model.retrying.contains(row.url) { + ProgressView() + .controlSize(.small) + .accessibilityLabel(String(localized: "Checking for a compatible build")) + } else { + Button(String(localized: "Try Again")) { + model.retryRejected(row.url) + } + } + case .noAction: + EmptyView() + } + } +} diff --git a/apple/TablePro/Views/Settings/Profiles/ConnectionCountCopy.swift b/apple/TablePro/Views/Settings/Profiles/ConnectionCountCopy.swift new file mode 100644 index 0000000000..5057652cff --- /dev/null +++ b/apple/TablePro/Views/Settings/Profiles/ConnectionCountCopy.swift @@ -0,0 +1,131 @@ +import SwiftUI + +enum ProfileKind: Hashable, Sendable { + case credential + case ssh + + func isLinked(_ connection: DatabaseConnection, to profileId: UUID) -> Bool { + switch self { + case .credential: connection.credentialMode == .profile(id: profileId) + case .ssh: connection.isLinked(toSSHProfile: profileId) + } + } +} + +struct PendingProfileDeletion: Identifiable, Equatable, Sendable { + let kind: ProfileKind + let id: UUID + let name: String + let dependentCount: Int + let someConnectionsUnreadable: Bool + + // Nil while the connections can't be read: the count, and so the consequences, are unknown. + @MainActor + static func make( + kind: ProfileKind, + id: UUID, + name: String, + connectionStorage: ConnectionStorage = .shared + ) -> PendingProfileDeletion? { + let connections = connectionStorage.loadConnections() + guard !connectionStorage.lastLoadFailed else { return nil } + return PendingProfileDeletion( + kind: kind, + id: id, + name: name, + dependentCount: connections.filter { kind.isLinked($0, to: id) }.count, + someConnectionsUnreadable: !connectionStorage.unreadableConnectionIds.isEmpty + ) + } + + var title: String { + String(format: String(localized: "Delete “%@”?"), name) + } + + var message: String { + let consequence = ConnectionCountCopy.deletionConsequence(kind: kind, dependentCount: dependentCount) + guard someConnectionsUnreadable else { return consequence } + let unknown = String(localized: "TablePro can't read some saved connections, so it can't tell whether they use this profile.") + return "\(consequence) \(unknown)" + } +} + +enum ConnectionCountCopy { + static func usage(_ count: Int) -> String { + switch count { + case 0: String(localized: "Not used") + case 1: String(format: String(localized: "%lld connection"), Int64(count)) + default: String(format: String(localized: "%lld connections"), Int64(count)) + } + } + + static func deletionConsequence(kind: ProfileKind, dependentCount: Int) -> String { + switch (kind, dependentCount) { + case (_, 0): + String(localized: "This profile will be permanently deleted.") + case (.credential, 1): + String(localized: "1 connection uses this profile. It keeps these credentials as its own.") + case (.credential, _): + String( + format: String(localized: "%lld connections use this profile. They keep these credentials as their own."), + Int64(dependentCount) + ) + case (.ssh, 1): + String(localized: "1 connection uses this profile. It keeps this configuration as its own SSH tunnel.") + case (.ssh, _): + String( + format: String(localized: "%lld connections use this profile. They keep this configuration as their own SSH tunnel."), + Int64(dependentCount) + ) + } + } + + static func unreadableProfiles(_ count: Int) -> String { + switch count { + case 1: + String(localized: "1 profile was saved by a newer version of TablePro and can't be shown here.") + default: + String( + format: String(localized: "%lld profiles were saved by a newer version of TablePro and can't be shown here."), + Int64(count) + ) + } + } + + static var deleteFailedTitle: String { + String(localized: "Couldn't Delete Profile") + } + + static var deleteFailedMessage: String { + String(localized: "Its saved secrets or the connections that use it couldn't be updated, so nothing was deleted.") + } + + static var duplicateFailedTitle: String { + String(localized: "Couldn't Duplicate Profile") + } + + static var duplicateFailedMessage: String { + String(localized: "Its saved secrets couldn't be read or copied, so no copy was made.") + } +} + +extension View { + func profileDeletionAlert( + _ pending: Binding, + onDelete: @escaping (PendingProfileDeletion) -> Void + ) -> some View { + alert( + pending.wrappedValue?.title ?? "", + isPresented: Binding( + get: { pending.wrappedValue != nil }, + set: { if !$0 { pending.wrappedValue = nil } } + ), + presenting: pending.wrappedValue + ) { item in + Button(String(localized: "Delete"), role: .destructive) { onDelete(item) } + Button(String(localized: "Cancel"), role: .cancel) {} + } message: { item in + Text(verbatim: item.message) + } + } +} diff --git a/apple/TablePro/Views/Settings/Profiles/CredentialProfileEditorSheet.swift b/apple/TablePro/Views/Settings/Profiles/CredentialProfileEditorSheet.swift index a7b87f66f0..2ea6e2c09a 100644 --- a/apple/TablePro/Views/Settings/Profiles/CredentialProfileEditorSheet.swift +++ b/apple/TablePro/Views/Settings/Profiles/CredentialProfileEditorSheet.swift @@ -1,266 +1,349 @@ -// -// CredentialProfileEditorSheet.swift -// TablePro -// - import SwiftUI import TableProPluginKit -/// One credential profile: the name every connection picks it by, the username, and where the -/// password comes from. +struct CredentialProfileDraft: Equatable { + var name = "" + var username = "" + var passwordKind: CredentialPasswordKind = .stored + var password = "" + var sourceKind: PasswordSourceKind = .file + var sourceValue = "" + var sourceField = "" + var commandReuseSeconds: Int? + var vaultAccess = VaultAccessDraft() + var secureFieldValues: [String: String] = [:] + var takenNames: [String] = [] + + var trimmedName: String { + name.trimmingCharacters(in: .whitespaces) + } + + var trimmedUsername: String { + username.trimmingCharacters(in: .whitespaces) + } + + // Two profiles with one name are indistinguishable in every picker that offers them. + var nameIsTaken: Bool { + !trimmedName.isEmpty && takenNames.contains { ProfileNames.matches($0, trimmedName) } + } + + var usernameComesFromSource: Bool { + passwordKind == .source && sourceKind.suppliesUsername + } + + var testedSource: PasswordSource? { + guard !sourceValue.trimmingCharacters(in: .whitespaces).isEmpty else { return nil } + if sourceKind == .vaultDatabaseRole { + guard !sourceField.trimmingCharacters(in: .whitespaces).isEmpty, vaultAccess.isComplete else { return nil } + } + return sourceKind.source(value: sourceValue, field: sourceField, reuseSeconds: nil, vaultAccess: vaultAccess) + } + + var passwordMode: CredentialPasswordMode { + switch passwordKind { + case .stored: .stored + case .prompt: .prompt + case .pgpass: .pgpass + case .source: + .source(sourceKind.source( + value: sourceValue, + field: sourceField, + reuseSeconds: commandReuseSeconds, + vaultAccess: vaultAccess + )) + } + } + + var validationIssues: [String] { + var issues: [String] = [] + if trimmedName.isEmpty { + issues.append(String(localized: "A profile needs a name.")) + } else if nameIsTaken { + issues.append(String(localized: "Another profile already has this name.")) + } + if passwordKind == .source, testedSource == nil { + issues.append(String(localized: "Enter where the password is read from.")) + } + return issues + } + + mutating func apply(_ mode: CredentialPasswordMode) { + passwordKind = mode.kind + guard case .source(let source) = mode else { return } + (sourceKind, sourceValue, sourceField) = PasswordSourceKind.decompose(source) + if case .command(_, let reuseSeconds) = source { + commandReuseSeconds = reuseSeconds + } + if let role = source.vaultDatabaseRole { + vaultAccess = VaultAccessDraft(role) + } + } +} + struct CredentialProfileEditorSheet: View { @Environment(\.dismiss) private var dismiss let existingProfile: CredentialProfile? var initialPassword: String? - /// Which engine's secrets to offer first, so a profile promoted from a Postgres connection - /// does not open on MySQL's fields. + // A profile promoted from a Postgres connection opens on Postgres's secrets, not MySQL's. var initialDatabaseType: DatabaseType? var onSave: ((CredentialProfile) -> Void)? var onDelete: (() -> Void)? - @State private var name: String = "" - @State private var username: String = "" - @State private var passwordKind: PasswordKind = .stored - @State private var password: String = "" - @State private var passwordWasPrefilled = false - @State private var sourceKind: PasswordSourceKind = .file - @State private var sourceValue: String = "" - @State private var sourceField: String = "" - @State private var commandReuseSeconds: Int? - @State private var vaultAccess = VaultAccessDraft() + @State private var draft = CredentialProfileDraft() + @State private var baseline = CredentialProfileDraft() + @State private var hasLoaded = false + @State private var isStored = false // A new profile keeps this id when saved, so its first connect signs in as the user Test Source leased. @State private var draftProfileId = UUID() + @State private var storedPasswordMode: CredentialPasswordMode? + @State private var passwordRead: ProfileSecretRead = .absent + @State private var fieldReads: [String: ProfileSecretRead] = [:] + @State private var passwordWasPrefilled = false + @State private var usageUnknown = false + @State private var vaultAddressPrompt = "https://vault.example.com:8200" + @State private var secureFieldTypes: [DatabaseType] = [] + @State private var secureFieldsByType: [DatabaseType: [ConnectionField]] = [:] @State private var secureFieldType: DatabaseType = .mysql - @State private var secureFieldValues: [String: String] = [:] - @State private var showingDeleteConfirmation = false - @State private var dependentCount = 0 + @State private var pendingDeletion: PendingProfileDeletion? @State private var saveError: String? - /// Read once when the sheet opens. `body` reads `nameIsUnique` and `isStored` several times per - /// pass, and each one used to decode the whole profiles file off disk, on every keystroke. - @State private var otherProfileNames: [String] = [] - @State private var isStored = false - @State private var secureFields: [ConnectionField] = [] - /// False when a keychain read failed rather than finding nothing. Saving then must not - /// treat an empty field as the user clearing a secret: a rename while the keychain was - /// locked would delete the password of every connection on the profile. - @State private var secretsWereReadable = true - private var storage: CredentialProfileStorage { .shared } - private var trimmedName: String { name.trimmingCharacters(in: .whitespaces) } - - private var isValid: Bool { - guard !trimmedName.isEmpty else { return false } - guard nameIsUnique else { return false } - if passwordKind == .source { - return testedSource != nil - } - return true - } - - private var usernameComesFromSource: Bool { - passwordKind == .source && sourceKind.suppliesUsername + private var profileId: UUID { + existingProfile?.id ?? draftProfileId } - /// Two profiles with one name are indistinguishable in every picker that offers them, which is - /// the reason the system's own profile editors refuse it. - private var nameIsUnique: Bool { - !otherProfileNames.contains { - $0.compare(trimmedName, options: [.caseInsensitive, .diacriticInsensitive]) == .orderedSame - } + // A rename while the Keychain was locked must not read an empty field as the user clearing a secret. + private var secretsWereReadable: Bool { + passwordRead != .unreadable && !fieldReads.values.contains(.unreadable) } var body: some View { VStack(spacing: 0) { Form { - Section(String(localized: "Profile")) { - TextField(String(localized: "Name"), text: $name, prompt: Text("Production reader")) - .accessibilityIdentifier("credential-profile-name") - if !trimmedName.isEmpty && !nameIsUnique { - NoticeLabel(String(localized: "Another profile already has this name.")) - .font(.caption) - } - TextField( - String(localized: "Username"), - text: $username, - prompt: usernameComesFromSource ? Text("Generated by Vault") : Text("app_reader") - ) - .disabled(usernameComesFromSource) - .accessibilityIdentifier("credential-profile-username") - } - + profileSection if !secretsWereReadable { Section { NoticeLabel( String(localized: "The Keychain could not be read, so the stored secrets are not shown. Editing the name is safe; they are left as they are.") ) - .font(.caption) } } passwordSection - secureFieldsSection + if !secureFieldTypes.isEmpty { + secureFieldsSection + } } .formStyle(.grouped) Divider() bottomBar } - .frame(minWidth: 480, minHeight: 420, idealHeight: 460) + .frame(minWidth: 520, idealWidth: 520, minHeight: 440, idealHeight: 560) .onAppear(perform: load) } - // MARK: - Password + private var profileSection: some View { + Section(String(localized: "Profile")) { + TextField(text: $draft.name, prompt: Text("Production reader")) { + Text("Name") + if draft.nameIsTaken { + NoticeLabel(String(localized: "Another profile already has this name.")) + } + } + .accessibilityIdentifier("credential-profile-name") + TextField( + String(localized: "Username"), + text: $draft.username, + prompt: draft.usernameComesFromSource ? Text("Generated by Vault") : Text(verbatim: "app_reader") + ) + .disabled(draft.usernameComesFromSource) + .accessibilityIdentifier("credential-profile-username") + } + } - @ViewBuilder private var passwordSection: some View { Section(String(localized: "Password")) { - Picker(String(localized: "Source"), selection: $passwordKind) { - ForEach(PasswordKind.allCases) { kind in + Picker(selection: $draft.passwordKind) { + ForEach(CredentialPasswordKind.allCases) { kind in Text(kind.displayName).tag(kind) } + } label: { + Text("Source") + Text(passwordKindHelp) } .accessibilityIdentifier("credential-profile-password-kind") - switch passwordKind { + switch draft.passwordKind { case .stored: RevealablePasswordField( title: String(localized: "Password"), - text: $password, + text: $draft.password, requiresAuthentication: passwordWasPrefilled ) - case .prompt: - Text("Every connection using this profile asks for the password once each time TablePro runs.") - .font(.caption) - .foregroundStyle(.secondary) - case .pgpass: - Text("Looked up in ~/.pgpass by the host, port, database and username of the PostgreSQL-family connection that is opening. Other connections ask for the password.") - .font(.caption) - .foregroundStyle(.secondary) + case .prompt, .pgpass: + EmptyView() case .source: - Picker(String(localized: "Read From"), selection: $sourceKind) { - ForEach(PasswordSourceKind.allCases) { kind in - Text(kind.displayName).tag(kind) - } - } - TextField(sourceKind.valueLabel, text: $sourceValue, prompt: Text(sourceKind.placeholder)) - if let fieldLabel = sourceKind.fieldLabel { - TextField(fieldLabel, text: $sourceField, prompt: Text(sourceKind.fieldPlaceholder)) - } - if sourceKind == .vaultDatabaseRole { - vaultAccessRows - } - if sourceKind == .command { - Picker(String(localized: "Reuse Result For"), selection: $commandReuseSeconds) { - Text("Never").tag(Int?.none) - ForEach(Self.reuseChoices(including: commandReuseSeconds), id: \.self) { seconds in - Text(Self.reuseLabel(seconds)).tag(Int?.some(seconds)) - } - } - .accessibilityIdentifier("credential-profile-command-reuse") - Text(String(localized: """ - {host}, {port}, {user} and {database} become the opening connection's values, \ - already quoted. The command also gets them as TABLEPRO_HOST, TABLEPRO_PORT, \ - TABLEPRO_USER and TABLEPRO_DATABASE. - """)) - .font(.caption) - .foregroundStyle(.secondary) + sourceRows + } + } + } + + private var passwordKindHelp: String { + switch draft.passwordKind { + case .source where draft.sourceKind == .vaultDatabaseRole: + String(localized: "It stays on this Mac and never syncs, because it names where your Vault token is sent.") + default: + draft.passwordKind.help + } + } + + @ViewBuilder private var sourceRows: some View { + Picker(selection: $draft.sourceKind) { + ForEach(PasswordSourceKind.allCases) { kind in + Text(kind.displayName).tag(kind) + } + } label: { + Text("Read From") + if draft.sourceKind == .vaultDatabaseRole { + Text(String(localized: """ + Connections on this profile share one database user. TablePro renews its lease while in use, revokes it \ + once the last connection disconnects or after 10 minutes unused, and never saves the generated password. + """)) + } + } + TextField(text: $draft.sourceValue, prompt: Text(verbatim: draft.sourceKind.placeholder)) { + Text(verbatim: draft.sourceKind.valueLabel) + if draft.sourceKind == .command { + Text(String(localized: """ + {host}, {port}, {user} and {database} become the opening connection's values, \ + already quoted. The command also gets them as TABLEPRO_HOST, TABLEPRO_PORT, \ + TABLEPRO_USER and TABLEPRO_DATABASE. + """)) + } + } + if let fieldLabel = draft.sourceKind.fieldLabel { + TextField(fieldLabel, text: $draft.sourceField, prompt: Text(verbatim: draft.sourceKind.fieldPlaceholder)) + } + if draft.sourceKind == .vaultDatabaseRole { + vaultAccessRows + } + if draft.sourceKind == .command { + Picker(String(localized: "Reuse Result For"), selection: $draft.commandReuseSeconds) { + Text("Never").tag(Int?.none) + ForEach(Self.reuseChoices(including: draft.commandReuseSeconds), id: \.self) { seconds in + Text(verbatim: SettingsFormat.duration(seconds: seconds)).tag(Int?.some(seconds)) } - Text(sourceKind == .vaultDatabaseRole - ? String(localized: "It stays on this Mac and never syncs, because it names where your Vault token is sent.") - : String(localized: "It stays on this Mac and never syncs, because it can name a command to run.")) - .font(.caption) - .foregroundStyle(.secondary) - if let testedSource { - PasswordSourceTestView( - source: testedSource, - context: { testContext }, - leaseOwner: { profileId }, - refusal: { - Self.testRefusal( - for: testedSource, - storedSource: storedSource, - storeIsTrusted: storage.storeIsTrusted - ) - } + } + .accessibilityIdentifier("credential-profile-command-reuse") + } + if let testedSource = draft.testedSource { + PasswordSourceTestView( + source: testedSource, + context: { testContext }, + leaseOwner: { profileId }, + refusal: { + Self.testRefusal( + for: testedSource, + storedSource: storedSource, + storeIsTrusted: storage.storeIsTrusted ) - if sourceKind == .command, mentionsConnectionDetails { - Text("A test here has no connection to take the host, port and database from.") - .font(.caption) - .foregroundStyle(.secondary) - } } + ) + if draft.sourceKind == .command, mentionsConnectionDetails { + SettingsHelpRow("A test here has no connection to take the host, port and database from.") } } } - @ViewBuilder - private var vaultAccessRows: some View { + @ViewBuilder private var vaultAccessRows: some View { TextField( String(localized: "Vault Address"), - text: $vaultAccess.address, - prompt: Text(verbatim: ProcessInfo.processInfo.environment["VAULT_ADDR"] ?? "https://vault.example.com:8200") + text: $draft.vaultAccess.address, + prompt: Text(verbatim: vaultAddressPrompt) ) .accessibilityIdentifier("credential-profile-vault-address") - Picker(String(localized: "Sign In With"), selection: Binding( - get: { vaultAccess.method }, - set: { vaultAccess.selectMethod($0) } - )) { + Picker(selection: vaultMethod) { ForEach(VaultAccessDraft.Method.allCases) { method in Text(method.displayName).tag(method) } + } label: { + Text("Sign In With") + switch draft.vaultAccess.method { + case .token: + Text("Reads VAULT_TOKEN, or ~/.vault-token from vault login.") + case .oidc: + Text("Your browser opens to sign in once per launch. The role must allow http://localhost:8250/oidc/callback.") + case .appRole: + EmptyView() + } } .accessibilityIdentifier("credential-profile-vault-method") - switch vaultAccess.method { + switch draft.vaultAccess.method { case .token: - Text("Reads VAULT_TOKEN, or ~/.vault-token from vault login.") - .font(.caption) - .foregroundStyle(.secondary) + EmptyView() case .appRole: - TextField(String(localized: "Role ID"), text: $vaultAccess.roleId) + TextField(String(localized: "Role ID"), text: $draft.vaultAccess.roleId) .accessibilityIdentifier("credential-profile-vault-role-id") TextField( String(localized: "Secret ID File"), - text: $vaultAccess.secretIdPath, + text: $draft.vaultAccess.secretIdPath, prompt: Text(verbatim: "~/.vault/approle-secret-id") ) .accessibilityIdentifier("credential-profile-vault-secret-id-path") - TextField(String(localized: "Auth Mount"), text: $vaultAccess.mount, prompt: Text(verbatim: VaultAuthMethod.defaultAppRoleMount)) + TextField( + String(localized: "Auth Mount"), + text: $draft.vaultAccess.mount, + prompt: Text(verbatim: VaultAuthMethod.defaultAppRoleMount) + ) case .oidc: - TextField(String(localized: "OIDC Role"), text: $vaultAccess.oidcRole, prompt: Text("Default role")) - TextField(String(localized: "Auth Mount"), text: $vaultAccess.mount, prompt: Text(verbatim: VaultAuthMethod.defaultOIDCMount)) - Text("Your browser opens to sign in once per launch. The role must allow http://localhost:8250/oidc/callback.") - .font(.caption) - .foregroundStyle(.secondary) + TextField(String(localized: "OIDC Role"), text: $draft.vaultAccess.oidcRole, prompt: Text("Default role")) + TextField( + String(localized: "Auth Mount"), + text: $draft.vaultAccess.mount, + prompt: Text(verbatim: VaultAuthMethod.defaultOIDCMount) + ) } - Text(String(localized: """ - Connections on this profile share one database user. TablePro renews its lease while in use, revokes it \ - once the last connection disconnects or after 10 minutes unused, and never saves the generated password. - """)) - .font(.caption) - .foregroundStyle(.secondary) } - // MARK: - Test Source + // Choosing a method also resets the fields it does not use, in one write. + private var vaultMethod: Binding { + Binding( + get: { draft.vaultAccess.method }, + set: { draft.vaultAccess.selectMethod($0) } + ) + } - private var testedSource: PasswordSource? { - guard !sourceValue.trimmingCharacters(in: .whitespaces).isEmpty else { return nil } - if sourceKind == .vaultDatabaseRole { - guard !sourceField.trimmingCharacters(in: .whitespaces).isEmpty, vaultAccess.isComplete else { return nil } + private var secureFieldsSection: some View { + Section(String(localized: "Additional Secrets")) { + Picker(selection: $secureFieldType) { + ForEach(secureFieldTypes, id: \.self) { type in + Text(verbatim: type.displayName).tag(type) + } + } label: { + Text("Database") + Text("A connection reads only the secrets its own database type declares, so one profile can carry several engines' keys.") + } + .accessibilityIdentifier("credential-profile-secure-field-type") + ForEach(secureFieldsByType[secureFieldType] ?? [], id: \.id) { field in + ConnectionFieldRow(field: field, value: secureFieldBinding(for: field)) + } } - return sourceKind.source(value: sourceValue, field: sourceField, reuseSeconds: nil, vaultAccess: vaultAccess) } - private var storedSource: PasswordSource? { - guard isStored, case .source(let source) = existingProfile?.passwordMode else { return nil } - return source + private func secureFieldBinding(for field: ConnectionField) -> Binding { + Binding( + get: { draft.secureFieldValues[field.id] ?? "" }, + set: { draft.secureFieldValues[field.id] = $0 } + ) } - private var profileId: UUID { - existingProfile?.id ?? draftProfileId + private var storedSource: PasswordSource? { + guard isStored, case .source(let source) = storedPasswordMode else { return nil } + return source } private var testContext: ConnectionScriptContext { @@ -269,13 +352,13 @@ struct CredentialProfileEditorSheet: View { connectionName: "", host: "", port: 0, - user: username.trimmingCharacters(in: .whitespaces), + user: draft.trimmedUsername, database: "" ) } private var mentionsConnectionDetails: Bool { - sourceValue.contains("TABLEPRO_") || testContext.substitutingPlaceholders(in: sourceValue) != sourceValue + draft.sourceValue.contains("TABLEPRO_") || testContext.substitutingPlaceholders(in: draft.sourceValue) != draft.sourceValue } // A source typed here is the user's own; one read back unchanged from a profiles file something else wrote is not. @@ -295,238 +378,205 @@ struct CredentialProfileEditorSheet: View { return kind.source(value: value, field: field, reuseSeconds: nil, vaultAccess: vaultAccess) } - // MARK: - Secure fields - - @ViewBuilder - private var secureFieldsSection: some View { - Section { - Picker(String(localized: "For"), selection: $secureFieldType) { - ForEach(DatabaseType.allKnownTypes, id: \.self) { type in - Text(type.rawValue).tag(type) - } - } - .onChange(of: secureFieldType) { _ in reloadSecureFields() } - if secureFields.isEmpty { - Text("This database type signs in with the username and password above.") - .font(.caption) - .foregroundStyle(.secondary) - } else { - ForEach(secureFields, id: \.id) { field in - ConnectionFieldRow(field: field, value: secureFieldBinding(for: field)) - } - } - } header: { - Text(String(localized: "Additional Secrets")) - } footer: { - Text("A connection reads only the secrets its own database type declares, so one profile can carry several engines' keys.") - .font(.caption) - .foregroundStyle(.secondary) - } - } - - private func reloadSecureFields() { - secureFields = PluginManager.shared.additionalConnectionFields(for: secureFieldType).filter(\.isSecure) - } - - private func secureFieldBinding(for field: ConnectionField) -> Binding { - Binding( - get: { secureFieldValues[field.id] ?? "" }, - set: { secureFieldValues[field.id] = $0 } - ) - } - - // MARK: - Bottom bar - private var bottomBar: some View { - HStack { + DialogFooter { if isStored { - Button(role: .destructive) { - dependentCount = storage.connectionsUsing(existingProfile?.id ?? UUID()).count - showingDeleteConfirmation = true - } label: { - Text("Delete Profile") + Button(String(localized: "Delete Profile"), role: .destructive) { + pendingDeletion = PendingProfileDeletion.make(kind: .credential, id: profileId, name: baseline.trimmedName) } + .disabled(usageUnknown) .accessibilityIdentifier("credential-profile-delete") - .alert(String(localized: "Delete Credential Profile?"), isPresented: $showingDeleteConfirmation) { - Button(String(localized: "Delete"), role: .destructive) { deleteProfile() } - Button(String(localized: "Cancel"), role: .cancel) {} - } message: { - if dependentCount > 0 { - Text("^[\(dependentCount) connection](inflect: true) use this profile. They keep these credentials as their own.") - } else { - Text("This profile will be permanently deleted.") - } - } + .profileDeletionAlert($pendingDeletion) { _ in deleteProfile() } } - - if let saveError { - NoticeLabel(saveError, severity: .error) - .font(.caption) - .lineLimit(2) - } - - Spacer() - + statusLabel + } actions: { Button(String(localized: "Cancel")) { dismiss() } .keyboardShortcut(.cancelAction) .accessibilityIdentifier("credential-profile-cancel") Button(isStored ? String(localized: "Save") : String(localized: "Create")) { saveProfile() } .keyboardShortcut(.defaultAction) - .disabled(!isValid) + .disabled(!draft.validationIssues.isEmpty) .accessibilityIdentifier("credential-profile-save") } .padding() } - // MARK: - Actions + @ViewBuilder private var statusLabel: some View { + if let saveError { + NoticeLabel(saveError, severity: .error) + .lineLimit(2) + } else if hasLoaded, draft != baseline, let issue = draft.validationIssues.first { + NoticeLabel(issue) + .lineLimit(2) + } + } private func load() { + guard !hasLoaded else { return } + hasLoaded = true + let profiles = storage.loadProfiles() - otherProfileNames = profiles.filter { $0.id != existingProfile?.id }.map { $0.name } - isStored = existingProfile.map { candidate in profiles.contains { $0.id == candidate.id } } ?? false - if let initialDatabaseType { - secureFieldType = initialDatabaseType + let stored = existingProfile.flatMap { existing in profiles.first { $0.id == existing.id } } + isStored = stored != nil + usageUnknown = ConnectionStorage.shared.isLibraryUnreadable + if let address = ProcessInfo.processInfo.environment["VAULT_ADDR"] { + vaultAddressPrompt = address } - reloadSecureFields() - guard let profile = existingProfile else { return } - name = profile.name - username = profile.username - for fieldId in profile.secureFieldIds { - if let value = storage.loadSecureField(fieldId: fieldId, for: profile.id) { - secureFieldValues[fieldId] = value - } else { - secretsWereReadable = false - } + var loaded = CredentialProfileDraft() + loaded.takenNames = profiles.filter { $0.id != profileId }.map(\.name) + let record = stored ?? existingProfile + if let record { + loaded.name = record.name + loaded.username = record.username + loaded.apply(record.passwordMode) } + storedPasswordMode = stored?.passwordMode - switch profile.passwordMode { - case .stored: - passwordKind = .stored - if let stored = storage.loadPassword(for: profile.id) { - password = stored - } else if let initialPassword { - password = initialPassword - } else if isStored { - secretsWereReadable = false + // A profile not saved yet has no Keychain items; its secrets come from the connection that promoted it. + if let stored { + if stored.passwordMode.usesStoredSecret { + passwordRead = storage.readPassword(for: stored.id) + loaded.password = passwordRead.value ?? "" } - passwordWasPrefilled = !password.isEmpty - case .prompt: - passwordKind = .prompt - case .pgpass: - passwordKind = .pgpass - case .source(let source): - passwordKind = .source - (sourceKind, sourceValue, sourceField) = PasswordSourceKind.decompose(source) - if case .command(_, let reuseSeconds) = source { - commandReuseSeconds = reuseSeconds - } - if let role = source.vaultDatabaseRole { - vaultAccess = VaultAccessDraft(role) + for fieldId in stored.secureFieldIds { + let read = storage.readSecureField(fieldId: fieldId, for: stored.id) + fieldReads[fieldId] = read + if let value = read.value { + loaded.secureFieldValues[fieldId] = value + } } + } else { + loaded.password = initialPassword ?? "" + } + passwordWasPrefilled = !loaded.password.isEmpty + + loadSecureFieldTypes(holding: Set(record?.secureFieldIds ?? [])) + draft = loaded + baseline = loaded + } + + private func loadSecureFieldTypes(holding heldFieldIds: Set) { + var types: [DatabaseType] = [] + var fieldsByType: [DatabaseType: [ConnectionField]] = [:] + for type in DatabaseType.allKnownTypes where fieldsByType[type] == nil { + let fields = PluginManager.shared.additionalConnectionFields(for: type).filter(\.isSecure) + guard !fields.isEmpty else { continue } + types.append(type) + fieldsByType[type] = fields + } + secureFieldTypes = types + secureFieldsByType = fieldsByType + if let initialDatabaseType, fieldsByType[initialDatabaseType] != nil { + secureFieldType = initialDatabaseType + } else if let held = types.first(where: { type in + fieldsByType[type, default: []].contains { heldFieldIds.contains($0.id) } + }) { + secureFieldType = held + } else if let first = types.first { + secureFieldType = first } } private func saveProfile() { - let liveFields = secureFieldValues.filter { !$0.value.isEmpty } - let profile = CredentialProfile( - id: profileId, - name: trimmedName, - username: username.trimmingCharacters(in: .whitespaces), - passwordMode: buildPasswordMode(), - secureFieldIds: secretsWereReadable - ? liveFields.keys.sorted() - : Array(Set(existingProfile?.secureFieldIds ?? []).union(liveFields.keys)).sorted(), - sortOrder: existingProfile?.sortOrder ?? 0 + // Read, then modify: the stored record may have changed since this sheet opened. + let stored = isStored ? storage.profile(for: profileId) : nil + var record = stored ?? CredentialProfile(id: profileId, name: draft.trimmedName) + record.name = draft.trimmedName + record.username = draft.trimmedUsername + record.passwordMode = draft.passwordMode + + let passwordChange = ProfileSecretChange.decide( + applies: draft.passwordKind == .stored, + value: draft.password, + read: passwordRead ) + let heldFieldIds = Set(record.secureFieldIds) + var fieldChanges: [String: ProfileSecretChange] = [:] + for fieldId in heldFieldIds.union(draft.secureFieldValues.keys) { + // A field that arrived after this sheet read the Keychain was never shown, so it is kept unless retyped. + let read = fieldReads[fieldId] ?? (heldFieldIds.contains(fieldId) ? .unreadable : .absent) + fieldChanges[fieldId] = .decide(applies: true, value: draft.secureFieldValues[fieldId] ?? "", read: read) + } + record.secureFieldIds = fieldChanges + .filter { fieldId, change in + if case .write = change { return true } + return change == .keep && heldFieldIds.contains(fieldId) + } + .map(\.key) + .sorted() - let persisted = isStored ? storage.updateProfile(profile) : storage.addProfile(profile) - /// The keychain writes below are keyed by the profile id, so running them for a profile - /// that never reached disk would leave secrets nothing can name. + let persisted = isStored ? storage.updateProfile(record) : storage.addProfile(record) + // Keychain items are keyed by the profile id, so writing them for a profile that never reached disk strands them. guard persisted else { saveError = String(localized: "Could not save the profile. Check disk space and permissions, then try again.") return } - saveError = nil + isStored = true + storedPasswordMode = record.passwordMode - if case .stored = profile.passwordMode, !password.isEmpty { - guard storage.savePassword(password, for: profileId) else { - saveError = String(localized: "Could not save the password to the Keychain. Nothing was changed.") - return - } - } else if secretsWereReadable { + var secretsSaved = apply(passwordChange, write: { storage.savePassword($0, for: profileId) }, delete: { storage.deletePassword(for: profileId) - } - - /// Only what was read back is eligible for deletion. A field whose value could not be read - /// is still there and still in use. - if secretsWereReadable { - let removed = Set(existingProfile?.secureFieldIds ?? []).subtracting(liveFields.keys) - for fieldId in removed { + }) + passwordRead = Self.read(after: passwordChange, before: passwordRead, saved: secretsSaved) + for (fieldId, change) in fieldChanges.sorted(by: { $0.key < $1.key }) { + let saved = apply(change, write: { storage.saveSecureField($0, fieldId: fieldId, for: profileId) }, delete: { storage.deleteSecureField(fieldId: fieldId, for: profileId) - } + }) + fieldReads[fieldId] = Self.read(after: change, before: fieldReads[fieldId] ?? .absent, saved: saved) + secretsSaved = secretsSaved && saved } - for (fieldId, value) in liveFields where !storage.saveSecureField(value, fieldId: fieldId, for: profileId) { - saveError = String(localized: "Could not save a secret to the Keychain. Nothing was changed.") + guard secretsSaved else { + saveError = String(localized: "The profile was saved, but its password couldn't be saved to the Keychain.") return } - - onSave?(profile) + saveError = nil + onSave?(record) dismiss() } - private func buildPasswordMode() -> CredentialPasswordMode { - switch passwordKind { - case .stored: .stored - case .prompt: .prompt - case .pgpass: .pgpass - case .source: - .source(sourceKind.source( - value: sourceValue, - field: sourceField, - reuseSeconds: commandReuseSeconds, - vaultAccess: vaultAccess - )) + private func apply(_ change: ProfileSecretChange, write: (String) -> Bool, delete: () -> Void) -> Bool { + switch change { + case .write(let value): + return write(value) + case .keep: + return true + case .delete: + delete() + return true } } - private static let reusePresets = [300, 900, 3_600, 28_800] - - private static func reuseChoices(including current: Int?) -> [Int] { - guard let current, !reusePresets.contains(current) else { return reusePresets } - return (reusePresets + [current]).sorted() - } - - private static func reuseLabel(_ seconds: Int) -> String { - Duration.seconds(seconds).formatted(.units(allowed: [.hours, .minutes, .seconds], width: .wide)) + private static func read(after change: ProfileSecretChange, before: ProfileSecretRead, saved: Bool) -> ProfileSecretRead { + switch change { + case .write(let value): saved ? .found(value) : before + case .keep: before + case .delete: .absent + } } private func deleteProfile() { - guard let profile = existingProfile else { return } - guard storage.deleteProfile(profile) else { - saveError = String(localized: "Could not delete the profile. Check disk space and permissions, then try again.") + guard let stored = storage.profile(for: profileId) else { + guard storage.lastLoadFailed else { + onDelete?() + dismiss() + return + } + saveError = ConnectionCountCopy.deleteFailedMessage + return + } + guard storage.deleteProfile(stored) else { + saveError = ConnectionCountCopy.deleteFailedMessage return } onDelete?() dismiss() } -} -// MARK: - Kinds - -extension CredentialProfileEditorSheet { - enum PasswordKind: String, CaseIterable, Identifiable { - case stored, prompt, pgpass, source - - var id: String { rawValue } + private static let reusePresets = [300, 900, 3_600, 28_800] - var displayName: String { - switch self { - case .stored: String(localized: "Saved in the Keychain") - case .prompt: String(localized: "Ask every time") - case .pgpass: String(localized: "~/.pgpass") - case .source: String(localized: "Read from elsewhere") - } - } + private static func reuseChoices(including current: Int?) -> [Int] { + guard let current, !reusePresets.contains(current) else { return reusePresets } + return (reusePresets + [current]).sorted() } } diff --git a/apple/TablePro/Views/Settings/Profiles/ProfilesSettingsModel.swift b/apple/TablePro/Views/Settings/Profiles/ProfilesSettingsModel.swift new file mode 100644 index 0000000000..f26c1a2524 --- /dev/null +++ b/apple/TablePro/Views/Settings/Profiles/ProfilesSettingsModel.swift @@ -0,0 +1,224 @@ +import Combine +import Foundation +import os + +enum ProfileNames { + // Every picker offers a profile by name alone, so a copy never reuses one. + static func available(basedOn name: String, taken: [String]) -> String { + let base = name.trimmingCharacters(in: .whitespacesAndNewlines) + let first = String(format: String(localized: "%@ (Copy)"), base) + guard isTaken(first, in: taken) else { return first } + for index in 2...(taken.count + 2) { + let candidate = String(format: String(localized: "%1$@ (Copy %2$lld)"), base, Int64(index)) + if !isTaken(candidate, in: taken) { return candidate } + } + return first + } + + static func matches(_ lhs: String, _ rhs: String) -> Bool { + lhs.trimmingCharacters(in: .whitespacesAndNewlines) + .compare( + rhs.trimmingCharacters(in: .whitespacesAndNewlines), + options: [.caseInsensitive, .diacriticInsensitive] + ) == .orderedSame + } + + private static func isTaken(_ name: String, in taken: [String]) -> Bool { + taken.contains { matches($0, name) } + } +} + +@MainActor +final class ProfilesSettingsModel: ObservableObject { + private static let logger = Logger(subsystem: "com.TablePro", category: "ProfilesSettingsModel") + + @Published private(set) var credentialProfiles: [CredentialProfile] = [] + @Published private(set) var sshProfiles: [SSHProfile] = [] + @Published private(set) var usage: [UUID: Int] = [:] + @Published private(set) var credentialLoadFailed = false + @Published private(set) var sshLoadFailed = false + @Published private(set) var unreadableProfileCount = 0 + @Published private(set) var usageUnknown = false + @Published private(set) var someConnectionsUnreadable = false + @Published private(set) var isLoaded = false + + private let credentialStorage: CredentialProfileStorage + private let sshStorage: SSHProfileStorage + private let connectionStorage: ConnectionStorage + private var cancellables: Set = [] + + init( + credentialStorage: CredentialProfileStorage = .shared, + sshStorage: SSHProfileStorage = .shared, + connectionStorage: ConnectionStorage = .shared, + appEvents: AppEvents = .shared, + notificationCenter: NotificationCenter = .default + ) { + self.credentialStorage = credentialStorage + self.sshStorage = sshStorage + self.connectionStorage = connectionStorage + + // Profiles also change from a connection window and from sync while this pane is on screen. + notificationCenter.publisher(for: .credentialProfilesDidChange) + .merge(with: notificationCenter.publisher(for: .sshProfilesDidChange)) + .map { _ in () } + .debounce(for: .milliseconds(100), scheduler: DispatchQueue.main) + .sink { [weak self] in self?.reloadProfiles() } + .store(in: &cancellables) + appEvents.connectionUpdated + .map { _ in () } + .debounce(for: .milliseconds(100), scheduler: DispatchQueue.main) + .sink { [weak self] in self?.recountUsage() } + .store(in: &cancellables) + } + + func refresh() { + reloadProfiles() + recountUsage() + if !isLoaded { isLoaded = true } + } + + func reloadProfiles() { + let credentials = credentialStorage.loadProfiles() + let credentialsFailed = credentialStorage.lastLoadFailed + let unreadable = credentialsFailed ? 0 : credentialStorage.unreadableProfileIds.count + let ssh = sshStorage.loadProfiles() + let sshFailed = sshStorage.lastLoadFailed + + // Refresh in place: an unchanged value never publishes, so the list does not redraw on every visit. + if credentialProfiles != credentials { credentialProfiles = credentials } + if credentialLoadFailed != credentialsFailed { credentialLoadFailed = credentialsFailed } + if unreadableProfileCount != unreadable { unreadableProfileCount = unreadable } + if sshProfiles != ssh { sshProfiles = ssh } + if sshLoadFailed != sshFailed { sshLoadFailed = sshFailed } + } + + func recountUsage() { + let connections = connectionStorage.loadConnections() + let unknown = connectionStorage.lastLoadFailed + var counts: [UUID: Int] = [:] + for connection in connections { + if let id = connection.credentialMode.profileId { + counts[id, default: 0] += 1 + } + if case .profile(let id, _) = connection.sshTunnelMode { + counts[id, default: 0] += 1 + } + } + let unreadable = unknown ? false : !connectionStorage.unreadableConnectionIds.isEmpty + + if usage != counts { usage = counts } + if usageUnknown != unknown { usageUnknown = unknown } + if someConnectionsUnreadable != unreadable { someConnectionsUnreadable = unreadable } + } + + func usageCount(for profileId: UUID) -> Int? { + usageUnknown ? nil : usage[profileId, default: 0] + } + + func pendingDeletion(of kind: ProfileKind, id: UUID, name: String) -> PendingProfileDeletion? { + guard !usageUnknown else { return nil } + return PendingProfileDeletion.make(kind: kind, id: id, name: name, connectionStorage: connectionStorage) + } + + func delete(_ pending: PendingProfileDeletion) -> Bool { + defer { refresh() } + switch pending.kind { + case .credential: + guard let stored = credentialStorage.profile(for: pending.id) else { return !credentialStorage.lastLoadFailed } + return credentialStorage.deleteProfile(stored) + case .ssh: + guard let stored = sshStorage.profile(for: pending.id) else { return !sshStorage.lastLoadFailed } + return sshStorage.deleteProfile(stored) + } + } + + func duplicateCredentialProfile(id: UUID) -> Bool { + defer { refresh() } + let profiles = credentialStorage.loadProfiles() + guard !credentialStorage.lastLoadFailed, let source = profiles.first(where: { $0.id == id }) else { return false } + + // Every secret is read before anything is written, so a locked Keychain leaves no half-made copy. + var password: String? + if source.passwordMode.usesStoredSecret { + switch credentialStorage.readPassword(for: source.id) { + case .found(let value): password = value + case .absent: break + case .unreadable: return false + } + } + var fields: [String: String] = [:] + for fieldId in source.secureFieldIds { + switch credentialStorage.readSecureField(fieldId: fieldId, for: source.id) { + case .found(let value): fields[fieldId] = value + case .absent: break + case .unreadable: return false + } + } + + let copy = CredentialProfile( + name: ProfileNames.available(basedOn: source.name, taken: profiles.map(\.name)), + username: source.username, + passwordMode: source.passwordMode, + secureFieldIds: source.secureFieldIds + ) + guard credentialStorage.addProfile(copy) else { return false } + + var written = true + if let password { + written = credentialStorage.savePassword(password, for: copy.id) + } + for (fieldId, value) in fields.sorted(by: { $0.key < $1.key }) where written { + written = credentialStorage.saveSecureField(value, fieldId: fieldId, for: copy.id) + } + guard written else { + Self.logger.error("Removing the copy of credential profile \(id.uuidString, privacy: .public): a secret could not be copied") + credentialStorage.deleteProfile(copy) + return false + } + return true + } + + func duplicateSSHProfile(id: UUID) -> Bool { + defer { refresh() } + let profiles = sshStorage.loadProfiles() + guard !sshStorage.lastLoadFailed, let source = profiles.first(where: { $0.id == id }) else { return false } + + var secrets: [SSHSecret: String] = [:] + for secret in SSHSecret.allCases { + switch sshStorage.readSecret(secret, for: source.id) { + case .found(let value): secrets[secret] = value + case .absent: break + case .unreadable: return false + } + } + + let copy = SSHProfile( + name: ProfileNames.available(basedOn: source.name, taken: profiles.map(\.name)), + host: source.host, + port: source.port, + username: source.username, + authMethod: source.authMethod, + privateKeyPath: source.privateKeyPath, + agentSocketPath: source.agentSocketPath, + jumpHosts: source.jumpHosts, + totpMode: source.totpMode, + totpAlgorithm: source.totpAlgorithm, + totpDigits: source.totpDigits, + totpPeriod: source.totpPeriod + ) + guard sshStorage.addProfile(copy) else { return false } + + var written = true + for secret in SSHSecret.allCases where written { + guard let value = secrets[secret] else { continue } + written = sshStorage.saveSecret(value, secret, for: copy.id) + } + guard written else { + Self.logger.error("Removing the copy of SSH profile \(id.uuidString, privacy: .public): a secret could not be copied") + sshStorage.deleteProfile(copy) + return false + } + return true + } +} diff --git a/apple/TablePro/Views/Settings/Profiles/ProfilesSettingsView.swift b/apple/TablePro/Views/Settings/Profiles/ProfilesSettingsView.swift index 74542bd7fe..c2c612aa80 100644 --- a/apple/TablePro/Views/Settings/Profiles/ProfilesSettingsView.swift +++ b/apple/TablePro/Views/Settings/Profiles/ProfilesSettingsView.swift @@ -1,24 +1,27 @@ -// -// ProfilesSettingsView.swift -// TablePro -// - import SwiftUI -/// The profiles a connection can point at, in one place. -/// -/// Both kinds used to be reachable only from inside a connection form's Network tab, through three -/// small buttons, with no list of them anywhere and no way to see which connections used one. -struct ProfilesSettingsView: View { - @State private var credentialProfiles: [CredentialProfile] = [] - @State private var sshProfiles: [SSHProfile] = [] +enum ProfileEditorRoute: Identifiable { + case newCredential + case credential(CredentialProfile) + case newSSH + case ssh(SSHProfile) + + var id: String { + switch self { + case .newCredential: "new-credential" + case .credential(let profile): "credential-\(profile.id.uuidString)" + case .newSSH: "new-ssh" + case .ssh(let profile): "ssh-\(profile.id.uuidString)" + } + } +} - @State private var editingCredentialProfile: CredentialProfile? - @State private var isAddingCredentialProfile = false - @State private var editingSSHProfile: SSHProfile? - @State private var isAddingSSHProfile = false +struct ProfilesSettingsView: View { + @ObservedObject var model: ProfilesSettingsModel + let presentError: @MainActor (_ title: String, _ message: String) -> Void - @State private var connectionCounts: [UUID: Int] = [:] + @State private var editor: ProfileEditorRoute? + @State private var pendingDeletion: PendingProfileDeletion? var body: some View { Form { @@ -26,208 +29,157 @@ struct ProfilesSettingsView: View { sshSection } .formStyle(.grouped) - .onAppear(perform: reload) - /// The Settings window is kept alive between openings, so a profile created from a - /// connection window has to reach this list while it is already on screen. - .onReceive(NotificationCenter.default.publisher(for: .credentialProfilesDidChange)) { _ in reload() } - .onReceive(NotificationCenter.default.publisher(for: .sshProfilesDidChange)) { _ in reload() } - .sheet(item: $editingCredentialProfile) { profile in - CredentialProfileEditorSheet( - existingProfile: profile, - onSave: { _ in reload() }, - onDelete: { reload() } - ) - } - .sheet(isPresented: $isAddingCredentialProfile) { - CredentialProfileEditorSheet(existingProfile: nil, onSave: { _ in reload() }) - } - .sheet(item: $editingSSHProfile) { profile in - SSHProfileEditorView( - existingProfile: profile, - onSave: { _ in reload() }, - onDelete: { reload() } - ) + .accessibilityElement(children: .contain) + .accessibilityIdentifier("settings-pane-profiles") + .sheet(item: $editor) { route in + switch route { + case .newCredential: + CredentialProfileEditorSheet(existingProfile: nil) + case .credential(let profile): + CredentialProfileEditorSheet(existingProfile: profile) + case .newSSH: + SSHProfileEditorView(existingProfile: nil) + case .ssh(let profile): + SSHProfileEditorView(existingProfile: profile) + } } - .sheet(isPresented: $isAddingSSHProfile) { - SSHProfileEditorView(existingProfile: nil, onSave: { _ in reload() }) + .profileDeletionAlert($pendingDeletion) { pending in + let deleted = model.delete(pending) + guard !deleted else { return } + report(title: ConnectionCountCopy.deleteFailedTitle, message: ConnectionCountCopy.deleteFailedMessage) } } - // MARK: - Credential profiles - private var credentialSection: some View { Section { - if credentialProfiles.isEmpty { - emptyRow(String(localized: "No credential profiles yet.")) + if model.credentialLoadFailed { + NoticeLabel( + String(localized: "Credential profiles couldn't be read, so none are shown. TablePro won't save over them."), + severity: .error + ) } else { - ForEach(credentialProfiles) { profile in - row( - title: profile.name, - detail: profile.summary, - symbol: "key.fill", - usedBy: connectionCounts[profile.id] ?? 0, - identifier: "credential-profile-row-\(profile.id.uuidString)" - ) { - editingCredentialProfile = profile + if model.unreadableProfileCount > 0 { + NoticeLabel(ConnectionCountCopy.unreadableProfiles(model.unreadableProfileCount)) + } + if model.credentialProfiles.isEmpty { + if model.isLoaded { + Text("No credential profiles") + .foregroundStyle(.secondary) + .accessibilityIdentifier("credential-profiles-empty") } - .contextMenu { - Button(String(localized: "Edit…")) { editingCredentialProfile = profile } - Button(String(localized: "Duplicate")) { duplicate(profile) } + } else { + ForEach(model.credentialProfiles) { profile in + credentialRow(profile) } } } - Button { - isAddingCredentialProfile = true - } label: { - Label(String(localized: "Add Credential Profile…"), systemImage: "plus") - } - .accessibilityIdentifier("add-credential-profile") + SettingsHelpRow( + "Connections that use a profile sign in with its username and password. Edit it once to update them all." + ) } header: { - Text(String(localized: "Credential Profiles")) + Text("Credential Profiles") } footer: { - Text("One username and password, shared by any number of connections. Change it here and every connection using it signs in with the new one.") - .font(.caption) - .foregroundStyle(.secondary) + SettingsSectionActions { + Button(String(localized: "Add Credential Profile…")) { + editor = .newCredential + } + .disabled(model.credentialLoadFailed) + .accessibilityIdentifier("add-credential-profile") + } } } - // MARK: - SSH profiles - private var sshSection: some View { Section { - if sshProfiles.isEmpty { - emptyRow(String(localized: "No SSH servers yet.")) + if model.sshLoadFailed { + NoticeLabel( + String(localized: "SSH profiles couldn't be read, so none are shown. TablePro won't save over them."), + severity: .error + ) + } else if model.sshProfiles.isEmpty { + if model.isLoaded { + Text("No SSH profiles") + .foregroundStyle(.secondary) + .accessibilityIdentifier("ssh-profiles-empty") + } } else { - ForEach(sshProfiles) { profile in - row( - title: profile.name, - detail: sshDetail(profile), - symbol: "network", - usedBy: connectionCounts[profile.id] ?? 0, - identifier: "ssh-profile-row-\(profile.id.uuidString)" - ) { - editingSSHProfile = profile - } - .contextMenu { - Button(String(localized: "Edit…")) { editingSSHProfile = profile } - } + ForEach(model.sshProfiles) { profile in + sshRow(profile) } } - Button { - isAddingSSHProfile = true - } label: { - Label(String(localized: "Add SSH Server…"), systemImage: "plus") - } - .accessibilityIdentifier("add-ssh-profile") + SettingsHelpRow( + "Connections that use an SSH profile tunnel through its server. Changes reach every connection that uses it." + ) } header: { - Text(String(localized: "SSH Servers")) + Text("SSH Profiles") } footer: { - Text("One bastion, many connections. Editing the server or its credentials reaches every connection tunnelling through it.") - .font(.caption) - .foregroundStyle(.secondary) - } - } - - private func sshDetail(_ profile: SSHProfile) -> String { - let user = profile.username.trimmingCharacters(in: .whitespaces) - guard !user.isEmpty else { return profile.host } - return "\(user)@\(profile.host)" - } - - // MARK: - Rows - - private func row( - title: String, - detail: String, - symbol: String, - usedBy: Int, - identifier: String, - action: @escaping () -> Void - ) -> some View { - Button(action: action) { - HStack(spacing: 10) { - Image(systemName: symbol) - .foregroundStyle(.secondary) - .frame(width: 18) - VStack(alignment: .leading, spacing: 2) { - Text(title) - Text(detail) - .font(.caption) - .foregroundStyle(.secondary) + SettingsSectionActions { + Button(String(localized: "Add SSH Profile…")) { + editor = .newSSH } - Spacer(minLength: 8) - Text(usedByLabel(usedBy)) - .font(.caption) - .foregroundStyle(.secondary) - Image(systemName: "chevron.right") - .font(.caption) - .foregroundStyle(.tertiary) + .disabled(model.sshLoadFailed) + .accessibilityIdentifier("add-ssh-profile") } - .contentShape(Rectangle()) } - .buttonStyle(.plain) - .accessibilityIdentifier(identifier) - .accessibilityLabel("\(title), \(detail), \(usedByLabel(usedBy))") } - private func usedByLabel(_ count: Int) -> String { - guard count > 0 else { return String(localized: "Unused") } - return String(format: String(localized: "Used by %lld"), Int64(count)) + private func credentialRow(_ profile: CredentialProfile) -> some View { + SettingsRecordRow( + title: profile.name, + subtitle: profile.summary, + value: usageValue(for: profile.id) + ) + .infoButton( + onEdit: { editor = .credential(profile) }, + onDuplicate: { duplicateCredential(profile) }, + removal: removal(of: .credential, id: profile.id, name: profile.name), + identifier: "credential-profile-edit-\(profile.id.uuidString)" + ) + .accessibilityIdentifier("credential-profile-row-\(profile.id.uuidString)") } - private func emptyRow(_ text: String) -> some View { - Text(text) - .foregroundStyle(.secondary) + private func sshRow(_ profile: SSHProfile) -> some View { + SettingsRecordRow( + title: profile.name, + subtitle: profile.address, + value: usageValue(for: profile.id) + ) + .infoButton( + onEdit: { editor = .ssh(profile) }, + onDuplicate: { duplicateSSH(profile) }, + removal: removal(of: .ssh, id: profile.id, name: profile.name), + identifier: "ssh-profile-edit-\(profile.id.uuidString)" + ) + .accessibilityIdentifier("ssh-profile-row-\(profile.id.uuidString)") } - // MARK: - Data - - private func reload() { - credentialProfiles = CredentialProfileStorage.shared.loadProfiles() - sshProfiles = SSHProfileStorage.shared.loadProfiles() + private func usageValue(for profileId: UUID) -> String? { + model.usageCount(for: profileId).map(ConnectionCountCopy.usage) + } - var counts: [UUID: Int] = [:] - for connection in ConnectionStorage.shared.loadConnections() { - if let id = connection.credentialMode.profileId { - counts[id, default: 0] += 1 - } - if case .profile(let id, _) = connection.sshTunnelMode { - counts[id, default: 0] += 1 - } + // Unknown usage means unknown consequences, so Delete is not offered until the connections read again. + private func removal(of kind: ProfileKind, id: UUID, name: String) -> SettingsRecordRemoval? { + guard !model.usageUnknown else { return nil } + return .delete { + pendingDeletion = model.pendingDeletion(of: kind, id: id, name: name) } - connectionCounts = counts } - /// The editor refuses two profiles with one name, so duplicating twice must not create them - /// either: every picker offers a profile by its name alone. - private func availableName(basedOn name: String) -> String { - let taken = Set(credentialProfiles.map { $0.name.lowercased() }) - let first = String(format: String(localized: "%@ (Copy)"), name) - guard taken.contains(first.lowercased()) else { return first } - for index in 2...99 { - let candidate = String(format: String(localized: "%1$@ (Copy %2$lld)"), name, Int64(index)) - if !taken.contains(candidate.lowercased()) { return candidate } - } - return first + private func duplicateCredential(_ profile: CredentialProfile) { + guard !model.duplicateCredentialProfile(id: profile.id) else { return } + report(title: ConnectionCountCopy.duplicateFailedTitle, message: ConnectionCountCopy.duplicateFailedMessage) } - private func duplicate(_ profile: CredentialProfile) { - let copy = CredentialProfile( - name: availableName(basedOn: profile.name), - username: profile.username, - passwordMode: profile.passwordMode, - secureFieldIds: profile.secureFieldIds - ) - guard CredentialProfileStorage.shared.addProfile(copy) else { return } - if case .stored = profile.passwordMode, - let password = CredentialProfileStorage.shared.loadPassword(for: profile.id) { - CredentialProfileStorage.shared.savePassword(password, for: copy.id) - } - for fieldId in profile.secureFieldIds { - if let value = CredentialProfileStorage.shared.loadSecureField(fieldId: fieldId, for: profile.id) { - CredentialProfileStorage.shared.saveSecureField(value, fieldId: fieldId, for: copy.id) - } + private func duplicateSSH(_ profile: SSHProfile) { + guard !model.duplicateSSHProfile(id: profile.id) else { return } + report(title: ConnectionCountCopy.duplicateFailedTitle, message: ConnectionCountCopy.duplicateFailedMessage) + } + + // A turn later, so the error sheet does not race the confirmation alert that is still closing. + private func report(title: String, message: String) { + let presentError = presentError + DispatchQueue.main.async { + presentError(title, message) } - reload() } } diff --git a/apple/TablePro/Views/Settings/Sections/CommandLineToolSection.swift b/apple/TablePro/Views/Settings/Sections/CommandLineToolSection.swift index 5cda970d70..025005f609 100644 --- a/apple/TablePro/Views/Settings/Sections/CommandLineToolSection.swift +++ b/apple/TablePro/Views/Settings/Sections/CommandLineToolSection.swift @@ -1,49 +1,73 @@ import AppKit import SwiftUI -struct CommandLineToolSection: View { +struct CommandLineToolPage: View { private let tool: CommandLineShim + @ObservedObject private var visit: SettingsPaneVisit - @State private var status: CommandLineShimStatus = .notLinked - @State private var command: String? + @State private var link: CommandLineToolLink? - init(tool: CommandLineShim = CommandLineShim()) { + init(visit: SettingsPaneVisit, tool: CommandLineShim = CommandLineShim()) { self.tool = tool - _command = State(initialValue: tool.linkCommand) + self._visit = ObservedObject(wrappedValue: visit) } var body: some View { - Section { - LabeledContent { - Text(statusText) - .foregroundStyle(.secondary) - } label: { - Text("tablepro command") - Text(tool.linkPath) - .font(.system(.caption, design: .monospaced)) - } + Form { + Section { + LabeledContent { + if let link { + Text(link.statusText) + .foregroundStyle(.secondary) + .accessibilityIdentifier("command-line-status") + } + } label: { + Text("tablepro command") + Text("Opens database URLs and files, runs queries and exports tables from the terminal. Run `tablepro help` to see every command.") + } - VStack(alignment: .leading, spacing: 6) { - Text(instruction) - .font(.caption) - .foregroundStyle(.secondary) + LabeledContent("Location") { + Text(verbatim: tool.linkPath) + .font(.system(.body, design: .monospaced)) + .foregroundStyle(.secondary) + .textSelection(.enabled) + } - if let command { - CopyableCodeBlock(text: command) + if let link { + VStack(alignment: .leading, spacing: 6) { + Text(link.instruction) + .font(.subheadline) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + + if let command = link.command { + CopyableCodeBlock(text: command) + } + } } } - } header: { - Text("Command Line") - } footer: { - Text("Opens database URLs and files, runs queries and exports tables from the terminal. Run `tablepro help` to see every command.") } - .onAppear(perform: syncStatus) + .formStyle(.grouped) + .accessibilityElement(children: .contain) + .accessibilityIdentifier(SettingsPage.commandLineTool.pageIdentifier) + .task(id: visit.count) { refresh() } .onReceive(NotificationCenter.default.publisher(for: NSApplication.didBecomeActiveNotification)) { _ in - syncStatus() + refresh() } } - private var statusText: String { + // The link changes from Terminal, so it is read on every show and every return to the app. + private func refresh() { + let status = tool.status() + link = CommandLineToolLink(status: status, command: tool.command(for: status)) + } +} + +private struct CommandLineToolLink: Equatable { + let status: CommandLineShimStatus + let command: String? + + var statusText: String { switch status { case .linked: String(localized: "Linked") @@ -54,7 +78,7 @@ struct CommandLineToolSection: View { } } - private var instruction: String { + var instruction: String { guard command != nil else { return String(localized: "TablePro is running from a disk image or a temporary location. Move it to the Applications folder first, then open it from there.") } @@ -67,9 +91,4 @@ struct CommandLineToolSection: View { return String(localized: "To replace that file with a link to this app, run this in Terminal:") } } - - private func syncStatus() { - status = tool.status() - command = tool.command(for: status) - } } diff --git a/apple/TablePro/Views/Settings/Sections/ConnectionAllowlistSection.swift b/apple/TablePro/Views/Settings/Sections/ConnectionAllowlistSection.swift new file mode 100644 index 0000000000..92f78fc559 --- /dev/null +++ b/apple/TablePro/Views/Settings/Sections/ConnectionAllowlistSection.swift @@ -0,0 +1,72 @@ +import SwiftUI + +// Rows only, so each sheet puts them in its own card under its own header. +struct ConnectionAllowlistSection: View { + @Binding var selection: Set + let connections: [DatabaseConnection] + let showsSelectAll: Bool + + @State private var search = "" + + var body: some View { + if connections.isEmpty { + Text("No saved connections") + .foregroundStyle(.secondary) + } else { + HStack(spacing: 8) { + NativeSearchField( + text: $search, + placeholder: String(localized: "Search connections"), + accessibilityIdentifier: "connection-allowlist-search" + ) + if showsSelectAll { + Button(String(localized: "Select All")) { + selection.formUnion(filtered.map(\.id)) + } + .disabled(filtered.isEmpty) + .accessibilityIdentifier("connection-allowlist-select-all") + Button(String(localized: "Select None")) { + selection.subtract(filtered.map(\.id)) + } + .disabled(filtered.isEmpty) + .accessibilityIdentifier("connection-allowlist-select-none") + } + } + + if filtered.isEmpty { + Text("No matching connections") + .foregroundStyle(.secondary) + } else { + ForEach(filtered) { connection in + Toggle(isOn: binding(for: connection.id)) { + Text(verbatim: connection.name) + Text(verbatim: connection.type.displayName) + } + .toggleStyle(.checkbox) + } + } + } + } + + private var filtered: [DatabaseConnection] { + let query = search.trimmingCharacters(in: .whitespacesAndNewlines) + guard !query.isEmpty else { return connections } + return connections.filter { connection in + connection.name.localizedStandardContains(query) + || connection.type.displayName.localizedStandardContains(query) + } + } + + private func binding(for id: UUID) -> Binding { + Binding( + get: { selection.contains(id) }, + set: { isOn in + if isOn { + selection.insert(id) + } else { + selection.remove(id) + } + } + ) + } +} diff --git a/apple/TablePro/Views/Settings/Sections/ConnectionsSettingsSection.swift b/apple/TablePro/Views/Settings/Sections/ConnectionsSettingsSection.swift deleted file mode 100644 index dd01138ce1..0000000000 --- a/apple/TablePro/Views/Settings/Sections/ConnectionsSettingsSection.swift +++ /dev/null @@ -1,64 +0,0 @@ -// -// ConnectionsSettingsSection.swift -// TablePro -// - -import SwiftUI -import TableProConnectionLibrary - -internal struct ConnectionsSettingsSection: View { - @Binding private var healthCheck: ConnectionHealthCheck - @ObservedObject private var listPreferences: ConnectionListPreferences - @ObservedObject private var recentConnections: RecentConnectionsStore - - internal init( - healthCheck: Binding, - listPreferences: ConnectionListPreferences = .shared, - recentConnections: RecentConnectionsStore = .shared - ) { - _healthCheck = healthCheck - self.listPreferences = listPreferences - self.recentConnections = recentConnections - } - - private var showsRecent: Binding { - Binding( - get: { listPreferences.showsRecent }, - set: { listPreferences.setShowsRecent($0) } - ) - } - - internal var body: some View { - Section("Connections") { - Toggle("Show recent connections", isOn: showsRecent) - .accessibilityIdentifier("show-recent-connections-toggle") - .help(String(localized: """ - Adds a Recent section with the connections you opened lately to the welcome window \ - and the connection switcher. - """)) - - LabeledContent("Recent connection history") { - Button("Clear Recent") { - recentConnections.clear() - } - .disabled(recentConnections.ledger.isEmpty) - .accessibilityIdentifier("clear-recent-connections-button") - .help(String(localized: "Forgets which connections you opened and when. Sorting by Last Connected starts over.")) - } - - Picker("Check connections:", selection: $healthCheck) { - ForEach(ConnectionHealthCheck.allCases) { option in - Text(option.title).tag(option) - } - } - .accessibilityIdentifier("connection-health-check-picker") - .help(String(localized: """ - TablePro runs a small query on each open connection so it can notice a dropped \ - one and reconnect before you hit it. Only when I use the connection stops that \ - background traffic, which is what a database that sleeps when idle, or bills \ - per query, needs; TablePro then checks the connection the first time you use \ - it after a pause. - """)) - } - } -} diff --git a/apple/TablePro/Views/Settings/Sections/DataGridSection.swift b/apple/TablePro/Views/Settings/Sections/DataGridSection.swift index d350bb320b..492a6dc32d 100644 --- a/apple/TablePro/Views/Settings/Sections/DataGridSection.swift +++ b/apple/TablePro/Views/Settings/Sections/DataGridSection.swift @@ -1,144 +1,224 @@ -// -// DataGridSection.swift -// TablePro -// - import SwiftUI struct DataGridSection: View { + static let pageSizes = [100, 500, 1_000, 5_000, 10_000] + static let exactCountThresholds = [1_000, 10_000, 100_000, 1_000_000, Int.max] + static let queryResultLimits = [100, 1_000, 5_000, 10_000, 50_000, 100_000, 500_000] + static let resultSetsKept = [0, 10, 20, 50, 100, 200, 500, 1_000] + @Binding var settings: DataGridSettings - @Binding var valueColors: ValueColorSettings + let typography: SettingsSlice + let valueColors: SettingsSlice + let editor: SettingsSlice var body: some View { Section { - Picker("Row height:", selection: $settings.rowHeight) { + DataFontRows(typography: typography) + + Picker("Row height", selection: $settings.rowHeight) { ForEach(DataGridRowHeight.allCases) { height in Text(height.displayName).tag(height) } } + .accessibilityIdentifier("data-row-height-picker") - Picker("Date format:", selection: $settings.dateFormat) { - ForEach(DateFormatOption.allCases) { format in - Text(format.displayName).tag(format) - } + Toggle("Show alternate row backgrounds", isOn: $settings.showAlternateRows) + .accessibilityIdentifier("data-alternate-rows-toggle") + + Toggle("Show row numbers", isOn: $settings.showRowNumbers) + .accessibilityIdentifier("data-row-numbers-toggle") + + Toggle(isOn: $settings.wrapText) { + Text("Wrap text in cells") + Text("Long values wrap onto up to 10 lines in new tabs. View > Wrap Text changes the open grid.") } + .accessibilityIdentifier("data-wrap-text-toggle") - VStack(alignment: .leading, spacing: 4) { - TextField("NULL display:", text: $settings.nullDisplay) - .help("Max \(SettingsValidationRules.nullDisplayMaxLength) characters") + Toggle(isOn: $settings.showInvisibleCharacters) { + Text("Show invisible characters") + Text("Marks zero-width, control and special space characters in cells and value fields.") + } + .accessibilityIdentifier("data-invisible-characters-toggle") - if let error = settings.nullDisplayValidationError { - NoticeLabel(error, severity: .error) - .font(.caption) + Toggle("Show inspector when a row is selected", isOn: $settings.autoShowInspector) + .accessibilityIdentifier("data-auto-inspector-toggle") + } header: { + Text("Grid") + } + + Section { + Picker("Date format", selection: $settings.dateFormat) { + ForEach(DateFormatOption.allCases) { format in + Text(format.displayName).tag(format) } } + .accessibilityIdentifier("data-date-format-picker") + + SettingsTextField( + "NULL display", + subtitle: "Up to \(SettingsValidationRules.nullDisplayMaxLength) characters", + text: $settings.nullDisplay, + prompt: Text(verbatim: "NULL"), + validate: DataGridSettings.nullDisplayValidationError(for:), + normalize: DataGridSettings.normalizedNullDisplay(_:) + ) + .accessibilityIdentifier("data-null-display-field") + + ColorValuesByTypeToggle(valueColors: valueColors) + + Toggle(isOn: $settings.enableSmartValueDetection) { + Text("Smart value detection") + Text("Shows UUIDs, Unix timestamps, JSON and serialized values in a readable form, judged from the first rows.") + } + .accessibilityIdentifier("data-smart-detection-toggle") - Toggle("Show alternate row backgrounds", isOn: $settings.showAlternateRows) - Toggle("Show row numbers", isOn: $settings.showRowNumbers) - Toggle("Auto-show inspector on row select", isOn: $settings.autoShowInspector) - Toggle("Smart value detection", isOn: $settings.enableSmartValueDetection) - Toggle("Show invisible characters", isOn: $settings.showInvisibleCharacters) - .help(String(localized: "Mark zero-width, control and special space characters in cells and value fields")) - Toggle("Wrap text in cells", isOn: $settings.wrapText) - .help(String(localized: "Long values wrap onto up to 10 lines. Applies to new tabs; View > Wrap Text changes the open grid.")) - Toggle("Color values by type", isOn: $valueColors.colorsValuesByType) - .help(String(localized: "Draw strings, numbers, dates and other typed values in the colors of the theme's Values section")) - .accessibilityIdentifier("color-values-by-type-toggle") - - Picker("Default row sort:", selection: $settings.defaultSortBehavior) { + JSONViewModePicker(editor: editor) + } header: { + Text("Values") + } + + Section { + Picker(selection: $settings.defaultSortBehavior) { ForEach(DefaultSortBehavior.allCases) { behavior in Text(behavior.displayName).tag(behavior) } + } label: { + Text("Default sort") + Text("Applied when a table first opens.") } + .accessibilityIdentifier("data-default-sort-picker") - Picker("Sort direction:", selection: $settings.defaultSortDirection) { + Picker(selection: $settings.defaultSortDirection) { ForEach(SortDirection.allCases) { direction in Text(direction.displayName).tag(direction) } + } label: { + Text("Sort direction") + Text("Also the direction of the first click on a column header.") } + .accessibilityIdentifier("data-sort-direction-picker") } header: { - Text("Data Grid") - } footer: { - Text("Default row sort is applied when a table first opens. Sort direction also sets which way the first click on a column header sorts.") + Text("Sorting") } Section { - Picker("Copy rows as:", selection: $settings.rowCopyFormat) { + Picker(selection: $settings.rowCopyFormat) { ForEach(RowCopyFormat.allCases) { format in Text(format.displayName).tag(format) } + } label: { + Text("Copy rows as") + Text("A single cell still copies its value. Edit > Copy Special offers every format.") } + .accessibilityIdentifier("data-copy-format-picker") } header: { Text("Copying") - } footer: { - Text("Copy uses this format for selected rows. A single cell still copies its value, and Edit > Copy Special offers every format.") - } - - Section("Pagination") { - Picker("Default page size:", selection: $settings.defaultPageSize) { - Text("100 rows").tag(100) - Text("500 rows").tag(500) - Text("1,000 rows").tag(1_000) - Text("5,000 rows").tag(5_000) - Text("10,000 rows").tag(10_000) - } - - Picker( - String(localized: "Count rows if estimate less than:"), - selection: $settings.countRowsIfEstimateLessThan - ) { - Text("1,000").tag(1_000) - Text("10,000").tag(10_000) - Text("100,000").tag(100_000) - Text("1,000,000").tag(1_000_000) - Text(String(localized: "Always count")).tag(Int.max) - } - .help(String(localized: "Tables with more estimated rows use approximate counts to avoid slow COUNT(*) queries")) } Section { - Toggle("Truncate query results", isOn: $settings.truncateQueryResults) - .help(String(localized: "Apply a row limit when running queries and cap results at the configured row count")) - - if settings.truncateQueryResults { - Picker("Row cap:", selection: $settings.queryResultRowCap) { - Text("100").tag(100) - Text("1,000").tag(1_000) - Text("5,000").tag(5_000) - Text("10,000").tag(10_000) - Text("50,000").tag(50_000) - Text("100,000").tag(100_000) - Text("500,000").tag(500_000) + Picker("Page size", selection: $settings.defaultPageSize) { + SettingsChoiceItems(Self.pageSizes, including: settings.defaultPageSize) { size in + Text(Self.rowsTitle(size)) } + } + .accessibilityIdentifier("data-page-size-picker") - if let error = settings.queryResultRowCapValidationError { - NoticeLabel(error, severity: .error) - .font(.caption) + Picker(selection: $settings.countRowsIfEstimateLessThan) { + SettingsChoiceItems(Self.exactCountThresholds, including: settings.countRowsIfEstimateLessThan) { threshold in + Text(Self.exactCountTitle(threshold)) } + } label: { + Text("Exact row count") + Text("Larger tables show an estimated count, which avoids a slow COUNT(*).") } - } header: { - Text("Query Result Row Cap") - } footer: { - if settings.truncateQueryResults, settings.queryResultRowCapValidationError == nil { - Text(""" - SELECT queries without their own LIMIT run with this cap applied. The query text in the \ - editor never changes. Capped results show a Fetch All button, and Execute Without Limit \ - skips the cap for one run. - """) + .accessibilityIdentifier("data-exact-count-picker") + + Picker(selection: Self.queryResultLimitBinding($settings)) { + Text("No limit").tag(Int?.none) + Divider() + SettingsChoiceItems( + Self.queryResultLimits.map { Optional($0) }, + including: settings.queryResultLimit ?? Self.queryResultLimits.first + ) { limit in + Text(Self.rowsTitle(limit ?? 0)) + } + } label: { + Text("Query result limit") + Text( + """ + SELECT queries without their own LIMIT stop at this many rows. The editor text never changes. \ + Fetch All and Execute Without Limit skip it once. + """ + ) } - } + .accessibilityIdentifier("data-result-limit-picker") - Section { - Picker("Results kept per run:", selection: $settings.resultSetsKeptPerRun) { - Text("No limit").tag(0) - ForEach([10, 20, 50, 100, 200, 500, 1_000], id: \.self) { count in - Text(count.formatted()).tag(count) + Picker(selection: $settings.resultSetsKeptPerRun) { + SettingsChoiceItems(Self.resultSetsKept, including: settings.resultSetsKeptPerRun) { count in + Text(Self.resultSetsKeptTitle(count)) } + } label: { + Text("Results kept per run") + Text("A run that returns more keeps only the newest. Pinned results always stay.") } + .accessibilityIdentifier("data-results-kept-picker") } header: { - Text("Multiple Results") - } footer: { - Text("A run that returns more results with rows keeps only the newest. Pinned results always stay.") + Text("Pages and Limits") + } + } + + // Limit and switch change together in one write, so neither is seen without the other. + static func queryResultLimitBinding(_ settings: Binding) -> Binding { + Binding( + get: { settings.wrappedValue.queryResultLimit }, + set: { settings.wrappedValue = settings.wrappedValue.withQueryResultLimit($0) } + ) + } + + static func rowsTitle(_ count: Int) -> String { + String(AttributedString(localized: "^[\(count) row](inflect: true)").characters) + } + + static func exactCountTitle(_ threshold: Int) -> String { + guard threshold != Int.max else { return String(localized: "Always") } + return String(AttributedString(localized: "Under ^[\(threshold) row](inflect: true)").characters) + } + + static func resultSetsKeptTitle(_ count: Int) -> String { + count == 0 ? String(localized: "No limit") : SettingsFormat.count(count) + } +} + +// Each row below follows only its own category, so a write elsewhere never redraws the grid rows. +private struct DataFontRows: View { + @ObservedObject var typography: SettingsSlice + + var body: some View { + TypographyRows(domain: .dataGrid, typography: $typography.value) + } +} + +private struct ColorValuesByTypeToggle: View { + @ObservedObject var valueColors: SettingsSlice + + var body: some View { + // ThemeValueColorsNote names this label. + Toggle(isOn: $valueColors.value.colorsValuesByType) { + Text("Color values by type") + Text("Draws strings, numbers, dates and other typed values in the theme's Values colors.") + } + .accessibilityIdentifier("color-values-by-type-toggle") + } +} + +private struct JSONViewModePicker: View { + @ObservedObject var editor: SettingsSlice + + var body: some View { + Picker("Default JSON view", selection: $editor.value.jsonViewerPreferredMode) { + Text("Text").tag(JSONViewMode.text) + Text("Tree").tag(JSONViewMode.tree) } + .accessibilityIdentifier("data-json-view-picker") } } diff --git a/apple/TablePro/Views/Settings/Sections/DataRewindSection.swift b/apple/TablePro/Views/Settings/Sections/DataRewindSection.swift index 3368e62ea7..5fb6a99b34 100644 --- a/apple/TablePro/Views/Settings/Sections/DataRewindSection.swift +++ b/apple/TablePro/Views/Settings/Sections/DataRewindSection.swift @@ -1,49 +1,104 @@ -// -// DataRewindSection.swift -// TablePro -// - import SwiftUI -struct DataRewindSection: View { +struct DataRewindPage: View { + @ObservedObject var history: SettingsSlice + let context: SettingsPaneContext @ObservedObject private var featureAccess = FeatureAccess.shared - @Binding var settings: HistorySettings + @State private var isClearing = false - private var isAvailable: Bool { - featureAccess.isAvailable(.dataRewind) + init(history: SettingsSlice, context: SettingsPaneContext) { + self.history = history + self.context = context } var body: some View { - Section("Data Rewind") { - Toggle("Keep saved changes for restoring", isOn: $settings.keepRewindHistory) - .disabled(!isAvailable) - - if isAvailable { - Text("Keeps what rows looked like before each save, on this Mac only, for 7 days. It is encrypted, and never synced.") - .font(.callout) - .foregroundStyle(.secondary) - .fixedSize(horizontal: false, vertical: true) - } else { - LicenseGateRow(feature: .dataRewind) + let isAvailable = featureAccess.isAvailable(.dataRewind) + Form { + if !isAvailable { + Section { + LicenseGateRow(feature: .dataRewind) + } } - LabeledContent("Clear saved changes") { - Button("Clear Saved Changes…") { - Task { @MainActor in - let confirmed = await AlertHelper.confirmDestructive( - title: String(localized: "Clear Saved Changes?"), - message: String( - localized: "Saves already committed stay committed. You will not be able to restore their previous values." - ), - confirmButton: String(localized: "Clear"), - cancelButton: String(localized: "Cancel") - ) - guard confirmed else { return } - Task { _ = await QueryHistoryManager.shared.clearRewindSnapshots() } - } + Section { + Toggle(isOn: Self.keepBinding($history.value, isAvailable: isAvailable)) { + Text("Keep saved changes for restoring") + Text("Keeps what rows looked like before each save, for 7 days, on this Mac only. Encrypted and never synced.") } .disabled(!isAvailable) + .accessibilityIdentifier("rewind-keep-toggle") + } + + // Never license gated: saved changes from a lapsed license can still be cleared. + Section { + LabeledContent { + Button("Clear Saved Changes…", action: confirmClear) + .disabled(isClearing) + .accessibilityIdentifier("rewind-clear-button") + } label: { + Text("Clear saved changes") + Text("Committed saves stay committed. Their previous values can no longer be restored.") + } } } + .formStyle(.grouped) + .accessibilityElement(children: .contain) + .accessibilityIdentifier(SettingsPage.dataRewind.pageIdentifier) + } + + static func isOn(_ settings: HistorySettings, isAvailable: Bool) -> Bool { + isAvailable && settings.keepRewindHistory + } + + // Reads off without a license but never writes that, so the choice returns with the license. + static func keepBinding(_ settings: Binding, isAvailable: Bool) -> Binding { + Binding( + get: { isOn(settings.wrappedValue, isAvailable: isAvailable) }, + set: { settings.wrappedValue.keepRewindHistory = $0 } + ) + } + + private func confirmClear() { + let context = context + Task { @MainActor in + let confirmed = await AlertHelper.confirmDestructive( + title: String(localized: "Clear Saved Changes?"), + message: String( + localized: "Saves already committed stay committed. You will not be able to restore their previous values." + ), + confirmButton: String(localized: "Clear"), + cancelButton: String(localized: "Cancel") + ) + guard confirmed else { return } + isClearing = true + let cleared = await SettingsClearing.run([ + { await QueryHistoryManager.shared.clearRewindSnapshots() }, + ]) + isClearing = false + if !cleared { + context.presentError( + title: String(localized: "Couldn't Clear Saved Changes"), + message: String(localized: "The saved changes couldn't be deleted. Try again.") + ) + } + } + } +} + +struct DataRewindDrillRow: View { + @ObservedObject var history: SettingsSlice + @ObservedObject private var featureAccess = FeatureAccess.shared + + init(history: SettingsSlice) { + self.history = history + } + + var body: some View { + let isOn = DataRewindPage.isOn(history.value, isAvailable: featureAccess.isAvailable(.dataRewind)) + SettingsDrillRow( + route: SettingsRoute.page(.dataRewind), + title: SettingsPage.dataRewind.title, + value: isOn ? String(localized: "On") : String(localized: "Off") + ) } } diff --git a/apple/TablePro/Views/Settings/Sections/FormatterSection.swift b/apple/TablePro/Views/Settings/Sections/FormatterSection.swift index 24ff238f25..00f39dd978 100644 --- a/apple/TablePro/Views/Settings/Sections/FormatterSection.swift +++ b/apple/TablePro/Views/Settings/Sections/FormatterSection.swift @@ -1,136 +1,166 @@ -// -// FormatterSection.swift -// TablePro -// - import AppKit import os import SwiftUI import TableProAutocomplete import UniformTypeIdentifiers -struct FormatterSection: View { - private static let logger = Logger(subsystem: "com.TablePro", category: "FormatterSection") - private static let previewMaxLines = 18 - private static let previewSQL = """ - select u.id as user_id, u.name as user_name, count(o.id) as order_count \ - from users u left join orders o on u.id = o.user_id \ - where u.status = 'active' and cast(o.created_at as date) >= '2026-01-01' \ - group by u.id, u.name order by order_count desc; - """ - private static let indentWidths = [2, 4, 8] - private static let lineWidths = [0, 80, 100, 120] +struct SQLFormattingPage: View { + private static let logger = Logger(subsystem: "com.TablePro", category: "SQLFormattingPage") + static let indentWidths = [2, 4, 8] + static let lineWidths = [80, 100, 120] - @Binding var settings: SQLFormatterSettings - let editor: EditorSettings - @ObservedObject private var themeEngine = ThemeEngine.shared + enum IndentWidthChoice: Hashable { + case editor + case fixed(Int) - @State private var isImporting = false - @State private var exportDocument: SQLFormatterRulesDocument? - @State private var importError: String? - @State private var exportError: String? + init(_ settings: SQLFormatterSettings) { + self = settings.indentFollowsTabWidth ? .editor : .fixed(settings.rules.indentWidth) + } - private enum IndentWidthChoice: Hashable { - case tabWidth - case fixed(Int) + // One whole-value write, so the follow flag and the width never land separately. + func applied(to settings: SQLFormatterSettings) -> SQLFormatterSettings { + var updated = settings + switch self { + case .editor: + updated.indentFollowsTabWidth = true + case .fixed(let width): + updated.indentFollowsTabWidth = false + updated.rules.indentWidth = width + } + return updated + } } - private enum KeywordCaseChoice: Hashable { + enum KeywordCaseChoice: Hashable { case editor case fixed(SQLFormatterCase) + + init(_ settings: SQLFormatterSettings) { + self = settings.keywordCaseFollowsEditor ? .editor : .fixed(settings.rules.keywordCase) + } + + func applied(to settings: SQLFormatterSettings) -> SQLFormatterSettings { + var updated = settings + switch self { + case .editor: + updated.keywordCaseFollowsEditor = true + case .fixed(let formatterCase): + updated.keywordCaseFollowsEditor = false + updated.rules.keywordCase = formatterCase + } + return updated + } } + @Binding var settings: SQLFormatterSettings + let editor: EditorSettings + let font: NSFont + + @State private var isImporting = false + @State private var exportDocument: SQLFormatterRulesDocument? + @State private var importError: String? + @State private var exportError: String? + var body: some View { - Section { - Picker("Indent with:", selection: $settings.rules.indentStyle) { - Text("Spaces").tag(SQLFormatterIndentStyle.spaces) - Text("Tabs").tag(SQLFormatterIndentStyle.tabs) + Form { + Section { + FormatterPreview(options: settings.options(for: editor), font: font) + .equatable() } - Picker("Indent width:", selection: indentWidthChoice) { - Text(String(format: String(localized: "Tab width (%d)"), editor.clampedTabWidth)) - .tag(IndentWidthChoice.tabWidth) - ForEach(Self.options(Self.indentWidths, including: settings.rules.indentWidth), id: \.self) { width in - Text(String(format: String(localized: "%d spaces"), width)).tag(IndentWidthChoice.fixed(width)) + + Section { + Picker("Indent with", selection: $settings.rules.indentStyle) { + Text("Spaces").tag(SQLFormatterIndentStyle.spaces) + Text("Tabs").tag(SQLFormatterIndentStyle.tabs) } + .accessibilityIdentifier("formatter-indent-style") + indentWidthPicker + } header: { + Text("Indentation") } - Picker("Keyword case:", selection: keywordCaseChoice) { - Text(String(format: String(localized: "Same as editor (%@)"), caseName(editorKeywordCase))) - .tag(KeywordCaseChoice.editor) - ForEach(SQLFormatterCase.allCases, id: \.self) { formatterCase in - Text(caseName(formatterCase)).tag(KeywordCaseChoice.fixed(formatterCase)) + + Section { + keywordCasePicker + Picker("Functions", selection: $settings.rules.functionCase) { + caseItems } - } - Picker("Function case:", selection: $settings.rules.functionCase) { - ForEach(SQLFormatterCase.allCases, id: \.self) { formatterCase in - Text(caseName(formatterCase)).tag(formatterCase) + .accessibilityIdentifier("formatter-function-case") + Picker(selection: $settings.rules.dataTypeCase) { + caseItems + } label: { + Text("Data types") + Text("Engines that match function and type names by exact case, such as ClickHouse, keep the case you typed.") } + .accessibilityIdentifier("formatter-data-type-case") + } header: { + Text("Case") } - .help(Text("Engines that match function names by exact case, such as ClickHouse, keep the case you typed.")) - Picker("Data type case:", selection: $settings.rules.dataTypeCase) { - ForEach(SQLFormatterCase.allCases, id: \.self) { formatterCase in - Text(caseName(formatterCase)).tag(formatterCase) + + Section { + lineWidthPicker + Picker(selection: $settings.rules.clauseItems) { + Text("Beside the keyword").tag(SQLFormatterClauseItems.sameLine) + Text("Below the keyword").tag(SQLFormatterClauseItems.newLine) + } label: { + Text("Clause items") + Text("Where a broken SELECT, SET, WITH, WHERE or HAVING list starts. A single item stays beside its keyword.") } - } - .help(Text("Engines that match type names by exact case, such as ClickHouse, keep the case you typed.")) - Picker("Commas:", selection: $settings.rules.commaPosition) { - Text("At the end of the line").tag(SQLFormatterCommaPosition.trailing) - Text("At the start of the line").tag(SQLFormatterCommaPosition.leading) - } - Picker("AND and OR:", selection: $settings.rules.logicalOperatorNewline) { - Text("At the start of the line").tag(SQLFormatterLogicalOperatorNewline.before) - Text("At the end of the line").tag(SQLFormatterLogicalOperatorNewline.after) - } - .help(Text("Where AND and OR go when a WHERE or HAVING condition breaks across lines.")) - Picker("Line width:", selection: $settings.rules.lineWidth) { - ForEach(Self.options(Self.lineWidths, including: settings.rules.lineWidth), id: \.self) { width in - Text(lineWidthName(width)).tag(width) + .accessibilityIdentifier("formatter-clause-items") + Picker("Commas", selection: $settings.rules.commaPosition) { + Text("At the end of the line").tag(SQLFormatterCommaPosition.trailing) + Text("At the start of the line").tag(SQLFormatterCommaPosition.leading) } + .accessibilityIdentifier("formatter-commas") + Picker(selection: $settings.rules.logicalOperatorNewline) { + Text("At the start of the line").tag(SQLFormatterLogicalOperatorNewline.before) + Text("At the end of the line").tag(SQLFormatterLogicalOperatorNewline.after) + } label: { + Text("AND and OR") + Text("Where they go when a WHERE or HAVING condition breaks.") + } + .accessibilityIdentifier("formatter-logical-operators") + Picker("Join condition", selection: $settings.rules.joinCondition) { + Text("On its own line").tag(SQLFormatterJoinCondition.newLine) + Text("On the JOIN line").tag(SQLFormatterJoinCondition.sameLine) + } + .accessibilityIdentifier("formatter-join-condition") + Toggle(isOn: $settings.rules.alignAliases) { + Text("Align column aliases") + Text("Lines up the AS of each SELECT item that sits on one line.") + } + .accessibilityIdentifier("formatter-align-aliases") + } header: { + Text("Line Breaks") } - .help(Text("A SELECT list, SET list or WHERE condition that fits in this width stays on one line.")) - Picker("Clause items:", selection: $settings.rules.clauseItems) { - Text("Beside the keyword").tag(SQLFormatterClauseItems.sameLine) - Text("Below the keyword").tag(SQLFormatterClauseItems.newLine) - } - .help(Text(""" - Where the items of a SELECT list, SET list, WITH list, or WHERE or HAVING condition start once it \ - breaks across lines. A single item stays beside its keyword. - """)) - Picker("Join condition:", selection: $settings.rules.joinCondition) { - Text("On its own line").tag(SQLFormatterJoinCondition.newLine) - Text("On the JOIN line").tag(SQLFormatterJoinCondition.sameLine) + + Section { + LabeledContent { + HStack(spacing: 8) { + importButton + exportButton + } + } label: { + Text("Rules file") + Text("A .sql-formatter.json in a linked SQL folder replaces these rules for files opened from that folder.") + } + } header: { + Text("Rules File") } - Toggle("Align column aliases", isOn: $settings.rules.alignAliases) - - preview - - LabeledContent("Rules file:") { - HStack { - Button("Import…") { isImporting = true } - .fileImporter(isPresented: $isImporting, allowedContentTypes: [.json]) { result in - importRules(result) - } - Button("Export…") { exportRules() } - .fileExporter( - isPresented: isExporting, - document: exportDocument, - contentType: .json, - defaultFilename: SQLFormatterRulesFile.exportFileName - ) { result in - if case .failure(let error) = result, (error as? CocoaError)?.code != .userCancelled { - reportExportFailure(error) - } - } - Button("Restore Defaults") { settings = .default } + + Section { + LabeledContent { + Button(String(localized: "Restore Defaults")) { settings = .default } .disabled(settings == .default) + .accessibilityIdentifier("formatter-restore-defaults") + } label: { + Text("Restore default rules") + Text("Returns every rule on this page to its default.") } } - } header: { - Text("Formatter") - } footer: { - Text("A .sql-formatter.json in a linked SQL folder replaces these rules for the files opened from that folder.") - .font(.caption) - .foregroundStyle(.secondary) } + .formStyle(.grouped) + .accessibilityElement(children: .contain) + .accessibilityIdentifier(SettingsPage.sqlFormatting.pageIdentifier) .alert( String(localized: "Couldn't Import Formatter Rules"), isPresented: isShowingImportError, @@ -138,7 +168,7 @@ struct FormatterSection: View { ) { _ in Button(String(localized: "OK")) {} } message: { message in - Text(message) + Text(verbatim: message) } .alert( String(localized: "Couldn't Export Formatter Rules"), @@ -147,88 +177,103 @@ struct FormatterSection: View { ) { _ in Button(String(localized: "OK")) {} } message: { message in - Text(message) + Text(verbatim: message) } } - // MARK: - Preview + private var indentWidthPicker: some View { + let widths = SettingsChoices.options(Self.indentWidths, including: settings.rules.indentWidth) + return Picker("Indent width", selection: indentWidthChoice) { + Text("Same as editor (\(editor.clampedTabWidth))").tag(IndentWidthChoice.editor) + Divider() + ForEach(widths.fixed, id: \.self) { width in + indentWidthTitle(width).tag(IndentWidthChoice.fixed(width)) + } + if let extra = widths.extra { + Divider() + indentWidthTitle(extra).tag(IndentWidthChoice.fixed(extra)) + } + } + .accessibilityIdentifier("formatter-indent-width") + } - private var previewText: String { - let formatted = try? SQLFormatterService().format( - Self.previewSQL, - dialect: .mysql, - options: settings.options(for: editor) - ) - return formatted?.formattedSQL ?? Self.previewSQL + // A tab counts as indent width columns when a line's width is measured. + private func indentWidthTitle(_ width: Int) -> Text { + settings.rules.indentStyle == .tabs + ? Text("^[\(width) column](inflect: true)") + : Text("^[\(width) space](inflect: true)") } - // Unwrapped, since a wrapped preview would hide the line breaks the line width decides. - private var preview: some View { - let text = previewText - let lineCount = min(text.split(separator: "\n", omittingEmptySubsequences: false).count, Self.previewMaxLines) - let lineHeight = NSLayoutManager().defaultLineHeight(for: themeEngine.editorFonts.font) - return HighlightedSQLTextView( - sql: text, - databaseType: .mysql, - accessibilityIdentifier: "formatter-preview" - ) - .frame(height: CGFloat(lineCount) * lineHeight + Self.previewChromeHeight) - .clipShape(RoundedRectangle(cornerRadius: 6)) - .overlay( - RoundedRectangle(cornerRadius: 6) - .stroke(Color(nsColor: .separatorColor), lineWidth: 0.5) - ) + private var keywordCasePicker: some View { + Picker("Keywords", selection: keywordCaseChoice) { + Text("Same as editor (\(Self.caseName(editorKeywordCase)))").tag(KeywordCaseChoice.editor) + Divider() + ForEach(SQLFormatterCase.allCases, id: \.self) { formatterCase in + Text(verbatim: Self.caseName(formatterCase)).tag(KeywordCaseChoice.fixed(formatterCase)) + } + } + .accessibilityIdentifier("formatter-keyword-case") } - // The text view's top and bottom inset, plus a legacy horizontal scroller when one takes room. - private static var previewChromeHeight: CGFloat { - let scroller = NSScroller.preferredScrollerStyle == .legacy - ? NSScroller.scrollerWidth(for: .regular, scrollerStyle: .legacy) - : 0 - return 24 + scroller + private var caseItems: some View { + ForEach(SQLFormatterCase.allCases, id: \.self) { formatterCase in + Text(verbatim: Self.caseName(formatterCase)).tag(formatterCase) + } } - // MARK: - Bindings + private var lineWidthPicker: some View { + let widths = Self.lineWidthOptions(including: settings.rules.lineWidth) + return Picker(selection: $settings.rules.lineWidth) { + Text("One item per line").tag(0) + Divider() + ForEach(widths.fixed, id: \.self) { width in + Text("^[\(width) character](inflect: true)").tag(width) + } + if let extra = widths.extra { + Divider() + Text("^[\(extra) character](inflect: true)").tag(extra) + } + } label: { + Text("Line width") + Text("A SELECT list, SET list or WHERE condition that fits stays on one line.") + } + .accessibilityIdentifier("formatter-line-width") + } - private var indentWidthChoice: Binding { - Binding( - get: { - settings.indentFollowsTabWidth - ? .tabWidth - : .fixed(settings.rules.indentWidth) - }, - set: { choice in - var formatter = settings - switch choice { - case .tabWidth: - formatter.indentFollowsTabWidth = true - case .fixed(let width): - formatter.indentFollowsTabWidth = false - formatter.rules.indentWidth = width + private var importButton: some View { + Button(String(localized: "Import…")) { isImporting = true } + .fileImporter(isPresented: $isImporting, allowedContentTypes: [.json]) { result in + importRules(result) + } + .accessibilityIdentifier("formatter-import") + } + + private var exportButton: some View { + Button(String(localized: "Export…")) { exportRules() } + .fileExporter( + isPresented: isExporting, + document: exportDocument, + contentType: .json, + defaultFilename: SQLFormatterRulesFile.exportFileName + ) { result in + if case .failure(let error) = result, (error as? CocoaError)?.code != .userCancelled { + reportExportFailure(error) } - settings = formatter } + .accessibilityIdentifier("formatter-export") + } + + private var indentWidthChoice: Binding { + Binding( + get: { IndentWidthChoice(settings) }, + set: { settings = $0.applied(to: settings) } ) } private var keywordCaseChoice: Binding { Binding( - get: { - settings.keywordCaseFollowsEditor - ? .editor - : .fixed(settings.rules.keywordCase) - }, - set: { choice in - var formatter = settings - switch choice { - case .editor: - formatter.keywordCaseFollowsEditor = true - case .fixed(let formatterCase): - formatter.keywordCaseFollowsEditor = false - formatter.rules.keywordCase = formatterCase - } - settings = formatter - } + get: { KeywordCaseChoice(settings) }, + set: { settings = $0.applied(to: settings) } ) } @@ -244,8 +289,6 @@ struct FormatterSection: View { Binding(get: { exportError != nil }, set: { if !$0 { exportError = nil } }) } - // MARK: - Import and export - private func importRules(_ result: Result) { guard case .success(let url) = result else { return } let isScoped = url.startAccessingSecurityScopedResource() @@ -272,13 +315,11 @@ struct FormatterSection: View { exportError = error.localizedDescription } - // MARK: - Labels - private var editorKeywordCase: SQLFormatterCase { editor.keywordCase.prefersUppercase ? .upper : .lower } - private func caseName(_ formatterCase: SQLFormatterCase) -> String { + static func caseName(_ formatterCase: SQLFormatterCase) -> String { switch formatterCase { case .upper: return String(localized: "UPPERCASE") case .lower: return String(localized: "lowercase") @@ -286,15 +327,67 @@ struct FormatterSection: View { } } - private func lineWidthName(_ width: Int) -> String { - width == 0 - ? String(localized: "One item per line") - : String(format: String(localized: "%d characters"), width) + // 0 is "One item per line", listed on its own above the widths. + static func lineWidthOptions(including current: Int) -> (fixed: [Int], extra: Int?) { + current == 0 ? (lineWidths, nil) : SettingsChoices.options(lineWidths, including: current) + } +} + +// Formats the sample only when its options or font change; other writes and theme ticks skip the body. +struct FormatterPreview: View, Equatable { + static let maxLines = 12 + static let sampleSQL = """ + select u.id as user_id, u.name as user_name, count(o.id) as order_count \ + from users u left join orders o on u.id = o.user_id \ + where u.status = 'active' and cast(o.created_at as date) >= '2026-01-01' \ + group by u.id, u.name order by order_count desc; + """ + + let options: SQLFormatterOptions + let font: NSFont + + static func == (lhs: FormatterPreview, rhs: FormatterPreview) -> Bool { + lhs.options == rhs.options && lhs.font == rhs.font + } + + // Unwrapped, since a wrapped preview would hide the line breaks the line width decides. + var body: some View { + let text = Self.formattedSample(options: options) + HighlightedSQLTextView( + sql: text, + databaseType: .mysql, + accessibilityIdentifier: "formatter-preview", + accessibilityLabel: String(localized: "Formatted preview"), + lineLayout: .unwrapped + ) + .frame(height: Self.height(lineCount: Self.lineCount(of: text), font: font)) + .clipShape(RoundedRectangle(cornerRadius: 6)) + .overlay( + RoundedRectangle(cornerRadius: 6) + .stroke(Color(nsColor: .separatorColor), lineWidth: 0.5) + ) + } + + static func formattedSample(options: SQLFormatterOptions) -> String { + let formatted = try? SQLFormatterService().format(sampleSQL, dialect: .mysql, options: options) + return formatted?.formattedSQL ?? sampleSQL + } + + static func lineCount(of text: String) -> Int { + text.split(separator: "\n", omittingEmptySubsequences: false).count } - // A value from an imported file that the picker does not offer still shows as selected. - private static func options(_ values: [Int], including current: Int) -> [Int] { - values.contains(current) ? values : (values + [current]).sorted() + static func height(lineCount: Int, font: NSFont) -> CGFloat { + let lineHeight = NSLayoutManager().defaultLineHeight(for: font) + return CGFloat(min(max(lineCount, 1), maxLines)) * lineHeight + chromeHeight + } + + // The text view's top and bottom inset, plus a legacy horizontal scroller when one takes room. + static var chromeHeight: CGFloat { + let scroller = NSScroller.preferredScrollerStyle == .legacy + ? NSScroller.scrollerWidth(for: .regular, scrollerStyle: .legacy) + : 0 + return 24 + scroller } } diff --git a/apple/TablePro/Views/Settings/Sections/HistorySection.swift b/apple/TablePro/Views/Settings/Sections/HistorySection.swift index 222f8a544f..2f37ec8c28 100644 --- a/apple/TablePro/Views/Settings/Sections/HistorySection.swift +++ b/apple/TablePro/Views/Settings/Sections/HistorySection.swift @@ -1,59 +1,118 @@ -// -// HistorySection.swift -// TablePro -// - import SwiftUI -struct HistorySection: View { - @Binding var settings: HistorySettings +struct QueryHistorySettingsPage: View { + static let maxEntries = [100, 500, 1_000, 5_000, 10_000, 0] + static let retentionDays = [7, 30, 90, 365, 0] + + @ObservedObject var history: SettingsSlice + let context: SettingsPaneContext + @State private var isClearing = false + + init(history: SettingsSlice, context: SettingsPaneContext) { + self.history = history + self.context = context + } var body: some View { - Section("Query History") { - Picker("Maximum entries:", selection: $settings.maxEntries) { - Text("100").tag(100) - Text("500").tag(500) - Text("1,000").tag(1_000) - Text("5,000").tag(5_000) - Text("10,000").tag(10_000) - Text("Unlimited").tag(0) - } + Form { + Section { + Toggle(isOn: $history.value.autoCleanup) { + Text("Remove old entries automatically") + Text( + """ + Removes entries past these limits at launch, every 100 queries and when a limit changes. \ + Removed entries can't be recovered. + """ + ) + } + .accessibilityIdentifier("history-auto-cleanup-toggle") - Picker("Keep entries for:", selection: $settings.maxDays) { - Text("7 days").tag(7) - Text("30 days").tag(30) - Text("90 days").tag(90) - Text("1 year").tag(365) - Text("Forever").tag(0) - } + Picker("Maximum entries", selection: $history.value.maxEntries) { + SettingsChoiceItems(Self.maxEntries, including: history.value.maxEntries) { count in + Text(Self.maxEntriesTitle(count)) + } + } + .disabled(!history.value.autoCleanup) + .accessibilityIdentifier("history-max-entries-picker") - Toggle("Auto cleanup", isOn: $settings.autoCleanup) - - LabeledContent("Clear all query history") { - Button("Clear History…") { - Task { @MainActor in - let confirmed = await AlertHelper.confirmDestructive( - title: String(localized: "Clear All History?"), - message: String( - localized: """ - This will permanently delete all query history entries, the saved changes kept \ - for restoring, and the earlier versions of your query tabs. This action cannot \ - be undone. - """ - ), - confirmButton: String(localized: "Clear"), - cancelButton: String(localized: "Cancel") - ) - if confirmed { - Task { - _ = await QueryHistoryManager.shared.clearEverything() - _ = await QueryHistoryManager.shared.clearRewindSnapshots() - _ = await QueryTabVersionStorage.shared.removeAll() - } - } + // Stays enabled while cleanup is off: it also bounds how long query tab versions are kept. + Picker(selection: $history.value.maxDays) { + SettingsChoiceItems(Self.retentionDays, including: history.value.maxDays) { days in + Text(Self.retentionTitle(days)) } + } label: { + Text("Keep entries for") + Text("Earlier versions of query tabs are kept this long too, up to 30 days.") + } + .accessibilityIdentifier("history-max-days-picker") + } + + Section { + LabeledContent { + Button("Clear History…", action: confirmClear) + .disabled(isClearing) + .accessibilityIdentifier("history-clear-button") + } label: { + Text("Clear query history") + Text("Also deletes saved changes kept for Data Rewind and earlier versions of query tabs.") } } } + .formStyle(.grouped) + .accessibilityElement(children: .contain) + .accessibilityIdentifier(SettingsPage.queryHistory.pageIdentifier) + } + + static func maxEntriesTitle(_ count: Int) -> String { + count == 0 ? String(localized: "No limit") : SettingsFormat.count(count) + } + + static func retentionTitle(_ days: Int) -> String { + days == 0 ? String(localized: "Forever") : SettingsFormat.days(days) + } + + private func confirmClear() { + let context = context + Task { @MainActor in + let confirmed = await AlertHelper.confirmDestructive( + title: String(localized: "Clear All History?"), + message: String( + localized: """ + This will permanently delete all query history entries, the saved changes kept \ + for restoring, and the earlier versions of your query tabs. This action cannot \ + be undone. + """ + ), + confirmButton: String(localized: "Clear"), + cancelButton: String(localized: "Cancel") + ) + guard confirmed else { return } + isClearing = true + let cleared = await SettingsClearing.run([ + { await QueryHistoryManager.shared.clearEverything() }, + { await QueryHistoryManager.shared.clearRewindSnapshots() }, + { await QueryTabVersionStorage.shared.removeAll() }, + ]) + isClearing = false + if !cleared { + context.presentError( + title: String(localized: "Couldn't Clear Query History"), + message: String(localized: "Part of the history couldn't be deleted. Try again.") + ) + } + } + } +} + +enum SettingsClearing { + // Every step runs even after one fails, so a failed history delete still clears the rest. + @MainActor + static func run(_ steps: [@MainActor () async -> Bool]) async -> Bool { + var cleared = true + for step in steps { + let succeeded = await step() + cleared = cleared && succeeded + } + return cleared } } diff --git a/apple/TablePro/Views/Settings/Sections/MCPGrantListView.swift b/apple/TablePro/Views/Settings/Sections/MCPGrantListView.swift index 55efe881c7..b073b94f20 100644 --- a/apple/TablePro/Views/Settings/Sections/MCPGrantListView.swift +++ b/apple/TablePro/Views/Settings/Sections/MCPGrantListView.swift @@ -1,47 +1,91 @@ -// -// MCPGrantListView.swift -// TablePro -// - import SwiftUI import TableProMCP -/// The approvals the user has already given, so a remembered answer stays visible and revocable. +// The Approved Connections page: a remembered answer stays visible here and can be forgotten. struct MCPGrantListView: View { - @ObservedObject private var mcpServerManager = MCPServerManager.shared - @State private var grants: [MCPConnectionGrant] = [] - @State private var connectionNames: [UUID: String] = [:] - @State private var tokenNames: [UUID: String] = [:] + @ObservedObject var model: MCPSettingsModel + let approval: MCPConnectionApproval + + @State private var isConfirmingForgetAll = false var body: some View { - Group { - if grants.isEmpty { - Text("No connections are approved yet.") - .foregroundStyle(.secondary) - } else { - ForEach(grants) { grant in - LabeledContent { - Button(String(localized: "Forget")) { - forget(grant) - } - } label: { - Text(name(for: grant)) - if let client = Self.clientName(forSubject: grant.subject, tokenNames: tokenNames) { - Text(client) + Form { + if approval != .oncePerConnection { + Section { + SettingsHelpRow(String( + format: String(localized: "Approval is set to “%@”, so these approvals are not used now. They apply again if you choose Ask Once for Each Connection."), + approval.displayName + )) + } + } + + Section { + if model.grants.isEmpty { + if model.hasLoadedGrants { + Text("No approved connections. A connection a client may reach without asking again appears here.") + .foregroundStyle(.secondary) + } + } else { + ForEach(model.grants) { grant in + row(grant) + } + } + } footer: { + if !model.grants.isEmpty { + SettingsSectionActions { + Button(String(localized: "Forget All…"), role: .destructive) { + isConfirmingForgetAll = true } + .accessibilityIdentifier("mcp-grants-forget-all") } } + } + } + .formStyle(.grouped) + .accessibilityElement(children: .contain) + .accessibilityIdentifier(SettingsPage.mcpApprovals.pageIdentifier) + .alert(String(localized: "Forget All Approvals?"), isPresented: $isConfirmingForgetAll) { + Button(String(localized: "Forget All"), role: .destructive) { + Task { await model.forgetEveryGrant() } + } + Button(String(localized: "Cancel"), role: .cancel) {} + } message: { + Text("Clients ask again the next time they reach a connection.") + } + } - Button(String(localized: "Forget All"), role: .destructive) { - forgetAll() - } + private func row(_ grant: MCPConnectionGrant) -> some View { + let connection = model.connectionNames[grant.connectionId] ?? String(localized: "Deleted connection") + let client = Self.clientName(forSubject: grant.subject, tokenNames: model.tokenNames) + let forgetLabel = client.map { + String(format: String(localized: "Forget %1$@ for %2$@"), connection, $0) + } ?? String(format: String(localized: "Forget %@"), connection) + return LabeledContent { + Button(String(localized: "Forget")) { + forget(grant) } + .accessibilityLabel(forgetLabel) + } label: { + Text(verbatim: connection) + Text(verbatim: Self.detail(client: client, grantedAt: grant.grantedAt)) } - .task { await refresh() } + .contextMenu { + Button(String(localized: "Forget")) { + forget(grant) + } + } + } + + private func forget(_ grant: MCPConnectionGrant) { + Task { await model.forgetGrant(grant) } } - private func name(for grant: MCPConnectionGrant) -> String { - connectionNames[grant.connectionId] ?? String(localized: "Deleted connection") + private static func detail(client: String?, grantedAt: Date) -> String { + let date = grantedAt.formatted(date: .abbreviated, time: .omitted) + guard let client else { + return String(format: String(localized: "Approved %@"), date) + } + return String(format: String(localized: "%1$@, approved %2$@"), client, date) } // Two clients approved for one connection would otherwise show as two identical rows. @@ -55,29 +99,4 @@ struct MCPGrantListView: View { return UUID(uuidString: subject).flatMap { tokenNames[$0] }.map(IntegrationsFormatting.displayTokenName) } } - - private func forget(_ grant: MCPConnectionGrant) { - Task { - await MCPServerManager.shared.forgetGrant(subject: grant.subject, connectionId: grant.connectionId) - await refresh() - } - } - - private func forgetAll() { - Task { - await MCPServerManager.shared.forgetEveryGrant() - await refresh() - } - } - - private func refresh() async { - grants = await mcpServerManager.connectionGrants() - .sorted { $0.grantedAt > $1.grantedAt } - connectionNames = Dictionary( - ConnectionStorage.shared.loadConnections().map { ($0.id, $0.name) }, - uniquingKeysWith: { first, _ in first } - ) - let tokens = await mcpServerManager.tokenStore?.list() ?? [] - tokenNames = Dictionary(tokens.map { ($0.id, $0.name) }, uniquingKeysWith: { first, _ in first }) - } } diff --git a/apple/TablePro/Views/Settings/Sections/MCPOutsideServerSheet.swift b/apple/TablePro/Views/Settings/Sections/MCPOutsideServerSheet.swift index c957e0ccbf..4cb1c71ac6 100644 --- a/apple/TablePro/Views/Settings/Sections/MCPOutsideServerSheet.swift +++ b/apple/TablePro/Views/Settings/Sections/MCPOutsideServerSheet.swift @@ -1,140 +1,237 @@ -// -// MCPOutsideServerSheet.swift -// TablePro -// - +import AppKit import SwiftUI import TableProMCP -/// Adds or edits one outside MCP server, and says which connections may reach it. -/// -/// The allowlist is in the same sheet as the address rather than behind a second screen, because a -/// server with no connections allowed does nothing and a reader who does not see the list has no -/// reason to look for it. Nothing is written until Save: Test uses the token typed into the field, -/// so checking an address you got wrong does not leave a server in the list you never meant to add. +// The allowlist sits beside the address: a server allowed on no connection does nothing. Nothing is written until Save. internal struct MCPOutsideServerSheet: View { internal let server: MCPServerConfiguration? + private enum TestState: Equatable { + case idle + case running + case succeeded(toolCount: Int) + case failed(message: String) + } + @Environment(\.dismiss) private var dismiss - @ObservedObject private var store = MCPServerStore.shared + @State private var newServerId = UUID() @State private var name = "" @State private var endpointText = "" @State private var token = "" @State private var allowedConnectionIds: Set = [] - @State private var validationError: MCPServerConfigurationError? + @State private var saveError: MCPServerSaveError? @State private var testState: TestState = .idle + @State private var testTask: Task? @State private var connections: [DatabaseConnection] = [] - - private enum TestState: Equatable { - case idle - case running - case succeeded(toolCount: Int) - case failed(message: String) - } + @State private var hasLoaded = false + @State private var isConfirmingRemoval = false var body: some View { - VStack(alignment: .leading, spacing: 0) { + VStack(spacing: 0) { Form { serverSection - connectionsSection + allowedOnSection } .formStyle(.grouped) Divider() - buttonBar + + footer + .padding() } - .frame(width: 520, height: 520) + .frame(width: 520, height: Self.height) .onAppear(perform: load) + .onDisappear { + testTask?.cancel() + } + .onChange(of: name) { _ in resetFeedback() } + .onChange(of: endpointText) { _ in resetFeedback() } + .onChange(of: token) { _ in resetFeedback() } + .alert(String(localized: "Remove Server?"), isPresented: $isConfirmingRemoval) { + Button(String(localized: "Remove"), role: .destructive, action: remove) + Button(String(localized: "Cancel"), role: .cancel) {} + } message: { + Text(String( + format: String(localized: "“%@” and its token are removed from this Mac. Sessions lose its tools."), + server?.name ?? "" + )) + } + } + + private static var height: CGFloat { + min(560, (NSScreen.main?.visibleFrame.height ?? 640) - 80) } private var serverSection: some View { Section { - TextField(String(localized: "Name"), text: $name) - TextField(String(localized: "Address"), text: $endpointText, prompt: Text(verbatim: "https://example.com/mcp")) - .autocorrectionDisabled() - SecureField(String(localized: "Token"), text: $token, prompt: tokenPrompt) - - HStack(spacing: 8) { - Button(String(localized: "Test"), action: runTest) - .disabled(testState == .running || token.isEmpty) - DelayedProgressIndicator(isActive: testState == .running) + TextField(text: $name, prompt: nil) { + Text("Name") + if let nameError { + NoticeLabel(nameError, severity: .error) + } + } + .accessibilityIdentifier("mcp-outside-server-name") + + TextField(text: $endpointText, prompt: Text(verbatim: "https://example.com/mcp")) { + Text("Address") + if let addressError { + NoticeLabel(addressError, severity: .error) + } + } + .autocorrectionDisabled() + .accessibilityIdentifier("mcp-outside-server-address") + + SecureField(text: $token, prompt: tokenPrompt) { + Text("Token") + if let tokenError { + NoticeLabel(tokenError, severity: .error) + } + } + .accessibilityIdentifier("mcp-outside-server-token") + + LabeledContent { + HStack(spacing: 8) { + DelayedProgressIndicator(isActive: testState == .running) + .accessibilityHidden(true) + Button(String(localized: "Test"), action: runTest) + .disabled(testState == .running || !canTest) + .accessibilityIdentifier("mcp-outside-server-test") + } + } label: { + Text("Connection test") testResult - Spacer(minLength: 0) } + + SettingsHelpRow("The address has to be HTTPS unless the server runs on this Mac. The token is kept in your Keychain and never synced.") } header: { Text("Server") - } footer: { - if let validationError { - NoticeLabel(message(for: validationError), severity: .error) - .font(.caption) - } else { - Text("The address has to be HTTPS unless the server runs on this Mac. The token is kept in your Keychain and never synced.") - .font(.caption) - .foregroundStyle(.secondary) - } } } @ViewBuilder private var testResult: some View { switch testState { - case .idle, .running: + case .idle: EmptyView() + case .running: + Text("Testing…") case .succeeded(let toolCount): - Text(toolCount == 1 - ? String(localized: "Answered with 1 tool.") - : String(format: String(localized: "Answered with %d tools."), toolCount)) - .font(.callout) - .foregroundStyle(.secondary) + Text("Answered with ^[\(toolCount) tool](inflect: true).") case .failed(let message): NoticeLabel(message, severity: .error) - .font(.callout) - .lineLimit(2) } } - private var connectionsSection: some View { + private var allowedOnSection: some View { Section { - if connections.isEmpty { - Text("No connections saved yet.") - .foregroundStyle(.secondary) - } else { - ForEach(connections) { connection in - Toggle(connection.name, isOn: binding(for: connection.id)) - } - } + ConnectionAllowlistSection( + selection: $allowedConnectionIds, + connections: connections, + showsSelectAll: false + ) + + // swiftlint:disable:next line_length + SettingsHelpRow("A session can call this server's tools only from a connection you tick. It is offered on no others, and a tool it once saw cannot be called by name from one.") } header: { Text("Allowed On") - } footer: { - Text("A session can call this server's tools only from a connection you tick. It is offered on no others, and a tool it once saw cannot be called by name from one.") - .font(.caption) - .foregroundStyle(.secondary) } } - private var buttonBar: some View { - HStack { - Spacer() - Button(String(localized: "Cancel"), role: .cancel) { dismiss() } - .keyboardShortcut(.cancelAction) + private var footer: some View { + DialogFooter { + if server != nil { + Button(String(localized: "Remove Server…"), role: .destructive) { + isConfirmingRemoval = true + } + .accessibilityIdentifier("mcp-outside-server-remove") + } + } actions: { + Button(String(localized: "Cancel"), role: .cancel) { + dismiss() + } + .keyboardShortcut(.cancelAction) + Button(String(localized: "Save"), action: save) .keyboardShortcut(.defaultAction) - .disabled(name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || endpointText.isEmpty) + .disabled(!canSave) + .accessibilityIdentifier("mcp-outside-server-save") } - .padding(16) } - /// An existing server's token is not read back into the field. The Keychain has it, the sheet - /// does not need it, and putting a live credential into a text field so it can be typed over is - /// how one ends up in a screenshot. + // The saved token is never read back into the field, so it cannot end up in a screenshot. private var tokenPrompt: Text { - server == nil - ? Text(String(localized: "Required")) - : Text(String(localized: "Leave blank to keep the saved token")) + keepsSavedToken + ? Text("Leave blank to keep the saved token") + : Text("Required") + } + + private var trimmedName: String { + name.trimmingCharacters(in: .whitespacesAndNewlines) + } + + private var trimmedEndpoint: String { + endpointText.trimmingCharacters(in: .whitespacesAndNewlines) + } + + private var typedEndpoint: URL? { + trimmedEndpoint.isEmpty ? nil : URL(string: trimmedEndpoint) + } + + // The saved token goes only where it was saved for: the same scheme, host and port. + private var keepsSavedToken: Bool { + guard let server, let typedEndpoint else { return false } + return MCPServerStore.sharesOrigin(server.endpoint, typedEndpoint) + } + + private var canTest: Bool { + !trimmedEndpoint.isEmpty && (!token.isEmpty || keepsSavedToken) + } + + private var canSave: Bool { + !trimmedName.isEmpty && !trimmedEndpoint.isEmpty && (!token.isEmpty || keepsSavedToken) + } + + private var nameError: String? { + guard case .invalid(let error)? = saveError else { return nil } + switch error { + case .emptyName: + return String(localized: "Give the server a name.") + case .reservedName: + return String(localized: "That name belongs to TablePro's own tools. Choose another.") + case .invalidEndpoint, .insecureEndpoint, .credentialsInEndpoint: + return nil + } + } + + private var addressError: String? { + guard case .invalid(let error)? = saveError else { return nil } + switch error { + case .invalidEndpoint: + return String(localized: "That is not an HTTP address.") + case .insecureEndpoint: + return String(localized: "A server on another machine has to be HTTPS.") + case .credentialsInEndpoint: + return String(localized: "Put the credential in the Token field, not in the address.") + case .emptyName, .reservedName: + return nil + } + } + + private var tokenError: String? { + switch saveError { + case .tokenRequired?: + return String(localized: "Type the server's token. A saved token stays with the address it was saved for.") + case .tokenNotSaved?: + return String(localized: "TablePro could not save the token to the Keychain, so the server was not saved. Try again.") + case .invalid?, nil: + return nil + } } private func load() { + guard !hasLoaded else { return } + hasLoaded = true connections = ConnectionStorage.shared.loadConnections() .sorted { $0.name.localizedStandardCompare($1.name) == .orderedAscending } guard let server else { return } @@ -143,44 +240,45 @@ internal struct MCPOutsideServerSheet: View { allowedConnectionIds = server.allowedConnectionIds } - private func binding(for connectionId: UUID) -> Binding { - Binding( - get: { allowedConnectionIds.contains(connectionId) }, - set: { isOn in - if isOn { - allowedConnectionIds.insert(connectionId) - } else { - allowedConnectionIds.remove(connectionId) - } - } - ) + private func resetFeedback() { + testTask?.cancel() + testTask = nil + testState = .idle + saveError = nil } - private func draft() -> MCPServerConfiguration { - MCPServerConfiguration( - id: server?.id ?? UUID(), - name: name.trimmingCharacters(in: .whitespacesAndNewlines), - endpoint: URL(string: endpointText.trimmingCharacters(in: .whitespacesAndNewlines)) - ?? URL(fileURLWithPath: "/"), + private func draft() -> MCPServerConfiguration? { + guard let typedEndpoint else { return nil } + return MCPServerConfiguration( + id: server?.id ?? newServerId, + name: trimmedName, + endpoint: typedEndpoint, allowedConnectionIds: allowedConnectionIds ) } private func runTest() { - let configuration = draft() + guard let configuration = draft() else { + saveError = .invalid(.invalidEndpoint) + return + } if let error = MCPServerConfigurationValidator.validate( name: configuration.name, - endpoint: URL(string: endpointText.trimmingCharacters(in: .whitespacesAndNewlines)) + endpoint: configuration.endpoint ) { - validationError = error - testState = .idle + saveError = .invalid(error) return } - validationError = nil + guard let probeToken = probeToken() else { + testState = .failed(message: String(localized: "TablePro could not read the saved token. Type it to test.")) + return + } + saveError = nil testState = .running - let probeToken = token - Task { @MainActor in + testTask?.cancel() + testTask = Task { let result = await MCPRemoteToolCoordinator.shared.probe(configuration, token: probeToken) + guard !Task.isCancelled else { return } switch result { case .success(let tools): testState = .succeeded(toolCount: tools.count) @@ -190,27 +288,29 @@ internal struct MCPOutsideServerSheet: View { } } + // Read at the click, never in the body: the typed token first, else the saved one for the saved origin. + private func probeToken() -> String? { + if !token.isEmpty { return token } + guard keepsSavedToken, let server else { return nil } + return MCPServerStore.shared.token(for: server.id) + } + private func save() { - let configuration = draft() - if let error = store.upsert(configuration, token: token.isEmpty ? nil : token) { - validationError = error + guard canSave else { return } + guard let configuration = draft() else { + saveError = .invalid(.invalidEndpoint) + return + } + if let error = MCPServerStore.shared.upsert(configuration, token: token.isEmpty ? nil : token) { + saveError = error return } dismiss() } - private func message(for error: MCPServerConfigurationError) -> String { - switch error { - case .emptyName: - String(localized: "Give the server a name.") - case .reservedName: - String(localized: "That name belongs to TablePro's own tools. Choose another.") - case .invalidEndpoint: - String(localized: "That is not an HTTP address.") - case .insecureEndpoint: - String(localized: "A server on another machine has to be HTTPS.") - case .credentialsInEndpoint: - String(localized: "Put the credential in the Token field, not in the address.") - } + private func remove() { + guard let server else { return } + MCPServerStore.shared.remove(id: server.id) + dismiss() } } diff --git a/apple/TablePro/Views/Settings/Sections/MCPOutsideServersSection.swift b/apple/TablePro/Views/Settings/Sections/MCPOutsideServersSection.swift index e2eb35543a..63fae29db7 100644 --- a/apple/TablePro/Views/Settings/Sections/MCPOutsideServersSection.swift +++ b/apple/TablePro/Views/Settings/Sections/MCPOutsideServersSection.swift @@ -1,57 +1,55 @@ -// -// MCPOutsideServersSection.swift -// TablePro -// - import SwiftUI import TableProMCP -/// Below the built-in server's sections because it is the opposite direction: what TablePro may ask -/// of an outside server. It works whether or not the built-in server is on. +// The opposite direction from the server above it, what TablePro may ask of an outside server, so it shows whether or not the server is on. internal struct MCPOutsideServersSection: View { + private struct SheetTarget: Identifiable { + let id: UUID + let server: MCPServerConfiguration? + } + @ObservedObject private var store = MCPServerStore.shared - @State private var editing: MCPServerConfiguration? - @State private var isAdding = false - @State private var deleteCandidate: MCPServerConfiguration? + @State private var sheet: SheetTarget? + @State private var removalCandidate: MCPServerConfiguration? var body: some View { Section { if store.servers.isEmpty { - emptyState + Text("No servers") + .foregroundStyle(.secondary) } else { ForEach(store.servers) { server in row(server) } } - Button { - isAdding = true - } label: { - Label(String(localized: "Add Server…"), systemImage: "plus") - } + // swiftlint:disable:next line_length + SettingsHelpRow("A session can call tools on a server you add here once you allow it on a connection. Every call waits for you to approve it, and the arguments leave this Mac.") } header: { Text("Outside MCP Servers") } footer: { - Text("A session can call tools on a server you add here once you allow it on a connection. Every call waits for you to approve it, and the arguments leave this Mac.") - .font(.caption) - .foregroundStyle(.secondary) - } - .sheet(isPresented: $isAdding) { - MCPOutsideServerSheet(server: nil) + SettingsSectionActions { + Button(String(localized: "Add Server…")) { + sheet = SheetTarget(id: UUID(), server: nil) + } + .accessibilityIdentifier("mcp-outside-server-add") + } } - .sheet(item: $editing) { server in - MCPOutsideServerSheet(server: server) + .sheet(item: $sheet) { target in + MCPOutsideServerSheet(server: target.server) } .alert( - String(localized: "Remove server?"), - isPresented: deleteAlertBinding, - presenting: deleteCandidate + String(localized: "Remove Server?"), + isPresented: removalBinding, + presenting: removalCandidate ) { server in - Button(String(localized: "Cancel"), role: .cancel) { deleteCandidate = nil } Button(String(localized: "Remove"), role: .destructive) { store.remove(id: server.id) - deleteCandidate = nil + removalCandidate = nil + } + Button(String(localized: "Cancel"), role: .cancel) { + removalCandidate = nil } } message: { server in Text(String( @@ -62,61 +60,29 @@ internal struct MCPOutsideServersSection: View { } private func row(_ server: MCPServerConfiguration) -> some View { - Button { - editing = server - } label: { - HStack(spacing: 10) { - VStack(alignment: .leading, spacing: 3) { - Text(server.name) - Text(server.endpoint.absoluteString) - .font(.system(.caption, design: .monospaced)) - .foregroundStyle(.secondary) - .lineLimit(1) - .truncationMode(.middle) - } - Spacer(minLength: 8) - Text(reachText(server)) - .font(.caption) - .foregroundStyle(.secondary) - Image(systemName: "chevron.right") - .font(.caption) - .foregroundStyle(.tertiary) - } - .contentShape(Rectangle()) - } - .buttonStyle(.plain) - .accessibilityLabel(server.name) - .accessibilityValue(reachText(server)) - .contextMenu { - Button(String(localized: "Edit…")) { editing = server } - Divider() - Button(role: .destructive) { - deleteCandidate = server - } label: { - Text(String(localized: "Remove…")) - } - } + SettingsRecordRow( + title: server.name, + subtitle: server.endpoint.absoluteString, + value: Self.reach(of: server) + ) + .infoButton( + onEdit: { sheet = SheetTarget(id: server.id, server: server) }, + removal: .remove { removalCandidate = server }, + identifier: "mcp-outside-server-edit-\(server.id.uuidString)" + ) } - /// How far the server reaches, which is the one thing about it worth reading at a glance. A - /// server allowed nowhere is inert, and saying so is more use than a status dot that would have - /// to connect to mean anything. - private func reachText(_ server: MCPServerConfiguration) -> String { + // How far a server reaches is the one thing worth reading at a glance: one allowed nowhere is inert. + static func reach(of server: MCPServerConfiguration) -> String { let count = server.allowedConnectionIds.count - if count == 0 { return String(localized: "No connections") } - if count == 1 { return String(localized: "1 connection") } - return String(format: String(localized: "%d connections"), count) - } - - private var emptyState: some View { - Text("No servers yet.") - .foregroundStyle(.secondary) + guard count > 0 else { return String(localized: "No connections") } + return String(AttributedString(localized: "^[\(count) connection](inflect: true)").characters) } - private var deleteAlertBinding: Binding { + private var removalBinding: Binding { Binding( - get: { deleteCandidate != nil }, - set: { if !$0 { deleteCandidate = nil } } + get: { removalCandidate != nil }, + set: { if !$0 { removalCandidate = nil } } ) } } diff --git a/apple/TablePro/Views/Settings/Sections/MCPSection.swift b/apple/TablePro/Views/Settings/Sections/MCPSection.swift index 96d67c7902..a63bc623fe 100644 --- a/apple/TablePro/Views/Settings/Sections/MCPSection.swift +++ b/apple/TablePro/Views/Settings/Sections/MCPSection.swift @@ -1,296 +1,167 @@ -import AppKit import SwiftUI import TableProMCP struct MCPSection: View { @Binding var settings: MCPSettings - @ObservedObject private var manager = MCPServerManager.shared - @State private var tokenList: [MCPAuthToken] = [] - @State private var showSetupSheet = false - @State private var showCreateSheet = false - @State private var showRevealSheet = false - @State private var revealedPlaintext: String = "" - @State private var tokenAlert: MCPTokenAlert? - @State private var rejectedPort: Int? + @ObservedObject var model: MCPSettingsModel + let onChangeAIPolicy: () -> Void + + @State private var showsClientSetup = false var body: some View { Section { - Toggle(String(localized: "Enable MCP Server"), isOn: $settings.enabled) - .accessibilityIdentifier("mcp-enable-server-toggle") + Toggle(isOn: $settings.enabled) { + Text("MCP server") + Text("Lets AI apps such as Claude and Cursor work with your connections through TablePro.") + } + .accessibilityIdentifier("mcp-enable-server-toggle") if settings.enabled { MCPStatusRow(configuredPort: settings.port) + + LabeledContent { + Button(String(localized: "Connect a Client…")) { + showsClientSetup = true + } + .accessibilityIdentifier("mcp-connect-client") + } label: { + Text("Clients") + Text("Add TablePro to Claude, Cursor and other apps on this Mac.") + } + + LabeledContent { + Button(String(localized: "View Activity…")) { + WindowOpener.shared.openIntegrationsActivity() + } + .accessibilityIdentifier("mcp-view-activity") + } label: { + Text("Activity") + Text("Requests, approvals and connected clients.") + } } } + .sheet(isPresented: $showsClientSetup) { + MCPClientSetupSheet() + } if settings.enabled { - configurationSection - connectionAccessSection - authenticationSection - helpSection + accessSection + serverSection } } - private var connectionAccessSection: some View { + private var accessSection: some View { Section { - Picker(String(localized: "Approval"), selection: $settings.connectionApproval) { + Picker(selection: $settings.connectionApproval) { ForEach(MCPConnectionApproval.allCases) { approval in Text(approval.displayName).tag(approval) } + } label: { + Text("Approval") + Text(settings.connectionApproval.explanation) } .pickerStyle(.menu) + .accessibilityIdentifier("mcp-approval-picker") + + SettingsDrillRow( + route: SettingsRoute.page(.mcpApprovals), + title: "Approved connections", + value: approvalsValue, + subtitle: settings.connectionApproval != .oncePerConnection + ? "Used only with Ask Once for Each Connection." + : nil + ) - Text(settings.connectionApproval.explanation) - .foregroundStyle(.secondary) - .font(.callout) + SettingsDrillRow(route: SettingsRoute.page(.mcpTokens), title: "Tokens", value: tokensValue) - MCPGrantListView() + MCPDefaultAIPolicyRow(onChange: onChangeAIPolicy) - Toggle( - String(localized: "Allow apps to list connections hidden from AI"), - isOn: $settings.allowsHiddenConnectionListing - ) + Toggle(isOn: $settings.allowsHiddenConnectionListing) { + Text("Allow apps to list connections hidden from AI") + // swiftlint:disable:next line_length + Text("A paired app, such as a launcher, can ask when it pairs to show connections whose AI Policy is Never, with their user names. It still cannot query them. Turning this off stops every app at once.") + } .accessibilityIdentifier("mcp-hidden-connection-listing-toggle") // swiftlint:disable:next line_length - Text(String(localized: "A paired app, such as a launcher, can ask when it pairs to show connections whose AI Policy is Never, with their user names. It still cannot query them. Turning this off stops every app at once.")) - .foregroundStyle(.secondary) - .font(.callout) + SettingsHelpRow("Approval is separate from what a client may reach. A connection blocked for external clients stays blocked, a read-only one stays read only, and Safe Mode still confirms destructive statements.") } header: { - Text("Connection Access") - } footer: { - // swiftlint:disable:next line_length - Text("Approval is separate from what a client may reach. A connection blocked for external clients stays blocked, a read-only one stays read only, and Safe Mode still confirms destructive statements.") - .font(.caption) - .foregroundStyle(.secondary) + Text("Access") } } - private var configurationSection: some View { + private var serverSection: some View { Section { - LabeledContent(String(localized: "Port")) { - TextField("", value: portBinding, format: .number.grouping(.never)) - .frame(width: 80) - .multilineTextAlignment(.trailing) - .accessibilityIdentifier("mcp-port-field") - } + SettingsNumberField( + "Port", + value: $settings.port, + range: MCPSettings.portRange, + width: 64, + invalid: .reject(String( + format: String(localized: "Choose a port from %d to %d."), + MCPSettings.portRange.lowerBound, + MCPSettings.portRange.upperBound + )), + identifier: "mcp-port-field" + ) - LabeledContent(String(localized: "Default row limit")) { - TextField("", value: $settings.defaultRowLimit, format: .number.grouping(.never)) - .frame(width: 80) - .multilineTextAlignment(.trailing) - } + SettingsNumberField( + "Default row limit", + subtitle: "Rows a query returns when the client sets no limit.", + value: $settings.defaultRowLimit, + range: settings.requestableRowLimitRange, + step: 100, + unit: "rows", + width: 72, + identifier: "mcp-default-row-limit-field" + ) - LabeledContent(String(localized: "Maximum row limit")) { - TextField("", value: $settings.maxRowLimit, format: .number.grouping(.never)) - .frame(width: 80) - .multilineTextAlignment(.trailing) - } + SettingsNumberField( + "Maximum row limit", + subtitle: "The most rows a client can ask for.", + value: maxRowLimit, + range: SettingsValidationRules.mcpRowLimitRange, + step: 1_000, + unit: "rows", + width: 72, + identifier: "mcp-max-row-limit-field" + ) - LabeledContent(String(localized: "Query timeout")) { - HStack(spacing: 4) { - TextField("", value: $settings.queryTimeoutSeconds, format: .number.grouping(.never)) - .frame(width: 80) - .multilineTextAlignment(.trailing) - Text(String(localized: "seconds")) - .foregroundStyle(.secondary) - } - } + SettingsNumberField( + "Query timeout", + value: $settings.queryTimeoutSeconds, + range: SettingsValidationRules.mcpQueryTimeoutRange, + step: 5, + unit: "seconds", + width: 56, + identifier: "mcp-query-timeout-field" + ) - Toggle(String(localized: "Log MCP queries in history"), isOn: $settings.logQueriesInHistory) + Toggle("Log MCP queries in history", isOn: $settings.logQueriesInHistory) + .accessibilityIdentifier("mcp-log-queries-toggle") } header: { - Text(String(localized: "Server Configuration")) - } footer: { - if let rejectedPort { - NoticeLabel( - String( - format: String(localized: "Port %d cannot be used. Choose a port from %d to %d."), - rejectedPort, - MCPSettings.portRange.lowerBound, - MCPSettings.portRange.upperBound - ), - severity: .error - ) - .font(.caption) - } + Text("Server") } } - // An out-of-range port is kept out of the settings, so the server never binds a port the field did not show. - private var portBinding: Binding { + // A lower maximum pulls the default down with it in the same write. + private var maxRowLimit: Binding { Binding( - get: { settings.port }, - set: { newValue in - if MCPSettings.portRange.contains(newValue) { - rejectedPort = nil - settings.port = newValue - } else { - rejectedPort = newValue - } - } + get: { settings.maxRowLimit }, + set: { settings = settings.withMaxRowLimit($0) } ) } - private var authenticationSection: some View { - Section(String(localized: "Authentication")) { - MCPTokenListView( - tokens: tokenList, - isStoreAvailable: manager.tokenStore != nil, - onGenerate: { showCreateSheet = true }, - onRevoke: { id in revoke(id) }, - onDelete: { ids in delete(ids) } - ) - } - .task(id: manager.tokenStore.map { ObjectIdentifier($0) }) { await refreshTokens() } - .sheet(isPresented: $showCreateSheet) { - MCPTokenCreateSheet { name, permissions, connectionIds, expiresAt in - await generate(name: name, permissions: permissions, connectionIds: connectionIds, expiresAt: expiresAt) - } - } - .sheet(isPresented: $showRevealSheet) { - if !revealedPlaintext.isEmpty { - MCPTokenRevealSheet( - plaintext: revealedPlaintext, - port: manager.listeningPort ?? settings.port, - configuredPort: settings.port - ) - } - } - .alert(tokenAlert?.title ?? "", isPresented: tokenAlertBinding, presenting: tokenAlert) { _ in - Button(String(localized: "OK")) {} - } message: { alert in - Text(verbatim: alert.message) - } + private var approvalsValue: String? { + guard model.hasLoadedGrants else { return nil } + return model.grants.isEmpty ? String(localized: "None") : SettingsFormat.count(model.grants.count) } - private var tokenAlertBinding: Binding { - Binding( - get: { tokenAlert != nil }, - set: { isPresented in - if !isPresented { - tokenAlert = nil - } - } - ) - } - - private var helpSection: some View { - Section { - Button(String(localized: "Connect a Client…")) { - showSetupSheet = true - } - .accessibilityIdentifier("mcp-connect-client") - Button(String(localized: "View Activity…")) { - WindowOpener.shared.openIntegrationsActivity() - } - .accessibilityIdentifier("mcp-view-activity") - } - .sheet(isPresented: $showSetupSheet) { - MCPClientSetupSheet() - } - } - - private func generate( - name: String, - permissions: TokenPermissions, - connectionIds: Set?, - expiresAt: Date? - ) async -> MCPTokenCreateFailure? { - guard let store = manager.tokenStore else { - return MCPTokenCreateFailure( - message: String(localized: "The MCP server is not running, so TablePro cannot save a token now. Start the server, then try again."), - endsSheet: true - ) - } - let access: ConnectionAccess = connectionIds.map { .limited($0) } ?? .all - do { - let result = try await store.generate( - name: name, - permissions: permissions, - connectionAccess: access, - expiresAt: expiresAt, - isBridgeCredential: false, - isClaudeAgentCredential: false, - extraScopes: [] - ) - revealedPlaintext = result.plaintext - showCreateSheet = false - showRevealSheet = true - await refreshTokens() - return nil - } catch { - return MCPTokenCreateFailure(message: Self.generateFailureMessage(error), endsSheet: false) - } - } - - private static func generateFailureMessage(_ error: Error) -> String { - switch error as? MCPTokenStoreError { - case .storedTokensUnreadable?: - String(localized: "TablePro could not read the tokens saved in the Keychain, so it will not save a new one over them. Restart TablePro and try again.") - case .randomGenerationFailed?: - String(localized: "macOS could not generate a secure token. Try again.") - case .keychainUnavailable?, .notSaved?, nil: - String(localized: "TablePro could not save the token to the Keychain, so it was not created. Try again.") - } - } - - private func revoke(_ id: UUID) { - Task { - guard manager.tokenStore != nil else { - tokenAlert = .serverNotRunning - return - } - if !(await manager.revokeToken(id: id)) { - tokenAlert = .revocationNotSaved - } - await refreshTokens() - } - } - - private func delete(_ ids: Set) { - Task { - guard let store = manager.tokenStore else { - tokenAlert = .serverNotRunning - return - } - var allSaved = true - for id in ids { - let saved = await store.delete(tokenId: id) - allSaved = allSaved && saved - } - if !allSaved { - tokenAlert = .deletionNotSaved - } - await refreshTokens() - } - } - - private func refreshTokens() async { - guard let store = manager.tokenStore else { return } - tokenList = await store.list().filter { !$0.isBridgeCredential } - } -} - -private enum MCPTokenAlert: Equatable { - case serverNotRunning - case revocationNotSaved - case deletionNotSaved - - var title: String { - switch self { - case .serverNotRunning: String(localized: "MCP Server Not Running") - case .revocationNotSaved: String(localized: "Couldn't Save the Revocation") - case .deletionNotSaved: String(localized: "Couldn't Save the Deletion") - } - } - - var message: String { - switch self { - case .serverNotRunning: - String(localized: "The MCP server is not running, so TablePro cannot change its tokens now. Start the server, then try again.") - case .revocationNotSaved, .deletionNotSaved: - String(localized: "TablePro could not save the change to the Keychain. The token works again after TablePro restarts.") - } + private var tokensValue: String? { + guard model.tokenStore != nil else { return String(localized: "Unavailable") } + guard model.hasLoadedTokens else { return nil } + if model.tokens.isEmpty { return String(localized: "None") } + return String(format: String(localized: "%lld active"), model.activeTokenCount) } } @@ -300,24 +171,42 @@ private struct MCPStatusRow: View { var body: some View { let presentation = MCPServerStatusPresentation(state: manager.state, configuredPort: configuredPort) - LabeledContent(String(localized: "Status")) { + LabeledContent { HStack(spacing: 8) { IntegrationStatusIndicator(status: presentation.status, label: presentation.title) if presentation.offersRetry { Button(String(localized: "Try Again")) { manager.retry() } - .controlSize(.small) .accessibilityIdentifier("mcp-status-try-again") } } + } label: { + Text("Status") + if let detail = presentation.detail { + Text(verbatim: detail) + .textSelection(.enabled) + } } - if let detail = presentation.detail { - Text(detail) - .font(.caption) - .foregroundStyle(.secondary) - .textSelection(.enabled) - .fixedSize(horizontal: false, vertical: true) + } +} + +// Read only: the policy belongs to AI, and MCP enforces it for connections without their own. +private struct MCPDefaultAIPolicyRow: View { + @ObservedObject private var ai = AppSettingsManager.shared.aiSlice + let onChange: () -> Void + + var body: some View { + LabeledContent { + HStack(spacing: 8) { + Text(ai.value.defaultConnectionPolicy.displayName) + .foregroundStyle(.secondary) + Button(String(localized: "Change…"), action: onChange) + .accessibilityIdentifier("mcp-default-ai-policy-change") + } + } label: { + Text("Default AI policy") + Text("Connections without their own AI Policy use it. Clients cannot query a connection set to Never.") } } } diff --git a/apple/TablePro/Views/Settings/Sections/MCPTokenCreateSheet.swift b/apple/TablePro/Views/Settings/Sections/MCPTokenCreateSheet.swift index 7e8b296c7b..5b94e21e6d 100644 --- a/apple/TablePro/Views/Settings/Sections/MCPTokenCreateSheet.swift +++ b/apple/TablePro/Views/Settings/Sections/MCPTokenCreateSheet.swift @@ -1,48 +1,147 @@ import SwiftUI -struct MCPTokenCreateFailure: Equatable, Sendable { +struct MCPTokenCreateFailure: Error, Equatable, Sendable { let message: String // Nothing in this sheet can fix a server that is not running, so the alert closes it. let endsSheet: Bool } +struct MCPTokenRequest: Equatable, Sendable { + let name: String + let permissions: TokenPermissions + let connectionIds: Set? + let expiresAt: Date? +} + +struct MCPTokenReveal: Sendable { + let plaintext: String + let setup: MCPHTTPClientSetup + let port: Int + let configuredPort: Int +} + +// One sheet, the form and then the token, so the plaintext lives only in this sheet's state and goes with it. struct MCPTokenCreateSheet: View { private enum Field: Hashable { case name } + private enum Access: Hashable { + case all + case selected + } + @Environment(\.dismiss) private var dismiss - let onGenerate: (String, TokenPermissions, Set?, Date?) async -> MCPTokenCreateFailure? + let onGenerate: (MCPTokenRequest) async -> Result - @State private var tokenName = "" + @State private var name = "" @State private var permissions: TokenPermissions = .readOnly - @State private var connectionAccess: ConnectionAccessMode = .all + @State private var access: Access = .all @State private var selectedConnectionIds: Set = [] - @State private var expirationOption: ExpirationOption = .never - @State private var customExpirationDate = Calendar.current.date(byAdding: .day, value: 30, to: .now) ?? .now + @State private var expiry: TokenExpiry = .never + @State private var customExpiry = TokenExpiry.defaultCustomDate() @State private var connections: [DatabaseConnection] = [] @State private var isGenerating = false @State private var failure: MCPTokenCreateFailure? + @State private var reveal: MCPTokenReveal? @FocusState private var focused: Field? var body: some View { + Group { + if let reveal { + MCPTokenRevealSheet(reveal: reveal) { + dismiss() + } + } else { + createForm + } + } + .frame(minWidth: 540, minHeight: 520) + } + + private var createForm: some View { VStack(spacing: 0) { Form { - nameSection - permissionsSection - connectionAccessSection - expirationSection + Section { + TextField(text: $name, prompt: Text("Cursor on my Mac")) { + Text("Name") + } + .focused($focused, equals: .name) + .accessibilityIdentifier("mcp-token-name-field") + + Picker(selection: $permissions) { + ForEach(TokenPermissions.allCases) { permission in + Text(permission.displayName).tag(permission) + } + } label: { + Text("Permissions") + Text(permissions.summary) + } + .pickerStyle(.segmented) + .accessibilityIdentifier("mcp-token-permissions-picker") + } + + Section { + Picker(selection: $access) { + Text("All").tag(Access.all) + Text("Selected").tag(Access.selected) + } label: { + Text("Connections") + } + .pickerStyle(.menu) + .accessibilityIdentifier("mcp-token-connections-picker") + + if access == .selected { + ConnectionAllowlistSection( + selection: $selectedConnectionIds, + connections: connections, + showsSelectAll: true + ) + } + } + + Section { + Picker(selection: $expiry) { + ForEach(TokenExpiry.allCases) { option in + Text(option.displayName).tag(option) + } + } label: { + Text("Expires") + } + .pickerStyle(.menu) + .accessibilityIdentifier("mcp-token-expiry-picker") + + if expiry == .custom { + DatePicker( + String(localized: "Expiration date"), + selection: $customExpiry, + in: Date.now..., + displayedComponents: .date + ) + } + } } .formStyle(.grouped) + .defaultFocus($focused, .name) Divider() - actionBar - .padding() + DialogFooter { + Button(String(localized: "Cancel"), role: .cancel) { + dismiss() + } + .keyboardShortcut(.cancelAction) + + Button(String(localized: "Generate"), action: generate) + .keyboardShortcut(.defaultAction) + .disabled(!canGenerate) + .accessibilityIdentifier("mcp-token-generate") + } + .padding() } - .frame(minWidth: 480, minHeight: 520) .task { connections = ConnectionStorage.shared.loadConnections() + .sorted { $0.name.localizedStandardCompare($1.name) == .orderedAscending } } .alert( String(localized: "Couldn't Create the Token"), @@ -60,6 +159,14 @@ struct MCPTokenCreateSheet: View { } } + private var trimmedName: String { + name.trimmingCharacters(in: .whitespacesAndNewlines) + } + + private var canGenerate: Bool { + !isGenerating && !trimmedName.isEmpty && !(access == .selected && selectedConnectionIds.isEmpty) + } + private var failureBinding: Binding { Binding( get: { failure != nil }, @@ -71,148 +178,24 @@ struct MCPTokenCreateSheet: View { ) } - private var nameSection: some View { - Section(String(localized: "Token Name")) { - TextField(String(localized: "e.g., Cursor on my Mac"), text: $tokenName) - .focused($focused, equals: .name) - } - } - - private var permissionsSection: some View { - Section(String(localized: "Permission Level")) { - Picker(String(localized: "Permission"), selection: $permissions) { - ForEach(TokenPermissions.allCases) { permission in - Text(permission.displayName).tag(permission) - } - } - .pickerStyle(.segmented) - .labelsHidden() - } - } - - private var connectionAccessSection: some View { - Section(String(localized: "Connection Access")) { - Picker(String(localized: "Access"), selection: $connectionAccess) { - Text(String(localized: "All Connections")).tag(ConnectionAccessMode.all) - Text(String(localized: "Select Connections")).tag(ConnectionAccessMode.selected) - } - .labelsHidden() - - if connectionAccess == .selected { - connectionList - } - } - } - - @ViewBuilder - private var connectionList: some View { - if connections.isEmpty { - Text(String(localized: "No saved connections")) - .foregroundStyle(.secondary) - } else { - ForEach(connections) { connection in - Toggle(isOn: connectionBinding(for: connection.id)) { - HStack(spacing: 6) { - Text(connection.name) - Text(connection.type.displayName) - .font(.caption) - .foregroundStyle(.secondary) - } - } - .toggleStyle(.checkbox) - } - } - } - - private var expirationSection: some View { - Section(String(localized: "Expiration")) { - Picker(String(localized: "Expires"), selection: $expirationOption) { - ForEach(ExpirationOption.allCases) { option in - Text(option.displayName).tag(option) - } - } - .labelsHidden() - - if expirationOption == .custom { - DatePicker( - String(localized: "Expiration date"), - selection: $customExpirationDate, - in: Date.now..., - displayedComponents: .date - ) - } - } - } - - private var actionBar: some View { - DialogFooter { - Button(String(localized: "Cancel"), role: .cancel) { - dismiss() - } - .keyboardShortcut(.cancelAction) - - Button(String(localized: "Generate")) { - let connectionIds: Set? = connectionAccess == .selected ? selectedConnectionIds : nil - isGenerating = true - Task { - failure = await onGenerate(tokenName, permissions, connectionIds, resolvedExpirationDate) - isGenerating = false - } - } - .keyboardShortcut(.defaultAction) - .disabled(isGenerating - || tokenName.trimmingCharacters(in: .whitespaces).isEmpty - || (connectionAccess == .selected && selectedConnectionIds.isEmpty)) - } - } - - private func connectionBinding(for id: UUID) -> Binding { - Binding( - get: { selectedConnectionIds.contains(id) }, - set: { isSelected in - if isSelected { - selectedConnectionIds.insert(id) - } else { - selectedConnectionIds.remove(id) - } - } + private func generate() { + guard canGenerate else { return } + let request = MCPTokenRequest( + name: trimmedName, + permissions: permissions, + connectionIds: access == .selected ? selectedConnectionIds : nil, + expiresAt: expiry.resolvedDate(custom: customExpiry) ) - } - - private var resolvedExpirationDate: Date? { - switch expirationOption { - case .never: nil - case .thirtyDays: Calendar.current.date(byAdding: .day, value: 30, to: .now) - case .sixtyDays: Calendar.current.date(byAdding: .day, value: 60, to: .now) - case .ninetyDays: Calendar.current.date(byAdding: .day, value: 90, to: .now) - case .custom: customExpirationDate - } - } -} - -private enum ConnectionAccessMode: String, Identifiable { - case all - case selected - - var id: String { rawValue } -} - -private enum ExpirationOption: String, CaseIterable, Identifiable { - case never - case thirtyDays - case sixtyDays - case ninetyDays - case custom - - var id: String { rawValue } - - var displayName: String { - switch self { - case .never: String(localized: "Never") - case .thirtyDays: String(localized: "30 days") - case .sixtyDays: String(localized: "60 days") - case .ninetyDays: String(localized: "90 days") - case .custom: String(localized: "Custom") + isGenerating = true + Task { + let result = await onGenerate(request) + isGenerating = false + switch result { + case .success(let issued): + reveal = issued + case .failure(let failed): + failure = failed + } } } } diff --git a/apple/TablePro/Views/Settings/Sections/MCPTokenListView.swift b/apple/TablePro/Views/Settings/Sections/MCPTokenListView.swift index 8f1e0f9ad9..784465c4dd 100644 --- a/apple/TablePro/Views/Settings/Sections/MCPTokenListView.swift +++ b/apple/TablePro/Views/Settings/Sections/MCPTokenListView.swift @@ -1,143 +1,247 @@ -import AppKit import SwiftUI import TableProMCP +enum MCPTokenAlert: Equatable { + case serverNotRunning + case revocationNotSaved + case deletionNotSaved + + var title: String { + switch self { + case .serverNotRunning: String(localized: "MCP Server Not Running") + case .revocationNotSaved: String(localized: "Couldn't Save the Revocation") + case .deletionNotSaved: String(localized: "Couldn't Save the Deletion") + } + } + + var message: String { + switch self { + case .serverNotRunning: + String(localized: "The MCP server is not running, so TablePro cannot change its tokens now. Start the server, then try again.") + case .revocationNotSaved, .deletionNotSaved: + String(localized: "TablePro could not save the change to the Keychain. The token works again after TablePro restarts.") + } + } +} + +// The Tokens page: a full-page list, so a long list of clients scrolls on its own. struct MCPTokenListView: View { - let tokens: [MCPAuthToken] - let isStoreAvailable: Bool - let onGenerate: () -> Void - let onRevoke: (UUID) -> Void - let onDelete: (Set) -> Void + private struct Confirmation: Identifiable { + enum Kind { + case revoke + case delete + } + + let kind: Kind + let tokens: [MCPAuthToken] + + var id: [UUID] { tokens.map(\.id) } + } + + @ObservedObject var model: MCPSettingsModel + let configuredPort: () -> Int @State private var selection: Set = [] - @State private var deleteCandidates: [MCPAuthToken] = [] + @State private var confirmation: Confirmation? + @State private var tokenAlert: MCPTokenAlert? + @State private var showsCreateSheet = false var body: some View { - VStack(alignment: .leading, spacing: 8) { - if tokens.isEmpty { - emptyState - } else { - List(selection: $selection) { - ForEach(tokens) { token in - MCPTokenRow(token: token) - .tag(token.id) - .contextMenu { - contextMenu(for: token) - } - } + SettingsFullPageList { + List(selection: $selection) { + ForEach(rows) { token in + MCPTokenRow( + token: token, + onRevoke: token.isActive ? { requestRevoke([token]) } : nil, + onDelete: { requestDelete([token]) } + ) + .tag(token.id) } - .frame(minHeight: 160) - .onDeleteCommand(perform: deleteSelectionFromKeyboard) } - - HStack(spacing: 8) { - Button { - onGenerate() - } label: { - Label(String(localized: "Generate Token"), systemImage: "plus") + .accessibilityIdentifier("mcp-tokens-list") + .contextMenu(forSelectionType: UUID.self) { ids in + menu(for: ids) + } + .onDeleteCommand { + requestDelete(tokens(in: selection)) + } + .alert( + confirmationTitle, + isPresented: confirmationBinding, + presenting: confirmation + ) { confirmation in + switch confirmation.kind { + case .revoke: + Button(String(localized: "Revoke"), role: .destructive) { + revoke(confirmation.tokens) + } + case .delete: + Button(String(localized: "Delete"), role: .destructive) { + delete(confirmation.tokens) + } } - .buttonStyle(.borderedProminent) - .disabled(!isStoreAvailable) - .accessibilityLabel(String(localized: "Generate token")) - - Spacer() + Button(String(localized: "Cancel"), role: .cancel) {} + } message: { confirmation in + Text(verbatim: Self.confirmationMessage(confirmation)) } + } emptyState: { + emptyState + } bar: { + SettingsListBar( + addLabel: String(localized: "Generate Token"), + removeLabel: String(localized: "Delete"), + canAdd: model.tokenStore != nil, + canRemove: !tokens(in: selection).isEmpty, + addHelp: String(localized: "Generate Token…"), + removeHelp: String(localized: "Delete…"), + addIdentifier: "mcp-token-add", + removeIdentifier: "mcp-token-remove", + onAdd: { showsCreateSheet = true }, + onRemove: { requestDelete(tokens(in: selection)) } + ) } - .alert( - deleteAlertTitle, - isPresented: deleteAlertBinding, - presenting: deleteCandidates.isEmpty ? nil : deleteCandidates - ) { candidates in - Button(String(localized: "Cancel"), role: .cancel) { - deleteCandidates = [] - } - Button(String(localized: "Delete"), role: .destructive) { - let ids = Set(candidates.map(\.id)) - onDelete(ids) - selection.subtract(ids) - deleteCandidates = [] + .sheet(isPresented: $showsCreateSheet) { + MCPTokenCreateSheet { request in + await model.generate(request, configuredPort: configuredPort()) } - } message: { candidates in - Text(verbatim: Self.deleteAlertMessage(for: candidates)) } + .alert(tokenAlert?.title ?? "", isPresented: tokenAlertBinding, presenting: tokenAlert) { _ in + Button(String(localized: "OK")) {} + } message: { alert in + Text(verbatim: alert.message) + } + .onChange(of: model.tokens.map(\.id)) { ids in + selection.formIntersection(ids) + } + .accessibilityElement(children: .contain) + .accessibilityIdentifier(SettingsPage.mcpTokens.pageIdentifier) + } + + // Tokens from a stopped server stay loaded but are not shown, since nothing can change them. + private var rows: [MCPAuthToken] { + model.tokenStore == nil ? [] : model.tokens } + private func tokens(in ids: Set) -> [MCPAuthToken] { + rows.filter { ids.contains($0.id) } + } + + @ViewBuilder private var emptyState: some View { - VStack(spacing: 8) { - Image(systemName: "key") - .font(.title) - .foregroundStyle(.tertiary) - Text(isStoreAvailable ? String(localized: "No tokens created") : String(localized: "Tokens are not available")) - .foregroundStyle(.secondary) - Text(isStoreAvailable - ? String(localized: "Generate a token so external clients can connect with their own credentials.") - : String(localized: "Tokens load while the MCP server is running.")) - .font(.caption) - .foregroundStyle(.tertiary) - .multilineTextAlignment(.center) + if model.tokenStore == nil { + UnavailableStateView( + String(localized: "Tokens Unavailable"), + systemImage: "key", + description: Text("Tokens load while the MCP server is running.") + ) + } else if model.hasLoadedTokens && model.tokens.isEmpty { + UnavailableStateView { + Label("No Tokens", systemImage: "key") + } description: { + Text("Generate a token so external clients can connect with their own credentials.") + } actions: { + Button(String(localized: "Generate Token…")) { + showsCreateSheet = true + } + .accessibilityIdentifier("mcp-token-generate-empty") + } } - .frame(maxWidth: .infinity) - .padding(.vertical, 24) } @ViewBuilder - private func contextMenu(for token: MCPAuthToken) -> some View { - if token.isActive { - Button(role: .destructive) { - onRevoke(token.id) - } label: { - Label(String(localized: "Revoke"), systemImage: "xmark.circle") + private func menu(for ids: Set) -> some View { + let targets = tokens(in: ids) + if !targets.isEmpty { + if targets.contains(where: { $0.isActive }) { + Button(String(localized: "Revoke…")) { + requestRevoke(targets) + } + } + if targets.count == 1, let token = targets.first { + Button(String(localized: "Copy ID")) { + ClipboardService.shared.writeText(token.id.uuidString) + } + } + Divider() + Button(String(localized: "Delete…"), role: .destructive) { + requestDelete(targets) } - } - Button { - copyTokenId(token.id) - } label: { - Label(String(localized: "Copy ID"), systemImage: "doc.on.doc") - } - Divider() - Button(role: .destructive) { - // A right-click inside a multiple selection acts on all of it, as in Finder. - deleteCandidates = selection.contains(token.id) ? selectedTokens : [token] - } label: { - Label(String(localized: "Delete…"), systemImage: "trash") } } - private var selectedTokens: [MCPAuthToken] { - tokens.filter { selection.contains($0.id) } + private func requestRevoke(_ targets: [MCPAuthToken]) { + let active = targets.filter { $0.isActive } + guard !active.isEmpty else { return } + confirmation = Confirmation(kind: .revoke, tokens: active) } - private func deleteSelectionFromKeyboard() { - deleteCandidates = selectedTokens + private func requestDelete(_ targets: [MCPAuthToken]) { + guard !targets.isEmpty else { return } + confirmation = Confirmation(kind: .delete, tokens: targets) } - private func copyTokenId(_ id: UUID) { - NSPasteboard.general.clearContents() - NSPasteboard.general.setString(id.uuidString, forType: .string) + private func revoke(_ targets: [MCPAuthToken]) { + let ids = Set(targets.map(\.id)) + Task { + tokenAlert = await model.revoke(ids) + } } - private var deleteAlertTitle: String { - deleteCandidates.count > 1 - ? String(format: String(localized: "Delete %d tokens?"), deleteCandidates.count) - : String(localized: "Delete token?") + private func delete(_ targets: [MCPAuthToken]) { + let ids = Set(targets.map(\.id)) + selection.subtract(ids) + Task { + tokenAlert = await model.delete(ids) + } } - private static func deleteAlertMessage(for candidates: [MCPAuthToken]) -> String { - guard candidates.count > 1 else { - return String( - format: String(localized: "“%@” will be permanently deleted. External clients using this token will lose access immediately."), - candidates.first?.name ?? "" - ) + private var confirmationTitle: String { + guard let confirmation else { return "" } + let count = confirmation.tokens.count + let name = confirmation.tokens.first?.name ?? "" + switch confirmation.kind { + case .revoke: + return count > 1 + ? String(format: String(localized: "Revoke %d Tokens?"), count) + : String(format: String(localized: "Revoke “%@”?"), name) + case .delete: + return count > 1 + ? String(format: String(localized: "Delete %d Tokens?"), count) + : String(format: String(localized: "Delete “%@”?"), name) } - return String(localized: "These tokens will be permanently deleted. External clients using them will lose access immediately.") } - private var deleteAlertBinding: Binding { + private static func confirmationMessage(_ confirmation: Confirmation) -> String { + let isSingle = confirmation.tokens.count == 1 + switch confirmation.kind { + case .revoke: + return isSingle + ? String(localized: "Apps using it lose access now. This can't be undone.") + : String(localized: "Apps using them lose access now. This can't be undone.") + case .delete: + return isSingle + ? String(localized: "Apps using it lose access now, and the token leaves this list.") + : String(localized: "Apps using them lose access now, and the tokens leave this list.") + } + } + + private var confirmationBinding: Binding { + Binding( + get: { confirmation != nil }, + set: { isPresented in + if !isPresented { + confirmation = nil + } + } + ) + } + + private var tokenAlertBinding: Binding { Binding( - get: { !deleteCandidates.isEmpty }, + get: { tokenAlert != nil }, set: { isPresented in if !isPresented { - deleteCandidates = [] + tokenAlert = nil } } ) @@ -146,56 +250,79 @@ struct MCPTokenListView: View { private struct MCPTokenRow: View { let token: MCPAuthToken + let onRevoke: (() -> Void)? + let onDelete: () -> Void var body: some View { HStack(spacing: 10) { - VStack(alignment: .leading, spacing: 3) { - Text(token.name) + VStack(alignment: .leading, spacing: 2) { + Text(verbatim: token.name) + .lineLimit(1) - HStack(spacing: 8) { + HStack(spacing: 4) { Text(token.permissions.displayName) - .font(.caption) - .foregroundStyle(.secondary) - - Text(token.prefix + "…") - .font(.system(.caption, design: .monospaced)) - .foregroundStyle(.secondary) - + Text(verbatim: "·") + connectionsText + Text(verbatim: "·") + Text(verbatim: token.prefix + "…") + .font(.subheadline.monospaced()) + Text(verbatim: "·") Text(lastUsedText) - .font(.caption) - .foregroundStyle(.tertiary) } + .font(.subheadline) + .foregroundStyle(.secondary) + .lineLimit(1) if token.extraScopes.contains(.connectionsDisplay) { - Text(String(localized: "Lists connections hidden from AI")) - .font(.caption) + Text("Lists connections hidden from AI") + .font(.subheadline) .foregroundStyle(.secondary) } } - Spacer() + Spacer(minLength: 8) - IntegrationStatusIndicator(status: tokenStatus) - .help(tokenStatus == .active - ? String(localized: "Active") - : tokenStatus == .expired - ? String(localized: "Expired") - : String(localized: "Revoked")) + status } .padding(.vertical, 2) + .accessibilityElement(children: .combine) + .accessibilityActions { + if let onRevoke { + Button(String(localized: "Revoke"), action: onRevoke) + } + Button(String(localized: "Delete"), action: onDelete) + } } - private var tokenStatus: IntegrationStatus { - if token.isExpired { return .expired } - return token.isActive ? .active : .revoked + @ViewBuilder + private var connectionsText: some View { + switch token.connectionAccess { + case .all: + Text("All connections") + case .limited(let ids): + Text("^[\(ids.count) connection](inflect: true)") + } + } + + @ViewBuilder + private var status: some View { + if !token.isActive { + IntegrationStatusIndicator(status: .revoked, label: String(localized: "Revoked")) + } else if token.isExpired { + IntegrationStatusIndicator(status: .expired, label: String(localized: "Expired")) + } else if let expiresAt = token.expiresAt { + Text(String(format: String(localized: "Expires %@"), expiresAt.formatted(date: .abbreviated, time: .omitted))) + .foregroundStyle(.secondary) + } else { + Text("Active") + .foregroundStyle(.secondary) + } } private var lastUsedText: String { guard let lastUsed = token.lastUsedAt else { return String(localized: "Never used") } - let formatter = RelativeDateTimeFormatter() - formatter.unitsStyle = .full - return formatter.localizedString(for: lastUsed, relativeTo: .now) + return String(format: String(localized: "Last used %@"), lastUsed.formatted(.relative(presentation: .named))) } } diff --git a/apple/TablePro/Views/Settings/Sections/MCPTokenRevealSheet.swift b/apple/TablePro/Views/Settings/Sections/MCPTokenRevealSheet.swift index 7dd6d41913..9d131d582e 100644 --- a/apple/TablePro/Views/Settings/Sections/MCPTokenRevealSheet.swift +++ b/apple/TablePro/Views/Settings/Sections/MCPTokenRevealSheet.swift @@ -1,136 +1,113 @@ -import AppKit import SwiftUI +// Shown inside MCPTokenCreateSheet once the token exists; it has no cancel action, only Done. struct MCPTokenRevealSheet: View { - let plaintext: String - let port: Int - let configuredPort: Int - @Environment(\.dismiss) private var dismiss + let reveal: MCPTokenReveal + let onDone: () -> Void @State private var isTokenRevealed = false @State private var selectedClientID: String - private let setup: MCPHTTPClientSetup - - init(plaintext: String, port: Int, configuredPort: Int) { - self.plaintext = plaintext - self.port = port - self.configuredPort = configuredPort - let setup = MCPHTTPClientSetup(port: port) - self.setup = setup - _selectedClientID = State(initialValue: setup.choices.first?.id ?? MCPHTTPClientSetup.otherClientID) + init(reveal: MCPTokenReveal, onDone: @escaping () -> Void) { + self.reveal = reveal + self.onDone = onDone + _selectedClientID = State(initialValue: reveal.setup.choices.first?.id ?? MCPHTTPClientSetup.otherClientID) } var body: some View { VStack(spacing: 0) { - ScrollView { - VStack(alignment: .leading, spacing: 20) { - warningBanner - tokenDisplay - setupInstructions + Form { + Section { + NoticeLabel(String(localized: "Copy this token now. TablePro won't show it again."), severity: .warning) + + LabeledContent { + HStack(spacing: 8) { + Text(verbatim: displayedToken) + .font(.body.monospaced()) + .textSelection(.enabled) + .lineLimit(1) + .truncationMode(.middle) + + Button { + isTokenRevealed.toggle() + } label: { + Image(systemName: isTokenRevealed ? "eye.slash" : "eye") + } + .buttonStyle(.borderless) + .accessibilityLabel(isTokenRevealed + ? String(localized: "Hide token") + : String(localized: "Reveal token")) + .help(isTokenRevealed + ? String(localized: "Hide token") + : String(localized: "Reveal token")) + + Button(String(localized: "Copy")) { + ClipboardService.shared.writeSecretText(reveal.plaintext) + AccessibilityAnnouncement.post(String(localized: "Copied to clipboard")) + } + .accessibilityLabel(String(localized: "Copy token")) + .accessibilityIdentifier("mcp-token-copy") + } + } label: { + Text("Token") + } + } + + Section { + Picker(String(localized: "Client"), selection: $selectedClientID) { + ForEach(reveal.setup.choices) { choice in + Text(verbatim: choice.name).tag(choice.id) + } + } + .pickerStyle(.menu) + .accessibilityIdentifier("mcp-token-client-picker") + + if reveal.port != reveal.configuredPort { + NoticeLabel(String( + format: String(localized: "Port %d was in use, so this address changes when TablePro restarts."), + reveal.configuredPort + )) + } + + if selectedClientID == MCPHTTPClientSetup.otherClientID { + otherClientInstructions + } else { + clientInstructions + } + } header: { + Text("Set Up a Client") } - .padding(20) } + .formStyle(.grouped) Divider() - HStack { - Spacer() - Button(String(localized: "Done")) { dismiss() } + DialogFooter { + Button(String(localized: "Done"), action: onDone) .keyboardShortcut(.defaultAction) + .accessibilityIdentifier("mcp-token-done") } .padding() } - .frame(minWidth: 540, minHeight: 520) - } - - private var warningBanner: some View { - NoticeLabel(String(localized: "This token will not be shown again"), severity: .warning) - .frame(maxWidth: .infinity, alignment: .leading) - } - - private var tokenDisplay: some View { - VStack(alignment: .leading, spacing: 8) { - Text(String(localized: "Token")) - .font(.headline) - - HStack(spacing: 8) { - Text(verbatim: displayedToken) - .font(.system(.body, design: .monospaced)) - .textSelection(.enabled) - .lineLimit(1) - .truncationMode(.middle) - - Spacer(minLength: 0) - - Button { - isTokenRevealed.toggle() - } label: { - Image(systemName: isTokenRevealed ? "eye.slash" : "eye") - } - .accessibilityLabel(isTokenRevealed - ? String(localized: "Hide token") - : String(localized: "Reveal token")) - .help(isTokenRevealed - ? String(localized: "Hide token") - : String(localized: "Reveal token")) - } - .padding(10) - .background(.quaternary) - .clipShape(RoundedRectangle(cornerRadius: 6)) - - Button { - ClipboardService.shared.writeSecretText(plaintext) - AccessibilityAnnouncement.post(String(localized: "Copied to clipboard")) - } label: { - Label(String(localized: "Copy Token"), systemImage: "doc.on.doc") - } - .accessibilityLabel(String(localized: "Copy token")) - } - } - - private var setupInstructions: some View { - VStack(alignment: .leading, spacing: 12) { - Text(String(localized: "Setup Instructions")) - .font(.headline) - - Picker(String(localized: "Client"), selection: $selectedClientID) { - ForEach(setup.choices) { choice in - Text(verbatim: choice.name).tag(choice.id) - } - } - .pickerStyle(.menu) - .fixedSize() - .accessibilityIdentifier("mcp-token-client-picker") - - if port != configuredPort { - NoticeLabel(String( - format: String(localized: "Port %d was in use, so this address changes when TablePro restarts."), - configuredPort - )) - } - - if selectedClientID == MCPHTTPClientSetup.otherClientID { - otherClientInstructions - } else { - clientInstructions - } - } } @ViewBuilder private var clientInstructions: some View { - if let copied = setup.render(clientID: selectedClientID, token: plaintext), - let shown = setup.render(clientID: selectedClientID, token: displayedToken) { + if let copied = reveal.setup.render(clientID: selectedClientID, token: reveal.plaintext), + let shown = reveal.setup.render(clientID: selectedClientID, token: displayedToken) { if let commandLine = copied.commandLine { - Text(String(localized: "Run this in Terminal:")) - CopyableCodeBlock(text: commandLine, displayText: shown.commandLine, isSecret: true) + VStack(alignment: .leading, spacing: 6) { + Text("Run this in Terminal:") + CopyableCodeBlock(text: commandLine, displayText: shown.commandLine, isSecret: true) + } } if let snippet = copied.snippet { - if let path = copied.displayConfigPath { - Text(String(format: String(localized: "Add this to %@:"), path)) + VStack(alignment: .leading, spacing: 6) { + if let path = copied.displayConfigPath { + Text(String(format: String(localized: "Add this to %@:"), path)) + } + CopyableCodeBlock(text: snippet, displayText: shown.snippet, isSecret: true) } - CopyableCodeBlock(text: snippet, displayText: shown.snippet, isSecret: true) } } else { otherClientInstructions @@ -138,11 +115,11 @@ struct MCPTokenRevealSheet: View { } private var otherClientInstructions: some View { - VStack(alignment: .leading, spacing: 8) { - Text(String(localized: "Give your client this address and header:")) - CopyableCodeBlock(text: setup.url) + VStack(alignment: .leading, spacing: 6) { + Text("Give your client this address and header:") + CopyableCodeBlock(text: reveal.setup.url) CopyableCodeBlock( - text: header(token: plaintext), + text: header(token: reveal.plaintext), displayText: header(token: displayedToken), isSecret: true ) @@ -154,10 +131,10 @@ struct MCPTokenRevealSheet: View { } private var displayedToken: String { - isTokenRevealed ? plaintext : maskedToken + isTokenRevealed ? reveal.plaintext : maskedToken } private var maskedToken: String { - String(plaintext.prefix(8)) + String(repeating: "\u{2022}", count: 24) + String(reveal.plaintext.prefix(8)) + String(repeating: "\u{2022}", count: 24) } } diff --git a/apple/TablePro/Views/Settings/Sections/PairingApprovalSheet.swift b/apple/TablePro/Views/Settings/Sections/PairingApprovalSheet.swift index 501dd6e6b9..247001ba1d 100644 --- a/apple/TablePro/Views/Settings/Sections/PairingApprovalSheet.swift +++ b/apple/TablePro/Views/Settings/Sections/PairingApprovalSheet.swift @@ -1,4 +1,3 @@ -import Combine import SwiftUI import TableProMCP @@ -9,7 +8,13 @@ struct PairingApproval: Sendable { let extraScopes: Set } +// Hosted by AlertHelper.runPairingApproval in its own window, so it works while Settings is closed. struct PairingApprovalSheet: View { + private enum Access: Hashable { + case all + case selected + } + let request: PairingRequest let codeExpiresAt: Date let allowsHiddenConnectionListing: Bool @@ -17,14 +22,12 @@ struct PairingApprovalSheet: View { @State private var permissions: TokenPermissions @State private var grantsHiddenConnections = false - @State private var connectionAccess: ConnectionAccessMode = .all + @State private var access: Access = .all @State private var selectedConnectionIds: Set = [] - @State private var expiry: ExpiryOption = .never + @State private var expiry: TokenExpiry = .never + @State private var customExpiry = TokenExpiry.defaultCustomDate() @State private var connections: [DatabaseConnection] = [] - @State private var connectionSearch: String = "" - @State private var now: Date = .now - - private let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect() + @State private var isExpired: Bool init( request: PairingRequest, @@ -37,8 +40,9 @@ struct PairingApprovalSheet: View { self.allowsHiddenConnectionListing = allowsHiddenConnectionListing self.onComplete = onComplete _permissions = State(initialValue: request.scopeRequest.permissions) + _isExpired = State(initialValue: codeExpiresAt <= .now) if let requested = request.requestedConnectionIds, !requested.isEmpty { - _connectionAccess = State(initialValue: .selected) + _access = State(initialValue: .selected) _selectedConnectionIds = State(initialValue: requested) } } @@ -49,7 +53,7 @@ struct PairingApprovalSheet: View { Divider() Form { permissionsSection - connectionAccessSection + connectionsSection if requestsHiddenConnections { hiddenConnectionsSection } @@ -65,12 +69,17 @@ struct PairingApprovalSheet: View { .frame(width: 520) .task { connections = ConnectionStorage.shared.loadConnections() - if connectionAccess == .all { + if access == .all { selectedConnectionIds = Set(connections.map(\.id)) } } - .onReceive(timer) { value in - now = value + .task { + let remaining = codeExpiresAt.timeIntervalSinceNow + if remaining > 0 { + try? await Task.sleep(for: .seconds(remaining)) + } + guard !Task.isCancelled else { return } + isExpired = true } } @@ -81,11 +90,13 @@ struct PairingApprovalSheet: View { .font(.headline) .lineLimit(2) .truncationMode(.tail) - Text(String(localized: "An external app is asking for an API token. Review the permissions before approving.")) - .font(.callout) + Text("An external app is asking for an API token. Review the permissions before approving.") + .font(.subheadline) .foregroundStyle(.secondary) destinationLabel - countdownLabel + TimelineView(.periodic(from: .now, by: 1)) { timeline in + countdownLabel(now: timeline.date) + } } .frame(maxWidth: .infinity, alignment: .leading) .padding() @@ -95,11 +106,11 @@ struct PairingApprovalSheet: View { private var destinationLabel: some View { HStack(spacing: 6) { Image(systemName: "arrow.up.forward.app") - .foregroundStyle(Color(nsColor: .secondaryLabelColor)) + .foregroundStyle(.secondary) .imageScale(.small) .accessibilityHidden(true) Text(String(format: String(localized: "Sends the code to %@"), request.redirectDisplayValue)) - .font(.caption) + .font(.subheadline) .foregroundStyle(.secondary) .lineLimit(2) .truncationMode(.middle) @@ -107,117 +118,66 @@ struct PairingApprovalSheet: View { } } - private var countdownLabel: some View { - HStack(spacing: 6) { - Image(systemName: isExpired ? "clock.badge.exclamationmark.fill" : "clock") - .foregroundStyle(isExpired ? .red : Color(nsColor: .secondaryLabelColor)) + private func countdownLabel(now: Date) -> some View { + let remaining = max(0, Int(codeExpiresAt.timeIntervalSince(now).rounded(.up))) + let expired = isExpired || remaining == 0 + return HStack(spacing: 6) { + Image(systemName: expired ? "clock.badge.exclamationmark.fill" : "clock") + .foregroundStyle(expired ? Color.red : Color.secondary) .imageScale(.small) .accessibilityHidden(true) - countdownText - .font(.caption) - .monospacedDigit() - .foregroundStyle(.secondary) - .contentTransition(.numericText()) - } - } - - private var remainingSeconds: Int { - let interval = codeExpiresAt.timeIntervalSince(now) - return max(0, Int(interval.rounded(.up))) - } - - private var isExpired: Bool { - remainingSeconds <= 0 - } - - private var countdownText: Text { - if isExpired { - return Text(String(localized: "Code expired")) + Group { + if expired { + Text("Code expired") + } else { + Text("Code expires in ^[\(remaining) second](inflect: true)") + } + } + .font(.subheadline) + .monospacedDigit() + .foregroundStyle(.secondary) + .contentTransition(.numericText()) } - return Text("Code expires in ^[\(remainingSeconds) second](inflect: true)") } private var permissionsSection: some View { - Section(String(localized: "Permission Level")) { - Picker(String(localized: "Permission"), selection: $permissions) { + Section { + Picker(selection: $permissions) { ForEach(TokenPermissions.allCases) { permission in Text(permission.displayName).tag(permission) } + } label: { + Text("Permissions") + Text(permissions.summary) } .pickerStyle(.segmented) - .labelsHidden() - - Text(permissionsDescription) - .font(.caption) - .foregroundStyle(.secondary) + .accessibilityIdentifier("pairing-permissions-picker") } } - private var connectionAccessSection: some View { - Section(String(localized: "Allowed Connections")) { - Picker(String(localized: "Access"), selection: $connectionAccess) { - Text(String(localized: "All Connections")).tag(ConnectionAccessMode.all) - Text(String(localized: "Select Connections")).tag(ConnectionAccessMode.selected) + private var connectionsSection: some View { + Section { + Picker(selection: $access) { + Text("All").tag(Access.all) + Text("Selected").tag(Access.selected) + } label: { + Text("Connections") } - .labelsHidden() - .onChange(of: connectionAccess) { newValue in - if newValue == .all { - selectedConnectionIds = Set(connections.map(\.id)) - } else if selectedConnectionIds.isEmpty { + .pickerStyle(.menu) + .accessibilityIdentifier("pairing-connections-picker") + .onChange(of: access) { newValue in + if newValue == .all || selectedConnectionIds.isEmpty { selectedConnectionIds = Set(connections.map(\.id)) } } - if connectionAccess == .selected { - connectionList - } - } - } - - @ViewBuilder - private var connectionList: some View { - if connections.isEmpty { - Text(String(localized: "No saved connections")) - .foregroundStyle(.secondary) - } else { - HStack { - NativeSearchField(text: $connectionSearch, placeholder: String(localized: "Search connections")) - Spacer() - Button(String(localized: "Select All")) { - selectedConnectionIds.formUnion(filteredConnections.map(\.id)) - } - Button(String(localized: "Deselect All")) { - selectedConnectionIds.subtract(filteredConnections.map(\.id)) - } - } - - ScrollView { - VStack(alignment: .leading, spacing: 0) { - ForEach(filteredConnections) { connection in - Toggle(isOn: connectionBinding(for: connection.id)) { - HStack(spacing: 6) { - Text(connection.name) - Text(connection.type.displayName) - .font(.caption) - .foregroundStyle(.secondary) - } - } - .toggleStyle(.checkbox) - .padding(.vertical, 2) - } - } + if access == .selected { + ConnectionAllowlistSection( + selection: $selectedConnectionIds, + connections: connections, + showsSelectAll: true + ) } - .frame(maxHeight: 200) - } - } - - private var filteredConnections: [DatabaseConnection] { - let trimmed = connectionSearch.trimmingCharacters(in: .whitespacesAndNewlines) - guard !trimmed.isEmpty else { return connections } - let lowercased = trimmed.lowercased() - return connections.filter { connection in - connection.name.lowercased().contains(lowercased) - || connection.type.displayName.lowercased().contains(lowercased) } } @@ -227,32 +187,46 @@ struct PairingApprovalSheet: View { // Off even when allowed: an agent with a shell can pair to its own redirect, and one Approve must not hand it these. private var hiddenConnectionsSection: some View { - Section(String(localized: "Connections Hidden from AI")) { + Section { if allowsHiddenConnectionListing { - Toggle(String(localized: "List connections hidden from AI"), isOn: $grantsHiddenConnections) - .accessibilityIdentifier("pairing-hidden-connections-toggle") - // swiftlint:disable:next line_length - Text(String(localized: "Adds connections whose AI Policy is Never to this app's list, with each user name. The app still cannot query them. Blocked connections stay hidden.")) - .font(.caption) - .foregroundStyle(.secondary) + Toggle(isOn: $grantsHiddenConnections) { + Text("List connections hidden from AI") + Text("Adds connections whose AI Policy is Never to this app's list, with each user name. The app still cannot query them. Blocked connections stay hidden.") + } + .accessibilityIdentifier("pairing-hidden-connections-toggle") } else { // swiftlint:disable:next line_length - Text(String(localized: "This app also asks to list connections hidden from AI. To allow that, turn on “Allow apps to list connections hidden from AI” in Settings > MCP, then pair again.")) - .font(.caption) + Text("This app also asks to list connections hidden from AI. To allow that, turn on “Allow apps to list connections hidden from AI” in Settings > MCP, then pair again.") + .font(.subheadline) .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) .accessibilityIdentifier("pairing-hidden-connections-refusal") } + } header: { + Text("Connections Hidden from AI") } } private var expirySection: some View { - Section(String(localized: "Expiration")) { - Picker(String(localized: "Expires"), selection: $expiry) { - ForEach(ExpiryOption.allCases) { option in + Section { + Picker(selection: $expiry) { + ForEach(TokenExpiry.allCases) { option in Text(option.displayName).tag(option) } + } label: { + Text("Expires") + } + .pickerStyle(.menu) + .accessibilityIdentifier("pairing-expiry-picker") + + if expiry == .custom { + DatePicker( + String(localized: "Expiration date"), + selection: $customExpiry, + in: Date.now..., + displayedComponents: .date + ) } - .labelsHidden() } } @@ -261,8 +235,8 @@ struct PairingApprovalSheet: View { Button(String(localized: "Approve")) { let approval = PairingApproval( grantedPermissions: permissions, - allowedConnectionIds: connectionAccess == .selected ? selectedConnectionIds : nil, - expiresAt: expiry.resolvedDate, + allowedConnectionIds: access == .selected ? selectedConnectionIds : nil, + expiresAt: expiry.resolvedDate(custom: customExpiry), extraScopes: grantsHiddenConnections && allowsHiddenConnectionListing ? [.connectionsDisplay] : [] ) onComplete(.success(approval)) @@ -278,68 +252,7 @@ struct PairingApprovalSheet: View { private var approveDisabled: Bool { if isExpired { return true } - if connectionAccess == .selected && selectedConnectionIds.isEmpty { return true } + if access == .selected && selectedConnectionIds.isEmpty { return true } return false } - - private func connectionBinding(for id: UUID) -> Binding { - Binding( - get: { selectedConnectionIds.contains(id) }, - set: { isSelected in - if isSelected { - selectedConnectionIds.insert(id) - } else { - selectedConnectionIds.remove(id) - } - } - ) - } - - private var permissionsDescription: String { - switch permissions { - case .readOnly: - String(localized: "Read schema and run SELECT queries.") - case .readWrite: - String(localized: "Read schema and run any non-destructive query, including INSERT, UPDATE, and DELETE.") - case .fullAccess: - String(localized: "Full access including destructive DDL after explicit confirmation.") - } - } -} - -private enum ConnectionAccessMode: String, Identifiable, Sendable { - case all - case selected - - var id: String { rawValue } -} - -private enum ExpiryOption: String, CaseIterable, Identifiable, Sendable { - case never - case oneDay - case sevenDays - case thirtyDays - case ninetyDays - - var id: String { rawValue } - - var displayName: String { - switch self { - case .never: String(localized: "Never") - case .oneDay: String(localized: "1 day") - case .sevenDays: String(localized: "7 days") - case .thirtyDays: String(localized: "30 days") - case .ninetyDays: String(localized: "90 days") - } - } - - var resolvedDate: Date? { - switch self { - case .never: nil - case .oneDay: Calendar.current.date(byAdding: .day, value: 1, to: .now) - case .sevenDays: Calendar.current.date(byAdding: .day, value: 7, to: .now) - case .thirtyDays: Calendar.current.date(byAdding: .day, value: 30, to: .now) - case .ninetyDays: Calendar.current.date(byAdding: .day, value: 90, to: .now) - } - } } diff --git a/apple/TablePro/Views/Settings/Sections/SyncSection.swift b/apple/TablePro/Views/Settings/Sections/SyncSection.swift deleted file mode 100644 index ba96e48ba2..0000000000 --- a/apple/TablePro/Views/Settings/Sections/SyncSection.swift +++ /dev/null @@ -1,112 +0,0 @@ -// -// SyncSection.swift -// TablePro -// - -import SwiftUI -import TableProSyncTransport - -struct SyncSection: View { - @ObservedObject private var featureAccess = FeatureAccess.shared - @ObservedObject private var settingsManager = AppSettingsManager.shared - @ObservedObject private var syncCoordinator = SyncCoordinator.shared - - private var isProAvailable: Bool { - featureAccess.isAvailable(.iCloudSync) - } - - var body: some View { - Section { - Toggle("Sync this Mac with iCloud", isOn: $settingsManager.sync.enabled) - .help("Syncs connections, table favorites, settings, and SSH profiles across your Macs via iCloud.") - .disabled(!isProAvailable) - - if !isProAvailable { - LicenseGateRow(feature: .iCloudSync) - } - } header: { - Text("iCloud Sync") - } - - if settingsManager.sync.enabled && isProAvailable { - statusSection - categoriesSection - } - } - - // MARK: - Status - - // A blocker is explained by the notice at the top of the pane, so the Status row only names it. - private var statusSection: some View { - let presentation = SyncStatusPresentation(status: syncCoordinator.syncStatus) - return Section("Sync Status") { - LabeledContent(String(localized: "Status")) { - HStack(spacing: 4) { - if syncCoordinator.syncStatus.isSyncing { - ProgressView() - .controlSize(.small) - } else { - Image(systemName: presentation.symbolName) - .foregroundStyle(presentation.isWarning ? Color.orange : Color.secondary) - .accessibilityHidden(true) - } - Text(presentation.title) - } - } - - if let lastSync = syncCoordinator.lastSyncDate { - LabeledContent(String(localized: "Last Synced")) { - Text(lastSync, style: .relative) - } - } - - if presentation.offersSyncNow { - Button(String(localized: "Sync Now")) { - Task { await syncCoordinator.syncNow() } - } - .disabled(syncCoordinator.syncStatus.isSyncing) - } - - if let detail = presentation.statusDetail { - Text(detail) - .font(.caption) - .foregroundStyle(.secondary) - .fixedSize(horizontal: false, vertical: true) - } - } - } - - // MARK: - Categories - - private var categoriesSection: some View { - Section("Sync Categories") { - Toggle("Connections", isOn: $settingsManager.sync.syncConnections) - .onChange(of: settingsManager.sync.syncConnections) { newValue in - if !newValue, settingsManager.sync.syncPasswords { - settingsManager.sync.syncPasswords = false - } - } - - if settingsManager.sync.syncConnections { - Toggle("Passwords", isOn: $settingsManager.sync.syncPasswords) - .help("Syncs passwords via iCloud Keychain (end-to-end encrypted).") - .padding(.leading, 20) - - Text("Only affects new saves. Re-save a password to update its sync.") - .font(.caption) - .foregroundStyle(.secondary) - .fixedSize(horizontal: false, vertical: true) - .padding(.leading, 20) - } - - Toggle("Groups & Tags", isOn: $settingsManager.sync.syncGroupsAndTags) - Toggle("SSH Profiles", isOn: $settingsManager.sync.syncSSHProfiles) - Toggle("Credential Profiles", isOn: $settingsManager.sync.syncCredentialProfiles) - Toggle("Settings", isOn: $settingsManager.sync.syncSettings) - Toggle("Table Favorites", isOn: $settingsManager.sync.syncTableFavorites) - Toggle("Table Folders", isOn: $settingsManager.sync.syncTableFolders) - Toggle("Database Favorites", isOn: $settingsManager.sync.syncDatabaseFavorites) - Toggle("Saved Queries", isOn: $settingsManager.sync.syncSQLFavorites) - } - } -} diff --git a/apple/TablePro/Views/Settings/Sections/TrustedExternalConnectionsSection.swift b/apple/TablePro/Views/Settings/Sections/TrustedExternalConnectionsSection.swift index e0a1dc3802..806bb88c6c 100644 --- a/apple/TablePro/Views/Settings/Sections/TrustedExternalConnectionsSection.swift +++ b/apple/TablePro/Views/Settings/Sections/TrustedExternalConnectionsSection.swift @@ -1,58 +1,126 @@ -// -// TrustedExternalConnectionsSection.swift -// TablePro -// - +import Combine import SwiftUI -struct TrustedExternalConnectionsSection: View { - private let store: ExternalConnectionTrustStore +internal struct TrustedLinkEntry: Identifiable, Equatable, Sendable { + internal let key: ExternalConnectionTrustKey + internal let title: String + // Two saved connections can share type, host, database and user, so the name tells their entries apart. + internal let savedConnectionName: String? + + internal var id: ExternalConnectionTrustKey { key } +} + +@MainActor +internal final class TrustedLinksModel: ObservableObject { + @Published internal private(set) var entries: [TrustedLinkEntry] = [] - @State private var entries: [TrustedExternalConnection] = [] + private let store: ExternalConnectionTrustStore + private let savedConnectionNames: @MainActor () -> [UUID: String] + private var changes: AnyCancellable? - init(store: ExternalConnectionTrustStore = .shared) { + internal init( + store: ExternalConnectionTrustStore = .shared, + savedConnectionNames: @escaping @MainActor () -> [UUID: String] = TrustedLinksModel.savedConnectionNames + ) { self.store = store + self.savedConnectionNames = savedConnectionNames + refresh() + changes = store.changes.sink { [weak self] _ in + self?.refresh() + } } - var body: some View { - Section { - if entries.isEmpty { - Text("No links are trusted yet.") - .foregroundStyle(.secondary) - } else { - ForEach(entries) { entry in - LabeledContent { - Button("Forget") { - store.revoke(entry.key) - refresh() - } - } label: { - Text(entry.key.displayDescription) - if let name = savedConnectionName(of: entry) { - Text(String(format: String(localized: "Saved connection “%@”"), name)) + internal func refresh() { + let trusted = store.entries().sorted { $0.trustedAt > $1.trustedAt } + let names = trusted.contains { $0.key.savedConnectionId != nil } ? savedConnectionNames() : [:] + let updated = trusted.map { entry in + TrustedLinkEntry( + key: entry.key, + title: entry.key.displayDescription, + savedConnectionName: entry.key.savedConnectionId.flatMap { names[$0] } + ) + } + guard updated != entries else { return } + entries = updated + } + + internal func forget(_ key: ExternalConnectionTrustKey) { + store.revoke(key) + } + + internal func forgetAll() { + store.revokeAll() + } + + static func savedConnectionNames() -> [UUID: String] { + Dictionary( + ConnectionStorage.shared.loadConnections().map { ($0.id, $0.name) }, + uniquingKeysWith: { first, _ in first } + ) + } +} + +internal struct TrustedLinksPage: View { + @EnvironmentObject private var model: TrustedLinksModel + @State private var isConfirmingForgetAll = false + + internal var body: some View { + Form { + Section { + if model.entries.isEmpty { + Text("No trusted links") + .foregroundStyle(.secondary) + } else { + ForEach(model.entries) { entry in + TrustedLinkRow(entry: entry) { + model.forget(entry.key) } } } - Button(String(localized: "Forget All"), role: .destructive) { - store.revokeAll() - refresh() + SettingsHelpRow( + "A link you chose Always Allow for connects without asking again. Only connections on this Mac can be trusted." + ) + } footer: { + SettingsSectionActions { + Button(String(localized: "Forget All…")) { + isConfirmingForgetAll = true + } + .disabled(model.entries.isEmpty) + .accessibilityIdentifier("trusted-links-forget-all-button") } } - } header: { - Text("Trusted Links") - } footer: { - Text("Links you chose to always allow. TablePro connects without asking. Only connections on this machine can be trusted.") } - .onAppear(perform: refresh) + .formStyle(.grouped) + .alert(String(localized: "Forget All Trusted Links?"), isPresented: $isConfirmingForgetAll) { + Button(String(localized: "Forget All"), role: .destructive) { + model.forgetAll() + } + Button(String(localized: "Cancel"), role: .cancel) {} + } message: { + Text("Each link asks again before it connects. This applies only to this Mac.") + } + .accessibilityElement(children: .contain) + .accessibilityIdentifier(SettingsPage.trustedLinks.pageIdentifier) } +} - // Two saved connections can share type, host, database and user, so the name tells their entries apart. - private func savedConnectionName(of entry: TrustedExternalConnection) -> String? { - entry.key.savedConnectionId.flatMap { ConnectionStorage.shared.loadConnection(id: $0)?.name } +private struct TrustedLinkRow: View { + let entry: TrustedLinkEntry + let onForget: () -> Void + + var body: some View { + SettingsRecordRow(title: entry.title, subtitle: subtitle) { + Button(String(localized: "Forget"), action: onForget) + .accessibilityLabel(String(format: String(localized: "Forget %@"), entry.title)) + } + .help(entry.title) + .contextMenu { + Button(String(localized: "Forget"), action: onForget) + } } - private func refresh() { - entries = store.entries().sorted { $0.trustedAt > $1.trustedAt } + private var subtitle: String? { + entry.savedConnectionName.map { String(format: String(localized: "Saved connection “%@”"), $0) } } } diff --git a/apple/TablePro/Views/Settings/Sections/TypographySection.swift b/apple/TablePro/Views/Settings/Sections/TypographySection.swift index e1daec9e3b..e3032fa4f0 100644 --- a/apple/TablePro/Views/Settings/Sections/TypographySection.swift +++ b/apple/TablePro/Views/Settings/Sections/TypographySection.swift @@ -1,55 +1,149 @@ import SwiftUI -/// Fonts are settings, not theme: importing Dracula must never change someone's font or size. -internal struct TypographySection: View { - internal enum Domain { +// Fonts are settings, not theme: importing a theme never changes someone's font or size. +internal struct TypographyRows: View { + internal enum Domain: Sendable { case editor case dataGrid - internal var caption: String { + internal var familyTitle: LocalizedStringKey { + switch self { + case .editor: "Family" + case .dataGrid: "Font" + } + } + + internal var sizeTitle: LocalizedStringKey { + switch self { + case .editor: "Size" + case .dataGrid: "Font size" + } + } + + internal var subtitle: String { switch self { case .editor: - return String(localized: "Applies to the SQL editor, the JSON viewer's Text mode, and the previews.") + String(localized: "The SQL editor, the JSON viewer's Text mode and SQL previews. Applies to this Mac.") case .dataGrid: - return String(localized: "Applies to grid cells, the inspector, cell popovers and the row diff.") + String(localized: "Grid cells, the inspector, cell popovers and the row diff. Applies to this Mac.") + } + } + + internal func missingFamilyNotice(_ family: String) -> String { + switch self { + case .editor: + String(format: String(localized: "%@ isn't installed. The editor uses System Mono."), family) + case .dataGrid: + String(format: String(localized: "%@ isn't installed. Grids use System Mono."), family) + } + } + + internal var familyIdentifier: String { + switch self { + case .editor: "editor-font-family" + case .dataGrid: "data-font-family" + } + } + + internal var sizeIdentifier: String { + switch self { + case .editor: "editor-font-size" + case .dataGrid: "data-font-size" + } + } + + internal func family(of typography: TypographySettings) -> String { + switch self { + case .editor: typography.editorFontFamily + case .dataGrid: typography.dataGridFontFamily + } + } + + internal func setFamily(_ family: String, in typography: inout TypographySettings) { + switch self { + case .editor: typography.editorFontFamily = family + case .dataGrid: typography.dataGridFontFamily = family + } + } + + // The size ThemeEngine draws, so an out-of-range stored size never leaves the pop-up blank. + internal func displayedSize(of typography: TypographySettings) -> Int { + switch self { + case .editor: typography.clampedEditorFontSize + case .dataGrid: typography.clampedDataGridFontSize + } + } + + internal func setSize(_ size: Int, in typography: inout TypographySettings) { + switch self { + case .editor: typography.editorFontSize = size + case .dataGrid: typography.dataGridFontSize = size } } } - internal let domain: Domain - @Binding internal var settings: TypographySettings + private let domain: Domain + @Binding private var typography: TypographySettings + @ObservedObject private var fonts = MonospacedFontFamilies.shared + + internal init(domain: Domain, typography: Binding) { + self.domain = domain + self._typography = typography + } internal var body: some View { - Section { - Picker(String(localized: "Family:"), selection: familyBinding) { - ForEach(EditorFontResolver.availableMonospacedFamilies) { family in - Text(family.displayName).tag(family.id) - } + let family = domain.family(of: typography) + let missing = Self.missingFamily(family, in: fonts.families) + + Picker(selection: Self.familyBinding(domain, of: $typography)) { + ForEach(fonts.families) { option in + Text(verbatim: option.displayName).tag(option.id) } + if let missing { + Divider() + Text(verbatim: Self.notInstalledTitle(missing)).tag(missing) + } + } label: { + Text(domain.familyTitle) + if let missing { + NoticeLabel(domain.missingFamilyNotice(missing), severity: .warning) + .font(.subheadline) + } else { + Text(domain.subtitle) + } + } + .accessibilityIdentifier(domain.familyIdentifier) - Picker(String(localized: "Size:"), selection: sizeBinding) { - ForEach(TypographySettings.sizeRange, id: \.self) { size in - Text(verbatim: "\(size) pt").tag(size) - } + Picker(selection: Self.sizeBinding(domain, of: $typography)) { + ForEach(TypographySettings.sizeRange, id: \.self) { size in + Text("\(size) pt").tag(size) } - } header: { - Text("Font") - } footer: { - Text(domain.caption) + } label: { + Text(domain.sizeTitle) } + .accessibilityIdentifier(domain.sizeIdentifier) } - private var familyBinding: Binding { - switch domain { - case .editor: return $settings.editorFontFamily - case .dataGrid: return $settings.dataGridFontFamily - } + // A saved family that is gone stays selectable, so the pop-up never draws blank and nothing is rewritten. + internal static func missingFamily(_ family: String, in families: [FontFamilyOption]) -> String? { + families.contains { $0.id == family } ? nil : family } - private var sizeBinding: Binding { - switch domain { - case .editor: return $settings.editorFontSize - case .dataGrid: return $settings.dataGridFontSize - } + internal static func notInstalledTitle(_ family: String) -> String { + String(format: String(localized: "%@ (Not Installed)"), family) + } + + internal static func familyBinding(_ domain: Domain, of typography: Binding) -> Binding { + Binding( + get: { domain.family(of: typography.wrappedValue) }, + set: { family in domain.setFamily(family, in: &typography.wrappedValue) } + ) + } + + internal static func sizeBinding(_ domain: Domain, of typography: Binding) -> Binding { + Binding( + get: { domain.displayedSize(of: typography.wrappedValue) }, + set: { size in domain.setSize(size, in: &typography.wrappedValue) } + ) } } diff --git a/apple/TablePro/Views/Settings/SettingsDetailViewController.swift b/apple/TablePro/Views/Settings/SettingsDetailViewController.swift new file mode 100644 index 0000000000..b37330b245 --- /dev/null +++ b/apple/TablePro/Views/Settings/SettingsDetailViewController.swift @@ -0,0 +1,85 @@ +import AppKit +import SwiftUI + +@MainActor +internal protocol SettingsPaneContextProviding: AnyObject { + func context(for pane: SettingsPane) -> SettingsPaneContext +} + +// Keeps one hosting controller per visited pane while the window is open: rebuilding a pane on +// every sidebar click cost 136 to 374 ms and dropped its scroll position and @State. +@MainActor +internal final class SettingsDetailViewController: NSViewController { + internal weak var provider: SettingsPaneContextProviding? + private var hosts: [SettingsPane: NSHostingController] = [:] + internal private(set) var shownPane: SettingsPane? + + internal init() { + super.init(nibName: nil, bundle: nil) + } + + @available(*, unavailable) + internal required init?(coder: NSCoder) { + fatalError("SettingsDetailViewController does not support NSCoder init") + } + + override internal func loadView() { + view = NSView() + } + + internal func host(for pane: SettingsPane) -> NSHostingController? { + hosts[pane] + } + + internal func show(_ pane: SettingsPane) { + guard isViewLoaded, let provider else { return } + let existing = hosts[pane] + guard pane != shownPane || existing == nil else { return } + let host = existing ?? makeHost(for: provider.context(for: pane)) + for (other, hidden) in hosts where other != pane { + // Hidden hosts leave the key view loop and the accessibility tree, and add nothing to a live resize. + hidden.view.isHidden = true + hidden.view.autoresizingMask = [] + } + host.view.frame = view.bounds + host.view.autoresizingMask = [.width, .height] + host.view.isHidden = false + // AX hit testing stops at the topmost subview under a point even when it is hidden. A reorder never leaves the window. + view.addSubview(host.view, positioned: .above, relativeTo: nil) + shownPane = pane + // A show before the window is key counts when it becomes key, so opening counts once. + if view.window?.isKeyWindow == true { + provider.context(for: pane).visit.bump() + } + } + + internal func windowDidBecomeKey() { + guard let shownPane, let provider else { return } + provider.context(for: shownPane).visit.bump() + } + + // After a close, so no pane observer or task outlives the window. + internal func releaseHosts() { + for host in hosts.values { + host.view.removeFromSuperview() + host.removeFromParent() + } + hosts.removeAll() + shownPane = nil + } + + private func makeHost(for context: SettingsPaneContext) -> NSHostingController { + let host = NSHostingController(rootView: SettingsPaneHost(context: context)) + // A split item's hosting controller fixes its fitting size as a required minimum unless this is cleared. + host.sizingOptions = [] + if #available(macOS 14.0, *) { + // The window title and toolbar belong to the shell; a pane's navigationTitle must not reach them. + host.sceneBridgingOptions = [] + } + addChild(host) + host.view.frame = view.bounds + view.addSubview(host.view) + hosts[context.pane] = host + return host + } +} diff --git a/apple/TablePro/Views/Settings/SettingsNavigation.swift b/apple/TablePro/Views/Settings/SettingsNavigation.swift new file mode 100644 index 0000000000..ec0a754340 --- /dev/null +++ b/apple/TablePro/Views/Settings/SettingsNavigation.swift @@ -0,0 +1,482 @@ +import Foundation + +enum SettingsSectionID: String, CaseIterable, Sendable { + case app + case workspace + case integrations + case account +} + +struct SettingsSection: Equatable, Sendable { + let id: SettingsSectionID + let panes: [SettingsPane] +} + +enum SettingsSidebarRow: Hashable, Sendable { + case pane(SettingsPane) + case page(title: String, location: SettingsLocation) + case spacer(before: SettingsSectionID) +} + +struct SettingsSearchResult: Hashable, Sendable { + struct Page: Hashable, Sendable { + let title: String + let location: SettingsLocation + } + + let pane: SettingsPane + let pages: [Page] +} + +// A root location matches its pane; any other location lists as a page row under it. +struct SettingsSearchEntry: Hashable, Sendable { + let title: String + let keywords: [String] + let location: SettingsLocation + + init(title: String, keywords: [String] = [], location: SettingsLocation) { + self.title = title + self.keywords = keywords + self.location = location + } +} + +enum SettingsNavigation { + static let sections: [SettingsSection] = [ + SettingsSection(id: .app, panes: [.general, .appearance, .notifications, .keyboard]), + SettingsSection(id: .workspace, panes: [.connections, .profiles, .sidebar, .editor, .data]), + SettingsSection(id: .integrations, panes: [.ai, .mcp, .plugins]), + SettingsSection(id: .account, panes: [.sync, .account]), + ] + + static let orderedPanes: [SettingsPane] = sections.flatMap(\.panes) + + static let defaultPane: SettingsPane = .general + + static func pane(forURLIdentifier identifier: String) -> SettingsPane? { + SettingsPane(urlIdentifier: identifier) + } + + // Dynamic entries are names only the running app knows: plugin names, AI provider names. + static func results(matching query: String, adding dynamicEntries: [SettingsSearchEntry] = []) -> [SettingsSearchResult] { + index(adding: dynamicEntries).results(matching: query) + } + + static func panes(matching query: String, adding dynamicEntries: [SettingsSearchEntry] = []) -> [SettingsPane] { + results(matching: query, adding: dynamicEntries).map(\.pane) + } + + static func rows(matching query: String, adding dynamicEntries: [SettingsSearchEntry] = []) -> [SettingsSidebarRow] { + guard SettingsSearchIndex.isFiltering(query) else { + return sections.enumerated().flatMap { offset, section -> [SettingsSidebarRow] in + let spacer: [SettingsSidebarRow] = offset == 0 ? [] : [.spacer(before: section.id)] + return spacer + section.panes.map { .pane($0) } + } + } + return results(matching: query, adding: dynamicEntries).flatMap { result -> [SettingsSidebarRow] in + [.pane(result.pane)] + result.pages.map { .page(title: $0.title, location: $0.location) } + } + } + + static var standardEntries: [SettingsSearchEntry] { + let panes = SettingsPane.allCases.map { + SettingsSearchEntry(title: $0.title, keywords: $0.searchKeywords, location: .root($0)) + } + let pages = SettingsPage.allCases.map { + SettingsSearchEntry(title: $0.title, keywords: $0.searchKeywords, location: SettingsLocation(page: $0)) + } + return panes + pages + } + + private static let standardIndex = SettingsSearchIndex(entries: standardEntries) + + private static func index(adding dynamicEntries: [SettingsSearchEntry]) -> SettingsSearchIndex { + dynamicEntries.isEmpty ? standardIndex : standardIndex.adding(dynamicEntries) + } +} + +// Each term must start a word of one entry, so "date" never finds "Update". +struct SettingsSearchIndex: Sendable { + private struct Prepared: Sendable { + let entry: SettingsSearchEntry + let wordStarts: [String] + + func matches(_ terms: [String]) -> Bool { + terms.allSatisfy { term in wordStarts.contains { $0.hasPrefix(term) } } + } + } + + private let locale: Locale + private let prepared: [Prepared] + + init(entries: [SettingsSearchEntry], locale: Locale = .current) { + self.locale = locale + self.prepared = entries.map { Self.prepare($0, locale: locale) } + } + + private init(locale: Locale, prepared: [Prepared]) { + self.locale = locale + self.prepared = prepared + } + + func adding(_ entries: [SettingsSearchEntry]) -> SettingsSearchIndex { + SettingsSearchIndex(locale: locale, prepared: prepared + entries.map { Self.prepare($0, locale: locale) }) + } + + func results(matching query: String) -> [SettingsSearchResult] { + let terms = Self.terms(in: query, locale: locale) + guard !terms.isEmpty else { + return SettingsNavigation.orderedPanes.map { SettingsSearchResult(pane: $0, pages: []) } + } + var matchedPanes: Set = [] + var pages: [SettingsPane: [SettingsSearchResult.Page]] = [:] + for item in prepared where item.matches(terms) { + let location = item.entry.location + if location.isRoot { + matchedPanes.insert(location.pane) + } else if pages[location.pane]?.contains(where: { $0.location == location }) != true { + pages[location.pane, default: []].append(.init(title: item.entry.title, location: location)) + } + } + return SettingsNavigation.orderedPanes.compactMap { pane in + let panePages = pages[pane] ?? [] + guard matchedPanes.contains(pane) || !panePages.isEmpty else { return nil } + return SettingsSearchResult(pane: pane, pages: panePages) + } + } + + static func isFiltering(_ query: String, locale: Locale = .current) -> Bool { + !terms(in: query, locale: locale).isEmpty + } + + static func terms(in query: String, locale: Locale) -> [String] { + query.split(whereSeparator: \.isWhitespace) + .map { fold(String($0).trimmingCharacters(in: .punctuationCharacters), locale: locale) } + .filter { term in term.contains { $0.isLetter || $0.isNumber } } + } + + static func fold(_ text: String, locale: Locale) -> String { + // Vietnamese đ is a letter of its own, not d with a diacritic, so folding keeps it. + text.folding(options: [.caseInsensitive, .diacriticInsensitive, .widthInsensitive], locale: locale) + .replacingOccurrences(of: "đ", with: "d") + } + + private static func prepare(_ entry: SettingsSearchEntry, locale: Locale) -> Prepared { + let texts = [entry.title] + entry.keywords + return Prepared(entry: entry, wordStarts: texts.flatMap { wordStarts(in: fold($0, locale: locale)) }) + } + + // Han text has no spaces, so each ideograph also starts a word. + private static func wordStarts(in text: String) -> [String] { + var starts: Set = [] + text.enumerateSubstrings(in: text.startIndex..