From 8c97466e0d0beb4625101465d2a496bbfaefd0e8 Mon Sep 17 00:00:00 2001 From: leoars <6502186+leoars@users.noreply.github.com> Date: Thu, 19 Nov 2026 16:33:20 -0300 Subject: [PATCH 1/6] [Claude] Sincroniza a fonte do beta.1: idiomas, temas, planos, PostGIS e Options MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fonte e testes do repositório de desenvolvimento de 3ab5272 (alpha.7) até 06b2219 (M1143): interface em 8 idiomas, temas do SSMS, plano em texto, JSON e Compare Showplan, PostGIS em EWKT, aviso de nova versão, páginas de Options com os padrões do SSMS, caixas de mensagem próprias e correções de teclado, escala e desempenho. Test-Integration ganha -KeyboardRealOnly e -SpatialOnly (mantendo -TestPort); Test-PackageLaunch abre em inglês. Co-Authored-By: Claude Opus 5.5 --- scripts/Test-Integration.ps1 | 20 +- scripts/Test-PackageLaunch.ps1 | 2 + src/PGMS.Desktop/ActivityMonitorView.xaml.cs | 11 +- src/PGMS.Desktop/AiQueryGenerator.cs | 4 +- src/PGMS.Desktop/AiSettingsDialog.xaml.cs | 2 +- src/PGMS.Desktop/App.xaml.cs | 2 + src/PGMS.Desktop/BackupDialog.xaml.cs | 6 +- src/PGMS.Desktop/ChangeScriptDialog.xaml.cs | 2 +- .../CheckConstraintDialog.xaml.cs | 2 +- src/PGMS.Desktop/CodeSnippetsManagerDialog.cs | 173 + src/PGMS.Desktop/ColumnTypeDialog.xaml.cs | 2 +- .../ConcurrentIndexDialog.xaml.cs | 4 +- src/PGMS.Desktop/ConnectionDialog.xaml | 2 +- src/PGMS.Desktop/ConnectionDialog.xaml.cs | 3 +- src/PGMS.Desktop/CrashReporter.cs | 2 +- src/PGMS.Desktop/CreateTypeDialog.xaml.cs | 2 +- src/PGMS.Desktop/DatabaseDiagramView.xaml.cs | 2 +- src/PGMS.Desktop/DatabaseEditDialog.xaml.cs | 2 +- src/PGMS.Desktop/DiagramDescriptionDialogs.cs | 4 +- src/PGMS.Desktop/DiagramDialogs.cs | 4 +- src/PGMS.Desktop/DockTitleTranslation.cs | 106 + src/PGMS.Desktop/DomainDialog.xaml.cs | 2 +- src/PGMS.Desktop/EditRowsView.xaml.cs | 4 +- src/PGMS.Desktop/EditorAppearance.cs | 2 +- src/PGMS.Desktop/EnumDialog.xaml.cs | 2 +- src/PGMS.Desktop/EnvironmentOptions.cs | 128 +- .../ExecutionPlanComparisonView.cs | 111 + src/PGMS.Desktop/ExecutionPlanView.cs | 43 +- src/PGMS.Desktop/ExplorerMenus.cs | 6 +- src/PGMS.Desktop/FeatureSearch.cs | 4 +- src/PGMS.Desktop/ForeignKeyDialog.xaml.cs | 2 +- src/PGMS.Desktop/IdentityColumnDialog.xaml.cs | 2 +- src/PGMS.Desktop/Localization.cs | 232 ++ src/PGMS.Desktop/LocalizedMessageBox.cs | 27 + src/PGMS.Desktop/MainWindow.Bookmarks.cs | 2 +- src/PGMS.Desktop/MainWindow.Close.cs | 11 +- src/PGMS.Desktop/MainWindow.CodeSnippets.cs | 22 + .../MainWindow.ConnectionTexts.cs | 1 + src/PGMS.Desktop/MainWindow.Connections.cs | 5 +- src/PGMS.Desktop/MainWindow.Customization.cs | 2 +- src/PGMS.Desktop/MainWindow.Databases.cs | 2 +- src/PGMS.Desktop/MainWindow.DeferredTabs.cs | 127 + src/PGMS.Desktop/MainWindow.Diagrams.cs | 6 +- src/PGMS.Desktop/MainWindow.Documents.cs | 151 + src/PGMS.Desktop/MainWindow.EditorSpecials.cs | 116 + src/PGMS.Desktop/MainWindow.Encoding.cs | 2 +- src/PGMS.Desktop/MainWindow.Extensions.cs | 2 +- src/PGMS.Desktop/MainWindow.Files.cs | 5 +- src/PGMS.Desktop/MainWindow.FindInFiles.cs | 6 +- src/PGMS.Desktop/MainWindow.Navigation.cs | 178 + src/PGMS.Desktop/MainWindow.ObjectScripts.cs | 2 +- src/PGMS.Desktop/MainWindow.Panes.cs | 3 +- src/PGMS.Desktop/MainWindow.PlanCommands.cs | 95 + src/PGMS.Desktop/MainWindow.Properties.cs | 2 + src/PGMS.Desktop/MainWindow.QueryDesigner.cs | 2 +- src/PGMS.Desktop/MainWindow.QueryMenu.cs | 1 + src/PGMS.Desktop/MainWindow.Recovery.cs | 71 +- src/PGMS.Desktop/MainWindow.Results.cs | 12 +- src/PGMS.Desktop/MainWindow.SchemaCompare.cs | 1 + src/PGMS.Desktop/MainWindow.TableChildren.cs | 6 +- src/PGMS.Desktop/MainWindow.Tabs.cs | 37 +- src/PGMS.Desktop/MainWindow.Templates.cs | 4 +- src/PGMS.Desktop/MainWindow.ToolWindows.cs | 89 +- src/PGMS.Desktop/MainWindow.Updates.cs | 87 + src/PGMS.Desktop/MainWindow.ViewDesigners.cs | 4 +- src/PGMS.Desktop/MainWindow.Warmup.cs | 2 +- src/PGMS.Desktop/MainWindow.xaml | 59 +- src/PGMS.Desktop/MainWindow.xaml.cs | 95 +- src/PGMS.Desktop/NavigationHistory.cs | 54 + src/PGMS.Desktop/ObjectExplorerDetailsView.cs | 17 + src/PGMS.Desktop/OptionsDialog.Keyboard.cs | 2 +- src/PGMS.Desktop/OptionsDialog.Search.cs | 11 +- src/PGMS.Desktop/OptionsDialog.xaml | 230 +- src/PGMS.Desktop/OptionsDialog.xaml.cs | 155 +- src/PGMS.Desktop/PGMS.Desktop.csproj | 2 +- src/PGMS.Desktop/PartitionDialog.xaml.cs | 4 +- src/PGMS.Desktop/PgmsMessageBox.cs | 205 + src/PGMS.Desktop/PreparedQueryDocument.cs | 3 + src/PGMS.Desktop/PrivilegeDialog.xaml.cs | 2 +- src/PGMS.Desktop/QueryDesignerControl.cs | 4 +- src/PGMS.Desktop/QueryHistoryWindow.xaml.cs | 4 +- src/PGMS.Desktop/QueryOptions.cs | 3 +- src/PGMS.Desktop/QueryOptionsDialog.xaml | 2 +- src/PGMS.Desktop/QueryOptionsPages.xaml | 1 + src/PGMS.Desktop/QueryOptionsPages.xaml.cs | 3 +- src/PGMS.Desktop/QueryRecoverySession.cs | 8 +- src/PGMS.Desktop/QueryRecoveryStore.cs | 5 + .../QueryStatisticsWindow.xaml.cs | 4 +- src/PGMS.Desktop/QueryView.Bookmarks.cs | 18 + src/PGMS.Desktop/QueryView.Completion.cs | 17 +- src/PGMS.Desktop/QueryView.Conveniences.cs | 27 +- src/PGMS.Desktop/QueryView.Editing.cs | 7 + src/PGMS.Desktop/QueryView.InfoBar.cs | 5 +- src/PGMS.Desktop/QueryView.LiveStatistics.cs | 4 +- src/PGMS.Desktop/QueryView.Options.cs | 11 + src/PGMS.Desktop/QueryView.Paging.cs | 25 +- src/PGMS.Desktop/QueryView.StackedResults.cs | 142 + src/PGMS.Desktop/QueryView.xaml.cs | 6 +- src/PGMS.Desktop/RegisteredServersHost.cs | 2 +- src/PGMS.Desktop/RelationEditDialog.xaml.cs | 2 +- src/PGMS.Desktop/Resources/Dark.xaml | 4 +- src/PGMS.Desktop/Resources/Shell.xaml | 47 +- src/PGMS.Desktop/Resources/Strings/de.json | 3330 +++++++++++++++++ src/PGMS.Desktop/Resources/Strings/es.json | 3330 +++++++++++++++++ src/PGMS.Desktop/Resources/Strings/fr.json | 3330 +++++++++++++++++ src/PGMS.Desktop/Resources/Strings/it.json | 3330 +++++++++++++++++ src/PGMS.Desktop/Resources/Strings/ja.json | 3330 +++++++++++++++++ src/PGMS.Desktop/Resources/Strings/ko.json | 3330 +++++++++++++++++ src/PGMS.Desktop/Resources/Strings/pt-BR.json | 3330 +++++++++++++++++ src/PGMS.Desktop/ResultDataGrid.cs | 107 + src/PGMS.Desktop/ResultGridStyle.cs | 44 +- src/PGMS.Desktop/RoleDropDialog.xaml.cs | 2 +- src/PGMS.Desktop/RolePasswordInput.cs | 2 +- src/PGMS.Desktop/RoleRenameDialog.xaml.cs | 2 +- src/PGMS.Desktop/SchemaCompareView.cs | 25 +- src/PGMS.Desktop/SchemaEditDialog.xaml.cs | 2 +- src/PGMS.Desktop/SequenceDialog.xaml.cs | 8 +- src/PGMS.Desktop/ServerTlsDialog.xaml.cs | 2 +- src/PGMS.Desktop/SqlFormatter.cs | 79 +- src/PGMS.Desktop/SqlTemplates.cs | 4 +- .../TableConstraintDialog.xaml.cs | 2 +- src/PGMS.Desktop/TableDesignerView.xaml.cs | 18 +- src/PGMS.Desktop/TableEditDialog.xaml.cs | 4 +- .../TablePropertiesDialog.xaml.cs | 2 +- src/PGMS.Desktop/TemplateExplorerView.cs | 4 + src/PGMS.Desktop/Theme.cs | 164 +- src/PGMS.Desktop/UpdateCheck.cs | 126 + src/PGMS.Desktop/ViewModels/CatalogNode.cs | 1 + src/PGMS.Desktop/WindowWorkArea.cs | 36 +- src/PGMS.PostgreSql/CatalogService.cs | 10 +- src/PGMS.PostgreSql/DataTypeCatalog.cs | 20 + src/PGMS.PostgreSql/QueryExecutionOptions.cs | 2 + src/PGMS.PostgreSql/QueryPlanComparison.cs | 80 + src/PGMS.PostgreSql/QueryPlanText.cs | 122 + src/PGMS.PostgreSql/QueryStreaming.cs | 30 +- src/PGMS.PostgreSql/SpatialText.cs | 224 ++ src/PGMS.PostgreSql/TableDesign.cs | 9 +- tests/PGMS.DesktopTests/DeferredTabChecks.cs | 225 ++ .../EditorAppearanceChecks.cs | 2 +- .../EditorConvenienceChecks.cs | 3 + .../PGMS.DesktopTests/EditorSpecialsChecks.cs | 74 + .../EnvironmentPagesChecks.cs | 296 ++ .../ExecutionPlanUiChecks.cs | 2 +- tests/PGMS.DesktopTests/FileTabChecks.cs | 2 +- .../PGMS.DesktopTests/FontsAndColorsChecks.cs | 2 +- tests/PGMS.DesktopTests/GridBenchChecks.cs | 135 + tests/PGMS.DesktopTests/HelpChecks.cs | 2 +- tests/PGMS.DesktopTests/HighlightingChecks.cs | 2 +- tests/PGMS.DesktopTests/LocalizationChecks.cs | 261 ++ .../PGMS.DesktopTests/NavigationTabChecks.cs | 139 + tests/PGMS.DesktopTests/OptionsPageChecks.cs | 2 +- tests/PGMS.DesktopTests/PaneChecks.cs | 4 +- .../PGMS.DesktopTests/ParityOptionsChecks.cs | 103 + tests/PGMS.DesktopTests/PlanSourceUiChecks.cs | 104 + tests/PGMS.DesktopTests/Program.cs | 15 +- .../QueryCloseCommandChecks.cs | 15 +- .../QueryConnectionChecks.cs | 2 +- tests/PGMS.DesktopTests/QueryPlanUiChecks.cs | 1 + .../PGMS.DesktopTests/QueryRecoveryChecks.cs | 1 + tests/PGMS.DesktopTests/RealKeyboardChecks.cs | 189 + .../PGMS.DesktopTests/RecoveryAsyncChecks.cs | 8 +- tests/PGMS.DesktopTests/RecoveryLoadChecks.cs | 4 + .../RepresentativeLoadChecks.cs | 12 +- .../PGMS.DesktopTests/ResultGridLookChecks.cs | 71 + .../ResultsDestinationChecks.cs | 18 + .../SchemaCompareUiChecks.cs | 4 +- .../SequenceConfirmationChecks.cs | 26 +- tests/PGMS.DesktopTests/SqlFormatChecks.cs | 2 +- tests/PGMS.DesktopTests/ThemeChecks.cs | 68 +- tests/PGMS.DesktopTests/TitleBarChecks.cs | 11 +- tests/PGMS.DesktopTests/UpdateCheckChecks.cs | 91 + .../ExtensionTypeChecks.cs | 6 +- tests/PGMS.IntegrationTests/Program.cs | 12 +- .../PGMS.IntegrationTests/QueryPlanChecks.cs | 1 + .../QueryPlanTextChecks.cs | 53 + tests/PGMS.IntegrationTests/SpatialChecks.cs | 191 + 176 files changed, 29402 insertions(+), 366 deletions(-) create mode 100644 src/PGMS.Desktop/CodeSnippetsManagerDialog.cs create mode 100644 src/PGMS.Desktop/DockTitleTranslation.cs create mode 100644 src/PGMS.Desktop/ExecutionPlanComparisonView.cs create mode 100644 src/PGMS.Desktop/Localization.cs create mode 100644 src/PGMS.Desktop/LocalizedMessageBox.cs create mode 100644 src/PGMS.Desktop/MainWindow.CodeSnippets.cs create mode 100644 src/PGMS.Desktop/MainWindow.DeferredTabs.cs create mode 100644 src/PGMS.Desktop/MainWindow.Documents.cs create mode 100644 src/PGMS.Desktop/MainWindow.EditorSpecials.cs create mode 100644 src/PGMS.Desktop/MainWindow.Navigation.cs create mode 100644 src/PGMS.Desktop/MainWindow.PlanCommands.cs create mode 100644 src/PGMS.Desktop/MainWindow.Updates.cs create mode 100644 src/PGMS.Desktop/NavigationHistory.cs create mode 100644 src/PGMS.Desktop/PgmsMessageBox.cs create mode 100644 src/PGMS.Desktop/QueryView.StackedResults.cs create mode 100644 src/PGMS.Desktop/Resources/Strings/de.json create mode 100644 src/PGMS.Desktop/Resources/Strings/es.json create mode 100644 src/PGMS.Desktop/Resources/Strings/fr.json create mode 100644 src/PGMS.Desktop/Resources/Strings/it.json create mode 100644 src/PGMS.Desktop/Resources/Strings/ja.json create mode 100644 src/PGMS.Desktop/Resources/Strings/ko.json create mode 100644 src/PGMS.Desktop/Resources/Strings/pt-BR.json create mode 100644 src/PGMS.Desktop/ResultDataGrid.cs create mode 100644 src/PGMS.Desktop/UpdateCheck.cs create mode 100644 src/PGMS.PostgreSql/QueryPlanComparison.cs create mode 100644 src/PGMS.PostgreSql/QueryPlanText.cs create mode 100644 src/PGMS.PostgreSql/SpatialText.cs create mode 100644 tests/PGMS.DesktopTests/DeferredTabChecks.cs create mode 100644 tests/PGMS.DesktopTests/EditorSpecialsChecks.cs create mode 100644 tests/PGMS.DesktopTests/EnvironmentPagesChecks.cs create mode 100644 tests/PGMS.DesktopTests/GridBenchChecks.cs create mode 100644 tests/PGMS.DesktopTests/LocalizationChecks.cs create mode 100644 tests/PGMS.DesktopTests/NavigationTabChecks.cs create mode 100644 tests/PGMS.DesktopTests/ParityOptionsChecks.cs create mode 100644 tests/PGMS.DesktopTests/PlanSourceUiChecks.cs create mode 100644 tests/PGMS.DesktopTests/RealKeyboardChecks.cs create mode 100644 tests/PGMS.DesktopTests/ResultGridLookChecks.cs create mode 100644 tests/PGMS.DesktopTests/UpdateCheckChecks.cs create mode 100644 tests/PGMS.IntegrationTests/QueryPlanTextChecks.cs create mode 100644 tests/PGMS.IntegrationTests/SpatialChecks.cs diff --git a/scripts/Test-Integration.ps1 b/scripts/Test-Integration.ps1 index 94dc5f6..68d37df 100644 --- a/scripts/Test-Integration.ps1 +++ b/scripts/Test-Integration.ps1 @@ -1,7 +1,14 @@ -param([switch]$ResultsTextOnly, [switch]$TableDesignOnly, [switch]$DiagramsOnly, [switch]$ServerTlsOnly, [switch]$SchemaContextOnly, [switch]$ReportsOnly, [switch]$SessionsOnly, [switch]$PlansOnly, [switch]$ExportOnly, [switch]$ActivityOnly, [switch]$QueryStatisticsOnly, [switch]$GlobalBackupOnly, [switch]$ColumnTypesOnly, [switch]$IndexMaintenanceOnly, [switch]$IndexExpressionsOnly, [switch]$PartitionTablesOnly, [switch]$DesktopOnly, [switch]$CascadeJournalOnly, [switch]$CascadeRoutinesOnly, [switch]$CascadeRollbackOnly, [switch]$RevokePreviewOnly, [switch]$GrantorConcurrencyOnly, [switch]$ExplicitGrantorOnly, [switch]$GrantorCatalogOnly, [switch]$DefaultProcessOnly, [switch]$DefaultDelegationOnly, [switch]$DefaultSchemasOnly, [switch]$DefaultTypesOnly, [switch]$DefaultRoutinesOnly, [switch]$DefaultSequencesOnly, [switch]$DefaultTablesOnly, [switch]$DefaultCancellationOnly, [switch]$DefaultUiOnly, [switch]$DefaultJournalOnly, [switch]$DefaultPrivilegesOnly, [switch]$RoutineBoundariesOnly, [switch]$RoutineProcessOnly, [switch]$RoutineConcurrencyOnly, [switch]$RoutinePrivilegesOnly, [string]$PostgresBin = 'C:\Program Files\PostgreSQL\17\bin', [switch]$BackupFormatsOnly, [switch]$IdentityColumnsOnly, [switch]$RestoreOwnershipOnly, [switch]$UnicodeBackupOnly, [switch]$PrivilegeJournalOnly, [switch]$MaintainPrivilegeOnly, [switch]$PrivilegeCommitOnly, [switch]$UnicodePasswordOnly, [switch]$MembershipOptionsOnly, [switch]$PrivilegeIdentityOnly, [switch]$ColumnPrivilegesOnly, [switch]$PrivilegeCancellationOnly, [switch]$EffectivePrivilegesOnly, [switch]$PrivilegeCommandsOnly, [switch]$SequencePrivilegesOnly, [switch]$CopyOnly, [switch]$AdvancedIndexesOnly, [switch]$SequencesOnly, [switch]$SequenceStateOnly, [switch]$SequenceOwnerOnly, [switch]$AccessibilityOnly, [switch]$ConnectionOnly, [switch]$StreamingOnly, [switch]$ExplorerOnly, [switch]$PropertiesOnly, [switch]$AcceptanceOnly, [ValidateRange(1024,65535)][int]$TestPort = 55439, [switch]$QueryHistoryOnly) +param([switch]$ResultsTextOnly, [switch]$TableDesignOnly, [switch]$DiagramsOnly, [switch]$ServerTlsOnly, [switch]$SchemaContextOnly, [switch]$ReportsOnly, [switch]$SessionsOnly, [switch]$PlansOnly, [switch]$ExportOnly, [switch]$ActivityOnly, [switch]$QueryStatisticsOnly, [switch]$GlobalBackupOnly, [switch]$ColumnTypesOnly, [switch]$IndexMaintenanceOnly, [switch]$IndexExpressionsOnly, [switch]$PartitionTablesOnly, [switch]$DesktopOnly, [switch]$CascadeJournalOnly, [switch]$CascadeRoutinesOnly, [switch]$CascadeRollbackOnly, [switch]$RevokePreviewOnly, [switch]$GrantorConcurrencyOnly, [switch]$ExplicitGrantorOnly, [switch]$GrantorCatalogOnly, [switch]$DefaultProcessOnly, [switch]$DefaultDelegationOnly, [switch]$DefaultSchemasOnly, [switch]$DefaultTypesOnly, [switch]$DefaultRoutinesOnly, [switch]$DefaultSequencesOnly, [switch]$DefaultTablesOnly, [switch]$DefaultCancellationOnly, [switch]$DefaultUiOnly, [switch]$DefaultJournalOnly, [switch]$DefaultPrivilegesOnly, [switch]$RoutineBoundariesOnly, [switch]$RoutineProcessOnly, [switch]$RoutineConcurrencyOnly, [switch]$RoutinePrivilegesOnly, [string]$PostgresBin = 'C:\Program Files\PostgreSQL\17\bin', [switch]$BackupFormatsOnly, [switch]$IdentityColumnsOnly, [switch]$RestoreOwnershipOnly, [switch]$UnicodeBackupOnly, [switch]$PrivilegeJournalOnly, [switch]$MaintainPrivilegeOnly, [switch]$PrivilegeCommitOnly, [switch]$UnicodePasswordOnly, [switch]$MembershipOptionsOnly, [switch]$PrivilegeIdentityOnly, [switch]$ColumnPrivilegesOnly, [switch]$PrivilegeCancellationOnly, [switch]$EffectivePrivilegesOnly, [switch]$PrivilegeCommandsOnly, [switch]$SequencePrivilegesOnly, [switch]$CopyOnly, [switch]$AdvancedIndexesOnly, [switch]$SequencesOnly, [switch]$SequenceStateOnly, [switch]$SequenceOwnerOnly, [switch]$AccessibilityOnly, [switch]$ConnectionOnly, [switch]$StreamingOnly, [switch]$ExplorerOnly, [switch]$PropertiesOnly, [switch]$AcceptanceOnly, [ValidateRange(1024,65535)][int]$TestPort = 55439, [switch]$QueryHistoryOnly, [switch]$SpatialOnly, [switch]$KeyboardRealOnly) $ErrorActionPreference = 'Stop' -if ((@($ResultsTextOnly, $TableDesignOnly, $DiagramsOnly, $SessionsOnly, $PlansOnly, $ExportOnly, $ActivityOnly, $QueryStatisticsOnly, $GlobalBackupOnly, $ColumnTypesOnly, $IndexMaintenanceOnly, $IndexExpressionsOnly, $PartitionTablesOnly, $CascadeJournalOnly, $CascadeRoutinesOnly, $CascadeRollbackOnly, $RevokePreviewOnly, $GrantorConcurrencyOnly, $ExplicitGrantorOnly, $GrantorCatalogOnly, $DefaultProcessOnly, $DefaultDelegationOnly, $DefaultSchemasOnly, $DefaultTypesOnly, $DefaultRoutinesOnly, $DefaultSequencesOnly, $DefaultTablesOnly, $DefaultCancellationOnly, $DefaultUiOnly, $DefaultJournalOnly, $DefaultPrivilegesOnly, $RoutineBoundariesOnly, $RoutineProcessOnly, $RoutineConcurrencyOnly, $RoutinePrivilegesOnly, $BackupFormatsOnly, $IdentityColumnsOnly, $RestoreOwnershipOnly, $UnicodeBackupOnly, $PrivilegeJournalOnly, $MaintainPrivilegeOnly, $PrivilegeCommitOnly, $UnicodePasswordOnly, $ServerTlsOnly, $SchemaContextOnly, $MembershipOptionsOnly, $PrivilegeIdentityOnly, $ColumnPrivilegesOnly, $PrivilegeCancellationOnly, $EffectivePrivilegesOnly, $PrivilegeCommandsOnly, $SequencePrivilegesOnly, $CopyOnly, $AdvancedIndexesOnly, $SequencesOnly, $SequenceStateOnly, $SequenceOwnerOnly, $AccessibilityOnly, $ConnectionOnly, $StreamingOnly, $ExplorerOnly, $ReportsOnly, $PropertiesOnly, $AcceptanceOnly, $QueryHistoryOnly) | Where-Object { $_ }).Count -gt 1) { throw 'Choose only one focused suite.' } -if ($DesktopOnly -and ($CascadeRoutinesOnly -or $CascadeRollbackOnly -or $RevokePreviewOnly -or $GrantorConcurrencyOnly -or $ExplicitGrantorOnly -or $GrantorCatalogOnly -or $DefaultDelegationOnly -or $DefaultSchemasOnly -or $DefaultTypesOnly -or $DefaultRoutinesOnly -or $DefaultSequencesOnly -or $DefaultTablesOnly -or $DefaultPrivilegesOnly -or $RoutineConcurrencyOnly -or $PrivilegeIdentityOnly -or $AcceptanceOnly -or $UnicodeBackupOnly)) { throw 'The selected focused suite has no desktop checks.' } +# Real keyboard input through SendInput; needs no cluster, but the PGMS window must reach the foreground, so nobody may type meanwhile. +if ($KeyboardRealOnly) { + Push-Location (Split-Path $PSScriptRoot -Parent) + try { dotnet run --project tests\PGMS.DesktopTests\PGMS.DesktopTests.csproj -c Release -- --keyboard-real; if ($LASTEXITCODE -ne 0) { throw 'Real keyboard checks failed.' } } + finally { Pop-Location } + return +} +if ((@($ResultsTextOnly, $TableDesignOnly, $DiagramsOnly, $SessionsOnly, $PlansOnly, $ExportOnly, $ActivityOnly, $QueryStatisticsOnly, $GlobalBackupOnly, $ColumnTypesOnly, $IndexMaintenanceOnly, $IndexExpressionsOnly, $PartitionTablesOnly, $CascadeJournalOnly, $CascadeRoutinesOnly, $CascadeRollbackOnly, $RevokePreviewOnly, $GrantorConcurrencyOnly, $ExplicitGrantorOnly, $GrantorCatalogOnly, $DefaultProcessOnly, $DefaultDelegationOnly, $DefaultSchemasOnly, $DefaultTypesOnly, $DefaultRoutinesOnly, $DefaultSequencesOnly, $DefaultTablesOnly, $DefaultCancellationOnly, $DefaultUiOnly, $DefaultJournalOnly, $DefaultPrivilegesOnly, $RoutineBoundariesOnly, $RoutineProcessOnly, $RoutineConcurrencyOnly, $RoutinePrivilegesOnly, $BackupFormatsOnly, $IdentityColumnsOnly, $RestoreOwnershipOnly, $UnicodeBackupOnly, $PrivilegeJournalOnly, $MaintainPrivilegeOnly, $PrivilegeCommitOnly, $UnicodePasswordOnly, $ServerTlsOnly, $SchemaContextOnly, $MembershipOptionsOnly, $PrivilegeIdentityOnly, $ColumnPrivilegesOnly, $PrivilegeCancellationOnly, $EffectivePrivilegesOnly, $PrivilegeCommandsOnly, $SequencePrivilegesOnly, $CopyOnly, $AdvancedIndexesOnly, $SequencesOnly, $SequenceStateOnly, $SequenceOwnerOnly, $AccessibilityOnly, $ConnectionOnly, $StreamingOnly, $ExplorerOnly, $ReportsOnly, $PropertiesOnly, $AcceptanceOnly, $QueryHistoryOnly, $SpatialOnly) | Where-Object { $_ }).Count -gt 1) { throw 'Choose only one focused suite.' } +if ($DesktopOnly -and ($CascadeRoutinesOnly -or $CascadeRollbackOnly -or $RevokePreviewOnly -or $GrantorConcurrencyOnly -or $ExplicitGrantorOnly -or $GrantorCatalogOnly -or $DefaultDelegationOnly -or $DefaultSchemasOnly -or $DefaultTypesOnly -or $DefaultRoutinesOnly -or $DefaultSequencesOnly -or $DefaultTablesOnly -or $DefaultPrivilegesOnly -or $RoutineConcurrencyOnly -or $PrivilegeIdentityOnly -or $AcceptanceOnly -or $UnicodeBackupOnly -or $SpatialOnly)) { throw 'The selected focused suite has no desktop checks.' } $projectRoot = Split-Path $PSScriptRoot -Parent $testRoot = Join-Path $projectRoot 'artifacts\postgres-test' $pgCtl = Join-Path $PostgresBin 'pg_ctl.exe' @@ -36,6 +43,8 @@ try { $listener.Start() } finally { $listener.Stop() } $previousTestPort = $env:PGMS_TEST_PORT try { # pg_stat_statements is preloaded only in this disposable cluster; the host service is never touched. + # Extension libraries load their own DLLs from the tools' bin (PostGIS): put it first on the server's PATH, for this script only. + $savedPath = $env:PATH; $env:PATH = "$PostgresBin;$env:PATH" $pgOptions = "-h 127.0.0.1 -p $TestPort -c ssl=on -c shared_preload_libraries=pg_stat_statements" # The server inherits pg_ctl's handles: keep them on files so a redirected caller never blocks. $start = Start-Process -FilePath $pgCtl -ArgumentList @('-D', "`"$dataPath`"", '-l', "`"$serverLog`"", '-o', "`"$pgOptions`"", '-w', 'start') -NoNewWindow -PassThru -RedirectStandardOutput (Join-Path $testRoot 'pg_ctl-start.log') -RedirectStandardError (Join-Path $testRoot 'pg_ctl-start.err') @@ -111,15 +120,18 @@ try { if ($DiagramsOnly) { $testArgs = @("--", "--diagrams") } if ($ResultsTextOnly) { $testArgs = @("--", "--results-text") } if ($QueryHistoryOnly) { $testArgs = @("--", "--query-history") } + # PostGIS checks: point -PostgresBin at a PostgreSQL copy that has PostGIS; integration only. + if ($SpatialOnly) { $testArgs = @("--", "--spatial") } if (!$CascadeJournalOnly -and !$DefaultProcessOnly -and !$DefaultCancellationOnly -and !$DefaultUiOnly -and !$DefaultJournalOnly -and !$RoutineBoundariesOnly -and !$RoutineProcessOnly -and !$DesktopOnly -and !$PrivilegeJournalOnly -and !$CopyOnly -and !$AccessibilityOnly -and !$ConnectionOnly -and !$ExplorerOnly -and !$QueryHistoryOnly) { dotnet run --project tests\PGMS.IntegrationTests\PGMS.IntegrationTests.csproj -c Release @testArgs if ($LASTEXITCODE -ne 0) { throw 'Integration checks failed' } } - if (!$CascadeRoutinesOnly -and !$CascadeRollbackOnly -and !$RevokePreviewOnly -and !$GrantorConcurrencyOnly -and !$ExplicitGrantorOnly -and !$GrantorCatalogOnly -and !$DefaultDelegationOnly -and !$DefaultSchemasOnly -and !$DefaultTypesOnly -and !$DefaultRoutinesOnly -and !$DefaultSequencesOnly -and !$DefaultTablesOnly -and !$DefaultPrivilegesOnly -and !$RoutineConcurrencyOnly -and !$AcceptanceOnly -and !$PrivilegeIdentityOnly -and !$UnicodeBackupOnly) { + if (!$SpatialOnly -and !$CascadeRoutinesOnly -and !$CascadeRollbackOnly -and !$RevokePreviewOnly -and !$GrantorConcurrencyOnly -and !$ExplicitGrantorOnly -and !$GrantorCatalogOnly -and !$DefaultDelegationOnly -and !$DefaultSchemasOnly -and !$DefaultTypesOnly -and !$DefaultRoutinesOnly -and !$DefaultSequencesOnly -and !$DefaultTablesOnly -and !$DefaultPrivilegesOnly -and !$RoutineConcurrencyOnly -and !$AcceptanceOnly -and !$PrivilegeIdentityOnly -and !$UnicodeBackupOnly) { dotnet run --project tests\PGMS.DesktopTests\PGMS.DesktopTests.csproj -c Release @testArgs if ($LASTEXITCODE -ne 0) { throw 'Desktop checks failed' } } } finally { Pop-Location } } finally { + if ($null -ne $savedPath) { $env:PATH = $savedPath } try { & $pgCtl -D $dataPath -m fast -w stop } finally { $env:PGMS_TEST_PORT = $previousTestPort } } diff --git a/scripts/Test-PackageLaunch.ps1 b/scripts/Test-PackageLaunch.ps1 index d4a79a6..1a966a8 100644 --- a/scripts/Test-PackageLaunch.ps1 +++ b/scripts/Test-PackageLaunch.ps1 @@ -11,6 +11,8 @@ $start.UseShellExecute = $false $start.WorkingDirectory = $package $start.WindowStyle = [Diagnostics.ProcessWindowStyle]::Hidden $start.Environment['PGMS_STATE_DIRECTORY'] = $state +# The interface follows the Windows language by default; English keeps the Connect to Server title below the same on every machine. +$start.Environment['PGMS_LANGUAGE'] = 'en' # Point runtime discovery at an empty directory; module inspection below is the decisive evidence. $emptyRuntime = Join-Path $state 'empty-runtime' New-Item -ItemType Directory -Path $emptyRuntime | Out-Null diff --git a/src/PGMS.Desktop/ActivityMonitorView.xaml.cs b/src/PGMS.Desktop/ActivityMonitorView.xaml.cs index 6604d88..8f1bb80 100644 --- a/src/PGMS.Desktop/ActivityMonitorView.xaml.cs +++ b/src/PGMS.Desktop/ActivityMonitorView.xaml.cs @@ -174,7 +174,7 @@ private ActivityFilter ReadFilter() pid = value; } string state = (StateFilter.SelectedItem as ComboBoxItem)?.Content as string ?? "All states"; - return new(DatabaseFilter.Text, UserFilter.Text, ApplicationFilter.Text, state == "All states" ? "" : state, pid){BlockedOnly=BlockedOnlyFilter.IsChecked==true}; + return new(DatabaseFilter.Text, UserFilter.Text, ApplicationFilter.Text, StateFilter.SelectedIndex <= 0 ? "" : state /* "All states" may be translated (M1129); the others are pg_stat_activity values */, pid){BlockedOnly=BlockedOnlyFilter.IsChecked==true}; } public Task ReloadAsync() => LoadAsync(page); // A request made while a refresh runs joins it instead of starting another one, so callers resume once current data is shown. @@ -237,7 +237,10 @@ private async Task RefreshPanelsAsync(CancellationToken token) { var active = await metrics.ReadActiveQueriesAsync(token); token.ThrowIfCancellationRequested(); Replace(activeRows, active); - ActiveQueriesNote.Text = $"{active.Count} running quer{(active.Count == 1 ? "y" : "ies")}, oldest first (at most {ActiveExpensiveQuery.MaximumRows}); the monitor's own reads are left out."; + // Whole sentences for singular and plural, so each translates as one pattern (B1 review, M1139). + ActiveQueriesNote.Text = active.Count == 1 + ? $"{active.Count} running query, oldest first (at most {ActiveExpensiveQuery.MaximumRows}); the monitor's own reads are left out." + : $"{active.Count} running queries, oldest first (at most {ActiveExpensiveQuery.MaximumRows}); the monitor's own reads are left out."; } catch (Exception ex) when (ex is NpgsqlException or System.IO.IOException or TimeoutException) { ActiveQueriesNote.Text = "Running queries not read: " + Describe(ex); } } @@ -318,8 +321,8 @@ private void CancelRefresh(object sender,RoutedEventArgs e) internal static bool ConfirmTerminate(Window? owner, ActivitySession session) { string text = $"Terminate PID {session.Pid}?\nDatabase: {session.Database}\nUser: {session.User}\nApplication: {session.Application}\n\nThe connection will close and its open transaction will roll back."; - var answer = owner is null ? MessageBox.Show(text, "Terminate Session", MessageBoxButton.YesNo, MessageBoxImage.Warning, MessageBoxResult.No) - : MessageBox.Show(owner, text, "Terminate Session", MessageBoxButton.YesNo, MessageBoxImage.Warning, MessageBoxResult.No); + var answer = owner is null ? LocalizedMessageBox.Show(text, "Terminate Session", MessageBoxButton.YesNo, MessageBoxImage.Warning, MessageBoxResult.No) + : LocalizedMessageBox.Show(owner, text, "Terminate Session", MessageBoxButton.YesNo, MessageBoxImage.Warning, MessageBoxResult.No); return answer == MessageBoxResult.Yes; } // Right-click selects the row first, so the menu always acts on the row under the pointer. diff --git a/src/PGMS.Desktop/AiQueryGenerator.cs b/src/PGMS.Desktop/AiQueryGenerator.cs index 066caad..39d85f2 100644 --- a/src/PGMS.Desktop/AiQueryGenerator.cs +++ b/src/PGMS.Desktop/AiQueryGenerator.cs @@ -20,7 +20,8 @@ public sealed record AiQueryResult(string Sql, string Provider, string Model); public sealed record AiTurn(string Request, string Sql); /// Query ▸ Explain/Fix/Optimize SQL with AI (M1115): the request written for the selected SQL; the user can change it before Generate. -public enum AiSqlAction { Explain, Fix, Optimize } +/// Paste: Edit ▸ Paste Special ▸ Paste with AI (PGMS-082, M1120), the clipboard SQL adapted to the connected database. +public enum AiSqlAction { Explain, Fix, Optimize, Paste } public static partial class AiQueryGenerator { @@ -30,6 +31,7 @@ public static partial class AiQueryGenerator { AiSqlAction.Explain => "Explain what this SQL does, step by step. Keep the SQL unchanged and put the explanation above it as -- comments.", AiSqlAction.Fix => "Fix this SQL so it runs on this database." + (string.IsNullOrEmpty(errorCode) ? "" : $" The server reported {errorCode}: {errorMessage}") + " Keep what it is meant to do; say what changed in -- comments.", + AiSqlAction.Paste => "Adapt this SQL, pasted from the clipboard, to this database: use its schemas, tables and columns and PostgreSQL syntax. Keep what it is meant to do; say what changed in -- comments.", _ => "Optimize this SQL for PostgreSQL without changing its results: better joins, filters that can use indexes, fewer passes. Say what changed and which indexes would help in -- comments; do not create them.", }; } diff --git a/src/PGMS.Desktop/AiSettingsDialog.xaml.cs b/src/PGMS.Desktop/AiSettingsDialog.xaml.cs index 0455f5b..ad309ca 100644 --- a/src/PGMS.Desktop/AiSettingsDialog.xaml.cs +++ b/src/PGMS.Desktop/AiSettingsDialog.xaml.cs @@ -123,7 +123,7 @@ public bool SaveSettings() private void RemoveKey(object sender, RoutedEventArgs e) { - if (MessageBox.Show(this, $"Remove the saved {shown} API key from this computer?", "AI Assistant Settings", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No) != MessageBoxResult.Yes) return; + if (LocalizedMessageBox.Show(this, $"Remove the saved {shown} API key from this computer?", "AI Assistant Settings", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No) != MessageBoxResult.Yes) return; RemoveSavedKey(); } public void RemoveSavedKey() diff --git a/src/PGMS.Desktop/App.xaml.cs b/src/PGMS.Desktop/App.xaml.cs index 1c73952..288d96d 100644 --- a/src/PGMS.Desktop/App.xaml.cs +++ b/src/PGMS.Desktop/App.xaml.cs @@ -5,6 +5,8 @@ public partial class App : Application protected override void OnStartup(StartupEventArgs e) { CrashReporter.Install(this); + Localization.Initialize(this); + WindowWorkArea.AttachToEveryWindow(); base.OnStartup(e); } } diff --git a/src/PGMS.Desktop/BackupDialog.xaml.cs b/src/PGMS.Desktop/BackupDialog.xaml.cs index a26f77c..a275539 100644 --- a/src/PGMS.Desktop/BackupDialog.xaml.cs +++ b/src/PGMS.Desktop/BackupDialog.xaml.cs @@ -204,7 +204,7 @@ private void Browse(object sender, RoutedEventArgs e) { if (!File.Exists(picker.FileName)) return; args.Cancel = true; - MessageBox.Show(this, "Choose a new file name. Existing backups are never overwritten.", "Back Up Database", MessageBoxButton.OK, MessageBoxImage.Information); + LocalizedMessageBox.Show(this, "Choose a new file name. Existing backups are never overwritten.", "Back Up Database", MessageBoxButton.OK, MessageBoxImage.Information); }; if (picker.ShowDialog(this) == true) ArchivePath.Text = picker.FileName; } @@ -230,7 +230,7 @@ internal async Task RunAsync() { if(!restore){Feedback.Text=$"{name} does not exist. Choose an existing database.";return;} string question=$"Create the database {name} and restore into it?\n\nIt is created with CREATE DATABASE … TEMPLATE template0 and kept if the restore fails."; - if(!(ConfirmCreateDatabase?.Invoke(name) ?? MessageBox.Show(this,question,Title,MessageBoxButton.YesNo,MessageBoxImage.Question,MessageBoxResult.No)==MessageBoxResult.Yes))return; + if(!(ConfirmCreateDatabase?.Invoke(name) ?? LocalizedMessageBox.Show(this,question,Title,MessageBoxButton.YesNo,MessageBoxImage.Question,MessageBoxResult.No)==MessageBoxResult.Yes))return; try{await BackupService.CreateRestoreDatabaseAsync(connectionString,name);created=true;databases=[..databases,name];} catch(Exception ex)when(ex is NpgsqlException or ArgumentException or IOException or InvalidOperationException or TimeoutException){Feedback.Text="The database was not created: "+(ex is PostgresException pg?$"{pg.SqlState}: {pg.MessageText}":ex.Message);return;} } @@ -240,7 +240,7 @@ internal async Task RunAsync() if(globals && restore) { if(GlobalReviewed.IsChecked!=true){Feedback.Text="Review the global SQL script and destination, then confirm the review checkbox.";return;} - if(MessageBox.Show(this,"Restore global objects on this server? Earlier statements can remain committed if a later command fails.\n\n"+Target.Text+"\n\nScript: "+ArchivePath.Text,Title,MessageBoxButton.YesNo,MessageBoxImage.Warning,MessageBoxResult.No)!=MessageBoxResult.Yes)return; + if(LocalizedMessageBox.Show(this,"Restore global objects on this server? Earlier statements can remain committed if a later command fails.\n\n"+Target.Text+"\n\nScript: "+ArchivePath.Text,Title,MessageBoxButton.YesNo,MessageBoxImage.Warning,MessageBoxResult.No)!=MessageBoxResult.Yes)return; } cancellation = new CancellationTokenSource(); LimitSchema.IsEnabled=SchemaFilterName.IsEnabled=SelectionKindSelector.IsEnabled=TableFilterName.IsEnabled=false; diff --git a/src/PGMS.Desktop/ChangeScriptDialog.xaml.cs b/src/PGMS.Desktop/ChangeScriptDialog.xaml.cs index 6b3c4f6..0e2c2aa 100644 --- a/src/PGMS.Desktop/ChangeScriptDialog.xaml.cs +++ b/src/PGMS.Desktop/ChangeScriptDialog.xaml.cs @@ -24,6 +24,6 @@ private void SaveFile(object sender, RoutedEventArgs e) var dialog = new Microsoft.Win32.SaveFileDialog { Filter = "SQL files (*.sql)|*.sql|All files (*.*)|*.*", DefaultExt = ".sql", FileName = "ChangeScript.sql" }; if (dialog.ShowDialog(this) != true) return; try { File.WriteAllText(dialog.FileName, Script.Text, new UTF8Encoding(false)); } - catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { MessageBox.Show(this, ex.Message, "PGMS", MessageBoxButton.OK, MessageBoxImage.Error); } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { LocalizedMessageBox.Show(this, ex.Message, "PGMS", MessageBoxButton.OK, MessageBoxImage.Error); } } } diff --git a/src/PGMS.Desktop/CheckConstraintDialog.xaml.cs b/src/PGMS.Desktop/CheckConstraintDialog.xaml.cs index ee4d243..54c2d16 100644 --- a/src/PGMS.Desktop/CheckConstraintDialog.xaml.cs +++ b/src/PGMS.Desktop/CheckConstraintDialog.xaml.cs @@ -72,7 +72,7 @@ public async Task InspectAsync() public async Task ApplyAsync() { if (busy) return; var request = Request; - if (request.Operation == CheckConstraintOperation.Drop && MessageBox.Show(this, Target.Text + "\n\n" + request.ToSql() + "\n\nDrop this CHECK constraint?", "Confirm constraint deletion", MessageBoxButton.YesNo, MessageBoxImage.Warning, MessageBoxResult.No) != MessageBoxResult.Yes) return; + if (request.Operation == CheckConstraintOperation.Drop && LocalizedMessageBox.Show(this, Target.Text + "\n\n" + request.ToSql() + "\n\nDrop this CHECK constraint?", "Confirm constraint deletion", MessageBoxButton.YesNo, MessageBoxImage.Warning, MessageBoxResult.No) != MessageBoxResult.Yes) return; SetBusy(true); Feedback.Text = "Applying operation…"; try { await new AdministrativeEditService(connection).ApplyAsync(request); WasApplied = true; busy = false; DialogResult = true; } catch (Exception ex) when (ex is NpgsqlException or System.IO.IOException or TimeoutException or InvalidOperationException or ArgumentException) { Feedback.Text = ex is PostgresException pg ? $"{pg.SqlState}: {pg.MessageText}" : ex.Message; } diff --git a/src/PGMS.Desktop/CodeSnippetsManagerDialog.cs b/src/PGMS.Desktop/CodeSnippetsManagerDialog.cs new file mode 100644 index 0000000..7841884 --- /dev/null +++ b/src/PGMS.Desktop/CodeSnippetsManagerDialog.cs @@ -0,0 +1,173 @@ +using System.Diagnostics; +using System.IO; +using System.Windows; +using System.Windows.Automation; +using System.Windows.Controls; +using Microsoft.Win32; + +namespace PGMS.Desktop; + +/// Tools ▸ Code Snippets Manager… (Ctrl+K, Ctrl+B; PGMS-082, M1122). The SSMS 22.11 dialog (629×470, M1063) was only seen to exist; +/// the layout follows the Visual Studio one it comes from: folders and snippets on the left, the selected snippet and its location on the right, +/// Import…, Remove and the folder of the user's snippets. Only .snippet files in the user's folder can be removed; PGMS's own are built in. +public sealed class CodeSnippetsManagerDialog : Window +{ + private readonly string userDirectory; + private readonly TreeView tree = new() { MinWidth = 230 }; + private readonly TextBlock title = new() { FontWeight = FontWeights.SemiBold, TextWrapping = TextWrapping.Wrap }; + private readonly TextBlock description = new() { TextWrapping = TextWrapping.Wrap, Margin = new Thickness(0, 6, 0, 0) }; + private readonly TextBlock kind = new() { Margin = new Thickness(0, 6, 0, 0) }; + private readonly TextBox location = new() { IsReadOnly = true, Margin = new Thickness(0, 6, 0, 0), BorderThickness = new Thickness(0), Background = System.Windows.Media.Brushes.Transparent, TextWrapping = TextWrapping.Wrap }; + private readonly TextBox code = new() { IsReadOnly = true, FontFamily = new System.Windows.Media.FontFamily("Consolas"), Margin = new Thickness(0, 8, 0, 0), VerticalScrollBarVisibility = ScrollBarVisibility.Auto, HorizontalScrollBarVisibility = ScrollBarVisibility.Auto, MinHeight = 120 }; + private readonly Button removeButton = new() { Content = "_Remove", MinWidth = 80, Margin = new Thickness(6, 0, 0, 0), IsEnabled = false }; + private readonly TextBlock status = new() { Margin = new Thickness(0, 8, 0, 0), TextWrapping = TextWrapping.Wrap }; + + /// Picks the file to import; tests replace it. Null means Cancel. + internal Func? PickFile { get; set; } + /// Confirms removing a file (receives its path); tests replace it. + internal Func? ConfirmRemove { get; set; } + internal TreeView Tree => tree; + internal string StatusText => status.Text; + internal string LocationText => location.Text; + + public CodeSnippetsManagerDialog(string? userDirectory = null) + { + this.userDirectory = userDirectory ?? SqlTemplateCatalog.UserSnippetsDirectory; + Title = "Code Snippets Manager"; + Width = 629; Height = 470; MinWidth = 520; MinHeight = 380; + WindowStartupLocation = WindowStartupLocation.CenterOwner; ShowInTaskbar = false; ResizeMode = ResizeMode.CanResizeWithGrip; + AutomationProperties.SetName(tree, "Snippets"); + AutomationProperties.SetName(location, "Location"); + AutomationProperties.SetName(code, "Code"); + var importButton = new Button { Content = "_Import…", MinWidth = 80 }; + var folderButton = new Button { Content = "Open _Folder", MinWidth = 90, Margin = new Thickness(6, 0, 0, 0), ToolTip = "Opens the folder of your snippets; .snippet files placed there appear in Insert Snippet and Surround With" }; + var closeButton = new Button { Content = "OK", MinWidth = 80, IsDefault = true, IsCancel = true }; + importButton.Click += (_, _) => Import(); + removeButton.Click += (_, _) => RemoveSelected(); + folderButton.Click += (_, _) => OpenFolder(); + closeButton.Click += (_, _) => Close(); + tree.SelectedItemChanged += (_, _) => ShowSelected(); + + var details = new DockPanel { Margin = new Thickness(10, 0, 0, 0) }; + var top = new StackPanel { Children = { title, description, kind, new TextBlock { Text = "Location:", Margin = new Thickness(0, 8, 0, 0) }, location } }; + DockPanel.SetDock(top, Dock.Top); details.Children.Add(top); details.Children.Add(code); + var middle = new Grid(); + middle.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }); + middle.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1.4, GridUnitType.Star) }); + middle.Children.Add(tree); Grid.SetColumn(details, 1); middle.Children.Add(details); + var left = new StackPanel { Orientation = Orientation.Horizontal, Children = { importButton, removeButton, folderButton } }; + var bottom = new DockPanel { Margin = new Thickness(0, 10, 0, 0) }; + DockPanel.SetDock(closeButton, Dock.Right); bottom.Children.Add(closeButton); bottom.Children.Add(left); + var root = new DockPanel { Margin = new Thickness(12) }; + var heading = new TextBlock { Text = "Snippets offered by Insert Snippet (Ctrl+K, Ctrl+X) and Surround With (Ctrl+K, Ctrl+S):", Margin = new Thickness(0, 0, 0, 8), TextWrapping = TextWrapping.Wrap }; + DockPanel.SetDock(heading, Dock.Top); DockPanel.SetDock(bottom, Dock.Bottom); DockPanel.SetDock(status, Dock.Bottom); + root.Children.Add(heading); root.Children.Add(bottom); root.Children.Add(status); root.Children.Add(middle); + Content = root; + Fill(); + } + + /// Folders in alphabetical order, each with its snippets; the user's files are marked by their location. + internal void Fill(string? select = null) + { + tree.Items.Clear(); + foreach (var group in SqlTemplateCatalog.Snippets(userDirectory).GroupBy(s => s.Folder).OrderBy(g => g.Key, StringComparer.CurrentCultureIgnoreCase)) + { + var folder = new TreeViewItem { Header = group.Key, IsExpanded = true }; + foreach (var snippet in group.OrderBy(s => s.Title, StringComparer.CurrentCultureIgnoreCase)) + { + var item = new TreeViewItem { Header = snippet.Title, Tag = snippet }; + AutomationProperties.SetName(item, snippet.Title); + folder.Items.Add(item); + } + tree.Items.Add(folder); + } + if (select is not null && tree.Items.OfType().SelectMany(f => f.Items.OfType()).FirstOrDefault(i => string.Equals((i.Tag as SqlSnippet)?.SourceFile, select, StringComparison.OrdinalIgnoreCase)) is { } chosen) + chosen.IsSelected = true; + ShowSelected(); + } + + internal SqlSnippet? Selected => (tree.SelectedItem as TreeViewItem)?.Tag as SqlSnippet; + + private void ShowSelected() + { + var snippet = Selected; + title.Text = snippet?.Title ?? "Select a snippet to see it."; + description.Text = snippet?.Description ?? ""; + kind.Text = snippet is null ? "" : "Type: " + string.Join(", ", new[] { snippet.IsExpansion ? "Expansion" : null, snippet.IsSurroundsWith ? "SurroundsWith" : null }.OfType()); + location.Text = snippet is null ? "" : snippet.SourceFile ?? "Built into PGMS"; + code.Text = snippet?.Code ?? ""; + removeButton.IsEnabled = snippet?.SourceFile is not null; + } + + /// Copies a .snippet file into the user's folder (a name already there gets a number) and selects it. Returns the new path. + internal string? Import() + { + string? source = PickFile is not null ? PickFile() : PickWithDialog(); + if (source is null) return null; + try + { + string destination = CodeSnippetFiles.Import(source, userDirectory); + Fill(destination); + status.Text = $"Imported {Path.GetFileName(destination)}."; + return destination; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException) { status.Text = ex.Message; return null; } + } + + private string? PickWithDialog() + { + var dialog = new OpenFileDialog { Title = "Import Code Snippet", Filter = "Code snippets (*.snippet)|*.snippet|All files (*.*)|*.*" }; + return dialog.ShowDialog(this) == true ? dialog.FileName : null; + } + + /// Deletes the .snippet file of the selected snippet from the user's folder, after confirmation; every snippet in that file goes. + internal bool RemoveSelected() + { + if (Selected?.SourceFile is not { } file) return false; + bool confirmed = ConfirmRemove?.Invoke(file) ?? LocalizedMessageBox.Show(this, $"Delete the file {file}?\n\nEvery snippet in this file is removed from Insert Snippet and Surround With.", "Code Snippets Manager", MessageBoxButton.YesNo, MessageBoxImage.Warning, MessageBoxResult.No) == MessageBoxResult.Yes; + if (!confirmed) return false; + try { CodeSnippetFiles.Remove(file, userDirectory); } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidOperationException) { status.Text = ex.Message; return false; } + Fill(); + status.Text = $"Removed {Path.GetFileName(file)}."; + return true; + } + + private void OpenFolder() + { + try + { + Directory.CreateDirectory(userDirectory); + Process.Start(new ProcessStartInfo("explorer.exe", "\"" + userDirectory + "\"") { UseShellExecute = true }); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or System.ComponentModel.Win32Exception) { status.Text = ex.Message; } + } +} + +/// File operations of the Code Snippets Manager, kept apart from the window for tests. +internal static class CodeSnippetFiles +{ + internal const long MaxBytes = 1024 * 1024; + + /// Checks that the file holds at least one snippet PGMS can read, then copies it to the root of the user's folder. + internal static string Import(string source, string userDirectory) + { + var info = new FileInfo(source); + if (!info.Exists) throw new FileNotFoundException($"{source} does not exist."); + if (info.Length > MaxBytes) throw new InvalidDataException($"{info.Name} is larger than 1 MiB; it was not imported."); + if (SqlSnippet.Load(File.ReadAllText(source), "").Count == 0) throw new InvalidDataException($"{info.Name} has no code snippet PGMS can read (CodeSnippet with Title and Code); it was not imported."); + Directory.CreateDirectory(userDirectory); + string name = Path.GetFileNameWithoutExtension(source), destination = Path.Combine(userDirectory, name + ".snippet"); + for (int n = 2; File.Exists(destination); n++) destination = Path.Combine(userDirectory, $"{name} ({n}).snippet"); + File.Copy(source, destination); + return destination; + } + + /// Deletes a snippet file, only when it is inside the user's folder. + internal static void Remove(string file, string userDirectory) + { + string root = Path.GetFullPath(userDirectory).TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar; + if (!Path.GetFullPath(file).StartsWith(root, StringComparison.OrdinalIgnoreCase)) throw new InvalidOperationException("Only snippet files in your snippets folder can be removed."); + File.Delete(file); + } +} diff --git a/src/PGMS.Desktop/ColumnTypeDialog.xaml.cs b/src/PGMS.Desktop/ColumnTypeDialog.xaml.cs index 2053a1d..94f85ff 100644 --- a/src/PGMS.Desktop/ColumnTypeDialog.xaml.cs +++ b/src/PGMS.Desktop/ColumnTypeDialog.xaml.cs @@ -61,7 +61,7 @@ public async Task ApplyAsync() { if(busy || !ApplyButton.IsEnabled)return;var request=Request; string confirmation=add?"Add this column? Domain defaults and constraints apply to existing rows.":"Convert stored values? Casts may truncate or round values. Review backups before applying."; - if(MessageBox.Show(this,Target.Text+"\n\n"+request.ToSql()+"\n\n"+confirmation,add?"Confirm Column Addition":"Confirm Column Conversion",MessageBoxButton.YesNo,MessageBoxImage.Warning,MessageBoxResult.No)!=MessageBoxResult.Yes){Feedback.Text="Operation canceled. Nothing was sent.";return;} + if(LocalizedMessageBox.Show(this,Target.Text+"\n\n"+request.ToSql()+"\n\n"+confirmation,add?"Confirm Column Addition":"Confirm Column Conversion",MessageBoxButton.YesNo,MessageBoxImage.Warning,MessageBoxResult.No)!=MessageBoxResult.Yes){Feedback.Text="Operation canceled. Nothing was sent.";return;} using var source=new CancellationTokenSource();cancellation=source;busy=true;RequiresParentRefresh=true;Update(true);CancelButton.Focus();Feedback.Text=add?"Adding column…":"Converting column…"; try{await new AdministrativeEditService(connection).ApplyAsync(request,source.Token);WasApplied=true;Feedback.Text="Command completed. Inspect the column before another change.";} catch(Exception ex)when(ex is NpgsqlException or System.IO.IOException or TimeoutException or OperationCanceledException or InvalidOperationException or ArgumentException){Feedback.Text=(source.IsCancellationRequested?"Conversion interrupted.":ex is PostgresException pg?$"{pg.SqlState}: {pg.MessageText}":ex.Message)+" Result not confirmed. Inspect before retrying; cancellation cannot undo a completed commit.";} diff --git a/src/PGMS.Desktop/ConcurrentIndexDialog.xaml.cs b/src/PGMS.Desktop/ConcurrentIndexDialog.xaml.cs index 87ce67a..b184849 100644 --- a/src/PGMS.Desktop/ConcurrentIndexDialog.xaml.cs +++ b/src/PGMS.Desktop/ConcurrentIndexDialog.xaml.cs @@ -87,7 +87,7 @@ public async Task ApplyAsync() if(!ApplyButton.IsEnabled || (proposal is null && maintenance is null))return; var operation=maintenance is null?IndexMaintenanceOperation.Reindex:(IndexMaintenanceOperation)Operation.SelectedValue; if(maintenance is not null && operation==IndexMaintenanceOperation.DropConcurrently && - MessageBox.Show(this,"Drop the inspected index? Table rows are preserved. This standalone command cannot be rolled back.","Drop Index",MessageBoxButton.YesNo,MessageBoxImage.Warning,MessageBoxResult.No)!=MessageBoxResult.Yes)return; + LocalizedMessageBox.Show(this,"Drop the inspected index? Table rows are preserved. This standalone command cannot be rolled back.","Drop Index",MessageBoxButton.YesNo,MessageBoxImage.Warning,MessageBoxResult.No)!=MessageBoxResult.Yes)return; using var source=new CancellationTokenSource();cancellation=source;busy=true;attempted=true;RequiresParentRefresh=true;Update(); Feedback.Text=maintenance is not null && operation==IndexMaintenanceOperation.Reindex?"Rebuilding inside a transaction; waiting for the server…":"Executing outside a transaction. Cancel may leave residues; waiting for the server…"; try @@ -129,7 +129,7 @@ public async Task InspectPendingAsync() public async Task ArchiveAsync() { if(!ArchiveButton.IsEnabled)return; - bool confirmed=MessageBox.Show(this,"Archive this inspected receipt? This only ends local tracking. It does not retry the command or change the database; any invalid index remains for explicit maintenance.","Archive Index Receipt",MessageBoxButton.YesNo,MessageBoxImage.Question,MessageBoxResult.No)==MessageBoxResult.Yes; + bool confirmed=LocalizedMessageBox.Show(this,"Archive this inspected receipt? This only ends local tracking. It does not retry the command or change the database; any invalid index remains for explicit maintenance.","Archive Index Receipt",MessageBoxButton.YesNo,MessageBoxImage.Question,MessageBoxResult.No)==MessageBoxResult.Yes; await ArchiveReviewedAsync(confirmed); } internal async Task ArchiveReviewedAsync(bool confirmed) diff --git a/src/PGMS.Desktop/ConnectionDialog.xaml b/src/PGMS.Desktop/ConnectionDialog.xaml index 98e7b08..6c90412 100644 --- a/src/PGMS.Desktop/ConnectionDialog.xaml +++ b/src/PGMS.Desktop/ConnectionDialog.xaml @@ -27,7 +27,7 @@ - + + + @@ -66,7 +68,7 @@ - + @@ -129,12 +131,13 @@ + - + @@ -200,13 +203,25 @@ + - + + + + + + + + + + + + @@ -228,6 +243,7 @@ + @@ -235,13 +251,21 @@ + - + + + + + + + + @@ -249,11 +273,23 @@ + + + + + + + + + + + + + + + + + + diff --git a/src/PGMS.Desktop/MainWindow.xaml.cs b/src/PGMS.Desktop/MainWindow.xaml.cs index 0d2840a..71ff378 100644 --- a/src/PGMS.Desktop/MainWindow.xaml.cs +++ b/src/PGMS.Desktop/MainWindow.xaml.cs @@ -35,12 +35,23 @@ public partial class MainWindow : Window public MainWindow() { + // One-time costs paid on a worker while the window loads (M1132): the link expressions of the editor (about 40 ms) and the JSON + // metadata of the settings file, which the UI thread would otherwise build on the first editor or the first write. + _ = Task.Run(() => + { + System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(typeof(SqlLinkPatterns).TypeHandle); + _ = System.Text.Json.JsonSerializer.Serialize(new EnvironmentOptions.Document()); + }); var fontsDocument = EnvironmentSettings.Load(); FontsAndColorsSettings.EditorAppearance = fontsDocument.EditorAppearanceChoice; FontsAndColorsSettings.Current = EffectiveFontsAndColors(fontsDocument); InitializeComponent(); + DockTitleTranslation.Watch(DockManager); // tab and tool window titles in the interface language (M1139); nothing in English + ApplyTabsAndDocuments(EnvironmentSettings.Load()); // Tabs, Documents and SQL Formatter options (M1141, M1142) PickInsertFile = PickInsertFileWithDialog; InitializeTabCommands(); + ConfigureNavigation(); + ConfigureCodeSnippets(); InitializeExplorerToolbar(); _ = QueryHistory; // startup cleanup of Query History WindowWorkArea.Attach(this); @@ -95,6 +106,7 @@ public MainWindow() ConfigureEncodingCommands(); ConfigureBookmarkCommands(); ConfigureHelpCommands(); + ConfigureEditorSpecials(); ConfigureTemplateCommands(); ConfigureFindInFilesCommands(); ConfigurePaneCommands(); @@ -143,7 +155,10 @@ public MainWindow() internal QueryView NewQueryTab(string? text = null) => NewQuery(text); /// Query History origin of text given here without a file (scripts, generated SQL); recovered drafts pass Typed. - private QueryView NewQuery(string? text = null, string? path = null, Guid? recoveryId = null, bool activate = true, PreparedQueryDocument? prepared = null, QueryHistoryOrigin origin = QueryHistoryOrigin.Other) + /// A restored tab kept as text until shown (M1133): the editor goes into it, keeping its title and place. + /// Options as they were when that tab was restored, so its new-window settings do not change by mounting later. + private QueryView NewQuery(string? text = null, string? path = null, Guid? recoveryId = null, bool activate = true, PreparedQueryDocument? prepared = null, QueryHistoryOrigin origin = QueryHistoryOrigin.Other, + LayoutDocument? deferredTab = null, EnvironmentOptions.Document? newTabSettings = null) { QueryView view; using (UiPhaseScope.Start(UiPhaseMeasured, "view-total")) @@ -161,15 +176,21 @@ private QueryView NewQuery(string? text = null, string? path = null, Guid? recov AttachQueryHistory(view); if (prepared is null && path is null && !string.IsNullOrWhiteSpace(text)) view.MarkOrigin(text, origin); // Tools ▸ Options ▸ Query Results ▸ General ▸ Default destination for results. - var environment = EnvironmentSettings.Load(); + var environment = newTabSettings ?? EnvironmentSettings.Load(); view.ResultsDestination = environment.DefaultResults; view.ApplyQueryOptions(environment.QueryOptionDefaults); + view.ApplyTextEditorSettings(environment.EditorSettings, newTab: true); + // Settings that reach open tabs at once (line numbers, tabs) follow the current Options in a tab mounted later. + if (newTabSettings is not null) view.ApplyTextEditorSettings(EnvironmentSettings.Load().EditorSettings, newTab: false); if (!ReferenceEquals(view.Appearance, FontsAndColorsSettings.Current)) view.ApplyAppearance(FontsAndColorsSettings.Current); // a spare made before Options changed view.JsonLinkRequested += OpenJsonDocument; view.PlanTabRequested += statements => OpenPlanDocument(statements, "Execution plan", PlanOrigin(view)); view.MissingIndexDetailsRequested += OpenMissingIndexDetails; + AttachPlanCommands(view.PlanDiagram, () => documents.TryGetValue(view, out var tab) ? tab.Title : "Query"); view.ExecutionNoted += (_, _) => NoteExecutionForToolWindows(view); - var document = new LayoutDocument { Title = path is null ? $"SQLQuery{++sequence}.sql" : Path.GetFileName(path), ContentId = Guid.NewGuid().ToString(), Content = view }; + view.CaretJumped += QueryCaretJumped; + var document = deferredTab ?? new LayoutDocument { Title = path is null ? $"SQLQuery{++sequence}.sql" : Path.GetFileName(path), ContentId = Guid.NewGuid().ToString(), Content = view }; + if (deferredTab is null) NoteQueryTabCreated(document); else deferredTab.Content = view; documents.Add(view, document); view.StateChanged += (_, _) => { @@ -183,8 +204,8 @@ private QueryView NewQuery(string? text = null, string? path = null, Guid? recov e.Cancel = true; _ = CloseQueryAsync(view); }; - document.Closed += async (_, _) => { documents.Remove(view); RefreshPropertiesWindow(); UpdateConnectionTexts(); await view.DisposeAsync(); RefreshCommands(); }; - AddDocument(document); + document.Closed += async (_, _) => { documents.Remove(view); queryTabOrder.Remove(document); RefreshPropertiesWindow(); UpdateConnectionTexts(); await view.DisposeAsync(); RefreshCommands(); }; + if (deferredTab is null) AddDocument(document); if (activate) document.IsActive = true; // The editor is not yet in the visual tree when the document is inserted. // Defer focus until layout has created it, so Ctrl+N accepts typing immediately. @@ -206,9 +227,32 @@ private void AddDocument(LayoutDocument document) pane = new LayoutDocumentPane(); DockManager.Layout.RootPanel.Children.Add(pane); } - pane.Children.Add(document); + // Environment ▸ Tabs and Windows (M1141): first after the pinned ones (the default since M1143, as in SSMS), or after the existing tabs. + // Recovered drafts always go after the open tabs, so they come back in the order they were saved (M1143). + if (insertTabsToRight || appendRestoredTabs) pane.Children.Add(document); + else pane.Children.Insert(pane.Children.Count(c => c is LayoutDocument d && pinnedTabs.Contains(d)), document); + } + + private bool insertTabsToRight = new EnvironmentOptions(EnvironmentOptions.DefaultPath).Load().TabsSettings.InsertTabsToRight; + private bool appendRestoredTabs; + private DocumentSettings documentSettings = new EnvironmentOptions(EnvironmentOptions.DefaultPath).Load().DocumentOptions; + /// Applies Environment ▸ Tabs and Windows and Documents after Options (and at startup). + internal void ApplyTabsAndDocuments(EnvironmentOptions.Document settings) + { + insertTabsToRight = settings.TabsSettings.InsertTabsToRight; + documentSettings = settings.DocumentOptions; + SqlFormatter.Settings = settings.FormatterSettings; + // M1143: Designers ▸ Table Options, Object Explorer ▸ General and Commands, Live Query Statistics. + TableDesignerView.DesignerSettings = settings.DesignerSettings; + explorerSettings = settings.ExplorerSettings; + if (catalogService is not null) catalogService.ShowSystemObjects = !explorerSettings.HideSystemObjects; // seen at the next expand or refresh + QueryView.DefaultLiveIntervalMilliseconds = settings.LiveStatistics.PollingMilliseconds; } + private ObjectExplorerSettings explorerSettings = new(); + /// Answers "rename this key, constraint or trigger?"; null asks. The test runner answers yes. + internal static Func? RenameConfirmPrompt { get; set; } + public bool TryOpenQueryFile(string path, out Exception? error) { try { OpenQueryFile(path); error = null; return true; } @@ -311,7 +355,7 @@ private async Task LoadExplorerAsync() catalogCancellation.Cancel(); catalogCancellation.Dispose(); catalogCancellation = new CancellationTokenSource(); var token = catalogCancellation.Token; - catalogService = new CatalogService(connection); + catalogService = new CatalogService(connection) { ShowSystemObjects = !explorerSettings.HideSystemObjects }; var root = new CatalogNode(new(CatalogKind.Server, catalogService.DisplayName), catalogService); await root.LoadAsync(token); if (token.IsCancellationRequested || explorerConnection != connection) return; // Disconnected while loading. @@ -619,7 +663,8 @@ private async void RoleProperties(object sender, RoutedEventArgs e) /// Explain, Fix or Optimize (M1115): the window opens with the selected SQL (or the whole document when nothing is /// selected) and a request written for it, which the user can change before Generate. - internal void OpenAiQuery(AiSqlAction? action, string? settingsPath = null) + /// For Paste with AI: the clipboard text, sent as the SQL to adapt. + internal void OpenAiQuery(AiSqlAction? action, string? settingsPath = null, string? clipboardSql = null) { if (ActiveQuery is not { } query) return; if (!query.IsConnected || query.ConnectionString is not { } connection) { Status.Text = "Connect this query window before generating SQL with AI."; return; } @@ -636,14 +681,14 @@ internal void OpenAiQuery(AiSqlAction? action, string? settingsPath = null) { Status.Text = "AI settings could not be read: " + ex.Message; return; } if (provider is null && attempt == 0) { - if (MessageBox.Show(this, "The AI assistant needs a provider, a model and, for Anthropic or OpenAI, an API key.\nOpen AI Assistant Settings now?", "Generate SQL with AI", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.Yes) != MessageBoxResult.Yes) return; + if (LocalizedMessageBox.Show(this, "The AI assistant needs a provider, a model and, for Anthropic or OpenAI, an API key.\nOpen AI Assistant Settings now?", "Generate SQL with AI", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.Yes) != MessageBoxResult.Yes) return; new AiSettingsDialog(store.FilePath) { Owner = this }.ShowDialog(); } } if (provider is null) { Status.Text = "The AI assistant is not configured."; return; } - string? sql = query.SelectedSql; - if (action is not null && string.IsNullOrWhiteSpace(sql)) sql = query.Editor.Text; - if (action is not null && string.IsNullOrWhiteSpace(sql)) { Status.Text = "Write or select the SQL to " + action.Value.ToString().ToLowerInvariant() + " first."; return; } + string? sql = action == AiSqlAction.Paste ? clipboardSql : query.SelectedSql; + if (action is not null && string.IsNullOrWhiteSpace(sql)) sql = action == AiSqlAction.Paste ? null : query.Editor.Text; + if (action is not null && string.IsNullOrWhiteSpace(sql)) { Status.Text = action == AiSqlAction.Paste ? "The clipboard has no text to paste." : "Write or select the SQL to " + action.Value.ToString().ToLowerInvariant() + " first."; return; } var dialog = new AiQueryDialog(provider, connection, sql, query.InsertGeneratedSql) { Owner = this }; if (action is { } chosen) dialog.Prefill(AiQueryGenerator.ActionRequest(chosen, chosen == AiSqlAction.Fix ? query.LastError?.Code : null, chosen == AiSqlAction.Fix ? query.LastError?.Message : null)); if (AiQueryShown is { } shown) { shown(dialog); return; } @@ -775,9 +820,9 @@ internal async Task CloseDesignerAsync(TableDesignerView view) } private async Task ConfirmDesignerCloseAsync(TableDesignerView view) { - if (view.IsBusy) { MessageBox.Show(this, "Cancel the running operation before closing this table.", "PGMS"); return false; } + if (view.IsBusy) { LocalizedMessageBox.Show(this, "Cancel the running operation before closing this table.", "PGMS"); return false; } if (!view.IsDirty) return true; - var answer = DesignerClosePrompt?.Invoke(view) ?? MessageBox.Show(this, "Save changes to the following items?\n\n" + view.Title.TrimEnd('*'), "PGMS", MessageBoxButton.YesNoCancel, MessageBoxImage.Question); + var answer = DesignerClosePrompt?.Invoke(view) ?? LocalizedMessageBox.Show(this, "Save changes to the following items?\n\n" + view.Title.TrimEnd('*'), "PGMS", MessageBoxButton.YesNoCancel, MessageBoxImage.Question); return answer == MessageBoxResult.No || (answer == MessageBoxResult.Yes && await view.SaveAsync() && !view.IsDirty); } private void DesignFromExplorer(object sender, RoutedEventArgs e) @@ -966,12 +1011,12 @@ private async void InsertFileAsText(object sender,RoutedEventArgs e) private void About(object sender, RoutedEventArgs e) => new AboutWindow { Owner = this }.ShowDialog(); /// Replaces the error box in tests, which would block the run. internal Action? ShowErrorOverride { get; set; } - private void ShowError(Exception error) { Status.Text = "Operation failed"; if (ShowErrorOverride is { } shown) { shown(error); return; } MessageBox.Show(this, error.Message, "PGMS", MessageBoxButton.OK, MessageBoxImage.Error); } + private void ShowError(Exception error) { Status.Text = "Operation failed"; if (ShowErrorOverride is { } shown) { shown(error); return; } LocalizedMessageBox.Show(this, error.Message, "PGMS", MessageBoxButton.OK, MessageBoxImage.Error); } private void ShowExplorer(object sender, RoutedEventArgs e) { var explorer = DockManager.Layout.Descendents().OfType().FirstOrDefault(a => a.ContentId == "explorer"); - if (explorer is not null) { explorer.Show(); explorer.IsActive = true; } + if (explorer is not null) { explorer.Show(); explorer.IsActive = true; FocusToolContent(ExplorerContent, () => ExplorerTree); } } private void ResetLayout(object sender, RoutedEventArgs e) @@ -985,7 +1030,7 @@ private void ResetLayout(object sender, RoutedEventArgs e) if (DockManager.Layout.Descendents().OfType().FirstOrDefault(a => a.ContentId == RegisteredServersId) is { } registered) registered.Content = null; tools.Children.Add(new LayoutAnchorable { Title = "Object Explorer", ContentId = "explorer", Content = ExplorerContent, CanClose = false }); var pane = new LayoutDocumentPane(); - foreach (var document in documents.Values.Concat(monitors.Values).Concat(reports.Values)) pane.Children.Add(document); + foreach (var document in QueryTabsInCreationOrder().Concat(monitors.Values).Concat(reports.Values)) pane.Children.Add(document); panel.Children.Add(tools); panel.Children.Add(pane); root.RootPanel = panel; DockManager.Layout = root; } @@ -993,6 +1038,7 @@ private void WindowLoaded(object sender, RoutedEventArgs e) { RestoreSavedLayout(); StartRecovery(); + ScheduleUpdateCheck(); // As SSMS does, the Connect dialog opens at startup and connects Object Explorer (pedido do usuário, 08/11/2026). Only for the real // application: test hosts use a plain Application and must not get a modal dialog. if (Application.Current is App) @@ -1048,7 +1094,16 @@ internal void ShowOptions(string? page = null) var dialog = new OptionsDialog(EnvironmentSettings, () => QueryHistory.ClearAsync(), KeyboardCommands()) { Owner = this }; if (page is not null && !dialog.SelectPagePath(page)) dialog.SelectPage(page); if (OptionsShown is { } shown) { shown(dialog); return; } - if (dialog.ShowDialog() == true) { ApplyFontsAndColors(); ApplyCustomization(); } + if (dialog.ShowDialog() == true) ApplyOptions(); + } + + /// What OK in Tools ▸ Options changes at once (tests call it after their own dialog). + internal void ApplyOptions() + { + ApplyFontsAndColors(); ApplyCustomization(); + var document = EnvironmentSettings.Load(); + ApplyTabsAndDocuments(document); + ApplyAutoRecover(document.Recovery); } /// Fonts and Colors applies at once to every open query window, as in SSMS. @@ -1058,6 +1113,8 @@ internal void ApplyFontsAndColors() FontsAndColorsSettings.EditorAppearance = fontsDocument.EditorAppearanceChoice; FontsAndColorsSettings.Current = EffectiveFontsAndColors(fontsDocument); foreach (var query in OpenQueries()) query.ApplyAppearance(FontsAndColorsSettings.Current); + var editor = fontsDocument.EditorSettings; // Text Editor ▸ Transact-SQL (M1122): line numbers and tabs reach every open window + foreach (var query in OpenQueries()) query.ApplyTextEditorSettings(editor, newTab: false); } private void RestoreSavedLayout() @@ -1115,6 +1172,8 @@ private async Task CloseWindowCoreAsync() catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or InvalidOperationException) { Status.Text = "Save failed; window remains open: " + ex.Message; return; } await TabCloseCompletion; + // Restored tabs never shown are mounted first, so each asks to save exactly as before (M1133). + MountDeferredQueries(); var accepted = new Dictionary(); foreach (var query in documents.Keys.ToArray()) { diff --git a/src/PGMS.Desktop/NavigationHistory.cs b/src/PGMS.Desktop/NavigationHistory.cs new file mode 100644 index 0000000..4a69ec0 --- /dev/null +++ b/src/PGMS.Desktop/NavigationHistory.cs @@ -0,0 +1,54 @@ +namespace PGMS.Desktop; + +/// Places visited for View ▸ Navigate Backward/Forward (PGMS-082, M1121): a document tab and, for a query tab, a caret offset. +/// Like a browser history: visiting a new place after going back drops the places ahead of it. +internal sealed class NavigationHistory where T : class +{ + internal const int Capacity = 100; + internal sealed record Place(T Target, int Offset); + + private readonly List places = []; + private int index = -1; + + public IReadOnlyList Places => places; + public int Index => index; + public Place? Current => index >= 0 && index < places.Count ? places[index] : null; + public bool CanGoBack => index > 0; + public bool CanGoForward => index >= 0 && index < places.Count - 1; + + /// A new place; the same target near the current offset only updates it. + public void Visit(T target, int offset, Func? near = null) + { + if (Current is { } current && ReferenceEquals(current.Target, target) && (current.Offset == offset || near?.Invoke(current.Offset, offset) == true)) + { places[index] = current with { Offset = offset }; return; } + if (index < places.Count - 1) places.RemoveRange(index + 1, places.Count - index - 1); + places.Add(new Place(target, offset)); + if (places.Count > Capacity) places.RemoveAt(0); + index = places.Count - 1; + } + + /// Remembers where the caret is now in the current place, so going forward again returns there. + public void UpdateCurrent(T target, int offset) + { + if (Current is { } current && ReferenceEquals(current.Target, target)) places[index] = current with { Offset = offset }; + } + + public Place? Back() => CanGoBack ? places[--index] : null; + public Place? Forward() => CanGoForward ? places[++index] : null; + + /// Drops every place of a target that no longer exists (a closed tab); consecutive places of one target merge. + public void Remove(Func gone) + { + var keep = new List(); + int newIndex = -1; + for (int i = 0; i < places.Count; i++) + { + if (gone(places[i].Target)) { if (i == index) newIndex = keep.Count - 1; continue; } + if (keep.Count > 0 && ReferenceEquals(keep[^1].Target, places[i].Target) && keep[^1].Offset == places[i].Offset) { if (i == index) newIndex = keep.Count - 1; continue; } + keep.Add(places[i]); + if (i == index) newIndex = keep.Count - 1; + } + places.Clear(); places.AddRange(keep); + index = places.Count == 0 ? -1 : Math.Clamp(newIndex < 0 ? 0 : newIndex, 0, places.Count - 1); + } +} diff --git a/src/PGMS.Desktop/ObjectExplorerDetailsView.cs b/src/PGMS.Desktop/ObjectExplorerDetailsView.cs index 66d31da..467fb78 100644 --- a/src/PGMS.Desktop/ObjectExplorerDetailsView.cs +++ b/src/PGMS.Desktop/ObjectExplorerDetailsView.cs @@ -111,6 +111,23 @@ public async Task RefreshAsync() await ShowAsync(folder); } + private static readonly double[] DefaultStarWidths = [2.0, 1.0, 1.0, 1.0]; + + /// Window ▸ Reset Current Object Explorer Details View (PGMS-082, M1121): column order and widths as created, no sorting, no search text. + public void ResetView() + { + for (int i = 0; i < grid.Columns.Count; i++) + { + var column = grid.Columns[i]; + column.DisplayIndex = i; + column.Width = new DataGridLength(DefaultStarWidths[Math.Min(i, DefaultStarWidths.Length - 1)], DataGridLengthUnitType.Star); + column.SortDirection = null; + } + grid.Items.SortDescriptions.Clear(); + search.Text = ""; + ApplySearch(); + } + private void ApplySearch() { string text = search.Text.Trim(); diff --git a/src/PGMS.Desktop/OptionsDialog.Keyboard.cs b/src/PGMS.Desktop/OptionsDialog.Keyboard.cs index 94888eb..6e1a782 100644 --- a/src/PGMS.Desktop/OptionsDialog.Keyboard.cs +++ b/src/PGMS.Desktop/OptionsDialog.Keyboard.cs @@ -25,7 +25,7 @@ internal void SelectPage(string header) { foreach (var category in Pages.Items.OfType()) foreach (var page in category.Items.OfType().Prepend(category)) - if (string.Equals(page.Header as string, header, StringComparison.OrdinalIgnoreCase) && page.Items.Count == 0) { page.IsSelected = true; return; } + if ((string.Equals(page.Header as string, header, StringComparison.OrdinalIgnoreCase) || string.Equals(Localization.EnglishHeader(page, null) as string, header, StringComparison.OrdinalIgnoreCase)) && page.Items.Count == 0) { page.IsSelected = true; return; } } internal IReadOnlyList ShownCommands => KeyboardCommandList.Items.Cast().ToList(); diff --git a/src/PGMS.Desktop/OptionsDialog.Search.cs b/src/PGMS.Desktop/OptionsDialog.Search.cs index d0827f3..e377cbd 100644 --- a/src/PGMS.Desktop/OptionsDialog.Search.cs +++ b/src/PGMS.Desktop/OptionsDialog.Search.cs @@ -27,10 +27,19 @@ internal IReadOnlyList SearchIndex() internal bool SelectPagePath(string path) { foreach (var (pagePath, page) in LeafPages()) - if (string.Equals(pagePath, path, StringComparison.OrdinalIgnoreCase)) { page.IsSelected = true; return true; } + if (string.Equals(pagePath, path, StringComparison.OrdinalIgnoreCase) || string.Equals(PathIn(page, translated: true), path, StringComparison.OrdinalIgnoreCase) + || string.Equals(PathIn(page, translated: false), path, StringComparison.OrdinalIgnoreCase)) { page.IsSelected = true; return true; } return false; } + /// The path of a page in English or in the interface language, whether or not the tree was translated yet (M1129): the Search index + /// is built from a translated window, and the window it opens may not be translated when the page is selected. + private static string PathIn(TreeViewItem page, bool translated) + { + string Name(TreeViewItem item) { var english = Localization.EnglishHeader(item, item.Header) as string ?? ""; return FeatureSearch.Text(translated ? Localization.T(english) : english); } + return page.Parent is TreeViewItem category ? Name(category) + " > " + Name(page) : Name(page); + } + private IEnumerable<(string Path, TreeViewItem Page)> LeafPages() { foreach (var category in Pages.Items.OfType()) diff --git a/src/PGMS.Desktop/OptionsDialog.xaml b/src/PGMS.Desktop/OptionsDialog.xaml index 38cbfb9..5d7b8e6 100644 --- a/src/PGMS.Desktop/OptionsDialog.xaml +++ b/src/PGMS.Desktop/OptionsDialog.xaml @@ -2,11 +2,22 @@ - + + + + - + + + + + + + + + @@ -15,6 +26,7 @@ + @@ -22,7 +34,18 @@ + + + + + + + + + + + @@ -41,6 +64,22 @@ + + + + + + + + + + + + + + @@ -64,6 +103,26 @@ + + + + + + + + + + + + + + + + + + @@ -141,6 +200,173 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/PGMS.Desktop/OptionsDialog.xaml.cs b/src/PGMS.Desktop/OptionsDialog.xaml.cs index 562c295..2c4b353 100644 --- a/src/PGMS.Desktop/OptionsDialog.xaml.cs +++ b/src/PGMS.Desktop/OptionsDialog.xaml.cs @@ -36,9 +36,103 @@ public OptionsDialog(EnvironmentOptions options, Func>? clearHistory = DefaultTableViewBox.SelectedItem = DefaultTableViewBox.Items.OfType().First(i => (string)i.Tag == designers.DefaultTableView.ToString()); LaunchAddTableBox.IsChecked = designers.LaunchAddTableOnNewDiagram; SelectRecentBox.IsChecked = document.AutoSelectRecentConnection; + CheckForUpdatesBox.IsChecked = document.CheckForUpdates; + // Same as Microsoft Windows (no saved language) first, then the languages by their own names. + LanguageBox.Items.Add(new ComboBoxItem { Content = "Same as Microsoft Windows", Tag = "" }); + foreach (var (code, name) in Localization.Languages) LanguageBox.Items.Add(new ComboBoxItem { Content = name, Tag = code }); + LanguageBox.SelectedItem = LanguageBox.Items.OfType().FirstOrDefault(i => (string)i.Tag == (document.Language ?? "")) ?? LanguageBox.Items[0]; QueryShortcutsGrid.ItemsSource = shortcutRows = EnvironmentOptions.Document.QueryShortcutKeys.Select(k => new QueryShortcutRow(k) { Text = document.QueryShortcut(k) ?? "" }).ToList(); + var editor = document.EditorSettings; + EditorWordWrapBox.IsChecked = editor.WordWrap; EditorLineNumbersBox.IsChecked = editor.LineNumbers; EditorIntelliSenseBox.IsChecked = editor.IntelliSense; + EditorTabSizeBox.Text = editor.TabSize.ToString(CultureInfo.InvariantCulture); + EditorInsertSpacesBox.IsChecked = editor.InsertSpaces; EditorKeepTabsBox.IsChecked = !editor.InsertSpaces; LoadFontsAndColors(document.Appearance); LoadKeyboard(document, commands ?? []); + // M1141: Environment ▸ AutoRecover, Documents, Tabs and Windows. + var recovery = document.Recovery; + AutoRecoverBox.IsChecked = recovery.Enabled; + AutoRecoverIntervalBox.Text = recovery.IntervalMinutes.ToString(CultureInfo.InvariantCulture); + AutoRecoverLifetimeBox.Text = recovery.LifetimeDays.ToString(CultureInfo.InvariantCulture); + var files = document.DocumentOptions; + DetectChangesBox.IsChecked = files.DetectChanges; ReloadUnmodifiedBox.IsChecked = files.ReloadUnmodified; AllowReadOnlyBox.IsChecked = files.AllowEditingReadOnly; + OpenFromActiveBox.IsChecked = files.OpenFromActiveDirectory; CheckLineEndingsBox.IsChecked = files.CheckLineEndings; SaveInBackgroundBox.IsChecked = files.SaveInBackground; + UseSaveEncodingBox.IsChecked = files.UseSaveEncoding; + SaveEncodingBox.SelectedItem = SaveEncodingBox.Items.OfType().First(i => (string)i.Tag == files.SaveEncoding.ToString()); + var tabs = document.TabsSettings; + InsertTabsRightBox.IsChecked = tabs.InsertTabsToRight; SkipLayoutConfirmBox.IsChecked = tabs.SkipLayoutConfirmation; + LoadFormatter(document.FormatterSettings); + // M1143: Table Options, Object Explorer ▸ General and rename, Live Query Statistics. + OverrideTimeoutBox.IsChecked = designers.OverrideTimeout; + DesignerTimeoutBox.Text = designers.TimeoutSeconds.ToString(CultureInfo.InvariantCulture); + WarnNoPrimaryKeyBox.IsChecked = designers.WarnNoPrimaryKey; + var explorer = document.ExplorerSettings; + HideSystemObjectsBox.IsChecked = explorer.HideSystemObjects; ConfirmRenameBox.IsChecked = explorer.ConfirmRename; + LivePollingBox.Text = document.LiveStatistics.PollingMilliseconds.ToString(CultureInfo.InvariantCulture); + } + + private (CheckBox Box, Func Get, Func Set)[] FormatterBoxes => [ + (FormatAlignBodiesBox, s => s.AlignClauseBodies, (s, v) => s with { AlignClauseBodies = v }), (FormatOnSaveBox, s => s.FormatOnSave, (s, v) => s with { FormatOnSave = v }), + (FormatMultiSelectBox, s => s.MultilineSelectList, (s, v) => s with { MultilineSelectList = v }), (FormatMultiSetBox, s => s.MultilineSetItems, (s, v) => s with { MultilineSetItems = v }), + (FormatMultiWhereBox, s => s.MultilineWherePredicates, (s, v) => s with { MultilineWherePredicates = v }), (FormatMultiGroupBox, s => s.MultilineGroupBy, (s, v) => s with { MultilineGroupBy = v }), + (FormatMultiHavingBox, s => s.MultilineHavingPredicates, (s, v) => s with { MultilineHavingPredicates = v }), (FormatMultiOrderBox, s => s.MultilineOrderBy, (s, v) => s with { MultilineOrderBy = v }), + (FormatMultiValuesBox, s => s.MultilineValues, (s, v) => s with { MultilineValues = v }), + (FormatNlFromBox, s => s.NewLineBeforeFrom, (s, v) => s with { NewLineBeforeFrom = v }), (FormatNlWhereBox, s => s.NewLineBeforeWhere, (s, v) => s with { NewLineBeforeWhere = v }), + (FormatNlGroupBox, s => s.NewLineBeforeGroupBy, (s, v) => s with { NewLineBeforeGroupBy = v }), (FormatNlHavingBox, s => s.NewLineBeforeHaving, (s, v) => s with { NewLineBeforeHaving = v }), + (FormatNlOrderBox, s => s.NewLineBeforeOrderBy, (s, v) => s with { NewLineBeforeOrderBy = v }), (FormatNlOffsetBox, s => s.NewLineBeforeOffset, (s, v) => s with { NewLineBeforeOffset = v }), + (FormatNlWindowBox, s => s.NewLineBeforeWindow, (s, v) => s with { NewLineBeforeWindow = v }), (FormatNlReturningBox, s => s.NewLineBeforeReturning, (s, v) => s with { NewLineBeforeReturning = v }), + (FormatNlJoinBox, s => s.NewLineBeforeJoin, (s, v) => s with { NewLineBeforeJoin = v }), (FormatNlAfterJoinBox, s => s.NewLineAfterJoin, (s, v) => s with { NewLineAfterJoin = v }), + (FormatNlOnBox, s => s.NewLineBeforeOn, (s, v) => s with { NewLineBeforeOn = v }), (FormatNlCloseBox, s => s.NewLineBeforeClosingParenthesis, (s, v) => s with { NewLineBeforeClosingParenthesis = v }), + (FormatTypeSpaceBox, s => s.SpaceBetweenTypeAndParameters, (s, v) => s with { SpaceBetweenTypeAndParameters = v })]; + + private void LoadFormatter(SqlFormatterSettings settings) + { + foreach (var (box, get, _) in FormatterBoxes) box.IsChecked = get(settings); + FormatCasingBox.SelectedItem = FormatCasingBox.Items.OfType().First(i => (string)i.Tag == settings.KeywordCasing.ToString()); + FormatIndentBox.Text = settings.IndentationSize.ToString(CultureInfo.InvariantCulture); + FormatNewLinesBox.Text = settings.NewLinesAfterStatement.ToString(CultureInfo.InvariantCulture); + } + + /// The SQL Formatter pages (M1142), or null after showing what is wrong. + private SqlFormatterSettings? ReadFormatter() + { + int? indent = ParseRange(FormatIndentBox.Text, SqlFormatterSettings.MinIndentation, SqlFormatterSettings.MaxIndentation); + int? lines = ParseRange(FormatNewLinesBox.Text, 0, SqlFormatterSettings.MaxNewLines); + if (indent is null || lines is null) + { + var (wrong, page) = indent is null ? (FormatIndentBox, FormatIndentationPage) : (FormatNewLinesBox, FormatNewLinePage); + var error = indent is null ? FormatterError : FormatNewLinesError; + error.Text = indent is null ? $"Enter an indentation size from {SqlFormatterSettings.MinIndentation} to {SqlFormatterSettings.MaxIndentation}." : $"Enter a number of new lines from 0 to {SqlFormatterSettings.MaxNewLines}."; + error.Visibility = Visibility.Visible; + page.IsSelected = true; + System.Windows.Input.FocusManager.SetFocusedElement(this, wrong); + wrong.Focus(); wrong.SelectAll(); + return null; + } + var settings = new SqlFormatterSettings(Enum.Parse((string)((ComboBoxItem)FormatCasingBox.SelectedItem).Tag)) with { IndentationSize = indent.Value, NewLinesAfterStatement = lines.Value }; + foreach (var (box, _, set) in FormatterBoxes) settings = set(settings, box.IsChecked == true); + return settings; + } + + /// The Environment pages of M1141, or null after showing what is wrong. + private (AutoRecoverSettings Recovery, DocumentSettings Documents, TabsAndWindowsSettings Tabs)? ReadEnvironmentPages() + { + int? interval = ParseRange(AutoRecoverIntervalBox.Text, AutoRecoverSettings.MinInterval, AutoRecoverSettings.MaxInterval); + int? lifetime = ParseRange(AutoRecoverLifetimeBox.Text, AutoRecoverSettings.MinLifetime, AutoRecoverSettings.MaxLifetime); + if (interval is null || lifetime is null) + { + var wrong = interval is null ? AutoRecoverIntervalBox : AutoRecoverLifetimeBox; + AutoRecoverError.Text = interval is null ? $"Enter a backup interval from {AutoRecoverSettings.MinInterval} to {AutoRecoverSettings.MaxInterval} minutes." : $"Enter a lifetime from {AutoRecoverSettings.MinLifetime} to {AutoRecoverSettings.MaxLifetime} days."; + AutoRecoverError.Visibility = Visibility.Visible; + AutoRecoverPage.IsSelected = true; + System.Windows.Input.FocusManager.SetFocusedElement(this, wrong); + wrong.Focus(); wrong.SelectAll(); + return null; + } + var recovery = new AutoRecoverSettings(AutoRecoverBox.IsChecked == true, interval.Value, lifetime.Value); + var documents = new DocumentSettings(DetectChangesBox.IsChecked == true, ReloadUnmodifiedBox.IsChecked == true, AllowReadOnlyBox.IsChecked == true, OpenFromActiveBox.IsChecked == true, + CheckLineEndingsBox.IsChecked == true, SaveInBackgroundBox.IsChecked == true, UseSaveEncodingBox.IsChecked == true, Enum.Parse((string)((ComboBoxItem)SaveEncodingBox.SelectedItem).Tag)); + var tabs = new TabsAndWindowsSettings(InsertTabsRightBox.IsChecked == true, SkipLayoutConfirmBox.IsChecked == true); + return (recovery, documents, tabs); } private readonly List shortcutRows = []; @@ -57,7 +151,7 @@ public sealed class QueryShortcutRow(string shortcut) internal async Task ClearHistoryAsync() { if (clearHistory is null) return; - bool confirmed = ConfirmClearHistory?.Invoke() ?? MessageBox.Show(this, QueryHistoryWindow.ClearQuestion, "Clear Query History", MessageBoxButton.YesNo, MessageBoxImage.Warning, MessageBoxResult.No) == MessageBoxResult.Yes; + bool confirmed = ConfirmClearHistory?.Invoke() ?? LocalizedMessageBox.Show(this, QueryHistoryWindow.ClearQuestion, "Clear Query History", MessageBoxButton.YesNo, MessageBoxImage.Warning, MessageBoxResult.No) == MessageBoxResult.Yes; if (!confirmed) return; ClearHistoryButton.IsEnabled = false; ClearHistoryStatus.Text = "Clearing…"; try { int removed = await clearHistory(); ClearHistoryStatus.Text = $"Query History cleared: {removed:N0} execution(s) removed."; } @@ -84,7 +178,24 @@ private void PageChanged(object sender, RoutedPropertyChangedEventArgs e KeyboardPanel.Visibility = page == KeyboardPage ? Visibility.Visible : Visibility.Collapsed; DesignersPanel.Visibility = page == DesignersPage ? Visibility.Visible : Visibility.Collapsed; ConnectionDialogPanel.Visibility = page == ConnectionDialogPage ? Visibility.Visible : Visibility.Collapsed; + ProductUpdatesPanel.Visibility = page == ProductUpdatesPage ? Visibility.Visible : Visibility.Collapsed; + InternationalPanel.Visibility = page == InternationalPage ? Visibility.Visible : Visibility.Collapsed; FontsAndColorsPanel.Visibility = page == FontsAndColorsPage ? Visibility.Visible : Visibility.Collapsed; + TextEditorPanel.Visibility = page == TextEditorPage ? Visibility.Visible : Visibility.Collapsed; + AutoRecoverPanel.Visibility = page == AutoRecoverPage ? Visibility.Visible : Visibility.Collapsed; + DocumentsPanel.Visibility = page == DocumentsPage ? Visibility.Visible : Visibility.Collapsed; + TabsPanel.Visibility = page == TabsPage ? Visibility.Visible : Visibility.Collapsed; + TaskListPanel.Visibility = page == TaskListPage ? Visibility.Visible : Visibility.Collapsed; + WindowsPanel.Visibility = page == WindowsPage ? Visibility.Visible : Visibility.Collapsed; + FormatAlignmentPanel.Visibility = page == FormatAlignmentPage ? Visibility.Visible : Visibility.Collapsed; + FormatFormattingPanel.Visibility = page == FormatFormattingPage ? Visibility.Visible : Visibility.Collapsed; + FormatGeneralPanel.Visibility = page == FormatGeneralPage ? Visibility.Visible : Visibility.Collapsed; + FormatIndentationPanel.Visibility = page == FormatIndentationPage ? Visibility.Visible : Visibility.Collapsed; + FormatMultilinePanel.Visibility = page == FormatMultilinePage ? Visibility.Visible : Visibility.Collapsed; + FormatNewLinePanel.Visibility = page == FormatNewLinePage ? Visibility.Visible : Visibility.Collapsed; + FormatSpacingPanel.Visibility = page == FormatSpacingPage ? Visibility.Visible : Visibility.Collapsed; + ExplorerGeneralPanel.Visibility = page == ExplorerGeneralPage ? Visibility.Visible : Visibility.Collapsed; + LiveStatisticsPanel.Visibility = page == LiveStatisticsPage ? Visibility.Visible : Visibility.Collapsed; int shared = Array.IndexOf(SharedPages, page); QueryPages.Visibility = shared >= 0 ? Visibility.Visible : Visibility.Collapsed; if (shared >= 0) QueryPages.ShowPage(shared); @@ -120,6 +231,16 @@ internal void Accept(object sender, RoutedEventArgs e) wrong.Focus(); wrong.SelectAll(); return; } + if (ParseRange(EditorTabSizeBox.Text, TextEditorSettings.MinTabSize, TextEditorSettings.MaxTabSize) is not { } tabSize) + { + TextEditorError.Text = $"Enter a tab and indent size from {TextEditorSettings.MinTabSize} to {TextEditorSettings.MaxTabSize}."; + TextEditorError.Visibility = Visibility.Visible; + TextEditorPage.IsSelected = true; + System.Windows.Input.FocusManager.SetFocusedElement(this, EditorTabSizeBox); + EditorTabSizeBox.Focus(); EditorTabSizeBox.SelectAll(); + return; + } + var textEditor = new TextEditorSettings(EditorWordWrapBox.IsChecked == true, EditorLineNumbersBox.IsChecked == true, tabSize, EditorInsertSpacesBox.IsChecked == true, EditorIntelliSenseBox.IsChecked == true); if (QueryPages.TryRead() is not { } queryDefaults) { SharedPages[QueryPages.RejectedPage].IsSelected = true; return; } int? days = ParseRange(HistoryDaysBox.Text, QueryHistorySettings.MinRetentionDays, QueryHistorySettings.MaxRetentionDays); int? count = ParseRange(HistoryCountBox.Text, QueryHistorySettings.MinExecutions, QueryHistorySettings.MaxExecutionsLimit); @@ -141,14 +262,38 @@ internal void Accept(object sender, RoutedEventArgs e) var destination = DefaultResultsBox.SelectedIndex switch { 1 => ResultsDestination.Text, 2 => ResultsDestination.File, _ => ResultsDestination.Grid }; var scripting = new PGMS.PostgreSql.ScriptingOptions(ScriptHeadersBox.IsChecked == true, ScriptDatabaseBox.IsChecked == true, ScriptExistenceBox.IsChecked == true); var tableView = Enum.Parse((string)((ComboBoxItem)DefaultTableViewBox.SelectedItem).Tag); - var designers = new DesignerOptions(tableView, LaunchAddTableBox.IsChecked == true); - bool selectRecent = SelectRecentBox.IsChecked == true; + var designers = new DesignerOptions(tableView, LaunchAddTableBox.IsChecked == true, OverrideTimeoutBox.IsChecked == true, + ParseRange(DesignerTimeoutBox.Text, DesignerOptions.MinTimeout, DesignerOptions.MaxTimeout) ?? 3600, WarnNoPrimaryKeyBox.IsChecked == true); + bool selectRecent = SelectRecentBox.IsChecked == true, checkUpdates = CheckForUpdatesBox.IsChecked == true; + string? language = (LanguageBox.SelectedItem as ComboBoxItem)?.Tag is string { Length: > 0 } code ? code : null; if (ReadFontsAndColors() is not { } fontsAndColors) return; + if (ReadEnvironmentPages() is not { } environment) return; + if (ReadFormatter() is not { } formatter) return; + int? designerTimeout = ParseRange(DesignerTimeoutBox.Text, DesignerOptions.MinTimeout, DesignerOptions.MaxTimeout) ?? (OverrideTimeoutBox.IsChecked == true ? null : 3600); + int? polling = ParseRange(LivePollingBox.Text, LiveQueryStatisticsSettings.Min, LiveQueryStatisticsSettings.Max); + if (designerTimeout is null || polling is null) + { + var (wrong, error, page, message) = designerTimeout is null + ? (DesignerTimeoutBox, DesignersError, DesignersPage, $"Enter a time-out from {DesignerOptions.MinTimeout} to {DesignerOptions.MaxTimeout:N0} seconds.") + : (LivePollingBox, LivePollingError, LiveStatisticsPage, $"Enter a polling interval from {LiveQueryStatisticsSettings.Min} to {LiveQueryStatisticsSettings.Max:N0} milliseconds."); + error.Text = message; error.Visibility = Visibility.Visible; page.IsSelected = true; + if (designerTimeout is null) OverrideTimeoutBox.IsChecked = true; + System.Windows.Input.FocusManager.SetFocusedElement(this, wrong); + wrong.Focus(); wrong.SelectAll(); + return; + } + designers = designers with { TimeoutSeconds = designerTimeout.Value }; + var explorerOptions = new ObjectExplorerSettings(HideSystemObjectsBox.IsChecked == true, ConfirmRenameBox.IsChecked == true); + var live = new LiveQueryStatisticsSettings(polling.Value); QueryShortcutsGrid.CommitEdit(DataGridEditingUnit.Row, true); var shortcuts = shortcutRows.Where(r => !string.IsNullOrWhiteSpace(r.Text)).ToDictionary(r => r.Shortcut, r => r.Text.Trim()); options.Update(d => d with { RestoreWindowPlacement = restore, Window = restore ? d.Window : null, SelectTopRows = selectTop.Value, EditTopRows = editTop.Value, DefaultResultsDestination = destination, QueryDefaults = queryDefaults, QueryHistory = historySettings, - RecentFilesCount = recentCount, RecentFiles = d.RecentFiles?.Take(recentCount).ToList(), Scripting = scripting, Designers = designers, AutoSelectRecentConnection = selectRecent, QueryShortcuts = shortcuts, - KeyboardShortcuts = keyboardShortcuts.Count == 0 ? null : new Dictionary(keyboardShortcuts), FontsAndColors = fontsAndColors == new FontsAndColorsSettings() ? null : fontsAndColors }); + RecentFilesCount = recentCount, RecentFiles = d.RecentFiles?.Take(recentCount).ToList(), Scripting = scripting, Designers = designers, AutoSelectRecentConnection = selectRecent, CheckForUpdates = checkUpdates, QueryShortcuts = shortcuts, + OptionsRevision = EnvironmentOptions.Document.CurrentOptionsRevision, KeyboardShortcuts = keyboardShortcuts.Count == 0 ? null : new Dictionary(keyboardShortcuts), FontsAndColors = fontsAndColors == new FontsAndColorsSettings() ? null : fontsAndColors, + TextEditor = textEditor == new TextEditorSettings() ? null : textEditor, Language = language, + AutoRecover = environment.Recovery == new AutoRecoverSettings() ? null : environment.Recovery, Documents = environment.Documents == new DocumentSettings() ? null : environment.Documents, + TabsAndWindows = environment.Tabs == new TabsAndWindowsSettings() ? null : environment.Tabs, SqlFormatter = formatter == new SqlFormatterSettings() ? null : formatter, + ObjectExplorer = explorerOptions == new ObjectExplorerSettings() ? null : explorerOptions, LiveQueryStatistics = live == new LiveQueryStatisticsSettings() ? null : live }); try { DialogResult = true; } catch (InvalidOperationException) { Close(); } // shown without ShowDialog } diff --git a/src/PGMS.Desktop/PGMS.Desktop.csproj b/src/PGMS.Desktop/PGMS.Desktop.csproj index 5827d0f..25dd1c3 100644 --- a/src/PGMS.Desktop/PGMS.Desktop.csproj +++ b/src/PGMS.Desktop/PGMS.Desktop.csproj @@ -17,5 +17,5 @@ - + diff --git a/src/PGMS.Desktop/PartitionDialog.xaml.cs b/src/PGMS.Desktop/PartitionDialog.xaml.cs index 6de4ac0..e74c599 100644 --- a/src/PGMS.Desktop/PartitionDialog.xaml.cs +++ b/src/PGMS.Desktop/PartitionDialog.xaml.cs @@ -149,7 +149,7 @@ public async Task ApplyAsync() if(busy || !ApplyButton.IsEnabled)return; if(Standalone){await ApplyStandaloneAsync();return;} var request=Request; - if(request is DetachPartitionEdit && MessageBox.Show(this,Target.Text+"\n\n"+request.ToSql()+"\n\nKeep the child table but remove its rows from parent queries?","Confirm Detach Partition",MessageBoxButton.YesNo,MessageBoxImage.Warning,MessageBoxResult.No)!=MessageBoxResult.Yes){Feedback.Text="Detach canceled. Nothing was sent.";return;} + if(request is DetachPartitionEdit && LocalizedMessageBox.Show(this,Target.Text+"\n\n"+request.ToSql()+"\n\nKeep the child table but remove its rows from parent queries?","Confirm Detach Partition",MessageBoxButton.YesNo,MessageBoxImage.Warning,MessageBoxResult.No)!=MessageBoxResult.Yes){Feedback.Text="Detach canceled. Nothing was sent.";return;} using var source=new CancellationTokenSource();cancellation=source;SetBusy(true);RequiresParentRefresh=true;Feedback.Text="Applying partition change…"; try{await new AdministrativeEditService(connection).ApplyAsync(request,source.Token);WasApplied=true;Feedback.Text="Command completed. Inspect again before another change.";} catch(Exception ex)when(Handled(ex)){Feedback.Text=Error(ex)+" Result not confirmed; inspect before retrying. Cancel cannot undo a completed commit.";} @@ -158,7 +158,7 @@ public async Task ApplyAsync() private async Task ApplyStandaloneAsync() { var parent=snapshot!.Parent;var child=SelectedChild!;string sql=ConcurrentPartitionDetachService.ToSql(parent,child); - if(MessageBox.Show(this,Target.Text+"\n\n"+sql+"\n\nThis runs outside a transaction and cannot be rolled back. Keep the child table but remove its rows from parent queries?",child.DetachPending?"Confirm Finalize Detach":"Confirm Concurrent Detach",MessageBoxButton.YesNo,MessageBoxImage.Warning,MessageBoxResult.No)!=MessageBoxResult.Yes){Feedback.Text="Detach canceled. Nothing was sent.";return;} + if(LocalizedMessageBox.Show(this,Target.Text+"\n\n"+sql+"\n\nThis runs outside a transaction and cannot be rolled back. Keep the child table but remove its rows from parent queries?",child.DetachPending?"Confirm Finalize Detach":"Confirm Concurrent Detach",MessageBoxButton.YesNo,MessageBoxImage.Warning,MessageBoxResult.No)!=MessageBoxResult.Yes){Feedback.Text="Detach canceled. Nothing was sent.";return;} using var source=new CancellationTokenSource();cancellation=source;SetBusy(true);RequiresParentRefresh=true;Feedback.Text=child.DetachPending?"Finalizing pending detach…":"Detaching concurrently; waiting for running queries on the parent…"; try{await new ConcurrentPartitionDetachService(connection).ApplyAsync(parent,child,true,source.Token);WasApplied=true;Feedback.Text="Partition detached and verified. Inspect again before another change.";} catch(PartitionDetachUncertainException ex){Feedback.Text=Outcome(ex);} diff --git a/src/PGMS.Desktop/PgmsMessageBox.cs b/src/PGMS.Desktop/PgmsMessageBox.cs new file mode 100644 index 0000000..66ba474 --- /dev/null +++ b/src/PGMS.Desktop/PgmsMessageBox.cs @@ -0,0 +1,205 @@ +using System.Media; +using System.Text; +using System.Windows; +using System.Windows.Automation; +using System.Windows.Controls; +using System.Windows.Input; +using System.Windows.Interop; +using System.Windows.Media; +using System.Windows.Media.Imaging; + +namespace PGMS.Desktop; + +/// +/// The message box of PGMS (B1 review, M1138): the layout of the Windows message box (icon and text over a button bar), drawn by WPF so the +/// buttons follow the interface language of PGMS and the theme. Same behavior as the native box: modal to its owner (or to the active window), +/// default button, Esc only when the box has Cancel or only OK, the window's close button only then, access keys on Yes and No, the system +/// sound of the icon, and Ctrl+C copying the caption, text and buttons as Windows does. +/// +public sealed class PgmsMessageBox : Window +{ + private readonly MessageBoxButton buttons; + private readonly string text; + private readonly List<(Button Button, MessageBoxResult Result, string Label)> choices = []; + + /// The answer; until a button is chosen it is the answer of the window's close button. + public MessageBoxResult Result { get; private set; } + /// The button that starts with the focus and answers Enter. + public MessageBoxResult DefaultResult { get; } + /// The message, already in the interface language. + public string Message => text; + /// The results of the buttons, in order (tests and diagnostics). + public IReadOnlyList Choices => [.. choices.Select(c => c.Result)]; + /// The labels of the buttons, in the interface language and without the access key mark. + public IReadOnlyList ButtonLabels => [.. choices.Select(c => c.Label.Replace("_", ""))]; + + private bool CanCancel => buttons is MessageBoxButton.OK or MessageBoxButton.OKCancel or MessageBoxButton.YesNoCancel; + + private PgmsMessageBox(string text, string caption, MessageBoxButton buttons, MessageBoxImage icon, MessageBoxResult defaultResult) + { + this.text = text; this.buttons = buttons; + Title = caption; + Localization.SetNoTranslate(this, true); // texts are already in the interface language; the message may quote SQL and names + ShowInTaskbar = false; ResizeMode = ResizeMode.NoResize; SizeToContent = SizeToContent.WidthAndHeight; + WindowStyle = WindowStyle.SingleBorderWindow; + UseLayoutRounding = true; SnapsToDevicePixels = true; + MinWidth = 280; MaxWidth = Math.Max(420, SystemParameters.WorkArea.Width * 0.6); + SetResourceReference(BackgroundProperty, "Pgms.DialogBackground"); + SetResourceReference(ForegroundProperty, "Pgms.PrimaryText"); + AutomationProperties.SetHelpText(this, text); + + var results = buttons switch + { + MessageBoxButton.OKCancel => new[] { MessageBoxResult.OK, MessageBoxResult.Cancel }, + MessageBoxButton.YesNo => [MessageBoxResult.Yes, MessageBoxResult.No], + MessageBoxButton.YesNoCancel => [MessageBoxResult.Yes, MessageBoxResult.No, MessageBoxResult.Cancel], + _ => [MessageBoxResult.OK], + }; + // As in Windows: a default that is not one of the buttons means the first button. + DefaultResult = results.Contains(defaultResult) ? defaultResult : results[0]; + Result = buttons switch { MessageBoxButton.OK => MessageBoxResult.OK, MessageBoxButton.OKCancel or MessageBoxButton.YesNoCancel => MessageBoxResult.Cancel, _ => MessageBoxResult.None }; + + var body = new DockPanel { Margin = new Thickness(0) }; + var bar = new StackPanel { Orientation = Orientation.Horizontal, HorizontalAlignment = HorizontalAlignment.Right, Margin = new Thickness(12, 11, 12, 11) }; + var barBorder = new Border { Child = bar }; + barBorder.SetResourceReference(Border.BackgroundProperty, "Pgms.DialogBackground"); + DockPanel.SetDock(barBorder, Dock.Bottom); + body.Children.Add(barBorder); + foreach (var result in results) + { + string label = Localization.T(result switch { MessageBoxResult.Yes => "_Yes", MessageBoxResult.No => "_No", MessageBoxResult.Cancel => "Cancel", _ => "OK" }); + var button = new Button { Content = new AccessText { Text = label }, MinWidth = 88, MinHeight = 26, Padding = new Thickness(10, 2, 10, 2), Margin = new Thickness(8, 0, 0, 0) }; + button.IsDefault = result == DefaultResult; + button.IsCancel = CanCancel && result == (buttons == MessageBoxButton.OK ? MessageBoxResult.OK : MessageBoxResult.Cancel); + AutomationProperties.SetName(button, label.Replace("_", "")); + var chosen = result; + button.Click += (_, _) => Answer(chosen); + choices.Add((button, result, label)); + bar.Children.Add(button); + } + + var content = new DockPanel { Margin = new Thickness(0) }; + content.SetResourceReference(Panel.BackgroundProperty, "Pgms.ContentBackground"); + var inner = new DockPanel { Margin = new Thickness(24, 22, 28, 22) }; + if (IconImage(icon) is { } image) + { + var picture = new Image { Source = image, Width = 32, Height = 32, VerticalAlignment = VerticalAlignment.Top, Margin = new Thickness(0, 0, 14, 0) }; + AutomationProperties.SetName(picture, icon.ToString()); + DockPanel.SetDock(picture, Dock.Left); + inner.Children.Add(picture); + } + var message = new TextBlock { Text = text, TextWrapping = TextWrapping.Wrap, VerticalAlignment = VerticalAlignment.Center, MaxWidth = MaxWidth - 120 }; + message.SetResourceReference(TextBlock.ForegroundProperty, "Pgms.PrimaryText"); + AutomationProperties.SetName(message, text); + inner.Children.Add(message); + content.Children.Add(inner); + body.Children.Add(content); + Content = body; + + sound = icon switch + { + MessageBoxImage.Error => SystemSounds.Hand, + MessageBoxImage.Warning => SystemSounds.Exclamation, + MessageBoxImage.Question => SystemSounds.Question, + MessageBoxImage.Information => SystemSounds.Asterisk, + _ => SystemSounds.Beep, + }; + Loaded += (_, _) => + { + choices.First(c => c.Result == DefaultResult).Button.Focus(); + if (PlaySounds) sound.Play(); + }; + PreviewKeyDown += OnKey; + Closing += (_, e) => { if (!answered && !CanCancel) e.Cancel = true; }; // Yes/No without Cancel: the close button does nothing, as in Windows + SourceInitialized += (_, _) => { if (!CanCancel) DisableCloseButton(); }; + } + + private readonly SystemSound sound; + private bool answered; + + /// Off in the test runner, so the checks do not beep. + internal static bool PlaySounds { get; set; } = true; + + /// Raised when a box is shown (tests answer it like a person, without global input). + internal static event Action? Opened; + + /// Chooses a button, as a click on it does. + public void Answer(MessageBoxResult result) + { + if (!choices.Any(c => c.Result == result)) throw new ArgumentException("The message box has no such button.", nameof(result)); + Result = result; answered = true; + Close(); + } + + private void OnKey(object sender, KeyEventArgs e) + { + if (e.Key == Key.C && Keyboard.Modifiers == ModifierKeys.Control) + { + try { Clipboard.SetText(CopyText()); } catch (System.Runtime.InteropServices.ExternalException) { } + e.Handled = true; + return; + } + // Access keys also work without Alt, as in the Windows message box (Y, N). + var key = e.Key == Key.System ? e.SystemKey : e.Key; + if (Keyboard.Modifiers is ModifierKeys.None or ModifierKeys.Alt && key is >= Key.A and <= Key.Z) + { + char letter = (char)('a' + (key - Key.A)); + foreach (var choice in choices) + { + int mark = choice.Label.IndexOf('_'); + if (mark >= 0 && mark + 1 < choice.Label.Length && char.ToLowerInvariant(choice.Label[mark + 1]) == letter) { e.Handled = true; Answer(choice.Result); return; } + } + } + } + + /// What Ctrl+C copies in a Windows message box: caption, text and buttons between dashed lines. + public string CopyText() + { + const string line = "---------------------------"; + var copy = new StringBuilder(); + copy.Append(line).Append("\r\n").Append(Title).Append("\r\n").Append(line).Append("\r\n").Append(text.Replace("\r\n", "\n").Replace("\n", "\r\n")).Append("\r\n").Append(line).Append("\r\n"); + foreach (var label in ButtonLabels) copy.Append(label).Append(" "); + copy.Append("\r\n").Append(line).Append("\r\n"); + return copy.ToString(); + } + + private void DisableCloseButton() + { + nint handle = new WindowInteropHelper(this).Handle; + nint menu = GetSystemMenu(handle, false); + if (menu != 0) EnableMenuItem(menu, 0xF060, 0x1); // SC_CLOSE, MF_GRAYED + } + + private static BitmapSource? IconImage(MessageBoxImage icon) + { + // The stock icons of Windows (IDI_HAND, IDI_QUESTION, IDI_EXCLAMATION, IDI_ASTERISK), shared and never destroyed. + int id = icon switch { MessageBoxImage.Error => 32513, MessageBoxImage.Question => 32514, MessageBoxImage.Warning => 32515, MessageBoxImage.Information => 32516, _ => 0 }; + if (id == 0) return null; + nint handle = LoadIcon(0, id); + if (handle == 0) return null; + var image = Imaging.CreateBitmapSourceFromHIcon(handle, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); + image.Freeze(); + return image; + } + + [System.Runtime.InteropServices.DllImport("user32.dll")] private static extern nint LoadIcon(nint instance, nint name); + + /// Shows a PGMS message box, modal to or to the active window of this thread, and returns the answer. + /// Without a WPF dispatcher on this thread (never the case in PGMS today) it falls back to the Windows message box. + public static MessageBoxResult Show(Window? owner, string text, string caption, MessageBoxButton button, MessageBoxImage icon, MessageBoxResult defaultResult) + { + if (System.Threading.Thread.CurrentThread.GetApartmentState() != System.Threading.ApartmentState.STA || Application.Current is null || !Application.Current.Dispatcher.CheckAccess()) + return owner is null ? MessageBox.Show(text, caption, button, icon, defaultResult) : MessageBox.Show(owner, text, caption, button, icon, defaultResult); + owner ??= Application.Current.Windows.OfType().FirstOrDefault(w => w.IsActive) ?? Application.Current.MainWindow; + var box = new PgmsMessageBox(text, caption, button, icon, defaultResult); + if (owner is not null && owner != box && owner.IsLoaded && new WindowInteropHelper(owner).Handle != 0 && owner.IsVisible) + { box.Owner = owner; box.WindowStartupLocation = WindowStartupLocation.CenterOwner; } + else box.WindowStartupLocation = WindowStartupLocation.CenterScreen; + box.ContentRendered += (_, _) => Opened?.Invoke(box); + box.ShowDialog(); + return box.Result; + } + + [System.Runtime.InteropServices.DllImport("user32.dll")] private static extern nint GetSystemMenu(nint window, bool revert); + [System.Runtime.InteropServices.DllImport("user32.dll")] private static extern int EnableMenuItem(nint menu, uint item, uint flags); +} diff --git a/src/PGMS.Desktop/PreparedQueryDocument.cs b/src/PGMS.Desktop/PreparedQueryDocument.cs index 82fe80e..0afdb7c 100644 --- a/src/PGMS.Desktop/PreparedQueryDocument.cs +++ b/src/PGMS.Desktop/PreparedQueryDocument.cs @@ -14,6 +14,9 @@ public static PreparedQueryDocument Create(string text, CancellationToken token var document = new TextDocument(text); PreparedLexicalStates.Prepare(document,text,token); token.ThrowIfCancellationRequested(); + // The outline of the statements is read here too, off the UI thread (M1132): the editor applies it when the document is attached. + SqlFolding.Prepare(document); + token.ThrowIfCancellationRequested(); document.SetOwnerThread(null); return new(document); } diff --git a/src/PGMS.Desktop/PrivilegeDialog.xaml.cs b/src/PGMS.Desktop/PrivilegeDialog.xaml.cs index cf724d2..5974646 100644 --- a/src/PGMS.Desktop/PrivilegeDialog.xaml.cs +++ b/src/PGMS.Desktop/PrivilegeDialog.xaml.cs @@ -390,7 +390,7 @@ internal async Task ApplyAsync() if(request.Cascade) { if(reviewed is null || reviewed.Request!=request)return; - if(MessageBox.Show(this,Target.Text+"\n\n"+request.ToSql()+$"\n\n{reviewed.PotentialChanges.Count} grant(s) are potentially affected. Independent access may remain. Revoke with CASCADE?", "Confirm Cascading Revoke", MessageBoxButton.YesNo, MessageBoxImage.Warning, MessageBoxResult.No)!=MessageBoxResult.Yes) + if(LocalizedMessageBox.Show(this,Target.Text+"\n\n"+request.ToSql()+$"\n\n{reviewed.PotentialChanges.Count} grant(s) are potentially affected. Independent access may remain. Revoke with CASCADE?", "Confirm Cascading Revoke", MessageBoxButton.YesNo, MessageBoxImage.Warning, MessageBoxResult.No)!=MessageBoxResult.Yes) { Feedback.Text="Cascading revoke canceled. Nothing was sent."; return; } } focus.Capture(); diff --git a/src/PGMS.Desktop/QueryDesignerControl.cs b/src/PGMS.Desktop/QueryDesignerControl.cs index 56e3bc9..cf09616 100644 --- a/src/PGMS.Desktop/QueryDesignerControl.cs +++ b/src/PGMS.Desktop/QueryDesignerControl.cs @@ -447,7 +447,7 @@ public async Task ChangeTypeAsync(DesignStatement kind) Regenerate(); DrawTables(); ShowRows(); } - private void Notice(string text) { if (NoticePrompt is { } prompt) prompt(text); else MessageBox.Show(Window.GetWindow(this)!, text, "PGMS"); } + private void Notice(string text) { if (NoticePrompt is { } prompt) prompt(text); else LocalizedMessageBox.Show(Window.GetWindow(this)!, text, "PGMS"); } private void RowsChanged(object? sender, NotifyCollectionChangedEventArgs e) { if (!syncing) ScheduleGridRead(); } private void ScheduleGridRead() @@ -929,7 +929,7 @@ public async Task ExecuteAsync() rows = result.Table.Rows.Count; results.Columns.Clear(); foreach (System.Data.DataColumn column in result.Table.Columns) - results.Columns.Add(new DataGridTextColumn { Header = column.Caption, CellStyle = ResultGridStyle.NullAwareCell($"[{column.ColumnName}]"), Binding = new Binding($"[{column.ColumnName}]") { Converter = new DatabaseValueConverter() } }); + results.Columns.Add(ResultGridStyle.TextColumn(column.Caption, column.ColumnName)); results.ItemsSource = result.Table.DefaultView; resultStatus.Text = $"{result.Table.Rows.Count} row(s)" + (result.Truncated ? $"; only the first {QueryDesignService.MaxRows} are shown." : ""); changedMark.Visibility = Visibility.Collapsed; diff --git a/src/PGMS.Desktop/QueryHistoryWindow.xaml.cs b/src/PGMS.Desktop/QueryHistoryWindow.xaml.cs index c524c69..50b8610 100644 --- a/src/PGMS.Desktop/QueryHistoryWindow.xaml.cs +++ b/src/PGMS.Desktop/QueryHistoryWindow.xaml.cs @@ -51,7 +51,7 @@ public partial class QueryHistoryWindow : Window public QueryHistoryWindow(QueryHistoryRecorder recorder, Func openInTab) { this.recorder = recorder; this.openInTab = openInTab; - Confirm = question => MessageBox.Show(this, question, "Query History", MessageBoxButton.YesNo, MessageBoxImage.Warning, MessageBoxResult.No) == MessageBoxResult.Yes; + Confirm = question => LocalizedMessageBox.Show(this, question, "Query History", MessageBoxButton.YesNo, MessageBoxImage.Warning, MessageBoxResult.No) == MessageBoxResult.Yes; InitializeComponent(); WindowWorkArea.Attach(this); Target.Text = $"Query History — executions recorded on this computer for the Windows user {Environment.UserName}.\nStored encrypted for this user (DPAPI) in {recorder.Store.DirectoryPath}; never sent to a server."; ConnectionFilter.Items.Add(new ComboBoxItem { Content = "All connections", Tag = null }); ConnectionFilter.SelectedIndex = 0; @@ -74,7 +74,7 @@ public async Task RefreshAsync() FillConnections(); Apply(); int executions = groups.Sum(g => g.Executions.Count); - Status.Text = $"{groups.Count:N0} distinct quer{(groups.Count == 1 ? "y" : "ies")}, {executions:N0} execution(s)." + + Status.Text = (groups.Count == 1 ? $"{groups.Count:N0} distinct query, {executions:N0} execution(s)." : $"{groups.Count:N0} distinct queries, {executions:N0} execution(s).") + (snapshot.UnreadableFiles > 0 ? $" {snapshot.UnreadableFiles} history file(s) could not be read (damaged, from another Windows user or renamed) and were left untouched; Clear History removes them." : ""); } catch (Exception ex) when (QueryHistoryRecorder.IsDiskError(ex)) { Status.Text = "Query History could not be read. " + ex.Message; } diff --git a/src/PGMS.Desktop/QueryOptions.cs b/src/PGMS.Desktop/QueryOptions.cs index c92959c..3306fce 100644 --- a/src/PGMS.Desktop/QueryOptions.cs +++ b/src/PGMS.Desktop/QueryOptions.cs @@ -10,7 +10,8 @@ public sealed record QueryOptions( bool RetainLineBreaks = true, bool GridDiscardResults = false, bool DisplayJsonAsLink = true, TextOutputFormat TextFormat = TextOutputFormat.ColumnAligned, string CustomDelimiter = ";", bool TextIncludeHeaders = true, bool TextIncludeQuery = false, bool TextRightAlignNumeric = false, bool TextDiscardResults = false, int TextMaxCharacters = TextResultsWriter.DefaultMaxCharacters, int GridPageRows = QueryOptions.DefaultGridPageRows, - int PlanWarningRatio = ExecutionPlanWarningOptions.DefaultRatio, int PlanWarningMinimumRows = ExecutionPlanWarningOptions.DefaultMinimum) + int PlanWarningRatio = ExecutionPlanWarningOptions.DefaultRatio, int PlanWarningMinimumRows = ExecutionPlanWarningOptions.DefaultMinimum, + bool GridStackResults = false) { public const int MaxTimeoutSeconds = 86400, MaxLockTimeoutMilliseconds = 86400000, MaxTextCharacters = 8192, DefaultGridPageRows = 100000, MinGridPageRows = 100, MaxGridPageRows = 1000000; diff --git a/src/PGMS.Desktop/QueryOptionsDialog.xaml b/src/PGMS.Desktop/QueryOptionsDialog.xaml index 009a62c..ceb06c8 100644 --- a/src/PGMS.Desktop/QueryOptionsDialog.xaml +++ b/src/PGMS.Desktop/QueryOptionsDialog.xaml @@ -2,7 +2,7 @@ - + diff --git a/src/PGMS.Desktop/QueryOptionsPages.xaml b/src/PGMS.Desktop/QueryOptionsPages.xaml index 994ad82..a20bc01 100644 --- a/src/PGMS.Desktop/QueryOptionsPages.xaml +++ b/src/PGMS.Desktop/QueryOptionsPages.xaml @@ -47,6 +47,7 @@ + diff --git a/src/PGMS.Desktop/QueryOptionsPages.xaml.cs b/src/PGMS.Desktop/QueryOptionsPages.xaml.cs index c8129f0..6afcf4e 100644 --- a/src/PGMS.Desktop/QueryOptionsPages.xaml.cs +++ b/src/PGMS.Desktop/QueryOptionsPages.xaml.cs @@ -47,6 +47,7 @@ private void LoadPage(int index, QueryOptions o) case ResultsGrid: RetainBox.IsChecked = o.RetainLineBreaks; GridDiscardBox.IsChecked = o.GridDiscardResults; + StackResultsBox.IsChecked = o.GridStackResults; JsonLinkBox.IsChecked = o.DisplayJsonAsLink; PageRowsBox.Text = o.GridPageRows.ToString(CultureInfo.InvariantCulture); break; @@ -94,7 +95,7 @@ private void UpdateDelimiter() return new QueryOptions(timeout, CheckTransactionsBox.IsChecked == true, NoCountBox.IsChecked == true, (QueryIsolationLevel)Math.Max(0, IsolationBox.SelectedIndex), lockTimeout, CompletionBox.IsChecked == true, RetainBox.IsChecked == true, GridDiscardBox.IsChecked == true, JsonLinkBox.IsChecked == true, - format, DelimiterBox.Text.Length == 1 ? DelimiterBox.Text : ";", TextHeadersBox.IsChecked == true, TextQueryBox.IsChecked == true, RightAlignBox.IsChecked == true, TextDiscardBox.IsChecked == true, maxCharacters, pageRows, planRatio, planMinimum); + format, DelimiterBox.Text.Length == 1 ? DelimiterBox.Text : ";", TextHeadersBox.IsChecked == true, TextQueryBox.IsChecked == true, RightAlignBox.IsChecked == true, TextDiscardBox.IsChecked == true, maxCharacters, pageRows, planRatio, planMinimum, StackResultsBox.IsChecked == true); } /// Page holding the last rejected value, for the host to select it in its tree. diff --git a/src/PGMS.Desktop/QueryRecoverySession.cs b/src/PGMS.Desktop/QueryRecoverySession.cs index 3cd5b40..4c94161 100644 --- a/src/PGMS.Desktop/QueryRecoverySession.cs +++ b/src/PGMS.Desktop/QueryRecoverySession.cs @@ -33,15 +33,16 @@ public static RecoveryReport Recover(string root, string activeDirectory, Action int maximumDocuments = QueryRecoveryStore.MaximumDocuments) => RecoverCoreAsync(root, activeDirectory, draft => { accept(draft); return ValueTask.FromResult(true); }, maximumDocuments, CancellationToken.None).GetAwaiter().GetResult(); + /// Environment ▸ AutoRecover (M1141): drafts written longer ago are removed instead of restored; null keeps every draft. public static Task RecoverAsync(string root, string activeDirectory, - Func> accept, int maximumDocuments = QueryRecoveryStore.MaximumDocuments, CancellationToken token = default) + Func> accept, int maximumDocuments = QueryRecoveryStore.MaximumDocuments, CancellationToken token = default, TimeSpan? lifetime = null) { ArgumentNullException.ThrowIfNull(accept); - return Task.Run(() => RecoverCoreAsync(root, activeDirectory, accept, maximumDocuments, token)); + return Task.Run(() => RecoverCoreAsync(root, activeDirectory, accept, maximumDocuments, token, lifetime)); } private static async Task RecoverCoreAsync(string root, string activeDirectory, - Func> accept, int maximumDocuments, CancellationToken token) + Func> accept, int maximumDocuments, CancellationToken token, TimeSpan? lifetime = null) { if (maximumDocuments < 0 || maximumDocuments > QueryRecoveryStore.MaximumDocuments) throw new ArgumentOutOfRangeException(nameof(maximumDocuments)); @@ -74,6 +75,7 @@ private static async Task RecoverCoreAsync(string root, string a if (restored >= maximumDocuments) { deferred++; continue; } try { + if (lifetime is { } keep && DateTime.UtcNow - session.Store.WrittenUtc(id) > keep) { session.Store.Remove(id); continue; } var draft = session.Store.Read(id); // Acceptance must retain the destination durably before returning true. if (!await accept(draft).ConfigureAwait(false)) { deferred++; continue; } diff --git a/src/PGMS.Desktop/QueryRecoveryStore.cs b/src/PGMS.Desktop/QueryRecoveryStore.cs index de4e8e2..3525076 100644 --- a/src/PGMS.Desktop/QueryRecoveryStore.cs +++ b/src/PGMS.Desktop/QueryRecoveryStore.cs @@ -10,6 +10,8 @@ public sealed record RecoveryDraft(Guid Id, string Title, string Text, SqlFileFo public int CommandTimeoutSeconds{get;init;} public bool WordWrap{get;init;} public bool ShowWhiteSpace{get;init;} + /// Window ▸ Pin Tab: a restored tab comes back pinned (B1 review, M1137). + public bool Pinned{get;init;} } /// One encrypted file per draft; callers own the session lease. @@ -100,6 +102,9 @@ public void Remove(Guid id) File.Delete(DraftPath(id)); } + /// When the draft was last written (Environment ▸ AutoRecover ▸ lifetime, M1141). + public DateTime WrittenUtc(Guid id) => File.GetLastWriteTimeUtc(DraftPath(id)); + private string DraftPath(Guid id) { if (id == Guid.Empty) throw new InvalidDataException("Recovery identity is missing."); diff --git a/src/PGMS.Desktop/QueryStatisticsWindow.xaml.cs b/src/PGMS.Desktop/QueryStatisticsWindow.xaml.cs index 62020c4..a064043 100644 --- a/src/PGMS.Desktop/QueryStatisticsWindow.xaml.cs +++ b/src/PGMS.Desktop/QueryStatisticsWindow.xaml.cs @@ -434,7 +434,7 @@ internal async Task ShowPlanAsync() internal async Task ResetSelectedAsync(bool? confirmed) { if (busy || Availability?.IsReadable != true || Statements.SelectedItem is not QueryStatisticsEntry { CanResetIndividually: true } selected) return; - bool proceed = confirmed ?? MessageBox.Show(this, $"Discard the statistics of query {selected.QueryId} for database \"{selected.Database}\" and user \"{selected.User}\"?\n\nOther statements keep their counters. This cannot be undone and PostgreSQL must authorize the call.", "Reset Selected Statement", MessageBoxButton.YesNo, MessageBoxImage.Warning, MessageBoxResult.No) == MessageBoxResult.Yes; + bool proceed = confirmed ?? LocalizedMessageBox.Show(this, $"Discard the statistics of query {selected.QueryId} for database \"{selected.Database}\" and user \"{selected.User}\"?\n\nOther statements keep their counters. This cannot be undone and PostgreSQL must authorize the call.", "Reset Selected Statement", MessageBoxButton.YesNo, MessageBoxImage.Warning, MessageBoxResult.No) == MessageBoxResult.Yes; if (!proceed) { Status.Text = "Selective reset not performed."; return; } SetBusy(true); try @@ -451,7 +451,7 @@ internal async Task ResetSelectedAsync(bool? confirmed) internal async Task ResetAsync(bool? confirmed) { if (busy || Availability?.IsReadable != true) return; - bool proceed = confirmed ?? MessageBox.Show(this, "Discard all pg_stat_statements entries on this server?\n\nThis affects every database and user on the server and cannot be undone. PostgreSQL must authorize the call.", "Reset Statistics", MessageBoxButton.YesNo, MessageBoxImage.Warning, MessageBoxResult.No) == MessageBoxResult.Yes; + bool proceed = confirmed ?? LocalizedMessageBox.Show(this, "Discard all pg_stat_statements entries on this server?\n\nThis affects every database and user on the server and cannot be undone. PostgreSQL must authorize the call.", "Reset Statistics", MessageBoxButton.YesNo, MessageBoxImage.Warning, MessageBoxResult.No) == MessageBoxResult.Yes; if (!proceed) { Status.Text = "Reset not performed."; return; } SetBusy(true); try diff --git a/src/PGMS.Desktop/QueryView.Bookmarks.cs b/src/PGMS.Desktop/QueryView.Bookmarks.cs index 0246c78..dfd68a5 100644 --- a/src/PGMS.Desktop/QueryView.Bookmarks.cs +++ b/src/PGMS.Desktop/QueryView.Bookmarks.cs @@ -93,6 +93,7 @@ internal void UpdateFoldings() { if (foldingManager is null) return; if (Editor.Document.TextLength > MaximumOutliningCharacters) { foldingManager.Clear(); return; } + if (SqlFolding.TakePrepared(Editor.Document) is { } ready) { foldingManager.UpdateFoldings(ready, -1); return; } try { foldingManager.UpdateFoldings(SqlFolding.Create(Editor.Document), -1); } catch (FormatException) { } // An unclosed string or comment keeps the previous outline until the text reads again. } @@ -177,6 +178,23 @@ protected override void OnRender(DrawingContext context) /// Regions of the SQL outline: each statement of more than one line (up to its semicolon) and each multi-line block comment. internal static class SqlFolding { + private static readonly System.Runtime.CompilerServices.ConditionalWeakTable>> prepared = []; + + /// Reads the outline of a document being prepared on a worker thread; returns it once, if the text did not change. + internal static void Prepare(TextDocument document) + { + if (document.TextLength > QueryView.MaximumOutliningCharacters) return; + try { prepared.AddOrUpdate(document, Tuple.Create(document.Version, Create(document).ToList())); } + catch (FormatException) { } + } + + internal static List? TakePrepared(TextDocument document) + { + if (!prepared.TryGetValue(document, out var entry)) return null; + prepared.Remove(document); + return entry.Item1.BelongsToSameDocumentAs(document.Version) && entry.Item1.CompareAge(document.Version) == 0 ? entry.Item2 : null; + } + internal static IEnumerable Create(TextDocument document) { string text = document.Text; diff --git a/src/PGMS.Desktop/QueryView.Completion.cs b/src/PGMS.Desktop/QueryView.Completion.cs index 6930706..89693d9 100644 --- a/src/PGMS.Desktop/QueryView.Completion.cs +++ b/src/PGMS.Desktop/QueryView.Completion.cs @@ -39,12 +39,27 @@ private void ConfigureCompletion() Editor.PreviewKeyDown += async (_, e) => { if (ProcessIntelliSenseKey(e.Key, Keyboard.Modifiers, Environment.TickCount64)) { e.Handled = true; return; } + if (Keyboard.Modifiers == (ModifierKeys.Control | ModifierKeys.Alt) && e.Key == Key.Space) { e.Handled = true; SwitchCompletionMode(); return; } if (Keyboard.Modifiers == ModifierKeys.Control && e.Key is Key.Space or Key.J) { e.Handled = true; await ShowCompletionAsync(); } else if (Keyboard.Modifiers == (ModifierKeys.Control | ModifierKeys.Shift) && e.Key == Key.R) { e.Handled = true; RefreshLocalCache(); } }; Editor.LostKeyboardFocus += (_, _) => intelliSenseChordDeadline = 0; } + /// Edit ▸ IntelliSense ▸ Switch Completion Mode (Ctrl+Alt+Space, PGMS-082, M1120), as in the Visual Studio editor of SSMS: in suggestion + /// mode the list only suggests, so Enter ends the line with what was typed and only Tab (or a double click) inserts the highlighted name. The mode + /// is shared by every query window and lasts until PGMS closes. + public static bool SuggestionMode { get; set; } + internal static event Action? SuggestionModeChanged; + + public void SwitchCompletionMode() + { + SuggestionMode = !SuggestionMode; + completionWindow?.Close(); + SuggestionModeChanged?.Invoke(); + QueryStatus.Text = SuggestionMode ? "IntelliSense suggestion mode: Tab inserts the highlighted name; Enter keeps what you typed." : "IntelliSense completion mode: Enter or Tab inserts the selected name."; + } + /// The Ctrl+B, Ctrl+I chord. Ctrl+I alone stays with Generate SQL with AI. internal bool ProcessIntelliSenseKey(Key key, ModifierKeys modifiers, long now) { @@ -103,7 +118,7 @@ internal sealed class SqlCompletionWindow(TextArea textArea) : CompletionWindow( { protected override void OnKeyDown(KeyEventArgs e) { - if (e.Key == Key.Enter && CompletionList.SelectedItem is null) { Close(); return; } + if (e.Key == Key.Enter && (CompletionList.SelectedItem is null || QueryView.SuggestionMode)) { Close(); return; } base.OnKeyDown(e); } } diff --git a/src/PGMS.Desktop/QueryView.Conveniences.cs b/src/PGMS.Desktop/QueryView.Conveniences.cs index 98607b1..73a057e 100644 --- a/src/PGMS.Desktop/QueryView.Conveniences.cs +++ b/src/PGMS.Desktop/QueryView.Conveniences.cs @@ -68,15 +68,38 @@ private void ConfigureConveniences() Editor.LostKeyboardFocus += (_, _) => { if (incrementalActive && !Editor.IsKeyboardFocusWithin) EndIncrementalSearch(); }; TrackDocument(); Editor.DocumentChanged += (_, _) => TrackDocument(); + Editor.TextArea.Caret.PositionChanged += (_, _) => NoticeCaretMove(); + } + + /// Lines the caret must move in one step, without an edit, for View ▸ Navigate Backward to remember the place (PGMS-082, M1121). + internal const int NavigationJumpLines = 10; + private int caretBefore; + private object? versionBefore; + /// A large caret jump (Go To Line, Find, a click far away, Ctrl+End…): the offset left and the offset reached. + public event Action? CaretJumped; + + private void NoticeCaretMove() + { + var document = Editor.Document; + int now = Editor.CaretOffset; + var version = document.Version; + int from = Math.Min(caretBefore, document.TextLength); + bool edited = !ReferenceEquals(version, versionBefore); + caretBefore = now; versionBefore = version; + if (edited || from == now) return; + if (Math.Abs(document.GetLineByOffset(now).LineNumber - document.GetLineByOffset(from).LineNumber) >= NavigationJumpLines) CaretJumped?.Invoke(this, from, now); } private void TrackDocument() { - if (trackedDocument is not null) trackedDocument.Changed -= DocumentChangedForLastEdit; + if (trackedDocument is not null) { trackedDocument.Changed -= DocumentChangedForLastEdit; trackedDocument.UpdateFinished -= DocumentUpdateFinished; } trackedDocument = Editor.Document; - if (trackedDocument is not null) trackedDocument.Changed += DocumentChangedForLastEdit; + if (trackedDocument is not null) { trackedDocument.Changed += DocumentChangedForLastEdit; trackedDocument.UpdateFinished += DocumentUpdateFinished; } } + /// After an edit the caret is where the edit left it; the next move is measured from there. + private void DocumentUpdateFinished(object? sender, EventArgs e) { caretBefore = Editor.CaretOffset; versionBefore = Editor.Document.Version; } + private void DocumentChangedForLastEdit(object? sender, DocumentChangeEventArgs e) { LastEditOffset = e.Offset + e.InsertionLength; diff --git a/src/PGMS.Desktop/QueryView.Editing.cs b/src/PGMS.Desktop/QueryView.Editing.cs index 33adfa5..0abfa11 100644 --- a/src/PGMS.Desktop/QueryView.Editing.cs +++ b/src/PGMS.Desktop/QueryView.Editing.cs @@ -99,6 +99,12 @@ private void ConfigureSqlEditing() foreach(var (command,run) in SqlEditorCommands.SelectionMoves) CommandBindings.Add(new CommandBinding(command,(_,e)=>{RunTextEdit(run);e.Handled=true;},(_,e)=>{e.CanExecute=true;e.Handled=true;})); ConfigureConveniences(); + // AvalonEdit binds Ctrl+I to its own Indent Selection, which swallowed the key before Generate SQL with AI (window binding) saw it. + var editing=Editor.TextArea.DefaultInputHandler.Editing; + // The gesture also lives on the routed command itself, and WPF matches a command binding's gestures too, so the command binding goes as well. + foreach(var binding in editing.InputBindings.OfType().Where(b=>b.Command==ICSharpCode.AvalonEdit.AvalonEditCommands.IndentSelection).ToList()) editing.InputBindings.Remove(binding); + foreach(var binding in editing.CommandBindings.Where(b=>b.Command==ICSharpCode.AvalonEdit.AvalonEditCommands.IndentSelection).ToList()) editing.CommandBindings.Remove(binding); + foreach(var binding in Editor.TextArea.CommandBindings.OfType().Where(b=>b.Command==ICSharpCode.AvalonEdit.AvalonEditCommands.IndentSelection).ToList()) Editor.TextArea.CommandBindings.Remove(binding); Editor.PreviewKeyDown+=(_,e)=>{if(ProcessIncrementalSearchKey(e.Key==Key.System?e.SystemKey:e.Key,Keyboard.Modifiers))e.Handled=true;else if(ProcessCommentKey(e.Key,Keyboard.Modifiers,Environment.TickCount64) || ProcessEditKey(e.Key==Key.System?e.SystemKey:e.Key,Keyboard.Modifiers,Environment.TickCount64))e.Handled=true;}; Editor.LostKeyboardFocus+=(_,_)=>{commentChordDeadline=0;lineChordDeadline=0;}; } @@ -114,6 +120,7 @@ internal bool ProcessCommentKey(Key key,ModifierKeys modifiers,long now) if(valid && modifiers==ModifierKeys.Control && key is Key.C or Key.U){CommentSelection(key==Key.U);return true;} if(valid && modifiers==ModifierKeys.Control && IsBackslash(key)){RunTextEdit(SqlTextCommands.DeleteHorizontalWhiteSpace);return true;} if(valid && modifiers==ModifierKeys.Control && key==Key.Z){MainWindow.RestoreClosedTabCommand.Execute(null,this);return true;} + if(valid && modifiers==ModifierKeys.Control && key==Key.B){MainWindow.CodeSnippetsManagerCommand.Execute(null,this);return true;} if(valid && modifiers==ModifierKeys.Control && key==Key.Q){RunTextEdit(SqlTextCommands.FormatSql);return true;} if(valid && modifiers==ModifierKeys.Control && key==Key.I){_=ShowQuickInfoAsync();return true;} if(valid && modifiers==ModifierKeys.Control && key is Key.X or Key.S){ShowSnippetPicker(key==Key.S);return true;} diff --git a/src/PGMS.Desktop/QueryView.InfoBar.cs b/src/PGMS.Desktop/QueryView.InfoBar.cs index 96e0e50..6b29009 100644 --- a/src/PGMS.Desktop/QueryView.InfoBar.cs +++ b/src/PGMS.Desktop/QueryView.InfoBar.cs @@ -87,7 +87,10 @@ private void OpenInfoMenu(object sender, RoutedEventArgs e) UpdateEditorInfo(); string current = button.Content as string ?? ""; foreach (var item in menu.Items.OfType()) - item.IsChecked = button == IndentationButton ? (string)item.Header == (current == "SPC" ? "Spaces" : "Tabs") : button == LineEndingButton && (string)item.Header == current; + { + object? header = Localization.EnglishHeader(item, item.Header); // The English text: the menu may be translated (M1126). + item.IsChecked = button == IndentationButton ? Equals(header, current == "SPC" ? "Spaces" : "Tabs") : button == LineEndingButton && Equals(header, current); + } menu.PlacementTarget = button; menu.Placement = PlacementMode.Top; menu.IsOpen = true; } } diff --git a/src/PGMS.Desktop/QueryView.LiveStatistics.cs b/src/PGMS.Desktop/QueryView.LiveStatistics.cs index 9fd0ee0..e84b29b 100644 --- a/src/PGMS.Desktop/QueryView.LiveStatistics.cs +++ b/src/PGMS.Desktop/QueryView.LiveStatistics.cs @@ -16,7 +16,9 @@ public partial class QueryView private DateTime liveStartedUtc; internal int LiveSamples { get; private set; } /// Seconds between samples; tests shorten it. - internal TimeSpan LiveInterval { get; set; } = TimeSpan.FromSeconds(1); + internal TimeSpan LiveInterval { get; set; } = TimeSpan.FromMilliseconds(DefaultLiveIntervalMilliseconds); + /// Tools ▸ Options ▸ Query Execution ▸ Live Query Statistics ▸ Node Polling Interval (M1141; 250 ms, as in SSMS, since M1143) for query windows opened from now on. + internal static int DefaultLiveIntervalMilliseconds { get; set; } = LiveQueryStatisticsSettings.DefaultPolling; public bool IncludeLiveStatistics { diff --git a/src/PGMS.Desktop/QueryView.Options.cs b/src/PGMS.Desktop/QueryView.Options.cs index cc471c0..775540d 100644 --- a/src/PGMS.Desktop/QueryView.Options.cs +++ b/src/PGMS.Desktop/QueryView.Options.cs @@ -12,6 +12,17 @@ public partial class QueryView /// Opens the formatted JSON of a result link in a new tab. internal event Action? JsonLinkRequested; + /// Text Editor ▸ Transact-SQL (M1122): line numbers and tabs always; word wrap and IntelliSense only for a new tab, where they start. + internal void ApplyTextEditorSettings(TextEditorSettings settings, bool newTab) + { + settings = settings.Normalized(); + Editor.ShowLineNumbers = settings.LineNumbers; + Editor.Options.IndentationSize = settings.TabSize; + Editor.Options.ConvertTabsToSpaces = settings.InsertSpaces; + if (newTab) { WordWrap = settings.WordWrap; IntelliSenseEnabled = settings.IntelliSense; } + UpdateEditorInfo(); + } + internal void ApplyQueryOptions(QueryOptions options) { QueryOptions = options.Normalized(); diff --git a/src/PGMS.Desktop/QueryView.Paging.cs b/src/PGMS.Desktop/QueryView.Paging.cs index 4c4e446..b38994f 100644 --- a/src/PGMS.Desktop/QueryView.Paging.cs +++ b/src/PGMS.Desktop/QueryView.Paging.cs @@ -46,16 +46,28 @@ private sealed class GridResultLoader internal GridResultLoader(QueryView view, int pageRows) { this.view = view; this.pageRows = pageRows; - idleDrain = new DispatcherTimer(TimeSpan.FromMilliseconds(500), DispatcherPriority.Background, (_, _) => { if (!queue.IsEmpty) Drain(); }, view.Dispatcher); + idleDrain = new DispatcherTimer(TimeSpan.FromMilliseconds(500), DispatcherPriority.Background, (_, _) => { if (!queue.IsEmpty) { RaiseTarget(Received); Drain(); } }, view.Dispatcher); } - private readonly record struct Pending(QueryBatch Batch, ResultPages? Pages, IReadOnlyList Rows); + /// Rows received when the batch was queued: a drain shows the batch once its target reaches this count. + private readonly record struct Pending(QueryBatch Batch, ResultPages? Pages, IReadOnlyList Rows, long Upto); private const int SliceMilliseconds = 30; private readonly ConcurrentQueue queue = new(); private ResultPages? current; private int scheduled; private bool finished; private long received, nextMilestone = 30; + // Rows the screen should show: the count at the last milestone (or idle tick). Rows that arrive after it wait for the next one, as in SSMS, + // instead of a drain that keeps taking them while the reader runs (M1132): that kept the window busy from row 100 to the end. + private long target; + + private void RaiseTarget(long rows) + { + for (long seen = Interlocked.Read(ref target); rows > seen; seen = Interlocked.Read(ref target)) + if (Interlocked.CompareExchange(ref target, rows, seen) == seen) return; + } + + private bool NextIsDue(bool everything) => queue.TryPeek(out var next) && (everything || next.Upto <= Interlocked.Read(ref target)); internal List Tables { get; } = []; internal long Received => Interlocked.Read(ref received); @@ -70,12 +82,13 @@ internal void Accept(QueryBatch batch) firstPage = batch.Rows.Where(current!.Add).ToArray(); Interlocked.Add(ref received, batch.Rows.Count); } - if (started is not null || firstPage.Count > 0 || batch.DisplayLimited) queue.Enqueue(new(batch, started, firstPage)); - // Observed in SSMS: rows 30 and 100, then every 10,000, and the end. long total = Received; + if (started is not null || firstPage.Count > 0 || batch.DisplayLimited) queue.Enqueue(new(batch, started, firstPage, total)); + // Observed in SSMS: rows 30 and 100, then every 10,000, and the end. bool first = total > 0 && total == batch.Rows.Count; if (started is null && !first && !batch.DisplayLimited && total < nextMilestone) return; if (total >= nextMilestone) nextMilestone = total < 100 ? 100 : (total / 10000 + 1) * 10000; + RaiseTarget(total); Schedule(); } @@ -93,8 +106,8 @@ internal void Drain(bool everything = false) if (everything) idleDrain.Stop(); Volatile.Write(ref scheduled, 0); var slice = Stopwatch.StartNew(); - while ((everything || slice.ElapsedMilliseconds < SliceMilliseconds) && queue.TryDequeue(out var item)) Apply(item); - if (!queue.IsEmpty) Schedule(); + while ((everything || slice.ElapsedMilliseconds < SliceMilliseconds) && NextIsDue(everything) && queue.TryDequeue(out var item)) Apply(item); + if (NextIsDue(false)) Schedule(); view.QueryStatus.Text = $"Executing query | {view.Database} | {Received:N0} displayed row(s)" + (view.displayLimited ? " | Display limited; reading remaining results" : ""); view.UpdatePager(); } diff --git a/src/PGMS.Desktop/QueryView.StackedResults.cs b/src/PGMS.Desktop/QueryView.StackedResults.cs new file mode 100644 index 0000000..313f527 --- /dev/null +++ b/src/PGMS.Desktop/QueryView.StackedResults.cs @@ -0,0 +1,142 @@ +using System.Windows; +using System.Windows.Controls; +using System.Windows.Input; +using System.Windows.Media; + +namespace PGMS.Desktop; + +/// Query Results ▸ Results to Grid ▸ "Show multiple result sets stacked in one tab" (PGMS-082, M1122): result grids one under the other, +/// as SSMS 22.11 shows them (M1110 lacuna), instead of the Result 1, Result 2… tabs. The tab items stay, so the selected result keeps working. +public partial class QueryView +{ + private ControlTemplate? tabbedResultsTemplate; + private Style? tabbedResultItemStyle; + private static ControlTemplate? stackedResultsTemplate; + private static Style? stackedResultItemStyle; + + /// True when the result grids of the last grid execution are stacked. + public bool AreResultSetsStacked { get; private set; } + + /// Called when a grid execution starts, with no result set shown, so no grid changes its parent. + private void ApplyResultSetLayout() + { + bool stacked = QueryOptions.GridStackResults; + if (stacked == AreResultSetsStacked) return; + tabbedResultsTemplate ??= ResultSets.Template; + tabbedResultItemStyle ??= ResultSets.ItemContainerStyle; + tabbedItemsPanel ??= ResultSets.ItemsPanel; + ResultSets.ItemsPanel = stacked ? StackedItemsPanel : tabbedItemsPanel; + if (stacked) + { + ResultSets.Template = stackedResultsTemplate ??= CreateStackedTemplate(); + ResultSets.ItemContainerStyle = stackedResultItemStyle ??= CreateStackedItemStyle(); + ResultSets.PreviewGotKeyboardFocus += SelectStackedResult; + ResultSets.PreviewMouseDown += SelectStackedResultByMouse; + } + else + { + ResultSets.Template = tabbedResultsTemplate; + ResultSets.ItemContainerStyle = tabbedResultItemStyle; + ResultSets.PreviewGotKeyboardFocus -= SelectStackedResult; + ResultSets.PreviewMouseDown -= SelectStackedResultByMouse; + } + AreResultSetsStacked = stacked; + } + + private static ControlTemplate CreateStackedTemplate() + { + var scroll = new FrameworkElementFactory(typeof(ScrollViewer)); + scroll.SetValue(ScrollViewer.VerticalScrollBarVisibilityProperty, ScrollBarVisibility.Auto); + scroll.SetValue(ScrollViewer.HorizontalScrollBarVisibilityProperty, ScrollBarVisibility.Disabled); + scroll.SetValue(ScrollViewer.CanContentScrollProperty, false); + scroll.SetValue(UIElement.FocusableProperty, false); + var presenter = new FrameworkElementFactory(typeof(ItemsPresenter)); + scroll.AppendChild(presenter); + var template = new ControlTemplate(typeof(TabControl)) { VisualTree = scroll }; + template.Seal(); + return template; + } + + private static Style CreateStackedItemStyle() + { + var border = new FrameworkElementFactory(typeof(Border)); + border.SetValue(Border.BorderThicknessProperty, new Thickness(0, 0, 0, 4)); + border.SetResourceReference(Border.BorderBrushProperty, SystemColors.ControlBrushKey); + var content = new FrameworkElementFactory(typeof(ContentPresenter)); + content.SetValue(ContentPresenter.ContentSourceProperty, "Content"); + border.AppendChild(content); + var style = new Style(typeof(TabItem)); + style.Setters.Add(new Setter(Control.TemplateProperty, new ControlTemplate(typeof(TabItem)) { VisualTree = border })); + style.Setters.Add(new Setter(UIElement.FocusableProperty, false)); + style.Seal(); + return style; + } + + private void SelectStackedResult(object sender, KeyboardFocusChangedEventArgs e) => SelectResultContaining(e.NewFocus as DependencyObject); + private void SelectStackedResultByMouse(object sender, MouseButtonEventArgs e) => SelectResultContaining(e.OriginalSource as DependencyObject); + + private void SelectResultContaining(DependencyObject? element) + { + for (var node = element; node is not null && node != ResultSets; node = node is Visual or System.Windows.Media.Media3D.Visual3D ? VisualTreeHelper.GetParent(node) : LogicalTreeHelper.GetParent(node)) + if (node is TabItem tab && ResultSets.Items.Contains(tab)) { if (!ReferenceEquals(ResultSets.SelectedItem, tab)) ResultSets.SelectedItem = tab; return; } + } + + private static ItemsPanelTemplate? stackedItemsPanel; + private ItemsPanelTemplate? tabbedItemsPanel; + private static ItemsPanelTemplate StackedItemsPanel + { + get + { + if (stackedItemsPanel is null) { stackedItemsPanel = new ItemsPanelTemplate(new FrameworkElementFactory(typeof(StackedResultsPanel))); stackedItemsPanel.Seal(); } + return stackedItemsPanel; + } + } +} + +/// Result grids one under the other: each gets an equal share of the visible height, never less than ; +/// past that the results area scrolls. Every grid has a finite height, so its rows stay virtualized. +public sealed class StackedResultsPanel : Panel +{ + public const double MinimumRowHeight = 160; + private ScrollViewer? viewer; + + public StackedResultsPanel() + { + Loaded += (_, _) => { viewer = FindViewport(); if (viewer is not null) viewer.SizeChanged += ViewportChanged; InvalidateMeasure(); }; + Unloaded += (_, _) => { if (viewer is not null) viewer.SizeChanged -= ViewportChanged; viewer = null; }; + } + + private void ViewportChanged(object sender, SizeChangedEventArgs e) { if (e.HeightChanged) InvalidateMeasure(); } + + private double RowHeight(Size available) + { + double viewport = double.IsInfinity(available.Height) ? (FindViewport()?.ViewportHeight ?? 0) : available.Height; + if (viewport <= 0 || double.IsNaN(viewport)) viewport = MinimumRowHeight * 2; + int count = Math.Max(1, InternalChildren.Count); + return Math.Max(MinimumRowHeight, Math.Floor(viewport / count)); + } + + private ScrollViewer? FindViewport() + { + for (DependencyObject? node = VisualTreeHelper.GetParent(this); node is not null; node = VisualTreeHelper.GetParent(node)) + if (node is ScrollViewer viewer) return viewer; + return null; + } + + protected override Size MeasureOverride(Size availableSize) + { + double row = RowHeight(availableSize); + double width = double.IsInfinity(availableSize.Width) ? 0 : availableSize.Width; + foreach (UIElement child in InternalChildren) { child.Measure(new Size(availableSize.Width, row)); width = Math.Max(width, double.IsInfinity(availableSize.Width) ? child.DesiredSize.Width : 0); } + return new Size(width, row * InternalChildren.Count); + } + + protected override Size ArrangeOverride(Size finalSize) + { + double viewport = FindViewport()?.ViewportHeight ?? finalSize.Height; + double row = RowHeight(new Size(finalSize.Width, viewport > 0 ? viewport : finalSize.Height)); + double y = 0; + foreach (UIElement child in InternalChildren) { child.Arrange(new Rect(0, y, finalSize.Width, row)); y += row; } + return new Size(finalSize.Width, y); + } +} diff --git a/src/PGMS.Desktop/QueryView.xaml.cs b/src/PGMS.Desktop/QueryView.xaml.cs index 4ab1c9e..eeb185e 100644 --- a/src/PGMS.Desktop/QueryView.xaml.cs +++ b/src/PGMS.Desktop/QueryView.xaml.cs @@ -21,6 +21,8 @@ public partial class QueryView : UserControl, IAsyncDisposable internal static readonly RoutedUICommand CopyWithoutHeaders = new("Copy without headers", nameof(CopyWithoutHeaders), typeof(QueryView)); public Guid RecoveryId { get; } public long RecoveryRevision{get;private set;} + /// State kept with the draft changed outside the text (Pin Tab): the next checkpoint writes the draft again. + internal void MarkRecoveryChanged()=>RecoveryRevision++; public long EditRevision { get; private set; } public string? FilePath { get; internal set; } public SqlFileVersion? FileVersion { get; internal set; } @@ -191,6 +193,7 @@ private async Task ExecuteSqlAsync(string? shortcutSql) Messages.Clear(); ClearResultPages(); ResultSets.Items.Clear(); + ApplyResultSetLayout(); displayLimited = false; resultsIncomplete = true; UpdateExport(); @@ -266,8 +269,7 @@ private void AddResultGrid(DataTable table, IReadOnlyList? types = null) foreach (DataColumn column in table.Columns) { string path = $"[{column.ColumnName}]"; - var text = new DataGridTextColumn { Header = column.Caption, SortMemberPath = column.ColumnName, CellStyle = ResultGridStyle.NullAwareCell(path), - Binding = new Binding(path) { Converter = new DatabaseValueConverter() } }; + var text = ResultGridStyle.TextColumn(column.Caption, column.ColumnName); if (QueryOptions.DisplayJsonAsLink && types is not null && column.Ordinal < types.Count && ResultJson.MayHoldJson(types[column.Ordinal])) text.ElementStyle = ResultGridStyle.JsonLinkText(path, OpenJsonLink); grid.Columns.Add(text); diff --git a/src/PGMS.Desktop/RegisteredServersHost.cs b/src/PGMS.Desktop/RegisteredServersHost.cs index 36a9116..5476358 100644 --- a/src/PGMS.Desktop/RegisteredServersHost.cs +++ b/src/PGMS.Desktop/RegisteredServersHost.cs @@ -23,7 +23,7 @@ public partial class MainWindow ResolveService = (host, port) => LocalServiceResolver(host, port), EditProfile = EditRegisteredProfile, PromptGroupName = parent => new ServerGroupDialog(parent) { Owner = this } is var dialog && dialog.ShowDialog() == true ? dialog.GroupNameValue : null, - Confirm = message => MessageBox.Show(this, message, "Registered Servers", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No) == MessageBoxResult.Yes + Confirm = message => LocalizedMessageBox.Show(this, message, "Registered Servers", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No) == MessageBoxResult.Yes }; private void ShowRegisteredServers(object sender, RoutedEventArgs e) => ShowRegisteredServers(); diff --git a/src/PGMS.Desktop/RelationEditDialog.xaml.cs b/src/PGMS.Desktop/RelationEditDialog.xaml.cs index 94b6804..26e34ee 100644 --- a/src/PGMS.Desktop/RelationEditDialog.xaml.cs +++ b/src/PGMS.Desktop/RelationEditDialog.xaml.cs @@ -99,7 +99,7 @@ public async Task ApplyAsync() { if (busy) return; var request = Request; - if (request.Operation == RelationOperation.DropIndex && MessageBox.Show(this, Target.Text + "\n\n" + request.ToSql() + "\n\nDrop this index?", "Confirm index deletion", MessageBoxButton.YesNo, MessageBoxImage.Warning, MessageBoxResult.No) != MessageBoxResult.Yes) return; + if (request.Operation == RelationOperation.DropIndex && LocalizedMessageBox.Show(this, Target.Text + "\n\n" + request.ToSql() + "\n\nDrop this index?", "Confirm index deletion", MessageBoxButton.YesNo, MessageBoxImage.Warning, MessageBoxResult.No) != MessageBoxResult.Yes) return; SetBusy(true); Feedback.Text = "Applying operation…"; try { await new AdministrativeEditService(connection).ApplyAsync(request); WasApplied = true; busy = false; DialogResult = true; } catch (Exception ex) when (ex is NpgsqlException or System.IO.IOException or TimeoutException or InvalidOperationException or ArgumentException) { Feedback.Text = ex is PostgresException pg ? $"{pg.SqlState}: {pg.MessageText}" : ex.Message; } diff --git a/src/PGMS.Desktop/Resources/Dark.xaml b/src/PGMS.Desktop/Resources/Dark.xaml index 22b5679..d2a3956 100644 --- a/src/PGMS.Desktop/Resources/Dark.xaml +++ b/src/PGMS.Desktop/Resources/Dark.xaml @@ -92,6 +92,7 @@ + @@ -180,7 +181,8 @@ - + + diff --git a/src/PGMS.Desktop/Resources/Shell.xaml b/src/PGMS.Desktop/Resources/Shell.xaml index 8347efc..14fbb24 100644 --- a/src/PGMS.Desktop/Resources/Shell.xaml +++ b/src/PGMS.Desktop/Resources/Shell.xaml @@ -41,7 +41,8 @@ - + + @@ -213,51 +214,29 @@ - - - - + + + + +