diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index c58678d..ffdf9f4 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -13,9 +13,17 @@ body: attributes: label: PGMS version / Versão do PGMS description: Release tag or build label shown in Help > About. / Tag da release ou rótulo de build exibido em Help > About. - placeholder: v0.1.0-alpha.7 (M1117) + placeholder: v0.1.0-beta.1 (M1145) validations: required: true + - type: input + id: language + attributes: + label: Interface language and theme / Idioma da interface e tema + description: Tools > Options > Environment > International Settings, and Tools > Theme. / Tools > Options > Environment > International Settings, e Tools > Theme. + placeholder: English, Cool Breeze + validations: + required: false - type: input id: environment attributes: diff --git a/.github/ISSUE_TEMPLATE/translation.yml b/.github/ISSUE_TEMPLATE/translation.yml new file mode 100644 index 0000000..a2c9677 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/translation.yml @@ -0,0 +1,55 @@ +name: Translation problem / Problema de tradução +description: A text of the interface is wrong, unclear or still in English. The translations have not been reviewed by native speakers yet. / Um texto da interface está errado, confuso ou ainda em inglês. As traduções ainda não foram revisadas por falantes nativos. +labels: [translation] +body: + - type: markdown + attributes: + value: | + Thank you for helping. Object Explorer folder names, Keyboard command names, SQL keywords and texts that come from the server or your data stay in English on purpose, as in SSMS. + + Obrigado pela ajuda. Os nomes das pastas do Object Explorer, os nomes de comando da página Keyboard, as palavras-chave do SQL e os textos que vêm do servidor ou dos seus dados ficam em inglês de propósito, como no SSMS. + - type: dropdown + id: language + attributes: + label: Language / Idioma + options: + - Português (Brasil) + - Español + - Deutsch + - Italiano + - Français + - 한국어 + - 日本語 + - English + validations: + required: true + - type: input + id: version + attributes: + label: PGMS version / Versão do PGMS + description: Shown in Help > About. / Exibida em Help > About. + placeholder: v0.1.0-beta.1 (M1145) + validations: + required: true + - type: input + id: where + attributes: + label: Where / Onde + description: Window, menu, page of Tools > Options or message. / Janela, menu, página de Tools > Options ou mensagem. + placeholder: Tools > Options > Environment > AutoRecover + validations: + required: true + - type: textarea + id: current + attributes: + label: Text shown / Texto exibido + render: text + validations: + required: true + - type: textarea + id: suggestion + attributes: + label: Suggested text / Texto sugerido + description: Optional. / Opcional. + validations: + required: false diff --git a/Directory.Build.props b/Directory.Build.props index e2e1c18..dfb6da6 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -1,6 +1,6 @@ - 0.1.0-alpha.7 + 0.1.0-beta.1 enable enable true diff --git a/README.md b/README.md index b54096e..c896df9 100644 --- a/README.md +++ b/README.md @@ -6,13 +6,13 @@ English | [Português (Brasil)](README.pt-BR.md) **The SQL Server Management Studio experience, for PostgreSQL.** A native Windows client with **database diagrams**, a **visual query designer** and **context-aware IntelliSense**, plus Object Explorer, F5 to run, execution plans, session monitoring and backup/restore, built for people who already think in SSMS. -**[Download v0.1.0-alpha.7 for Windows x64](https://github.com/leoars/PostgresManagementStudio/releases/tag/v0.1.0-alpha.7)** · Graphical installer (EN/pt-BR) or portable ZIP, .NET runtime included · Works with PostgreSQL 16–18 +**[Download v0.1.0-beta.1 for Windows x64](https://github.com/leoars/PostgresManagementStudio/releases/tag/v0.1.0-beta.1)** · Graphical installer (EN/pt-BR) or portable ZIP, .NET runtime included · Works with PostgreSQL 16–18 · Interface in 8 languages ![PGMS editor, Object Explorer and query results](docs/assets/pgms-results-m959.jpg) -> Early pre-release. Querying, browsing and monitoring are the core of this alpha; administration and backup run through reviewable SQL and the official PostgreSQL tools. Full SSMS parity is not claimed. See [known limits](docs/en/validation.md) and [release notes](docs/en/release-notes.md). +> First beta, still a pre-release: the features are complete for this version and it is meant for real work, but it can have bugs. Administration and backup run through reviewable SQL and the official PostgreSQL tools. Full SSMS parity is not claimed. See [known limits](docs/en/validation.md), the [release notes](docs/en/release-notes.md) and [how to report a problem](#contribute-and-report-problems). -**Contents:** [Highlights](#highlights) · [New in alpha.7](#new-in-alpha7) · [Why PGMS](#why-pgms) · [Features](#features) · [Get started](#get-started) · [Documentation](#documentation) · [Contribute and report problems](#contribute-and-report-problems) · [License](#license) +**Contents:** [Highlights](#highlights) · [New in beta.1](#new-in-beta1) · [Why PGMS](#why-pgms) · [Features](#features) · [Get started](#get-started) · [Languages](#languages) · [Documentation](#documentation) · [Contribute and report problems](#contribute-and-report-problems) · [License](#license) ## Highlights @@ -49,17 +49,20 @@ Press `Ctrl+Space` and get what fits that position. After `FROM`: tables, views - **Execution plan advice.** Graphical plans flag operators that discard many rows and suggest a missing index as a commented `CREATE INDEX` script, checked against the catalog and never run for you. - **Schema Compare.** Compare two databases and get a change script in a query tab connected to the target, for you to review and run. - **Query History.** Every query you run, grouped and searchable, stored only on your computer and encrypted for your Windows user. +- **PostGIS.** `geometry` and `geography` values appear as EWKT text in the grid, Results to Text, copy and export, and Table Designer accepts types such as `geometry(Point,4326)`. -## New in alpha.7 +## New in beta.1 -- **AI conversation** and **Explain / Fix / Optimize SQL with AI**. -- **Dark theme**, Editor Appearance, Fonts and Colors, and Presenter Mode. -- **Unexpected errors are logged** to `%LOCALAPPDATA%\PGMS\logs` and shown in a window with **Report Issue**, instead of closing PGMS silently. -- Editor: Format SQL, Parameter Info and Quick Info, bookmarks, outlining, templates and snippets, Find in Files, spell checking of comments and strings, and the SSMS Edit ▸ Advanced commands. -- Schema Compare, Live Query Statistics (progress, waits and blockers), Object Explorer Details (`F7`), the Properties window (`F4`), Error List and Output. -- Object Explorer: extensions, maintenance (Vacuum, Analyze, Refresh Materialized View), menus for keys, constraints and triggers, composite types, foreign servers and logical replication. -- Backup with LZ4/Zstandard, parallel restore and restoring only chosen items; client certificates in Connect. -- Window layouts, Split Tab, Full Screen, Restore Closed Tab, a menu in the title bar with Search (`Ctrl+Q`), Keyboard and Query Shortcuts, Import and Export Settings and External Tools. +- **Interface in 8 languages:** English, Português (Brasil), Español, Deutsch, Italiano, Français, 한국어 and 日本語 (see [Languages](#languages)). +- **The 13 SSMS color themes** (Cool Breeze by default), plus Use system setting. +- **Execution plans:** Show Execution Plan JSON or as Text, and **Compare Showplan** with another plan file or the previous plan of the same tab, with the operators that differ highlighted in the drawing. +- **PostGIS** values shown as EWKT (above). +- **Update notice:** a few seconds after start, release packages ask the GitHub API whether a newer release exists (GitHub sees your IP address, as with any web request) and show **Update available** in the title bar. Nothing is downloaded or installed. You can turn it off in Tools ▸ Options ▸ Environment ▸ Product Updates. +- **More of the SSMS Options:** AutoRecover, Documents, Tabs, Windows, the seven SQL Formatter pages, Table Options, Object Explorer General and Commands, and Live Query Statistics. Each option works or is shown disabled with the reason. +- Editor and windows: Paste Special (Format SQL, Paste with AI), Switch Completion Mode, File ▸ New ▸ File, Code Snippets Manager, Navigate Backward/Forward, Pin Tab (kept on recovered and reopened tabs), All Windows, several result sets in tabs or stacked. +- PGMS message boxes with buttons in the PGMS language; keyboard and screen reader fixes; windows fit the screen at 150–175% scaling; faster result grids. + +**Defaults that changed to match SSMS:** new tabs open first (after pinned tabs), unsaved queries are backed up every 5 minutes, system schemas and template databases are listed in Object Explorer (in the System Schemas and System Databases folders), Table Designer saves stop after 3600 seconds, Live Query Statistics reads every 250 ms and Format SQL writes `VARCHAR (20)`. Settings you changed yourself are kept; each one can be changed back in Tools ▸ Options. See the [release notes](docs/en/release-notes.md) for details and limits. @@ -80,7 +83,7 @@ See the [release notes](docs/en/release-notes.md) for details and limits. - Reviewed SQL administration for supported databases, schemas, tables, columns, identity, indexes, constraints, sequences, roles and privileges. - Session/blocker monitoring, with distinct query cancellation and session termination. - Logical backup/restore through external PostgreSQL tools: custom, tar, SQL and directory formats, gzip/LZ4/Zstandard, parallel and partial restore, plus reviewed global operations. -- Light, dark or system theme, Fonts and Colors, keyboard shortcuts and window layouts. +- The SSMS themes (Cool Breeze, Light, Dark and the color themes), Fonts and Colors, keyboard shortcuts, window layouts and an interface in 8 languages. ## Get started @@ -99,7 +102,7 @@ Get-FileHash .\PGMS-* -Algorithm SHA256 Compare the hashes with `SHA256SUMS.txt` in the release. Starting with v0.1.0-alpha.2 the assets are built by the [release workflow](.github/workflows/release.yml) on GitHub Actions and carry a build provenance attestation, so you can also confirm that the ZIP or installer came from that workflow and this repository (requires the [GitHub CLI](https://cli.github.com/)): ```powershell -gh attestation verify .\PGMS-0.1.0-alpha.7-Setup-x64.exe --repo leoars/PostgresManagementStudio +gh attestation verify .\PGMS-0.1.0-beta.1-Setup-x64.exe --repo leoars/PostgresManagementStudio ``` v0.1.0-alpha.1 was built on the maintainer's machine and has checksums only. Code signing through the SignPath Foundation open source program is planned. @@ -117,6 +120,12 @@ dotnet run --project src/PGMS.Desktop The self-contained portable package includes .NET/WPF, but no PostgreSQL server or tools. Local candidate ZIPs and acceptance artifacts are absent from a fresh clone. See [setup and packaging](docs/en/getting-started.md). +## Languages + +The interface is available in English, Português (Brasil), Español, Deutsch, Italiano, Français, 한국어 and 日本語. By default PGMS follows the Windows display language (English when Windows uses another one); choose another in **Tools ▸ Options ▸ Environment ▸ International Settings** and restart PGMS. As in SSMS, some things stay in English on purpose: Object Explorer folder names, command names in the Keyboard page, SQL keywords and anything that comes from the server or your data. + +**The translations have not been reviewed by native speakers yet.** If a text is wrong, unclear or still in English, please [report a translation problem](https://github.com/leoars/PostgresManagementStudio/issues/new?template=translation.yml) with the language, the window and the text you saw. The guides are maintained in English and Brazilian Portuguese only. + ## Documentation | Topic | English | Português (Brasil) | @@ -128,12 +137,14 @@ The self-contained portable package includes .NET/WPF, but no PostgreSQL server | Evidence and limits | [Validation](docs/en/validation.md) | [Validação](docs/pt-BR/validation.md) | | Attribution | [Licensing](docs/en/licensing.md) | [Licenças](docs/pt-BR/licensing.md) | -[Documentation index](docs/README.md). Public guides are maintained in both languages; the original internal development history is not included in this curated source repository. Bilingual documentation does not localize the application UI. +[Documentation index](docs/README.md). Public guides are maintained in both languages; the original internal development history is not included in this curated source repository. ## Contribute and report problems **If PGMS hits an error.** An unexpected error opens a window with the details; PGMS also writes them to a daily log in `%LOCALAPPDATA%\PGMS\logs` (kept 30 days, nothing sent over the network). Choose **Report Issue**, describe what you were doing and attach the log or the text from **Copy Details** after reading it: an error message can quote what the server sent. You can usually choose **Continue**; your open queries keep their text. +**Any other problem.** [Open a bug report](https://github.com/leoars/PostgresManagementStudio/issues/new?template=bug_report.yml): the form asks for the PGMS version (Help ▸ About), the Windows and PostgreSQL versions, how you installed PGMS, the steps, what you expected and what happened, and the log when there is one. + See [CONTRIBUTING.md](CONTRIBUTING.md) and the [code of conduct](CODE_OF_CONDUCT.md). English and Brazilian Portuguese are welcome. Issue templates guide bug reports and feature requests; usage questions go to [Discussions](https://github.com/leoars/PostgresManagementStudio/discussions). Use synthetic data and remove credentials and personal information from reports. For vulnerabilities, follow [SECURITY.md](SECURITY.md). ## License diff --git a/README.pt-BR.md b/README.pt-BR.md index 4971d1a..257c8b7 100644 --- a/README.pt-BR.md +++ b/README.pt-BR.md @@ -6,13 +6,13 @@ **A experiência do SQL Server Management Studio, para PostgreSQL.** Cliente nativo Windows com **diagramas de banco**, **Query Designer visual** e **IntelliSense por contexto**, além de Object Explorer, F5 para executar, planos de execução, monitor de sessões e backup/restore, feito para quem já pensa em SSMS. -**[Baixar v0.1.0-alpha.7 para Windows x64](https://github.com/leoars/PostgresManagementStudio/releases/tag/v0.1.0-alpha.7)** · Instalador gráfico (EN/pt-BR) ou ZIP portátil, runtime .NET incluído · Funciona com PostgreSQL 16 a 18 +**[Baixar v0.1.0-beta.1 para Windows x64](https://github.com/leoars/PostgresManagementStudio/releases/tag/v0.1.0-beta.1)** · Instalador gráfico (EN/pt-BR) ou ZIP portátil, runtime .NET incluído · Funciona com PostgreSQL 16 a 18 · Interface em 8 idiomas ![Editor, Object Explorer e resultados do PGMS](docs/assets/pgms-results-m959.jpg) -> Pré-release inicial. Consultas, navegação e monitoramento são o núcleo desta alpha; administração e backup usam SQL revisável e as ferramentas oficiais do PostgreSQL. Não se declara paridade integral com SSMS. Veja os [limites conhecidos](docs/pt-BR/validation.md) e as [notas da versão](docs/pt-BR/release-notes.md). +> Primeiro beta, ainda pré-release: as funções desta versão estão completas e ela se destina a trabalho real, mas pode ter defeitos. Administração e backup usam SQL revisável e as ferramentas oficiais do PostgreSQL. Não se declara paridade integral com SSMS. Veja os [limites conhecidos](docs/pt-BR/validation.md), as [notas da versão](docs/pt-BR/release-notes.md) e [como relatar um problema](#contribuir-e-relatar-problemas). -**Conteúdo:** [Destaques](#destaques) · [Novidades da alpha.7](#novidades-da-alpha7) · [Por que o PGMS](#por-que-o-pgms) · [Funcionalidades](#funcionalidades) · [Começar](#começar) · [Documentação](#documentação) · [Contribuir e relatar problemas](#contribuir-e-relatar-problemas) · [Licença](#licença) +**Conteúdo:** [Destaques](#destaques) · [Novidades do beta.1](#novidades-do-beta1) · [Por que o PGMS](#por-que-o-pgms) · [Funcionalidades](#funcionalidades) · [Começar](#começar) · [Idiomas](#idiomas) · [Documentação](#documentação) · [Contribuir e relatar problemas](#contribuir-e-relatar-problemas) · [Licença](#licença) ## Destaques @@ -49,17 +49,20 @@ Aperte `Ctrl+Space` e receba o que cabe naquela posição. Depois de `FROM`: tab - **Dicas no plano de execução.** O plano gráfico marca operadores que descartam muitas linhas e sugere um índice faltante como script `CREATE INDEX` comentado, conferido no catálogo e nunca executado por conta própria. - **Schema Compare.** Compare dois bancos e receba um script de mudanças numa aba de consulta conectada ao destino, para você revisar e executar. - **Query History.** Cada consulta que você executa, agrupada e pesquisável, guardada só no seu computador e criptografada para o seu usuário do Windows. +- **PostGIS.** Valores `geometry` e `geography` aparecem como texto EWKT na grade, no Results to Text, na cópia e na exportação, e o Table Designer aceita tipos como `geometry(Point,4326)`. -## Novidades da alpha.7 +## Novidades do beta.1 -- **Conversa com a IA** e **Explain / Fix / Optimize SQL with AI**. -- **Tema escuro**, Editor Appearance, Fonts and Colors e Presenter Mode. -- **Erros inesperados ficam registrados** em `%LOCALAPPDATA%\PGMS\logs` e aparecem numa janela com **Report Issue**, em vez de fechar o PGMS em silêncio. -- Editor: Format SQL, Parameter Info e Quick Info, marcadores, outlining, modelos e trechos, Find in Files, verificação ortográfica de comentários e cadeias e os comandos de Edit ▸ Advanced do SSMS. -- Schema Compare, Live Query Statistics (progresso, esperas e bloqueios), Object Explorer Details (`F7`), a janela Properties (`F4`), Error List e Output. -- Object Explorer: extensões, manutenção (Vacuum, Analyze, Refresh Materialized View), menus de chaves, constraints e triggers, tipos compostos, servidores estrangeiros e replicação lógica. -- Backup com LZ4/Zstandard, restore paralelo e restauração só dos itens escolhidos; certificados de cliente no Connect. -- Layouts de janela, Split Tab, Full Screen, Restore Closed Tab, menu na barra de título com Search (`Ctrl+Q`), Keyboard e Query Shortcuts, Import and Export Settings e External Tools. +- **Interface em 8 idiomas:** English, Português (Brasil), Español, Deutsch, Italiano, Français, 한국어 e 日本語 (veja [Idiomas](#idiomas)). +- **Os 13 temas de cores do SSMS** (Cool Breeze por padrão), mais Use system setting. +- **Planos de execução:** Show Execution Plan JSON ou as Text, e **Compare Showplan** com outro arquivo de plano ou com o plano anterior da mesma aba, com os operadores que diferem destacados no desenho. +- Valores **PostGIS** em EWKT (acima). +- **Aviso de nova versão:** alguns segundos depois de abrir, os pacotes de release perguntam à API do GitHub se há versão mais nova (o GitHub vê o seu endereço IP, como em qualquer acesso à web) e mostram **Update available** na barra de título. Nada é baixado nem instalado. Dá para desligar em Tools ▸ Options ▸ Environment ▸ Product Updates. +- **Mais opções do SSMS:** AutoRecover, Documents, Tabs, Windows, as sete páginas do SQL Formatter, Table Options, General e Commands do Object Explorer e Live Query Statistics. Cada opção funciona ou aparece desabilitada com o motivo. +- Editor e janelas: Paste Special (Format SQL, Paste with AI), Switch Completion Mode, File ▸ New ▸ File, Code Snippets Manager, Navigate Backward/Forward, Pin Tab (mantido em abas recuperadas e reabertas), All Windows, vários conjuntos de resultados em abas ou empilhados. +- Caixas de mensagem do PGMS com os botões no idioma do PGMS; correções de teclado e leitor de tela; janelas que cabem na tela em 150–175% de escala; grades de resultados mais rápidas. + +**Padrões que mudaram para seguir o SSMS:** abas novas abrem primeiro (depois das fixadas), consultas não salvas têm cópia a cada 5 minutos, esquemas de sistema e bancos modelo aparecem no Object Explorer (nas pastas System Schemas e System Databases), salvamentos do Table Designer param depois de 3600 segundos, o Live Query Statistics lê a cada 250 ms e o Format SQL escreve `VARCHAR (20)`. Configurações que você mudou continuam como estavam; cada uma pode ser mudada de volta em Tools ▸ Options. Veja as [notas da versão](docs/pt-BR/release-notes.md) para detalhes e limites. @@ -80,7 +83,7 @@ Veja as [notas da versão](docs/pt-BR/release-notes.md) para detalhes e limites. - Administração com SQL revisável nos casos suportados de bancos, schemas, tabelas, colunas, identity, índices, constraints, sequences, roles e privilégios. - Monitor de sessões/bloqueadores, com cancelamento de consulta e encerramento de sessão distintos. - Backup/restore lógico por ferramentas externas PostgreSQL: custom, tar, SQL e diretório, gzip/LZ4/Zstandard, restore paralelo e parcial, além de operações globais revisadas. -- Tema claro, escuro ou do sistema, Fonts and Colors, atalhos de teclado e layouts de janela. +- Os temas do SSMS (Cool Breeze, Light, Dark e os temas coloridos), Fonts and Colors, atalhos de teclado, layouts de janela e interface em 8 idiomas. ## Começar @@ -99,7 +102,7 @@ Get-FileHash .\PGMS-* -Algorithm SHA256 Compare os hashes com o `SHA256SUMS.txt` da release. A partir da v0.1.0-alpha.2 os assets são compilados pelo [workflow de release](.github/workflows/release.yml) no GitHub Actions e trazem atestado de proveniência de build, então você também pode confirmar que o ZIP ou o instalador saiu desse workflow e deste repositório (exige o [GitHub CLI](https://cli.github.com/)): ```powershell -gh attestation verify .\PGMS-0.1.0-alpha.7-Setup-x64.exe --repo leoars/PostgresManagementStudio +gh attestation verify .\PGMS-0.1.0-beta.1-Setup-x64.exe --repo leoars/PostgresManagementStudio ``` A v0.1.0-alpha.1 foi compilada na máquina do mantenedor e tem apenas checksums. A assinatura de código pelo programa open source da SignPath Foundation está planejada. @@ -117,6 +120,12 @@ dotnet run --project src/PGMS.Desktop O pacote portátil self-contained inclui .NET/WPF, sem servidor ou ferramentas PostgreSQL. ZIPs candidatos e artefatos locais de aceitação não vêm em um clone novo. Veja [preparação e empacotamento](docs/pt-BR/getting-started.md). +## Idiomas + +A interface está disponível em English, Português (Brasil), Español, Deutsch, Italiano, Français, 한국어 e 日本語. Por padrão o PGMS segue o idioma de exibição do Windows (inglês quando o Windows usa outro); escolha outro em **Tools ▸ Options ▸ Environment ▸ International Settings** e abra o PGMS de novo. Como no SSMS, algumas coisas ficam em inglês de propósito: os nomes das pastas do Object Explorer, os nomes de comando da página Keyboard, as palavras-chave do SQL e tudo o que vem do servidor ou dos seus dados. + +**As traduções ainda não foram revisadas por falantes nativos.** Se um texto estiver errado, confuso ou ainda em inglês, [relate um problema de tradução](https://github.com/leoars/PostgresManagementStudio/issues/new?template=translation.yml) com o idioma, a janela e o texto que você viu. Os guias são mantidos só em inglês e português do Brasil. + ## Documentação | Assunto | English | Português (Brasil) | @@ -128,12 +137,14 @@ O pacote portátil self-contained inclui .NET/WPF, sem servidor ou ferramentas P | Provas e limites | [Validation](docs/en/validation.md) | [Validação](docs/pt-BR/validation.md) | | Atribuição | [Licensing](docs/en/licensing.md) | [Licenças](docs/pt-BR/licensing.md) | -[Índice da documentação](docs/README.md). Guias públicos são mantidos nos dois idiomas; o histórico interno original não está incluído nesta cópia pública selecionada. Documentação bilíngue não localiza a interface do aplicativo. +[Índice da documentação](docs/README.md). Guias públicos são mantidos nos dois idiomas; o histórico interno original não está incluído nesta cópia pública selecionada. ## Contribuir e relatar problemas **Se o PGMS der erro.** Um erro inesperado abre uma janela com os detalhes; o PGMS também os grava num log diário em `%LOCALAPPDATA%\PGMS\logs` (guardado por 30 dias, nada é enviado pela rede). Escolha **Report Issue**, conte o que você estava fazendo e anexe o log ou o texto de **Copy Details** depois de lê-lo: uma mensagem de erro pode citar o que o servidor enviou. Em geral dá para escolher **Continue**; as consultas abertas mantêm o texto. +**Qualquer outro problema.** [Abra um relato de defeito](https://github.com/leoars/PostgresManagementStudio/issues/new?template=bug_report.yml): o formulário pede a versão do PGMS (Help ▸ About), as versões do Windows e do PostgreSQL, a forma de instalação, os passos, o que você esperava e o que aconteceu, e o log quando houver. + Veja [CONTRIBUTING.pt-BR.md](CONTRIBUTING.pt-BR.md) e o [código de conduta](CODE_OF_CONDUCT.pt-BR.md). Os modelos de issue orientam relatos de defeito e pedidos de funcionalidade; dúvidas de uso vão para [Discussions](https://github.com/leoars/PostgresManagementStudio/discussions). Inglês e português do Brasil são bem-vindos. Use dados sintéticos e remova credenciais e informações pessoais dos relatos. Para vulnerabilidades, siga [SECURITY.pt-BR.md](SECURITY.pt-BR.md). ## Licença diff --git a/SECURITY.md b/SECURITY.md index 3fc72ef..ae80d50 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -2,7 +2,7 @@ English | [Português (Brasil)](SECURITY.pt-BR.md) -PGMS is in development. There is no published supported release series or guaranteed response time. Current development and the v0.1.0-alpha.7 pre-release are the starting points for investigation; historical packages do not automatically receive fixes. +PGMS is in development. There is no published supported release series or guaranteed response time. Current development and the v0.1.0-beta.1 pre-release are the starting points for investigation; historical packages do not automatically receive fixes. Do not disclose an unpatched vulnerability or real credentials in a public issue. Use GitHub's **Report a vulnerability** on this repository if private reporting is enabled. If it is unavailable, open an issue asking the maintainer for a private contact channel without including vulnerability details. Never post database dumps, saved profiles, DPAPI payloads, access tokens or private keys. diff --git a/SECURITY.pt-BR.md b/SECURITY.pt-BR.md index 05dbeff..298cf6c 100644 --- a/SECURITY.pt-BR.md +++ b/SECURITY.pt-BR.md @@ -2,7 +2,7 @@ [English](SECURITY.md) | Português (Brasil) -O PGMS está em desenvolvimento. Não há série de releases publicada com suporte nem prazo de resposta garantido. O desenvolvimento atual e a pré-release v0.1.0-alpha.7 são o ponto de partida para investigação; pacotes históricos não recebem correções automaticamente. +O PGMS está em desenvolvimento. Não há série de releases publicada com suporte nem prazo de resposta garantido. O desenvolvimento atual e a pré-release v0.1.0-beta.1 são o ponto de partida para investigação; pacotes históricos não recebem correções automaticamente. Não divulgue vulnerabilidade sem correção ou credenciais reais em uma issue pública. Use **Report a vulnerability** no GitHub deste repositório se o relato privado estiver habilitado. Se estiver indisponível, abra uma issue pedindo ao mantenedor um canal privado, sem detalhes da vulnerabilidade. Nunca publique dumps, perfis salvos, payloads DPAPI, tokens ou chaves privadas. diff --git a/docs/en/distribution.md b/docs/en/distribution.md index 0c2fe3e..8d540be 100644 --- a/docs/en/distribution.md +++ b/docs/en/distribution.md @@ -1,8 +1,10 @@ -# PGMS v0.1.0-alpha.7 — portable distribution (M1117) +# PGMS v0.1.0-beta.1 — portable distribution (M1145) English | Português (Brasil): LEIA-ME.md in the package, or docs/pt-BR/distribution.md in the source repository. -Extract the entire directory and run PGMS.exe. A win-x64 self-contained package includes .NET/WPF; keep its DLLs, resources, LICENSE, notices and licenses directory together. No SSMS is required. No PostgreSQL server or client tools are bundled. Use PostgreSQL 16–18 and matching-major pg_dump/pg_restore/psql/pg_dumpall for applicable operations. No signed installer, MSI or automatic update is provided. +Extract the entire directory and run PGMS.exe. A win-x64 self-contained package includes .NET/WPF; keep its DLLs, resources, LICENSE, notices and licenses directory together. No SSMS is required. No PostgreSQL server or client tools are bundled. Use PostgreSQL 16–18 and matching-major pg_dump/pg_restore/psql/pg_dumpall for applicable operations. No signed installer, MSI or automatic update is provided; a release package only checks GitHub for a newer release (Tools > Options > Environment > Product Updates turns it off). + +The interface follows the Windows display language when it is one of English, Portuguese (Brazil), Spanish, German, Italian, French, Korean or Japanese, and English otherwise; Tools > Options > Environment > International Settings chooses another. The translations have not been reviewed by native speakers; please report problems in the repository below. Connect with the intended PostgreSQL role and appropriate TLS settings (VerifyFull by default). Review SQL, target and role before administering. Only run trusted restore scripts; SQL can issue COMMIT, reconnect or execute local psql commands. Cancel is a request and may arrive after COMMIT. Check the destination before retrying. diff --git a/docs/en/getting-started.md b/docs/en/getting-started.md index fd95180..b823c99 100644 --- a/docs/en/getting-started.md +++ b/docs/en/getting-started.md @@ -2,7 +2,7 @@ English | [Português (Brasil)](../pt-BR/getting-started.md) -[Download v0.1.0-alpha.7](https://github.com/leoars/PostgresManagementStudio/releases/tag/v0.1.0-alpha.7): [graphical installer](graphical-installer.md), portable ZIP or PowerShell 7 installer. The graphical installer offers current-user and all-users modes and does not require PowerShell. See [release notes](release-notes.md). +[Download v0.1.0-beta.1](https://github.com/leoars/PostgresManagementStudio/releases/tag/v0.1.0-beta.1): [graphical installer](graphical-installer.md), portable ZIP or PowerShell 7 installer. The graphical installer offers current-user and all-users modes and does not require PowerShell. See [release notes](release-notes.md). ### Windows SmartScreen warning @@ -15,7 +15,7 @@ Get-FileHash .\PGMS-* -Algorithm SHA256 Compare the hashes with `SHA256SUMS.txt` in the release. Starting with v0.1.0-alpha.2 the assets are built by the [release workflow](../../.github/workflows/release.yml) on GitHub Actions and carry a build provenance attestation, so you can also confirm that the ZIP or installer came from that workflow and this repository (requires the [GitHub CLI](https://cli.github.com/); see [development](development.md)): ```powershell -gh attestation verify .\PGMS-0.1.0-alpha.7-Setup-x64.exe --repo leoars/PostgresManagementStudio +gh attestation verify .\PGMS-0.1.0-beta.1-Setup-x64.exe --repo leoars/PostgresManagementStudio ``` v0.1.0-alpha.1 was built on the maintainer's machine and has checksums only. Code signing through the SignPath Foundation open source program is planned. diff --git a/docs/en/graphical-installer.md b/docs/en/graphical-installer.md index bc947b4..6b38e49 100644 --- a/docs/en/graphical-installer.md +++ b/docs/en/graphical-installer.md @@ -2,7 +2,7 @@ English | [Português (Brasil)](../pt-BR/graphical-installer.md) -Download `PGMS-0.1.0-alpha.7-Setup-x64.exe` from the [alpha.7 release](https://github.com/leoars/PostgresManagementStudio/releases/tag/v0.1.0-alpha.7) and check it against `SHA256SUMS.txt` (and, optionally, `gh attestation verify`). Since v0.1.0-alpha.2 the installer is built by the release workflow from the same payload as the portable ZIP of that release; in v0.1.0-alpha.1 it was added later to wrap the existing M1008 payload. The installer does not require PowerShell or a separately installed .NET runtime. +Download `PGMS-0.1.0-beta.1-Setup-x64.exe` from the [beta.1 release](https://github.com/leoars/PostgresManagementStudio/releases/tag/v0.1.0-beta.1) and check it against `SHA256SUMS.txt` (and, optionally, `gh attestation verify`). Since v0.1.0-alpha.2 the installer is built by the release workflow from the same payload as the portable ZIP of that release; in v0.1.0-alpha.1 it was added later to wrap the existing M1008 payload. The installer does not require PowerShell or a separately installed .NET runtime. ## Installation choices diff --git a/docs/en/release-notes.md b/docs/en/release-notes.md index 90f6b1f..254bed8 100644 --- a/docs/en/release-notes.md +++ b/docs/en/release-notes.md @@ -1,104 +1,82 @@ -# v0.1.0-alpha.7 — Windows x64 +# v0.1.0-beta.1 — Windows x64 English | [Português (Brasil)](../pt-BR/release-notes.md) -Seventh public pre-release of PGMS. It is an alpha for evaluation with synthetic/disposable data. Build label: M1117. The binaries are built and attested by the same [release workflow](../../.github/workflows/release.yml) as the previous releases. Original work is under Apache-2.0, with credits in `NOTICE`; releases through alpha.4 remain under MIT. +First beta of PGMS, still published as a pre-release. The features of this version are complete and it is meant for real work; it can still have bugs, so keep backups and report what you find. Build label: M1145. The binaries are built and attested by the same [release workflow](../../.github/workflows/release.yml) as the previous releases. Original work is under Apache-2.0, with credits in `NOTICE`; releases through alpha.4 remain under MIT. + +> **Not tested on a clean Windows machine.** This beta was installed and run only on the maintainer's computer, which already has PostgreSQL, SSMS and development tools. It has not been tested on a clean Windows virtual machine or by another Windows user without administrator rights. If the installer or the first start fails on your machine, please [report it](https://github.com/leoars/PostgresManagementStudio/issues/new?template=bug_report.yml). ## Highlights -- **AI assistant: conversation and Explain/Fix/Optimize.** The **Generate SQL with AI** window now takes follow-up requests: the last five requests of the conversation and the SQL written for them go with the next one, and **New Conversation** starts over. **Query ▸ Explain SQL with AI**, **Fix SQL with AI** and **Optimize SQL with AI** open the window with the selected SQL (or the document) and a request already written; **Fix** adds the SQLSTATE and the main message of the last error of the tab, but never its DETAIL, which can quote row values. Nothing is sent until you press **Generate**, and nothing is executed: the SQL only goes into the editor. The database structure goes to the provider you set (Anthropic, OpenAI or a local Ollama); table data is never read or sent. With Ollama, PGMS now asks for a context window that fits the prompt and trims the structure to the model's maximum, instead of letting the server cut the prompt silently. -- **Configure Server TLS** is unchanged: a guided setup that installs a certificate and turns on TLS, restoring the previous settings if it fails. It requires a superuser connection to a server running on Windows. -- **Unexpected errors are logged.** An error that PGMS did not handle no longer closes the program silently. It is written to a daily log in `%LOCALAPPDATA%\PGMS\logs` (kept 30 days; password values in `key=value` text are masked) and a window shows the error with **Copy Details**, **Open Log Folder**, **Report Issue**, **Continue** (the default) and **Close PGMS**. Nothing is sent over the network. -- **Dark theme.** **Tools ▸ Theme** offers Light, Dark and Use system setting. In the dark theme the shell, menus, standard controls, result grids, the tree and the Properties window follow it; database diagrams and graphical plans stay light, like paper. **Tools ▸ Editor Appearance** sets the editor colors on its own (including two extra-contrast modes) and **View ▸ Presenter Mode** (`Ctrl+Shift+F5`) enlarges the editor, results and window text for a presentation. - -## What changed since v0.1.0-alpha.6 - -**Editor** -- **Edit ▸ Advanced:** toggle line and block comments, upper/lower case, move, sort, join and duplicate lines, delete horizontal white space, tabify/untabify, indentation, Insert File As Text, Expand Selection, Containing Block, Expand to Line, next/previous subword, Incremental Search, **Format SQL** (`Ctrl+K`, `Ctrl+Q`; only spaces, line breaks and keyword case change) and **Toggle Spell Checker** (comments and strings, through the Windows spell checker). -- An editor information bar with zoom (20–400 %, `Ctrl`+wheel), line and column (opens Go To Line), tabs/spaces, line ending (CRLF/LF/CR) and encoding, with **Set End of Line Sequence**, **Set Indentation** and **Set Encoding** (Unicode encodings). -- **IntelliSense:** Parameter Info (`Ctrl+Shift+Space`) and Quick Info (`Ctrl+K`, `Ctrl+I`, or hovering). -- **Bookmarks** per tab (`Ctrl+K`, `Ctrl+K` and the SSMS chords) and **Outlining** by statement and block comment. -- **Templates and snippets:** Template Explorer (`Ctrl+Alt+T`) with PostgreSQL templates and your own `.sql` files, Specify Values for Template Parameters (`Ctrl+Shift+M`), Insert Snippet and Surround With. -- The error position reported by the server is underlined in the editor, counted in the information bar and reached by **Go To Next/Previous Issue in File** (`Alt+PgDn`/`Alt+PgUp`). -- **Find in Files** and **Replace in Files** (`Ctrl+Shift+H`) over a folder, the open documents or the current one, with a Find Results pane. -- Clipboard history (`Ctrl+Shift+V`) and Go To Last Edit Location (`Ctrl+Shift+Backspace`). -- Lines over 10,000 characters are shown cut, with a marker that opens the whole line, so the editor no longer pauses on them. - -**Files, tabs and windows** -- **File ▸ New ▸ Query with Current Connection** and **Database Engine Query**; **Open ▸ File** connects the new tab with the current connection, and **File Disconnected…** opens without connecting; **Disconnect All Queries**. -- Save All, Recent Files (count in Tools ▸ Options), Close All Tabs and **Restore Closed Tab**, also for queries without a file. -- **Window:** next/previous pane (`F6`), Show Results Pane (`Ctrl+R`), Split Tab, Dock, Auto Hide, Move To New Window, saved window layouts (up to ten) and **View ▸ Full Screen**. -- The menu now shares the title bar, with the window buttons and a **Search** box (`Ctrl+Q`) that finds menu commands and Tools ▸ Options pages and settings. -- **View ▸ Properties Window** (`F4`), **Error List** (`Ctrl+\`, `E`) with the last error of each tab, and **Output** (`Ctrl+Alt+O`) with the messages and executions of the session. -- **File ▸ Page Setup…** and **Print…** for the SQL of the active tab. -- Connection texts closer to SSMS: the server node shows `host:port (PostgreSQL version - login)` and the query status bar shows server, login with backend PID, database, time and rows. - -**Queries and results** -- Results/Messages tabs are above the results, and **Save Results As…** in the grid menu opens **Save Grid Results** (`.csv` comma separated or `.txt` tab separated, with headers). The export options band is still available from **Export Options…**. -- **Query ▸ Include Live Query Statistics** shows, once a second over a separate connection, the state, elapsed time, waits, blocking sessions and `pg_stat_progress_*` progress (CREATE INDEX, VACUUM, ANALYZE, CLUSTER, COPY) of the running query. PostgreSQL has no per-operator counters, so there is no live plan. -- **Query Shortcuts** (`Alt+F1`, `Ctrl+1` to `Ctrl+0`) in Tools ▸ Options, empty by default. -- Extension types such as PostGIS `geometry` are shown as the text the server sends (hexadecimal EWKB), without errors. - -**Object Explorer and administration** -- **Object Explorer Details** (`F7`), the contents of the selected node with search. -- **Keys**, **Constraints** and **Triggers**: Modify, Rename, Delete with the exact command (no CASCADE), New Foreign Key… and New Constraint…; Enable/Disable of triggers; New Function…, New Stored Procedure… and New Trigger… from templates. -- An **Extensions** folder per database with New Extension…, Update Extension… and Delete. -- A **Maintenance** submenu with Vacuum…, Analyze… and Refresh Materialized View…; the command opens in a query tab, not run directly. -- Composite Types, Foreign Servers and Replication (local publications and subscriptions), read only. -- The filter gains **Does not equal**. -- **Role Memberships** lists effective memberships, direct and inherited, with the path. -- **Tools ▸ Schema Compare** compares two databases (read only) and writes a change script into a query tab connected to the target. It never runs the script. -- **Back Up:** LZ4 and Zstandard compression. **Restore:** parallel jobs (1–32) and **Choose Items…** to restore only some items of an archive. -- **Connect:** client certificate, client key and key password (stored with DPAPI); backup and restore receive the key password through a temporary private service file. - -**Settings** -- Tools ▸ Options: **Fonts and Colors** (Text Editor, Grid Results, Text Results), **Keyboard** (one shortcut per menu command), Object Explorer **Scripting** options, **Designers** and **Connection Dialog** options. -- **Tools ▸ Import and Export Settings…** (a `.pgmssettings` file with the Options), **External Tools…** and **Customize…** for the toolbars. -- **Help ▸ View Help** (`Ctrl+F1`) opens the packaged guide; **Release Notes** opens the release list. - -**PostgreSQL 16:** four defects found by a complete regression on PostgreSQL 16.15 were fixed, among them `MAINTAIN` being offered on servers before 17. +- **Interface in 8 languages.** English, Português (Brasil), Español, Deutsch, Italiano, Français, 한국어 and 日本語. PGMS follows the Windows display language by default (English when Windows uses another one); **Tools ▸ Options ▸ Environment ▸ International Settings** chooses another, applied when PGMS starts again. Object Explorer folder names and the command names of the Keyboard page stay in English, as in SSMS; SQL, data and server messages are never translated. **The translations have not been reviewed by native speakers yet**: please [report any translation problem](https://github.com/leoars/PostgresManagementStudio/issues/new?template=translation.yml). +- **AI assistant** (unchanged since alpha.7): **Query ▸ Generate SQL with AI…** (`Ctrl+I`) with follow-up requests, and **Explain**, **Fix** and **Optimize SQL with AI**. It works with Anthropic, OpenAI or a local Ollama, with your own key. The request, the database structure (names, types, keys, comments) and, for **Fix**, the SQLSTATE and main message of the last error go to the provider you set; table data is never read or sent, nothing is sent until you press **Generate**, and the SQL is never run for you. +- **Configure Server TLS** (unchanged): a guided setup that installs a certificate and turns on TLS, restoring the previous settings if it fails. It requires a superuser connection to a server running on Windows. +- **Themes as in SSMS.** **Tools ▸ Theme** lists the 13 SSMS themes in the SSMS order (Cool Breeze, the look PGMS always had, is the default; Light is the SSMS gray; Dark; and the color themes) plus **Use system setting**. +- **Execution plans.** The plan menu adds **Show Execution Plan JSON**, **Show Execution Plan as Text** (the `EXPLAIN` text layout, built without running the query again) and **Compare Showplan**, which compares the plan with a saved plan file or with the previous plan of the same tab. Operators that differ are shaded in both drawings (amber: other values; pink: only in one plan), with a Differences grid. +- **PostGIS.** `geometry` and `geography` values appear as EWKT text (`SRID=4326;POINT(1 2)`) in the grid, Results to Text, copy and export; Table Designer accepts types such as `geometry(Point,4326)` and lists the types of installed extensions. +- **Update notice.** A few seconds after start, release packages ask the GitHub API whether a newer release exists (GitHub sees your IP address, as with any web request) and show **Update available** in the title bar, with Open the release page and Skip This Version. **Help ▸ Check for Updates** asks at once. Nothing is downloaded or installed. Turn it off in **Tools ▸ Options ▸ Environment ▸ Product Updates**. + +## What changed since v0.1.0-alpha.7 + +**Options** +- New pages, each option with a real effect or shown disabled with the reason: Environment ▸ **AutoRecover** (on/off, interval in minutes, lifetime in days), **Documents** (files changed outside PGMS, read-only files, Open from the folder of the active file, mixed line endings, save in the background, save encoding), **Tabs**, **Task List** (read only) and **Windows**; the seven **SQL Formatter** pages (keyword casing, Format on save, alignment, indentation, multiline lists, new lines, spacing); Designers ▸ **Table Options** (save time-out, warning on a table without a primary key); Object Explorer ▸ **General** (Hide system objects) and **Commands** (confirm renames); Query Execution ▸ **Live Query Statistics** (polling interval); Text Editor ▸ **Transact-SQL** (word wrap, line numbers, tabs, IntelliSense for new windows). +- **Defaults that follow SSMS:** new tabs open first, after the pinned tabs; unsaved queries are backed up every 5 minutes; system schemas (`pg_catalog`, `information_schema`) and template databases are listed in Object Explorer, in the **System Schemas** and **System Databases** folders, the first folder under Schemas and under Databases (with Hide system objects on, the folders and their objects are hidden); a Table Designer statement that runs longer than 3600 seconds stops the save and nothing is changed; Live Query Statistics reads every 250 ms; Format SQL writes a space between a type and its parameters (`VARCHAR (20)`). Recovered queries still come back in their saved order. Change any of these back in Tools ▸ Options. +- **Results to Grid ▸ Show multiple result sets stacked in one tab** (off by default: one tab per result set). + +**Editor and windows** +- **Edit ▸ Paste Special** ▸ Format SQL (pastes formatted, one Undo) and Paste with AI…; **Edit ▸ IntelliSense ▸ Switch Completion Mode** (`Ctrl+Alt+Space`); **File ▸ New ▸ File…** (`Ctrl+Alt+N`); **Tools ▸ Code Snippets Manager…** (`Ctrl+K`, `Ctrl+B`). +- **View ▸ Navigate Backward/Forward** (`Ctrl+-`, `Ctrl+Shift+-`), **All Windows** in Full Screen (`Shift+Alt+M`), **Window ▸ Pin Tab** (pinned tabs stay pinned when recovered or reopened with Restore Closed Tab) and Reset Current Object Explorer Details View; the Standard and SQL Editor toolbars have the SSMS buttons in the SSMS order. +- Message boxes are drawn by PGMS, with the buttons in the PGMS language, the usual keys (Enter, Esc, access letters), the system icon and sound, and `Ctrl+C` to copy the text. +- Tab titles and composed messages are translated; file and query names are not. + +**Performance and accessibility** +- Result grids draw each cell with one element and expose fewer automation objects: scrolling and loading large results are faster. The grid fills in the same steps as SSMS (30, 100, 10,000 rows, then the end). +- When PGMS reopens after an unexpected close, only the active recovered tab builds its editor at once; the others build when shown. +- Keyboard and screen reader fixes from a pass with real key presses: tool window focus and size, Tab no longer stuck in toolbars (toolbars are out of the Tab order, as in SSMS), auto-hidden panes and splitters out of the Tab order, names read by Narrator in Connect and in editable combo boxes. Every window now fits the screen's work area, so dialogs are no longer cut at 175% scaling. Tabs, Error List, Output and Schema Compare follow the dark theme. ## Downloads -From [this release](https://github.com/leoars/PostgresManagementStudio/releases/tag/v0.1.0-alpha.7): +From [this release](https://github.com/leoars/PostgresManagementStudio/releases/tag/v0.1.0-beta.1): | File | Purpose | | --- | --- | -| `PGMS-0.1.0-alpha.7-Setup-x64.exe` | Graphical installer (English/pt-BR). Current user without administrator rights, or all users with elevation. No PowerShell or separate .NET runtime required. | -| `PGMS-0.1.0-alpha.7-win-x64.zip` | Portable application with .NET/WPF runtime. Extract the entire folder and run PGMS.exe. Includes the managed PowerShell 7 scripts. | +| `PGMS-0.1.0-beta.1-Setup-x64.exe` | Graphical installer (English/pt-BR). Current user without administrator rights, or all users with elevation. No PowerShell or separate .NET runtime required. | +| `PGMS-0.1.0-beta.1-win-x64.zip` | Portable application with .NET/WPF runtime. Extract the entire folder and run PGMS.exe. Includes the managed PowerShell 7 scripts. | | `SHA256SUMS.txt` | SHA256 of every asset in this release. Hashes check correspondence, not authorship. | | `package-manifest.json` | SHA256 manifest of every file inside the ZIP, as checked by `Verify-Package.ps1`. | | `RELEASE-NOTES.md`, `RELEASE-NOTES.pt-BR.md` | These notes. | +The installer updates an existing installation in place; profiles, drafts, Query History and settings live in `%LOCALAPPDATA%\PGMS` and are not removed. An update over alpha.7 on a clean machine is not certified yet (see [Validation](#validation)). + ## Verify what you downloaded The binaries are not code-signed, so Windows SmartScreen may warn on first launch. Before choosing **Run anyway**, confirm the checksum and the provenance: ```powershell Get-FileHash .\PGMS-* -Algorithm SHA256 -gh attestation verify .\PGMS-0.1.0-alpha.7-Setup-x64.exe --repo leoars/PostgresManagementStudio +gh attestation verify .\PGMS-0.1.0-beta.1-Setup-x64.exe --repo leoars/PostgresManagementStudio ``` Compare the hashes with `SHA256SUMS.txt`. The second command needs the [GitHub CLI](https://cli.github.com/) and confirms that the file was produced by this repository's release workflow at the tagged commit; run it for the ZIP as well. Code signing through the SignPath Foundation open source program is planned; no date is promised. ## Report a problem -When PGMS shows the unexpected error window, choose **Report Issue** and attach the log from **Open Log Folder** (`%LOCALAPPDATA%\PGMS\logs`). Say what you were doing, the PostgreSQL version and whether it happens again. Read the log before attaching it: an error message can quote what the server sent. Use the [issue templates](https://github.com/leoars/PostgresManagementStudio/issues/new/choose). +When PGMS shows the unexpected error window, choose **Report Issue** and attach the log from **Open Log Folder** (`%LOCALAPPDATA%\PGMS\logs`). For any other problem, [open a bug report](https://github.com/leoars/PostgresManagementStudio/issues/new?template=bug_report.yml): it asks for the PGMS version (Help ▸ About), the Windows and PostgreSQL versions, the installation method, the interface language, the steps and the log when there is one. Read the log before attaching it: an error message can quote what the server sent. Translation problems have [their own form](https://github.com/leoars/PostgresManagementStudio/issues/new?template=translation.yml). ## Scope -SQL editor with IntelliSense and independent sessions, Object Explorer, paged Results and Results to Text/File, CSV/JSON export, database diagrams and designers, graphical plans, reviewed PostgreSQL administration, identity/privileges, Activity Monitor, query statistics, Schema Compare and logical backup/restore. PostgreSQL 16 to 18 and same-major client tools are required for database operations and backup/restore; server/tools are not bundled. SSMS is neither required nor distributed. +SQL editor with IntelliSense and independent sessions, Object Explorer, paged Results and Results to Text/File, CSV/JSON export, database diagrams and designers, graphical, text and JSON plans with comparison, reviewed PostgreSQL administration, identity/privileges, Activity Monitor, query statistics, Query History, Schema Compare, logical backup/restore and the AI assistant. PostgreSQL 16 to 18 and same-major client tools are required for database operations and backup/restore; server/tools are not bundled. SSMS is neither required nor distributed. ## Validation -Application behavior: the M1117 source passed the complete regression of this repository on PostgreSQL 17.11 (see [validation](validation.md#v010-alpha7--m1117--2026-11-17)) on an isolated loopback cluster; the host PostgreSQL service is not used. Most features added since alpha.6 were validated by focused automated suites while they were built; a complete regression on PostgreSQL 16.15 and 18.6 was last run on an earlier source (M1066). The new AI actions and the conversation were tested with a local fake provider only, not with a real one. PostGIS itself was not installed in the test cluster: a stand-in `geometry` type was used. +Application behavior: the M1145 source passed the complete regression of this repository on PostgreSQL 17.11, and the M1141 source (the same features without the six default changes of M1143 and the system folders of M1145) passed it on 16.15, 17.11 and 18.6 (see [validation](validation.md#v010-beta1--m1145--2026-11-20)), on an isolated loopback cluster; the host PostgreSQL service is not used. Keyboard-only navigation with real key presses, Narrator, 100/150/175% scaling in three themes and three languages, and the performance scenarios of the project were checked on the maintainer's machine before the default changes. PostGIS was tested with the official PostGIS 3.7.0 package on PostgreSQL 17.11. The AI features were tested with a local fake provider, not with a real one. -A clean-Windows VM installation, another Windows user without privileges and physical DPI/keyboard/screen-reader observations of the new screens are not certified by this release. +A clean-Windows VM installation and another Windows user without privileges are not certified by this release. ## Known limits -Windows x64 only. Unsigned executable and installer; SmartScreen warns. No MSI, automatic update or production-support guarantee. Full SSMS parity is not claimed. Dark theme: diagrams and plans stay light; colored themes are not available. One caret only (no multiple carets). Several result sets are shown in tabs, not stacked. Live Query Statistics has no live plan. PostGIS values are shown as hexadecimal text, without WKT, GeoJSON or a map. Results: sorting, copy and export apply to the current page; rows after the first page stay in a temporary file, unencrypted, until the next execution or until the tab closes; Results to Text keeps the 10,000-row and 250,000-cell limits, and Results to File has neither. IntelliSense does not know CTE columns, temporary tables or `SET search_path` of the session. Query Designer: `UNION` and `WITH` open only in the SQL pane. Find Missing Foreign Keys is a heuristic: a matching name is a hint, not proof. The error log masks passwords only in `key=value` form. +Windows x64 only. Unsigned executable and installer; SmartScreen warns. No MSI, winget or automatic update (only the update notice). Full SSMS parity is not claimed. Translations without native review. One caret only (no multiple carets). Live Query Statistics has no live plan, because PostgreSQL has no per-operator counters while a query runs; there is no plan Analyze. OpenAI was not tested with a real key. Configure Server TLS needs a Windows server and a superuser. Running a 10,000 × 20 query with five tabs open can pause the interface for about 0.4 s, and reopening five recovered drafts takes about 2 s. With system objects shown, `template0` appears Offline and cannot be expanded (it does not accept connections). Results: sorting, copy and export apply to the current page; rows after the first page stay in a temporary file, unencrypted, until the next execution or until the tab closes. IntelliSense does not know CTE columns, temporary tables or `SET search_path` of the session. Query Designer: `UNION` and `WITH` open only in the SQL pane. The error log masks passwords only in `key=value` form. ## Previous releases -v0.1.0-alpha.6 (2026-11-13, diagram indexes and descriptions, Query History, Script as, plan warnings) and v0.1.0-alpha.5 (2026-11-08, database diagrams, Query Designer, IntelliSense; Apache-2.0) remain available with their original assets and notes. v0.1.0-alpha.4 (2026-11-07, Activity Monitor in a tab), v0.1.0-alpha.3 (2026-11-02, Query Statistics), v0.1.0-alpha.2 (2026-11-01, first CI-built release with attestation) and v0.1.0-alpha.1 (2026-10-31) remain available with their original assets and notes, under MIT. +v0.1.0-alpha.7 (2026-11-17, AI conversation, dark theme, error log), v0.1.0-alpha.6 (2026-11-13, diagram indexes and descriptions, Query History, Script as, plan warnings) and v0.1.0-alpha.5 (2026-11-08, database diagrams, Query Designer, IntelliSense; Apache-2.0) remain available with their original assets and notes. v0.1.0-alpha.4 (2026-11-07), v0.1.0-alpha.3 (2026-11-02), v0.1.0-alpha.2 (2026-11-01, first CI-built release with attestation) and v0.1.0-alpha.1 (2026-10-31) remain available with their original assets and notes, under MIT. diff --git a/docs/en/user-guide.md b/docs/en/user-guide.md index a43cbe2..0985e42 100644 --- a/docs/en/user-guide.md +++ b/docs/en/user-guide.md @@ -36,6 +36,8 @@ In Object Explorer, right-click **Database Diagrams** under a database and choos **Display Estimated Execution Plan** (`Ctrl+L`) and **Include Actual Execution Plan** (`Ctrl+M`) draw the plan as operators linked by arrows proportional to the rows. **Warnings.** In an actual plan, an operator whose filter discarded many rows gets a yellow triangle, and its tooltip and properties have a **Warnings** section with the counts of Filter, Join Filter and Index Recheck. It is a PGMS rule, not a PostgreSQL warning: by default it appears when the discarded rows are at least 10 times the rows returned and at least 1,000, both set in **Query Options ▸ Execution ▸ Advanced** and, for new tabs, in **Tools ▸ Options**. **Missing index.** When a warned scan filters by simple comparisons, the plan header gets a green line with a suggested index and the context menu enables **Missing Index Details…**, which opens a query tab with the `CREATE INDEX` (and a `CONCURRENTLY` variant) commented out; nothing runs. The suggestion is a heuristic (equality columns first, then the `ORDER BY` under a `LIMIT` or one range column) checked against the catalog, so it is not offered when a valid b-tree index already starts with those columns. It does not cover joins, `OR`, expressions or `INCLUDE`, and it does not estimate selectivity: test it before creating the index. +**Text, JSON and comparison.** The context menu of a plan (in the query tab or in its own tab) has **Show Execution Plan JSON**, the server's JSON indented in a new tab, and **Show Execution Plan as Text**, the layout of `EXPLAIN` in text built from that JSON without running the query again. **Compare Showplan** compares the plan with a saved plan file, and **Compare with Previous Plan** with the plan the same tab had before. The **Showplan Comparison** tab shows both plans side by side; operators matched by name and depth that have other values are shaded amber in both drawings, operators that exist in only one plan are shaded pink, and the **Differences** grid lists the totals and each operator. There is no Analyze, which in SSMS looks for SQL Server scenarios. + ## Generate SQL with AI **Query ▸ Generate SQL with AI…** sends your request and the structure of the database (names, types, keys, comments; never table data) to the provider set in **Tools ▸ AI Assistant Settings…**: Anthropic, OpenAI or a local Ollama, with your own key, stored encrypted for your Windows user. The SQL is shown for review and only inserted into the editor. The structure sent is limited by **Context limit** in the settings (200,000 characters by default). When the database does not fit, PGMS first sends only the table names, with their comments, and lets the provider choose the relevant tables; then it sends those tables, the tables their foreign keys reference and the tables whose names share words with your request. Tables left out are listed by name. **View Sent Context…** shows what was sent in each call. The first call costs tokens too. @@ -113,19 +115,37 @@ When the server reports the position of an error, the editor underlines it, the A line longer than 10,000 characters is shown cut, with a marker that opens the whole line; the file and the SQL that runs are not changed. +**Edit ▸ Paste Special ▸ Format SQL** pastes the clipboard formatted (one Undo), and **Paste with AI…** opens Generate SQL with AI with the pasted SQL; nothing is sent until you press Generate. **Edit ▸ IntelliSense ▸ Switch Completion Mode** (`Ctrl+Alt+Space`) toggles suggestion mode, where `Enter` keeps what you typed and `Tab` inserts the suggestion. **File ▸ New ▸ File…** (`Ctrl+Alt+N`) creates a SQL file, a text file or a SQL file from a template, and **Tools ▸ Code Snippets Manager…** (`Ctrl+K`, `Ctrl+B`) imports `.snippet` files into your snippets folder. + ## Tabs, windows and settings -**File ▸ New ▸ Query with Current Connection** (`Ctrl+N`) uses the connection of the active tab or of Object Explorer; **Database Engine Query** asks for one. **Open ▸ File…** connects the new tab the same way, and **File Disconnected…** opens without connecting. **File ▸ Recent Files**, **Save All**, **Window ▸ Close All Tabs** and **Restore Closed Tab** work as in SSMS; a closed query without a file comes back with its text, disconnected. **Window** also has **Next/Previous Pane** (`F6`/`Shift+F6`), **Show Results Pane** (`Ctrl+R`), **Split Tab**, **Dock**, **Auto Hide**, **Move To New Window**, up to ten saved window layouts and **Auto Hide All**; **View ▸ Full Screen** is `Shift+Alt+Enter`. +**File ▸ New ▸ Query with Current Connection** (`Ctrl+N`) uses the connection of the active tab or of Object Explorer; **Database Engine Query** asks for one. **Open ▸ File…** connects the new tab the same way, and **File Disconnected…** opens without connecting. **File ▸ Recent Files**, **Save All**, **Window ▸ Close All Tabs** and **Restore Closed Tab** work as in SSMS; a closed query without a file comes back with its text, disconnected. **Window** also has **Next/Previous Pane** (`F6`/`Shift+F6`), **Show Results Pane** (`Ctrl+R`), **Split Tab**, **Dock**, **Auto Hide**, **Move To New Window**, up to ten saved window layouts and **Auto Hide All**; **View ▸ Full Screen** is `Shift+Alt+Enter`, and in Full Screen **View ▸ All Windows** (`Shift+Alt+M`) hides and shows the tool windows. **View ▸ Navigate Backward/Forward** (`Ctrl+-`, `Ctrl+Shift+-`) returns to earlier places: tab changes and jumps of ten or more lines. **Window ▸ Pin Tab** keeps a tab at the start, with a pin, and **Close All Tabs** leaves it open; a pinned tab stays pinned when it is recovered after a crash or reopened with Restore Closed Tab. Message boxes are drawn by PGMS, in the PGMS language, with `Enter`, `Esc`, access letters and `Ctrl+C` to copy their text. The menu shares the title bar with the window buttons and **Search** (`Ctrl+Q`), which finds menu commands and Tools ▸ Options pages and settings; `Enter` runs or opens the result. **View ▸ Properties Window** (`F4`) shows the session of the active query (server, login, database, backend PID, version, SSL mode, last execution). **View ▸ Error List** (`Ctrl+\`, `E`) has the error of the last execution of each open tab; double-click goes to it. **View ▸ Output** (`Ctrl+Alt+O`) keeps the messages and executions of the session (5,000 lines in memory). **File ▸ Page Setup…** and **Print…** print the SQL of the active tab. -**Tools ▸ Options** includes **Fonts and Colors** (editor, Grid Results and Text Results), **Keyboard** (one shortcut per menu command, which wins over the built-in one), **Query Shortcuts** (`Alt+F1`, `Ctrl+1` to `Ctrl+0`, empty by default; the text runs in the session of the active tab, followed by the selection), Object Explorer **Scripting**, **Designers** and **Connection Dialog**. **Tools ▸ Theme** chooses Light, Dark or the Windows setting; in Dark, diagrams and graphical plans stay light. **Tools ▸ Editor Appearance** sets the editor colors separately, with two extra-contrast modes, and **View ▸ Presenter Mode** (`Ctrl+Shift+F5`) enlarges the editor, results and window text for the session. **Tools ▸ Import and Export Settings…** saves, loads or resets the Options in a `.pgmssettings` file (without window position, recent files, connections, passwords or AI settings). **Tools ▸ External Tools…** adds programs to the Tools menu, run only when you choose them, and **Tools ▸ Customize…** shows or hides the toolbars. +**Tools ▸ Options** includes **Fonts and Colors** (editor, Grid Results and Text Results), **Keyboard** (one shortcut per menu command, which wins over the built-in one), **Query Shortcuts** (`Alt+F1`, `Ctrl+1` to `Ctrl+0`, empty by default; the text runs in the session of the active tab, followed by the selection), Object Explorer **Scripting**, **Designers** and **Connection Dialog**. **Tools ▸ Theme** lists the 13 SSMS themes in the SSMS order (Cool Breeze is the default; Light is the SSMS gray; Dark; and the color themes) and **Use system setting** (Cool Breeze when Windows is light, Dark when it is dark); in Dark, diagrams and graphical plans stay light. **Tools ▸ Editor Appearance** sets the editor colors separately, with two extra-contrast modes, and **View ▸ Presenter Mode** (`Ctrl+Shift+F5`) enlarges the editor, results and window text for the session. **Tools ▸ Import and Export Settings…** saves, loads or resets the Options in a `.pgmssettings` file (without window position, recent files, connections, passwords or AI settings). **Tools ▸ External Tools…** adds programs to the Tools menu, run only when you choose them, and **Tools ▸ Customize…** shows or hides the toolbars. + +More Options pages follow SSMS 22.11; options PGMS cannot apply are shown disabled with the reason: + +- **Environment ▸ AutoRecover:** back up unsaved queries every 5 minutes by default (1 to 60), and discard copies older than 7 days. A crash loses at most the changes of the last interval. +- **Environment ▸ Documents:** a file changed outside PGMS is reloaded when PGMS becomes active (it asks first when the tab has unsaved changes); read-only files open without editing unless allowed; File ▸ Open starts in the folder of the active file; mixed line endings can be normalized to CRLF when a file opens; save in the background when PGMS loses focus; save every file in a chosen Unicode encoding. +- **Environment ▸ Tabs:** **Insert new tabs to the right of existing tabs** is off by default, as in SSMS, so a new tab goes first, after the pinned tabs. Recovered queries always come back after the open tabs, in their saved order. **Windows:** applying a saved window layout asks first unless the confirmation is skipped. +- **SQL Formatter** (seven pages): keyword casing, Format on save, aligned clause bodies, indentation size, lists on several lines, new lines before clauses and joins, blank lines between statements and a space between a type and its parameters (on by default, `VARCHAR (20)`). +- **Designers ▸ Table Options:** a Table Designer statement that runs longer than the time-out (on, 3600 seconds) stops the save and nothing is changed; optional warning before saving a table without a primary key. +- **Object Explorer ▸ General:** **Hide system objects** is off by default, as in SSMS: `pg_catalog` and `information_schema` are listed in the **System Schemas** folder, the first folder under Schemas, and the template databases in **System Databases**, the first folder under Databases. On, the folders and their objects are hidden. A change shows after a refresh. **Commands:** renaming a key, constraint or trigger in place asks first. +- **Query Execution ▸ Live Query Statistics:** how often live statistics are read (250 ms by default). +- **Text Editor ▸ Transact-SQL:** word wrap, line numbers, tab size and spaces, and IntelliSense. +- **Environment ▸ International Settings:** the interface language (see below). **Product Updates:** the update notice. + +**Languages.** The interface is available in English, Português (Brasil), Español, Deutsch, Italiano, Français, 한국어 and 日本語. **Same as Microsoft Windows** (the default) follows the Windows display language, or English when Windows uses another one; the language changes when PGMS starts again. Object Explorer folder names, command names in the Keyboard page, SQL, data and server messages stay in English or as they are. The translations have not been reviewed by native speakers yet; please report problems with the [translation form](https://github.com/leoars/PostgresManagementStudio/issues/new?template=translation.yml). + +**Update notice.** A few seconds after start, a release package asks the GitHub API (`api.github.com`) for the list of PGMS releases; GitHub sees your IP address, as with any web request, and nothing else is sent. When a newer version exists, **Update available** appears in the title bar, next to Search, with **Open the release page**, **Skip This Version** and the options. Nothing is downloaded or installed. **Help ▸ Check for Updates** asks at once; **Tools ▸ Options ▸ Environment ▸ Product Updates** turns the automatic check off. A failed automatic check is silent. ## Results and running queries -Results, Messages, the plan and the session tabs are above the results. **Save Results As…** in the grid menu opens **Save Grid Results**: a `.csv` file separated by commas or a `.txt` file separated by tabs, always with headers, for the current page. **Export Options…** opens the CSV/JSON export band. Several result sets of one execution are shown in tabs. Values of extension types, such as PostGIS `geometry`, are shown as the text the server sends (hexadecimal EWKB); a type created while PGMS is open is named `unknown type (oid N)` until you reconnect. +Results, Messages, the plan and the session tabs are above the results. **Save Results As…** in the grid menu opens **Save Grid Results**: a `.csv` file separated by commas or a `.txt` file separated by tabs, always with headers, for the current page. **Export Options…** opens the CSV/JSON export band. Several result sets of one execution are shown in tabs, or stacked in one tab when **Tools ▸ Options ▸ Query Results ▸ Results to Grid ▸ Show multiple result sets stacked in one tab** is on. PostGIS `geometry` and `geography` values are shown as EWKT (`SRID=4326;POINT(1 2)`, the same text as `ST_AsEWKT`) in the grid, Results to Text, copy and export, and Table Designer accepts types such as `geometry(Point,4326)`. Other extension types are shown as the text the server sends; after a type PGMS does not know yet, the session reads the types again. -**Query ▸ Include Live Query Statistics** adds a tab that, once a second and over a separate connection, shows the state, elapsed time, waits and blocking PIDs of the running query, and the progress reported by `pg_stat_progress_*` for CREATE INDEX, VACUUM, ANALYZE, CLUSTER and COPY. PostgreSQL has no per-operator counters while a query runs, so there is no live plan. +**Query ▸ Include Live Query Statistics** adds a tab that, every 250 ms by default (Tools ▸ Options ▸ Query Execution ▸ Live Query Statistics) and over a separate connection, shows the state, elapsed time, waits and blocking PIDs of the running query, and the progress reported by `pg_stat_progress_*` for CREATE INDEX, VACUUM, ANALYZE, CLUSTER and COPY. PostgreSQL has no per-operator counters while a query runs, so there is no live plan. ## Object Explorer additions @@ -141,4 +161,4 @@ An error that PGMS did not handle is written to a daily log in `%LOCALAPPDATA%\P ## Save and recover -Save SQL files explicitly. Background recovery stores bounded encrypted drafts and may reopen them disconnected after interruption. Review recovered tabs and use **Save As**. This is not a backup system or proof that every latest keystroke was persisted. Conflicting external file changes are refused. Close the app before backing up local state; DPAPI is tied to the Windows user. Builds earlier than M934 cannot read the newer recovery container. See [validation](validation.md) for the exact cross-version recovery tested. +Save SQL files explicitly. Background recovery (every 5 minutes by default; see Tools ▸ Options ▸ Environment ▸ AutoRecover) stores bounded encrypted drafts and may reopen them disconnected after interruption. Review recovered tabs and use **Save As**. This is not a backup system or proof that every latest keystroke was persisted. Conflicting external file changes are refused. Close the app before backing up local state; DPAPI is tied to the Windows user. Builds earlier than M934 cannot read the newer recovery container. See [validation](validation.md) for the exact cross-version recovery tested. diff --git a/docs/en/validation.md b/docs/en/validation.md index 8ad8e0f..33b4175 100644 --- a/docs/en/validation.md +++ b/docs/en/validation.md @@ -2,7 +2,7 @@ English | [Português (Brasil)](../pt-BR/validation.md) -Current pre-release: v0.1.0-alpha.7, build label M1117 (adds the AI conversation and Explain/Fix/Optimize, the dark theme and appearance settings, logging of unexpected errors, many editor, window and Object Explorer commands, Schema Compare, Live Query Statistics and parallel/partial restore to the M1062 source of alpha.6; built by the release workflow on GitHub Actions with a build provenance attestation; see the [release notes](release-notes.md)). Milestone labels are internal identifiers, not guarantees that a local rebuild has the same binary identity. The initial public source import used M1002. The private operational history and raw acceptance evidence are intentionally not included. +Current pre-release: v0.1.0-beta.1, build label M1145, the first beta (adds the interface in 8 languages, the SSMS color themes, text/JSON plans and Compare Showplan, PostGIS values as EWKT, the update notice, more SSMS Options pages with SSMS defaults, PGMS message boxes, and keyboard, scaling and performance fixes to the M1117 source of alpha.7; see the [release notes](release-notes.md)). Previous: v0.1.0-alpha.7, build label M1117 (adds the AI conversation and Explain/Fix/Optimize, the dark theme and appearance settings, logging of unexpected errors, many editor, window and Object Explorer commands, Schema Compare, Live Query Statistics and parallel/partial restore to the M1062 source of alpha.6; built by the release workflow on GitHub Actions with a build provenance attestation; see the [release notes](release-notes.md)). Milestone labels are internal identifiers, not guarantees that a local rebuild has the same binary identity. The initial public source import used M1002. The private operational history and raw acceptance evidence are intentionally not included. The imported implementation previously passed 5,187 automated checks (2,115 PostgreSQL integration and 3,072 WPF), plus package opening, installed profile preservation and three-draft recovery through rollback/restart. Those are historical observations, not newly executed tests for every source revision. Reproduce current behavior with the public build and test scripts; report your actual environment and results. The clean-import checks for the initial public revision are recorded below after execution. @@ -38,6 +38,12 @@ A complete run passed 2,236 integration + 3,315 WPF = 5,551 checks on PostgreSQL The window was compared, during development, with the Query Store of SSMS 22.11 on an identical synthetic workload against SQL Server LocalDB and the disposable PostgreSQL cluster. Both listed the same statements with matching counts. Differences found then: one window instead of seven Query Store reports; server-wide cumulative counters instead of per-database time intervals; no chart, plan, logical reads or header sorting; full records exposed as row names to screen readers. Header sorting, I/O and block metrics, generic plans, the top-N chart, time windows and short row names were added afterward. Remaining differences: one window instead of separate reports, windows computed by subtracting samples rather than stored intervals, and no per-statement CPU time, which PostgreSQL does not record. Physical DPI and screen-reader observations of this window are not newly certified. +## v0.1.0-beta.1 / M1145 — 2026-11-20 + +In the development repository, the M1145 source (M1143 plus the System Databases and System Schemas folders of Object Explorer) passed the complete regression on PostgreSQL 17.11: 3,151 integration + 5,781 WPF = 8,932 checks, in the first attempt, on a disposable loopback cluster with `pg_stat_statements` preloaded. The M1143 source had passed it on 17.11 with 3,151 + 5,770 = 8,921. The M1141 source, with the same features and the earlier defaults, had passed it on 16.15 (3,093 + 5,728 = 8,821), 17.11 and 18.6 (3,151 + 5,762 = 8,913 each); the 17.11 and 18.6 runs passed on the second attempt (an outdated test of the Options page order, then updated, and an intermittent driver exception in a live-statistics cancellation test that passed unchanged). M1143 changes only defaults of the interface and M1145 only groups the same catalog rows into folders; neither was repeated on 16.15 and 18.6. The difference on 16.15 comes from checks that only apply to 17 and later (`MAINTAIN`, `pg_dump --filter`). + +Beta gates run on the maintainer's machine before the default changes of M1143: keyboard-only navigation of the newer screens with real key presses (22 checks), Narrator listened to by the maintainer, 100/150/175 % scaling in Cool Breeze, Dark and Light with English, Korean and Japanese (200 % was not possible on that monitor), and the performance scenarios of the project. Two performance limits were accepted: running a 10,000 × 20 query with five tabs open pauses the interface for 350–460 ms (limit 250 ms), and restoring five recovered drafts takes about 2.05 s (limit 2 s). PostGIS ran with the official PostGIS 3.7.0 package on a copy of the PostgreSQL 17.11 binaries. The AI features ran against a local fake provider. A clean-Windows VM, another Windows user and an update over alpha.7 on a clean machine were not tested. The translations are machine translations checked by script for placeholders and access keys, not reviewed by native speakers. + ## v0.1.0-alpha.7 / M1117 — 2026-11-17 A complete run passed 3,135 integration + 5,440 WPF = 8,575 checks on PostgreSQL 17.11, on a disposable loopback cluster with `pg_stat_statements` preloaded, in the first attempt. The locally built self-contained package passed manifest verification (526 files), guide and archive checks, the launch check and a current-user graphical installation and removal; the global installation was not run. The launch check now cancels the Connect dialog that PGMS opens at startup before closing the main window: it had been failing intermittently because the dialog could open before the close request. In the development repository, the features added since alpha.6 were validated by focused suites as they were built; the complete regression ran on PostgreSQL 16.15 and 18.6 only on an earlier source (M1066). The AI conversation and Explain/Fix/Optimize ran against a local fake provider, not a real one. PostGIS was not installed: a stand-in `geometry` type was used. Unexpected-error handling was exercised through the same methods the global handlers call; the handlers were not triggered by a real crash. New screens were exercised by automated tests and, for the dark theme and the title bar, by hand with keyboard and mouse on one monitor at 100 %; a clean-Windows VM and screen readers were not used. diff --git a/docs/pt-BR/distribution.md b/docs/pt-BR/distribution.md index 86053ca..dcb6e54 100644 --- a/docs/pt-BR/distribution.md +++ b/docs/pt-BR/distribution.md @@ -1,8 +1,10 @@ -# PGMS v0.1.0-alpha.7 — distribuição portátil (M1117) +# PGMS v0.1.0-beta.1 — distribuição portátil (M1145) [English]: READ-ME.md no pacote, ou docs/en/distribution.md no repositório. Português (Brasil). -Extraia todo o diretório e execute PGMS.exe. Pacote win-x64 self-contained inclui .NET/WPF; preserve DLLs, recursos, LICENSE, avisos e pasta licenses juntos. SSMS não é necessário. Não inclui servidor ou ferramentas PostgreSQL. Use PostgreSQL 16–18 e pg_dump/pg_restore/psql/pg_dumpall da mesma versão principal conforme a operação. Sem instalador assinado, MSI ou atualização automática. +Extraia todo o diretório e execute PGMS.exe. Pacote win-x64 self-contained inclui .NET/WPF; preserve DLLs, recursos, LICENSE, avisos e pasta licenses juntos. SSMS não é necessário. Não inclui servidor ou ferramentas PostgreSQL. Use PostgreSQL 16–18 e pg_dump/pg_restore/psql/pg_dumpall da mesma versão principal conforme a operação. Sem instalador assinado, MSI ou atualização automática; um pacote de release só pergunta ao GitHub se há versão mais nova (Tools > Options > Environment > Product Updates desliga). + +A interface segue o idioma de exibição do Windows quando ele é inglês, português (Brasil), espanhol, alemão, italiano, francês, coreano ou japonês, e inglês nos outros casos; Tools > Options > Environment > International Settings escolhe outro. As traduções não foram revisadas por falantes nativos; relate problemas no repositório indicado abaixo. Conecte com a role pretendida e TLS adequado (VerifyFull por padrão). Revise SQL, destino e role antes de administrar. Execute restore somente com scripts confiáveis; SQL pode emitir COMMIT, reconectar ou executar comandos locais psql. Cancelar é solicitação e pode chegar após COMMIT. Confira o destino antes de repetir. diff --git a/docs/pt-BR/getting-started.md b/docs/pt-BR/getting-started.md index d866ac5..9ede1dd 100644 --- a/docs/pt-BR/getting-started.md +++ b/docs/pt-BR/getting-started.md @@ -2,7 +2,7 @@ [English](../en/getting-started.md) | Português (Brasil) -[Baixar v0.1.0-alpha.7](https://github.com/leoars/PostgresManagementStudio/releases/tag/v0.1.0-alpha.7): [instalador gráfico](graphical-installer.md), ZIP portátil ou instalador PowerShell 7. O instalador gráfico oferece modos por usuário e para todos, dispensando PowerShell. Veja [notas da versão](release-notes.md). +[Baixar v0.1.0-beta.1](https://github.com/leoars/PostgresManagementStudio/releases/tag/v0.1.0-beta.1): [instalador gráfico](graphical-installer.md), ZIP portátil ou instalador PowerShell 7. O instalador gráfico oferece modos por usuário e para todos, dispensando PowerShell. Veja [notas da versão](release-notes.md). ### Aviso do SmartScreen do Windows @@ -15,7 +15,7 @@ Get-FileHash .\PGMS-* -Algorithm SHA256 Compare os hashes com o `SHA256SUMS.txt` da release. A partir da v0.1.0-alpha.2 os assets são compilados pelo [workflow de release](../../.github/workflows/release.yml) no GitHub Actions e trazem atestado de proveniência de build, então você também pode confirmar que o ZIP ou o instalador saiu desse workflow e deste repositório (exige o [GitHub CLI](https://cli.github.com/); veja [desenvolvimento](development.md)): ```powershell -gh attestation verify .\PGMS-0.1.0-alpha.7-Setup-x64.exe --repo leoars/PostgresManagementStudio +gh attestation verify .\PGMS-0.1.0-beta.1-Setup-x64.exe --repo leoars/PostgresManagementStudio ``` A v0.1.0-alpha.1 foi compilada na máquina do mantenedor e tem apenas checksums. A assinatura de código pelo programa open source da SignPath Foundation está planejada. diff --git a/docs/pt-BR/graphical-installer.md b/docs/pt-BR/graphical-installer.md index ece7f23..441dfba 100644 --- a/docs/pt-BR/graphical-installer.md +++ b/docs/pt-BR/graphical-installer.md @@ -2,7 +2,7 @@ [English](../en/graphical-installer.md) | Português (Brasil) -Baixe `PGMS-0.1.0-alpha.7-Setup-x64.exe` na [release alpha.7](https://github.com/leoars/PostgresManagementStudio/releases/tag/v0.1.0-alpha.7) e confira contra o `SHA256SUMS.txt` (e, opcionalmente, com `gh attestation verify`). Desde a v0.1.0-alpha.2 o instalador é compilado pelo workflow de release a partir do mesmo payload do ZIP portátil daquela release; na v0.1.0-alpha.1 ele foi adicionado depois, embrulhando o payload M1008 existente. O instalador dispensa PowerShell e runtime .NET instalado separadamente. +Baixe `PGMS-0.1.0-beta.1-Setup-x64.exe` na [release beta.1](https://github.com/leoars/PostgresManagementStudio/releases/tag/v0.1.0-beta.1) e confira contra o `SHA256SUMS.txt` (e, opcionalmente, com `gh attestation verify`). Desde a v0.1.0-alpha.2 o instalador é compilado pelo workflow de release a partir do mesmo payload do ZIP portátil daquela release; na v0.1.0-alpha.1 ele foi adicionado depois, embrulhando o payload M1008 existente. O instalador dispensa PowerShell e runtime .NET instalado separadamente. ## Opções de instalação diff --git a/docs/pt-BR/release-notes.md b/docs/pt-BR/release-notes.md index 5fe50be..39f5d7e 100644 --- a/docs/pt-BR/release-notes.md +++ b/docs/pt-BR/release-notes.md @@ -1,104 +1,82 @@ -# v0.1.0-alpha.7 — Windows x64 +# v0.1.0-beta.1 — Windows x64 [English](../en/release-notes.md) | Português (Brasil) -Sétima pré-release pública do PGMS. É uma alpha para avaliação com dados sintéticos ou descartáveis. Rótulo de build: M1117. Os binários são gerados e atestados pelo mesmo [workflow de release](../../.github/workflows/release.yml) das versões anteriores. O trabalho próprio está sob Apache-2.0, com créditos no `NOTICE`; as versões até a alpha.4 continuam sob MIT. +Primeiro beta do PGMS, ainda publicado como pré-release. As funções desta versão estão completas e ela se destina a trabalho real; ainda pode ter defeitos, então mantenha backups e relate o que encontrar. Rótulo de build: M1145. Os binários são gerados e atestados pelo mesmo [workflow de release](../../.github/workflows/release.yml) das versões anteriores. O trabalho original está sob Apache-2.0, com créditos no `NOTICE`; as versões até a alpha.4 continuam sob MIT. + +> **Não testado numa máquina Windows limpa.** Este beta foi instalado e executado só no computador do mantenedor, que já tem PostgreSQL, SSMS e ferramentas de desenvolvimento. Ele não foi testado numa máquina virtual Windows limpa nem por outro usuário Windows sem direitos de administrador. Se o instalador ou a primeira abertura falhar na sua máquina, por favor [relate](https://github.com/leoars/PostgresManagementStudio/issues/new?template=bug_report.yml). ## Destaques -- **Assistente de IA: conversa e Explain/Fix/Optimize.** A janela **Generate SQL with AI** agora aceita pedidos de seguimento: os cinco últimos pedidos da conversa e o SQL escrito para eles vão junto com o próximo, e **New Conversation** recomeça. **Query ▸ Explain SQL with AI**, **Fix SQL with AI** e **Optimize SQL with AI** abrem a janela com o SQL selecionado (ou o documento) e um pedido já escrito; o **Fix** acrescenta o SQLSTATE e a mensagem principal do último erro da aba, mas nunca o DETAIL, que pode citar valores de linhas. Nada é enviado antes de você clicar em **Generate**, e nada é executado: o SQL só vai para o editor. A estrutura do banco vai para o provedor que você configurar (Anthropic, OpenAI ou um Ollama local); dados das tabelas nunca são lidos nem enviados. Com o Ollama, o PGMS agora pede uma janela de contexto que caiba o prompt e corta a estrutura no máximo do modelo, em vez de deixar o servidor cortar o prompt em silêncio. -- **Configure Server TLS** não mudou: um assistente que instala um certificado e liga o TLS, restaurando as configurações anteriores se falhar. Exige conexão de superusuário a um servidor rodando no Windows. -- **Erros inesperados ficam registrados.** Um erro que o PGMS não tratou não fecha mais o programa em silêncio. Ele vai para um log diário em `%LOCALAPPDATA%\PGMS\logs` (guardado por 30 dias; valores de senha em texto `chave=valor` são mascarados) e uma janela mostra o erro com **Copy Details**, **Open Log Folder**, **Report Issue**, **Continue** (o padrão) e **Close PGMS**. Nada é enviado pela rede. -- **Tema escuro.** **Tools ▸ Theme** oferece Light, Dark e Use system setting. No tema escuro, a moldura, os menus, os controles padrão, as grades de resultados, a árvore e a janela Properties acompanham; diagramas e planos gráficos continuam claros, como papel. **Tools ▸ Editor Appearance** define as cores do editor separadamente (inclusive dois modos de contraste extra) e **View ▸ Presenter Mode** (`Ctrl+Shift+F5`) aumenta o texto do editor, dos resultados e da janela para apresentações. - -## O que mudou desde a v0.1.0-alpha.6 - -**Editor** -- **Edit ▸ Advanced:** comentar e descomentar linhas e blocos, maiúsculas/minúsculas, mover, ordenar, juntar e duplicar linhas, apagar espaços horizontais, tabify/untabify, indentação, Insert File As Text, Expand Selection, Containing Block, Expand to Line, próxima/anterior subpalavra, Incremental Search, **Format SQL** (`Ctrl+K`, `Ctrl+Q`; só espaços, quebras de linha e caixa das palavras-chave mudam) e **Toggle Spell Checker** (comentários e cadeias, pelo verificador ortográfico do Windows). -- Uma barra de informações do editor com zoom (20–400 %, `Ctrl`+roda), linha e coluna (abre Go To Line), tabulações/espaços, fim de linha (CRLF/LF/CR) e codificação, com **Set End of Line Sequence**, **Set Indentation** e **Set Encoding** (codificações Unicode). -- **IntelliSense:** Parameter Info (`Ctrl+Shift+Space`) e Quick Info (`Ctrl+K`, `Ctrl+I`, ou passando o mouse). -- **Marcadores** por aba (`Ctrl+K`, `Ctrl+K` e os acordes do SSMS) e **Outlining** por instrução e comentário de bloco. -- **Modelos e trechos:** Template Explorer (`Ctrl+Alt+T`) com modelos PostgreSQL e seus próprios arquivos `.sql`, Specify Values for Template Parameters (`Ctrl+Shift+M`), Insert Snippet e Surround With. -- A posição do erro informada pelo servidor fica sublinhada no editor, contada na barra de informações e alcançada por **Go To Next/Previous Issue in File** (`Alt+PgDn`/`Alt+PgUp`). -- **Find in Files** e **Replace in Files** (`Ctrl+Shift+H`) numa pasta, nos documentos abertos ou no atual, com o painel Find Results. -- Histórico da área de transferência (`Ctrl+Shift+V`) e Go To Last Edit Location (`Ctrl+Shift+Backspace`). -- Linhas com mais de 10.000 caracteres aparecem cortadas, com um marcador que abre a linha inteira, e o editor não trava mais nelas. - -**Arquivos, abas e janelas** -- **File ▸ New ▸ Query with Current Connection** e **Database Engine Query**; **Open ▸ File** conecta a aba nova com a conexão atual, e **File Disconnected…** abre sem conectar; **Disconnect All Queries**. -- Save All, Recent Files (quantidade em Tools ▸ Options), Close All Tabs e **Restore Closed Tab**, também para consultas sem arquivo. -- **Window:** próximo/anterior painel (`F6`), Show Results Pane (`Ctrl+R`), Split Tab, Dock, Auto Hide, Move To New Window, layouts de janela salvos (até dez) e **View ▸ Full Screen**. -- O menu agora divide a barra de título com os botões da janela e uma caixa **Search** (`Ctrl+Q`) que encontra comandos do menu e páginas e configurações de Tools ▸ Options. -- **View ▸ Properties Window** (`F4`), **Error List** (`Ctrl+\`, `E`) com o último erro de cada aba e **Output** (`Ctrl+Alt+O`) com as mensagens e execuções da sessão. -- **File ▸ Page Setup…** e **Print…** para o SQL da aba ativa. -- Textos de conexão mais próximos do SSMS: o nó do servidor mostra `host:porta (PostgreSQL versão - login)` e a barra de estado da consulta mostra servidor, login com o PID do backend, banco, tempo e linhas. - -**Consultas e resultados** -- As abas Results/Messages ficam acima dos resultados, e **Save Results As…** no menu da grade abre **Save Grid Results** (`.csv` separado por vírgula ou `.txt` separado por tabulação, com cabeçalhos). A faixa de opções de exportação continua em **Export Options…**. -- **Query ▸ Include Live Query Statistics** mostra, uma vez por segundo e por uma conexão separada, o estado, o tempo decorrido, as esperas, as sessões que bloqueiam e o progresso de `pg_stat_progress_*` (CREATE INDEX, VACUUM, ANALYZE, CLUSTER, COPY) da consulta em execução. O PostgreSQL não tem contadores por operador, então não há plano ao vivo. -- **Query Shortcuts** (`Alt+F1`, `Ctrl+1` a `Ctrl+0`) em Tools ▸ Options, vazios por padrão. -- Tipos de extensões, como o `geometry` do PostGIS, aparecem como o texto que o servidor envia (EWKB em hexadecimal), sem erro. - -**Object Explorer e administração** -- **Object Explorer Details** (`F7`), o conteúdo do nó selecionado com busca. -- **Keys**, **Constraints** e **Triggers**: Modify, Rename, Delete com o comando exato (sem CASCADE), New Foreign Key… e New Constraint…; Enable/Disable de triggers; New Function…, New Stored Procedure… e New Trigger… a partir de modelos. -- Uma pasta **Extensions** em cada banco com New Extension…, Update Extension… e Delete. -- Um submenu **Maintenance** com Vacuum…, Analyze… e Refresh Materialized View…; o comando abre numa aba de consulta, sem ser executado direto. -- Composite Types, Foreign Servers e Replication (publicações e assinaturas locais), só leitura. -- O filtro ganha **Does not equal**. -- **Role Memberships** lista as associações efetivas, diretas e herdadas, com o caminho. -- **Tools ▸ Schema Compare** compara dois bancos (só leitura) e escreve um script de mudanças numa aba de consulta conectada ao destino. Nunca executa o script. -- **Back Up:** compressão LZ4 e Zstandard. **Restore:** jobs paralelos (1–32) e **Choose Items…** para restaurar só alguns itens de um arquivo. -- **Connect:** certificado de cliente, chave de cliente e senha da chave (guardada com DPAPI); backup e restore recebem a senha da chave por um arquivo de serviço temporário e privado. - -**Configurações** -- Tools ▸ Options: **Fonts and Colors** (Text Editor, Grid Results, Text Results), **Keyboard** (um atalho por comando do menu), opções de **Scripting** do Object Explorer, **Designers** e **Connection Dialog**. -- **Tools ▸ Import and Export Settings…** (um arquivo `.pgmssettings` com as opções), **External Tools…** e **Customize…** para as barras de ferramentas. -- **Help ▸ View Help** (`Ctrl+F1`) abre o guia do pacote; **Release Notes** abre a lista de releases. - -**PostgreSQL 16:** quatro defeitos achados por uma regressão completa no PostgreSQL 16.15 foram corrigidos, entre eles o `MAINTAIN` oferecido em servidores anteriores ao 17. +- **Interface em 8 idiomas.** English, Português (Brasil), Español, Deutsch, Italiano, Français, 한국어 e 日本語. Por padrão o PGMS segue o idioma de exibição do Windows (inglês quando o Windows usa outro); **Tools ▸ Options ▸ Environment ▸ International Settings** escolhe outro, aplicado quando o PGMS abre de novo. Os nomes das pastas do Object Explorer e os nomes de comando da página Keyboard ficam em inglês, como no SSMS; SQL, dados e mensagens do servidor nunca são traduzidos. **As traduções ainda não foram revisadas por falantes nativos**: por favor [relate qualquer problema de tradução](https://github.com/leoars/PostgresManagementStudio/issues/new?template=translation.yml). +- **Assistente de IA** (sem mudança desde a alpha.7): **Query ▸ Generate SQL with AI…** (`Ctrl+I`) com pedidos de continuação, e **Explain**, **Fix** e **Optimize SQL with AI**. Funciona com Anthropic, OpenAI ou um Ollama local, com a sua chave. O pedido, a estrutura do banco (nomes, tipos, chaves, comentários) e, no **Fix**, o SQLSTATE e a mensagem principal do último erro vão ao provedor configurado; dados das tabelas nunca são lidos nem enviados, nada é enviado antes de **Generate**, e o PGMS nunca executa o SQL por conta própria. +- **Configure Server TLS** (sem mudança): configuração guiada que instala um certificado e liga o TLS, restaurando a configuração anterior se falhar. Exige conexão de superusuário a um servidor em Windows. +- **Temas como no SSMS.** **Tools ▸ Theme** lista os 13 temas do SSMS na ordem dele (Cool Breeze, a aparência de sempre do PGMS, é o padrão; Light é o cinza do SSMS; Dark; e os temas coloridos), mais **Use system setting**. +- **Planos de execução.** O menu do plano ganha **Show Execution Plan JSON**, **Show Execution Plan as Text** (o layout em texto do `EXPLAIN`, montado sem executar a consulta de novo) e **Compare Showplan**, que compara o plano com um arquivo de plano salvo ou com o plano anterior da mesma aba. Os operadores que diferem ficam sombreados nos dois desenhos (âmbar: outros valores; rosa: só num plano), com uma grade Differences. +- **PostGIS.** Valores `geometry` e `geography` aparecem como texto EWKT (`SRID=4326;POINT(1 2)`) na grade, no Results to Text, na cópia e na exportação; o Table Designer aceita tipos como `geometry(Point,4326)` e lista os tipos das extensões instaladas. +- **Aviso de nova versão.** Alguns segundos depois de abrir, os pacotes de release perguntam à API do GitHub se há versão mais nova (o GitHub vê o seu endereço IP, como em qualquer acesso à web) e mostram **Update available** na barra de título, com Open the release page e Skip This Version. **Help ▸ Check for Updates** pergunta na hora. Nada é baixado nem instalado. Desligue em **Tools ▸ Options ▸ Environment ▸ Product Updates**. + +## O que mudou desde a v0.1.0-alpha.7 + +**Opções** +- Páginas novas, cada opção com efeito real ou mostrada desabilitada com o motivo: Environment ▸ **AutoRecover** (liga/desliga, intervalo em minutos, vida útil em dias), **Documents** (arquivos mudados fora do PGMS, arquivos somente leitura, Open a partir da pasta do arquivo ativo, finais de linha mistos, salvar em segundo plano, codificação ao salvar), **Tabs**, **Task List** (só leitura) e **Windows**; as sete páginas do **SQL Formatter** (caixa das palavras-chave, Format on save, alinhamento, recuo, listas em várias linhas, quebras de linha, espaçamento); Designers ▸ **Table Options** (tempo limite ao salvar, aviso de tabela sem chave primária); Object Explorer ▸ **General** (Hide system objects) e **Commands** (confirmar renomeações); Query Execution ▸ **Live Query Statistics** (intervalo de leitura); Text Editor ▸ **Transact-SQL** (quebra de linha, números de linha, tabulação, IntelliSense para janelas novas). +- **Padrões que seguem o SSMS:** abas novas abrem primeiro, depois das fixadas; consultas não salvas têm cópia a cada 5 minutos; esquemas de sistema (`pg_catalog`, `information_schema`) e bancos modelo aparecem no Object Explorer, nas pastas **System Schemas** e **System Databases**, a primeira pasta em Schemas e em Databases (com Hide system objects ligado, as pastas e seus objetos somem); uma instrução do Table Designer que passe de 3600 segundos interrompe o salvamento e nada é alterado; o Live Query Statistics lê a cada 250 ms; o Format SQL escreve um espaço entre o tipo e os parâmetros (`VARCHAR (20)`). Consultas recuperadas continuam voltando na ordem salva. Qualquer um desses pode ser mudado de volta em Tools ▸ Options. +- **Results to Grid ▸ Show multiple result sets stacked in one tab** (desligada por padrão: uma aba por conjunto de resultados). + +**Editor e janelas** +- **Edit ▸ Paste Special** ▸ Format SQL (cola formatado, um Undo) e Paste with AI…; **Edit ▸ IntelliSense ▸ Switch Completion Mode** (`Ctrl+Alt+Space`); **File ▸ New ▸ File…** (`Ctrl+Alt+N`); **Tools ▸ Code Snippets Manager…** (`Ctrl+K`, `Ctrl+B`). +- **View ▸ Navigate Backward/Forward** (`Ctrl+-`, `Ctrl+Shift+-`), **All Windows** em Full Screen (`Shift+Alt+M`), **Window ▸ Pin Tab** (abas fixadas continuam fixadas quando recuperadas ou reabertas com Restore Closed Tab) e Reset Current Object Explorer Details View; as barras Standard e SQL Editor têm os botões do SSMS na ordem dele. +- As caixas de mensagem são desenhadas pelo PGMS, com os botões no idioma do PGMS, as teclas de sempre (Enter, Esc, letras de acesso), o ícone e o som do sistema, e `Ctrl+C` para copiar o texto. +- Títulos de abas e mensagens compostas são traduzidos; nomes de arquivos e consultas, não. + +**Desempenho e acessibilidade** +- As grades de resultados desenham cada célula com um elemento e expõem menos objetos de automação: rolar e carregar resultados grandes ficou mais rápido. A grade se preenche nos mesmos passos do SSMS (30, 100, 10.000 linhas e depois o fim). +- Quando o PGMS reabre depois de um fechamento inesperado, só a aba recuperada ativa monta o editor na hora; as outras montam quando mostradas. +- Correções de teclado e leitor de tela vindas de uma passada com teclas reais: foco e tamanho das janelas de ferramentas, Tab não fica mais preso nas barras (as barras ficam fora da ordem de Tab, como no SSMS), painéis auto-ocultos e divisores fora da ordem de Tab, nomes lidos pelo Narrador no Connect e em caixas de combinação editáveis. Toda janela agora cabe na área útil da tela, então os diálogos não ficam mais cortados em 175% de escala. Abas, Error List, Output e Schema Compare seguem o tema escuro. ## Downloads -Em [esta release](https://github.com/leoars/PostgresManagementStudio/releases/tag/v0.1.0-alpha.7): +Desta [release](https://github.com/leoars/PostgresManagementStudio/releases/tag/v0.1.0-beta.1): | Arquivo | Finalidade | | --- | --- | -| `PGMS-0.1.0-alpha.7-Setup-x64.exe` | Instalador gráfico (inglês/pt-BR). Usuário atual sem administrador, ou todos os usuários com elevação. Não exige PowerShell nem runtime .NET separado. | -| `PGMS-0.1.0-alpha.7-win-x64.zip` | Aplicativo portátil com runtime .NET/WPF. Extraia a pasta inteira e execute PGMS.exe. Inclui os scripts gerenciados de PowerShell 7. | -| `SHA256SUMS.txt` | SHA256 de cada asset desta release. Hashes conferem correspondência, não autoria. | -| `package-manifest.json` | Manifesto SHA256 de cada arquivo dentro do ZIP, conferido por `Verify-Package.ps1`. | +| `PGMS-0.1.0-beta.1-Setup-x64.exe` | Instalador gráfico (inglês/pt-BR). Usuário atual sem direitos de administrador, ou todos os usuários com elevação. Não exige PowerShell nem runtime .NET separado. | +| `PGMS-0.1.0-beta.1-win-x64.zip` | Aplicativo portátil com runtime .NET/WPF. Extraia a pasta inteira e execute PGMS.exe. Inclui os scripts gerenciados do PowerShell 7. | +| `SHA256SUMS.txt` | SHA256 de cada arquivo desta release. Hashes conferem correspondência, não autoria. | +| `package-manifest.json` | Manifesto SHA256 de cada arquivo dentro do ZIP, conferido pelo `Verify-Package.ps1`. | | `RELEASE-NOTES.md`, `RELEASE-NOTES.pt-BR.md` | Estas notas. | +O instalador atualiza uma instalação existente no lugar; perfis, rascunhos, Query History e configurações ficam em `%LOCALAPPDATA%\PGMS` e não são removidos. A atualização sobre a alpha.7 numa máquina limpa ainda não foi certificada (veja [Validação](#validação)). + ## Confira o que você baixou -Os binários não têm assinatura de código, então o Windows SmartScreen pode avisar na primeira execução. Antes de escolher **Executar assim mesmo**, confira o checksum e a procedência: +Os binários não têm assinatura de código, então o SmartScreen do Windows pode avisar na primeira execução. Antes de escolher **Executar assim mesmo**, confira o checksum e a procedência: ```powershell Get-FileHash .\PGMS-* -Algorithm SHA256 -gh attestation verify .\PGMS-0.1.0-alpha.7-Setup-x64.exe --repo leoars/PostgresManagementStudio +gh attestation verify .\PGMS-0.1.0-beta.1-Setup-x64.exe --repo leoars/PostgresManagementStudio ``` -Compare os hashes com `SHA256SUMS.txt`. O segundo comando precisa do [GitHub CLI](https://cli.github.com/) e confirma que o arquivo foi produzido pelo workflow de release deste repositório no commit da tag; rode-o também para o ZIP. A assinatura de código pelo programa de código aberto da SignPath Foundation está planejada; não há data prometida. +Compare os hashes com o `SHA256SUMS.txt`. O segundo comando precisa do [GitHub CLI](https://cli.github.com/) e confirma que o arquivo foi produzido pelo workflow de release deste repositório no commit da tag; rode também para o ZIP. A assinatura de código pelo programa de código aberto da SignPath Foundation está planejada, sem data prometida. ## Relatar um problema -Quando o PGMS mostrar a janela de erro inesperado, escolha **Report Issue** e anexe o log de **Open Log Folder** (`%LOCALAPPDATA%\PGMS\logs`). Diga o que você estava fazendo, a versão do PostgreSQL e se o erro se repete. Leia o log antes de anexar: uma mensagem de erro pode citar o que o servidor enviou. Use os [modelos de issue](https://github.com/leoars/PostgresManagementStudio/issues/new/choose). +Quando o PGMS mostrar a janela de erro inesperado, escolha **Report Issue** e anexe o log de **Open Log Folder** (`%LOCALAPPDATA%\PGMS\logs`). Para qualquer outro problema, [abra um relato de defeito](https://github.com/leoars/PostgresManagementStudio/issues/new?template=bug_report.yml): ele pede a versão do PGMS (Help ▸ About), as versões do Windows e do PostgreSQL, a forma de instalação, o idioma da interface, os passos e o log quando houver. Leia o log antes de anexar: uma mensagem de erro pode citar o que o servidor enviou. Problemas de tradução têm [formulário próprio](https://github.com/leoars/PostgresManagementStudio/issues/new?template=translation.yml). ## Escopo -Editor SQL com IntelliSense e sessões independentes, Object Explorer, Results paginados e Results to Text/File, exportação CSV/JSON, diagramas de banco e designers, planos gráficos, administração PostgreSQL revisada, identity/privilégios, Activity Monitor, estatísticas de consultas, Schema Compare e backup/restore lógico. PostgreSQL 16 a 18 e ferramentas cliente da mesma versão principal são necessários para operações de banco e backup/restore; servidor e ferramentas não acompanham. O SSMS não é necessário nem distribuído. +Editor SQL com IntelliSense e sessões independentes, Object Explorer, Results paginado e Results to Text/File, exportação CSV/JSON, diagramas de banco e designers, planos gráficos, em texto e em JSON com comparação, administração PostgreSQL revisada, identidade/privilégios, Activity Monitor, estatísticas de consultas, Query History, Schema Compare, backup/restore lógico e o assistente de IA. PostgreSQL 16 a 18 e ferramentas cliente da mesma versão principal são necessários para operações no banco e backup/restore; servidor e ferramentas não acompanham o pacote. O SSMS não é necessário nem distribuído. ## Validação -Comportamento do aplicativo: a fonte M1117 passou na regressão completa deste repositório no PostgreSQL 17.11 (ver [validação](validation.md#v010-alpha7--m1117--17112026)) num cluster isolado em loopback; o serviço PostgreSQL do host não é usado. A maior parte das funções acrescentadas desde a alpha.6 foi validada por recortes automatizados durante a construção; a última regressão completa no PostgreSQL 16.15 e 18.6 foi sobre uma fonte anterior (M1066). As ações novas de IA e a conversa foram testadas só com um provedor falso local, não com um real. O PostGIS não foi instalado no cluster de testes: foi usado um tipo `geometry` substituto. +Comportamento do aplicativo: a fonte M1145 passou na regressão completa deste repositório no PostgreSQL 17.11, e a fonte M1141 (as mesmas funções sem as seis mudanças de padrão do M1143 e as pastas de sistema do M1145) passou no 16.15, 17.11 e 18.6 (veja [validação](validation.md#v010-beta1--m1145--20112026)), num cluster isolado em loopback; o serviço PostgreSQL do host não é usado. Navegação só pelo teclado com teclas reais, Narrador, escala de 100/150/175% em três temas e três idiomas e os cenários de desempenho do projeto foram conferidos na máquina do mantenedor antes das mudanças de padrão. O PostGIS foi testado com o pacote oficial PostGIS 3.7.0 no PostgreSQL 17.11. As funções de IA foram testadas com um provedor falso local, não com um real. -Instalação numa VM Windows limpa, outro usuário Windows sem privilégios e observações físicas de DPI, teclado e leitor de tela das telas novas não são certificadas por esta release. +Instalação numa VM Windows limpa e por outro usuário Windows sem privilégios não são certificadas por esta release. ## Limites conhecidos -Somente Windows x64. Executável e instalador sem assinatura; o SmartScreen avisa. Sem MSI, atualização automática ou garantia de suporte em produção. Não há alegação de paridade integral com o SSMS. Tema escuro: diagramas e planos continuam claros; não há temas coloridos. Um cursor só (sem cursores múltiplos). Vários conjuntos de resultados aparecem em abas, não empilhados. Live Query Statistics não tem plano ao vivo. Valores do PostGIS aparecem como texto hexadecimal, sem WKT, GeoJSON ou mapa. Resultados: ordenação, cópia e exportação valem para a página atual; as linhas depois da primeira página ficam num arquivo temporário, sem criptografia, até a próxima execução ou até fechar a aba; Results to Text mantém os limites de 10.000 linhas e 250.000 células, e Results to File não tem nenhum dos dois. O IntelliSense não conhece colunas de CTE, tabelas temporárias nem o `SET search_path` da sessão. Query Designer: `UNION` e `WITH` abrem só no painel SQL. Find Missing Foreign Keys é uma heurística: um nome parecido é pista, não prova. O log de erros mascara senhas só no formato `chave=valor`. +Só Windows x64. Executável e instalador sem assinatura; o SmartScreen avisa. Sem MSI, winget ou atualização automática (só o aviso de nova versão). Não há alegação de paridade completa com o SSMS. Traduções sem revisão nativa. Um cursor só (sem múltiplos cursores). O Live Query Statistics não tem plano ao vivo, porque o PostgreSQL não tem contadores por operador enquanto a consulta roda; não há Analyze de plano. O OpenAI não foi testado com chave real. O Configure Server TLS precisa de servidor Windows e superusuário. Executar uma consulta de 10.000 × 20 com cinco abas abertas pode pausar a interface por cerca de 0,4 s, e reabrir cinco rascunhos recuperados leva cerca de 2 s. Com objetos de sistema visíveis, o `template0` aparece Offline e não pode ser expandido (ele não aceita conexões). Resultados: ordenação, cópia e exportação valem para a página atual; as linhas depois da primeira página ficam num arquivo temporário, sem criptografia, até a próxima execução ou até a aba fechar. O IntelliSense não conhece colunas de CTE, tabelas temporárias nem o `SET search_path` da sessão. Query Designer: `UNION` e `WITH` abrem só no painel SQL. O log de erros mascara senhas só na forma `chave=valor`. ## Versões anteriores -v0.1.0-alpha.6 (13/11/2026, índices e descrições nos diagramas, Query History, Script as, avisos no plano) e v0.1.0-alpha.5 (08/11/2026, diagramas de banco, Query Designer, IntelliSense; Apache-2.0) continuam disponíveis com seus assets e notas originais. v0.1.0-alpha.4 (07/11/2026, Activity Monitor em aba), v0.1.0-alpha.3 (02/11/2026, Query Statistics), v0.1.0-alpha.2 (01/11/2026, primeira release do CI com atestado) e v0.1.0-alpha.1 (31/10/2026) continuam disponíveis com seus assets e notas originais, sob MIT. +v0.1.0-alpha.7 (17/11/2026, conversa com a IA, tema escuro, log de erros), v0.1.0-alpha.6 (13/11/2026, índices e descrições no diagrama, Query History, Script as, avisos no plano) e v0.1.0-alpha.5 (08/11/2026, diagramas de banco, Query Designer, IntelliSense; Apache-2.0) continuam disponíveis com os arquivos e notas originais. v0.1.0-alpha.4 (07/11/2026), v0.1.0-alpha.3 (02/11/2026), v0.1.0-alpha.2 (01/11/2026, primeira release gerada pelo CI com atestado) e v0.1.0-alpha.1 (31/10/2026) continuam disponíveis com os arquivos e notas originais, sob MIT. diff --git a/docs/pt-BR/user-guide.md b/docs/pt-BR/user-guide.md index a2b2809..5fba88a 100644 --- a/docs/pt-BR/user-guide.md +++ b/docs/pt-BR/user-guide.md @@ -36,6 +36,8 @@ No Object Explorer, clique com o botão direito em **Database Diagrams**, dentro **Display Estimated Execution Plan** (`Ctrl+L`) e **Include Actual Execution Plan** (`Ctrl+M`) desenham o plano como operadores ligados por setas proporcionais às linhas. **Avisos.** No plano real, um operador cujo filtro descartou muitas linhas ganha um triângulo amarelo, e a dica e as propriedades dele têm uma seção **Warnings** com as contagens de Filter, Join Filter e Index Recheck. É uma regra do PGMS, não um aviso do PostgreSQL: por padrão aparece quando as linhas descartadas são pelo menos 10 vezes as retornadas e pelo menos 1.000, valores ajustáveis em **Query Options ▸ Execution ▸ Advanced** e, para abas novas, em **Tools ▸ Options**. **Índice faltante.** Quando uma varredura com aviso filtra por comparações simples, o cabeçalho do plano ganha uma linha verde com a sugestão de índice e o menu habilita **Missing Index Details…**, que abre uma aba de consulta com o `CREATE INDEX` (e uma variante `CONCURRENTLY`) comentado; nada é executado. A sugestão é uma heurística (colunas de igualdade primeiro, depois o `ORDER BY` sob um `LIMIT` ou uma coluna de faixa) conferida no catálogo, então não aparece quando um índice b-tree válido já começa por essas colunas. Não cobre junções, `OR`, expressões nem `INCLUDE`, e não estima seletividade: teste antes de criar o índice. +**Texto, JSON e comparação.** O menu de contexto de um plano (na aba da consulta ou na aba própria) tem **Show Execution Plan JSON**, o JSON do servidor indentado numa aba nova, e **Show Execution Plan as Text**, o layout do `EXPLAIN` em texto montado a partir desse JSON sem executar a consulta de novo. **Compare Showplan** compara o plano com um arquivo de plano salvo, e **Compare with Previous Plan**, com o plano que a mesma aba tinha antes. A aba **Showplan Comparison** mostra os dois planos lado a lado; operadores casados por nome e profundidade que têm outros valores ficam sombreados em âmbar nos dois desenhos, operadores que só existem num plano ficam em rosa, e a grade **Differences** lista os totais e cada operador. Não há Analyze, que no SSMS procura cenários do SQL Server. + ## Gerar SQL com IA **Query ▸ Generate SQL with AI…** envia o seu pedido e a estrutura do banco (nomes, tipos, chaves, comentários; nunca dados das tabelas) ao provedor configurado em **Tools ▸ AI Assistant Settings…**: Anthropic, OpenAI ou um Ollama local, com a sua própria chave, guardada criptografada para o seu usuário do Windows. O SQL aparece para revisão e só é inserido no editor. A estrutura enviada é limitada pelo **Context limit** das configurações (200.000 caracteres por padrão). Quando o banco não cabe, o PGMS primeiro envia só os nomes das tabelas, com os comentários, e deixa o provedor escolher as relevantes; depois envia essas tabelas, as tabelas que as chaves estrangeiras delas referenciam e as tabelas cujos nomes têm palavras em comum com o pedido. As que ficam de fora são listadas pelo nome. **View Sent Context…** mostra o que foi enviado em cada chamada. A primeira chamada também consome tokens. @@ -113,19 +115,37 @@ Quando o servidor informa a posição de um erro, o editor o sublinha, a barra d Uma linha com mais de 10.000 caracteres aparece cortada, com um marcador que abre a linha inteira; o arquivo e o SQL executado não mudam. +**Edit ▸ Paste Special ▸ Format SQL** cola a área de transferência formatada (um Undo), e **Paste with AI…** abre o Generate SQL with AI com o SQL colado; nada é enviado antes de Generate. **Edit ▸ IntelliSense ▸ Switch Completion Mode** (`Ctrl+Alt+Space`) alterna o modo de sugestão, em que `Enter` mantém o que você digitou e `Tab` insere a sugestão. **File ▸ New ▸ File…** (`Ctrl+Alt+N`) cria um arquivo SQL, um arquivo de texto ou um arquivo SQL a partir de um modelo, e **Tools ▸ Code Snippets Manager…** (`Ctrl+K`, `Ctrl+B`) importa arquivos `.snippet` para a sua pasta de trechos. + ## Abas, janelas e configurações -**File ▸ New ▸ Query with Current Connection** (`Ctrl+N`) usa a conexão da aba ativa ou do Object Explorer; **Database Engine Query** pede uma. **Open ▸ File…** conecta a aba nova do mesmo jeito, e **File Disconnected…** abre sem conectar. **File ▸ Recent Files**, **Save All**, **Window ▸ Close All Tabs** e **Restore Closed Tab** funcionam como no SSMS; uma consulta fechada sem arquivo volta com o texto, desconectada. **Window** também tem **Next/Previous Pane** (`F6`/`Shift+F6`), **Show Results Pane** (`Ctrl+R`), **Split Tab**, **Dock**, **Auto Hide**, **Move To New Window**, até dez layouts de janela salvos e **Auto Hide All**; **View ▸ Full Screen** é `Shift+Alt+Enter`. +**File ▸ New ▸ Query with Current Connection** (`Ctrl+N`) usa a conexão da aba ativa ou do Object Explorer; **Database Engine Query** pede uma. **Open ▸ File…** conecta a aba nova do mesmo jeito, e **File Disconnected…** abre sem conectar. **File ▸ Recent Files**, **Save All**, **Window ▸ Close All Tabs** e **Restore Closed Tab** funcionam como no SSMS; uma consulta fechada sem arquivo volta com o texto, desconectada. **Window** também tem **Next/Previous Pane** (`F6`/`Shift+F6`), **Show Results Pane** (`Ctrl+R`), **Split Tab**, **Dock**, **Auto Hide**, **Move To New Window**, até dez layouts de janela salvos e **Auto Hide All**; **View ▸ Full Screen** é `Shift+Alt+Enter`, e em Full Screen **View ▸ All Windows** (`Shift+Alt+M`) esconde e mostra as janelas de ferramentas. **View ▸ Navigate Backward/Forward** (`Ctrl+-`, `Ctrl+Shift+-`) volta a lugares anteriores: trocas de aba e saltos de dez linhas ou mais. **Window ▸ Pin Tab** mantém uma aba no início, com um alfinete, e **Close All Tabs** a deixa aberta; uma aba fixada continua fixada quando é recuperada depois de uma falha ou reaberta com Restore Closed Tab. As caixas de mensagem são desenhadas pelo PGMS, no idioma do PGMS, com `Enter`, `Esc`, letras de acesso e `Ctrl+C` para copiar o texto. O menu divide a barra de título com os botões da janela e o **Search** (`Ctrl+Q`), que encontra comandos do menu e páginas e configurações de Tools ▸ Options; `Enter` executa ou abre o resultado. **View ▸ Properties Window** (`F4`) mostra a sessão da consulta ativa (servidor, login, banco, PID do backend, versão, modo SSL, última execução). **View ▸ Error List** (`Ctrl+\`, `E`) tem o erro da última execução de cada aba aberta; o duplo clique vai até ele. **View ▸ Output** (`Ctrl+Alt+O`) guarda as mensagens e execuções da sessão (5.000 linhas na memória). **File ▸ Page Setup…** e **Print…** imprimem o SQL da aba ativa. -**Tools ▸ Options** inclui **Fonts and Colors** (editor, Grid Results e Text Results), **Keyboard** (um atalho por comando do menu, que ganha do atalho embutido), **Query Shortcuts** (`Alt+F1`, `Ctrl+1` a `Ctrl+0`, vazios por padrão; o texto roda na sessão da aba ativa, seguido da seleção), **Scripting** do Object Explorer, **Designers** e **Connection Dialog**. **Tools ▸ Theme** escolhe Light, Dark ou a configuração do Windows; no Dark, diagramas e planos gráficos continuam claros. **Tools ▸ Editor Appearance** define as cores do editor separadamente, com dois modos de contraste extra, e **View ▸ Presenter Mode** (`Ctrl+Shift+F5`) aumenta o texto do editor, dos resultados e da janela durante a sessão. **Tools ▸ Import and Export Settings…** salva, carrega ou redefine as opções num arquivo `.pgmssettings` (sem posição da janela, arquivos recentes, conexões, senhas ou configurações de IA). **Tools ▸ External Tools…** acrescenta programas ao menu Tools, executados só quando você os escolhe, e **Tools ▸ Customize…** mostra ou esconde as barras de ferramentas. +**Tools ▸ Options** inclui **Fonts and Colors** (editor, Grid Results e Text Results), **Keyboard** (um atalho por comando do menu, que ganha do atalho embutido), **Query Shortcuts** (`Alt+F1`, `Ctrl+1` a `Ctrl+0`, vazios por padrão; o texto roda na sessão da aba ativa, seguido da seleção), **Scripting** do Object Explorer, **Designers** e **Connection Dialog**. **Tools ▸ Theme** lista os 13 temas do SSMS na ordem dele (Cool Breeze é o padrão; Light é o cinza do SSMS; Dark; e os temas coloridos) e **Use system setting** (Cool Breeze com o Windows claro, Dark com o Windows escuro); no Dark, diagramas e planos gráficos continuam claros. **Tools ▸ Editor Appearance** define as cores do editor separadamente, com dois modos de contraste extra, e **View ▸ Presenter Mode** (`Ctrl+Shift+F5`) aumenta o texto do editor, dos resultados e da janela durante a sessão. **Tools ▸ Import and Export Settings…** salva, carrega ou redefine as opções num arquivo `.pgmssettings` (sem posição da janela, arquivos recentes, conexões, senhas ou configurações de IA). **Tools ▸ External Tools…** acrescenta programas ao menu Tools, executados só quando você os escolhe, e **Tools ▸ Customize…** mostra ou esconde as barras de ferramentas. + +Mais páginas de Options seguem o SSMS 22.11; opções que o PGMS não consegue aplicar aparecem desabilitadas com o motivo: + +- **Environment ▸ AutoRecover:** cópia das consultas não salvas a cada 5 minutos por padrão (1 a 60), e descarte de cópias com mais de 7 dias. Uma falha perde no máximo as mudanças do último intervalo. +- **Environment ▸ Documents:** um arquivo mudado fora do PGMS é recarregado quando o PGMS fica ativo (pergunta antes se a aba tem mudanças não salvas); arquivos somente leitura abrem sem edição, a menos que permitido; File ▸ Open começa na pasta do arquivo ativo; finais de linha mistos podem ser normalizados para CRLF ao abrir; salvar em segundo plano quando o PGMS perde o foco; salvar todo arquivo numa codificação Unicode escolhida. +- **Environment ▸ Tabs:** **Insert new tabs to the right of existing tabs** fica desligada por padrão, como no SSMS, então uma aba nova vai primeiro, depois das fixadas. Consultas recuperadas sempre voltam depois das abas abertas, na ordem salva. **Windows:** aplicar um layout de janela salvo pergunta antes, a menos que a confirmação seja pulada. +- **SQL Formatter** (sete páginas): caixa das palavras-chave, Format on save, corpos de cláusula alinhados, tamanho do recuo, listas em várias linhas, quebras de linha antes de cláusulas e junções, linhas em branco entre instruções e espaço entre o tipo e os parâmetros (ligado por padrão, `VARCHAR (20)`). +- **Designers ▸ Table Options:** uma instrução do Table Designer que passe do tempo limite (ligado, 3600 segundos) interrompe o salvamento e nada é alterado; aviso opcional antes de salvar uma tabela sem chave primária. +- **Object Explorer ▸ General:** **Hide system objects** fica desligada por padrão, como no SSMS: `pg_catalog` e `information_schema` aparecem na pasta **System Schemas**, a primeira dentro de Schemas, e os bancos modelo em **System Databases**, a primeira dentro de Databases. Ligada, as pastas e seus objetos somem. Uma mudança aparece depois de atualizar. **Commands:** renomear uma chave, restrição ou gatilho no lugar pergunta antes. +- **Query Execution ▸ Live Query Statistics:** a frequência de leitura das estatísticas ao vivo (250 ms por padrão). +- **Text Editor ▸ Transact-SQL:** quebra de linha, números de linha, tamanho da tabulação e espaços, e IntelliSense. +- **Environment ▸ International Settings:** o idioma da interface (veja abaixo). **Product Updates:** o aviso de nova versão. + +**Idiomas.** A interface está disponível em English, Português (Brasil), Español, Deutsch, Italiano, Français, 한국어 e 日本語. **Same as Microsoft Windows** (o padrão) segue o idioma de exibição do Windows, ou inglês quando o Windows usa outro; o idioma muda quando o PGMS abre de novo. Nomes das pastas do Object Explorer, nomes de comando da página Keyboard, SQL, dados e mensagens do servidor ficam em inglês ou como estão. As traduções ainda não foram revisadas por falantes nativos; relate problemas pelo [formulário de tradução](https://github.com/leoars/PostgresManagementStudio/issues/new?template=translation.yml). + +**Aviso de nova versão.** Alguns segundos depois de abrir, um pacote de release pede à API do GitHub (`api.github.com`) a lista de releases do PGMS; o GitHub vê o seu endereço IP, como em qualquer acesso à web, e nada mais é enviado. Quando existe versão mais nova, **Update available** aparece na barra de título, ao lado do Search, com **Open the release page**, **Skip This Version** e as opções. Nada é baixado nem instalado. **Help ▸ Check for Updates** pergunta na hora; **Tools ▸ Options ▸ Environment ▸ Product Updates** desliga a consulta automática. Uma falha da consulta automática é silenciosa. ## Resultados e consultas em execução -As abas Results, Messages, do plano e da sessão ficam acima dos resultados. **Save Results As…** no menu da grade abre **Save Grid Results**: um arquivo `.csv` separado por vírgulas ou `.txt` separado por tabulações, sempre com cabeçalhos, com a página atual. **Export Options…** abre a faixa de exportação CSV/JSON. Vários conjuntos de resultados de uma execução aparecem em abas. Valores de tipos de extensões, como o `geometry` do PostGIS, aparecem como o texto que o servidor envia (EWKB em hexadecimal); um tipo criado com o PGMS aberto aparece como `unknown type (oid N)` até você reconectar. +As abas Results, Messages, do plano e da sessão ficam acima dos resultados. **Save Results As…** no menu da grade abre **Save Grid Results**: um arquivo `.csv` separado por vírgulas ou `.txt` separado por tabulações, sempre com cabeçalhos, com a página atual. **Export Options…** abre a faixa de exportação CSV/JSON. Vários conjuntos de resultados de uma execução aparecem em abas, ou empilhados numa aba quando **Tools ▸ Options ▸ Query Results ▸ Results to Grid ▸ Show multiple result sets stacked in one tab** está ligada. Valores `geometry` e `geography` do PostGIS aparecem como EWKT (`SRID=4326;POINT(1 2)`, o mesmo texto do `ST_AsEWKT`) na grade, no Results to Text, na cópia e na exportação, e o Table Designer aceita tipos como `geometry(Point,4326)`. Outros tipos de extensões aparecem como o texto que o servidor envia; depois de um tipo que o PGMS ainda não conhece, a sessão relê os tipos. -**Query ▸ Include Live Query Statistics** acrescenta uma aba que, uma vez por segundo e por uma conexão separada, mostra o estado, o tempo decorrido, as esperas e os PIDs que bloqueiam a consulta em execução, e o progresso informado por `pg_stat_progress_*` para CREATE INDEX, VACUUM, ANALYZE, CLUSTER e COPY. O PostgreSQL não tem contadores por operador durante a execução, então não há plano ao vivo. +**Query ▸ Include Live Query Statistics** acrescenta uma aba que, a cada 250 ms por padrão (Tools ▸ Options ▸ Query Execution ▸ Live Query Statistics) e por uma conexão separada, mostra o estado, o tempo decorrido, as esperas e os PIDs que bloqueiam a consulta em execução, e o progresso informado por `pg_stat_progress_*` para CREATE INDEX, VACUUM, ANALYZE, CLUSTER e COPY. O PostgreSQL não tem contadores por operador durante a execução, então não há plano ao vivo. ## Novidades no Object Explorer @@ -141,4 +161,4 @@ Um erro que o PGMS não tratou é gravado num log diário em `%LOCALAPPDATA%\PGM ## Salvar e recuperar -Salve arquivos SQL explicitamente. Recuperação em background mantém rascunhos criptografados com limites e pode reabri-los desconectados após interrupção. Revise abas recuperadas e use **Save As**. Isso não é sistema de backup nem prova de persistência de cada última tecla. Alterações externas conflitantes no arquivo são recusadas. Feche o app antes de copiar estado local; DPAPI depende do usuário Windows. Builds anteriores a M934 não leem o contêiner de recuperação mais recente. Veja a [validação](validation.md) para a recuperação entre versões realmente testada. +Salve arquivos SQL explicitamente. Recuperação em background (a cada 5 minutos por padrão; veja Tools ▸ Options ▸ Environment ▸ AutoRecover) mantém rascunhos criptografados com limites e pode reabri-los desconectados após interrupção. Revise abas recuperadas e use **Save As**. Isso não é sistema de backup nem prova de persistência de cada última tecla. Alterações externas conflitantes no arquivo são recusadas. Feche o app antes de copiar estado local; DPAPI depende do usuário Windows. Builds anteriores a M934 não leem o contêiner de recuperação mais recente. Veja a [validação](validation.md) para a recuperação entre versões realmente testada. diff --git a/docs/pt-BR/validation.md b/docs/pt-BR/validation.md index 1d1210a..fcedb15 100644 --- a/docs/pt-BR/validation.md +++ b/docs/pt-BR/validation.md @@ -2,7 +2,7 @@ [English](../en/validation.md) | Português (Brasil) -Pré-release atual: v0.1.0-alpha.7, rótulo M1117 (acrescenta à fonte M1062 da alpha.6 a conversa e Explain/Fix/Optimize da IA, o tema escuro e as configurações de aparência, o registro de erros inesperados, muitos comandos do editor, das janelas e do Object Explorer, Schema Compare, Live Query Statistics e restore paralelo/parcial; gerada pelo workflow de release no GitHub Actions com atestado de proveniência; veja as [notas da versão](release-notes.md)). Anterior: v0.1.0-alpha.6, rótulo M1062 (acrescenta índices, descrições e Export for AI nos diagramas, Query History, Script as, avisos e sugestão de índice nos planos e a escolha de tabelas do SQL assistido por IA em bancos grandes à fonte M1053 da alpha.5; compilada pelo workflow de release no GitHub Actions com atestado de proveniência de build). Marcos são identificadores internos, não garantia de identidade binária de uma recompilação local. A importação pública inicial usou M1002. Histórico operacional e provas brutas privados não são incluídos intencionalmente. +Pré-release atual: v0.1.0-beta.1, rótulo M1145, o primeiro beta (acrescenta à fonte M1117 da alpha.7 a interface em 8 idiomas, os temas coloridos do SSMS, planos em texto/JSON e Compare Showplan, valores PostGIS em EWKT, o aviso de nova versão, mais páginas de Options do SSMS com os padrões dele, caixas de mensagem do PGMS e correções de teclado, escala e desempenho; veja as [notas da versão](release-notes.md)). Anterior: v0.1.0-alpha.7, rótulo M1117 (acrescenta à fonte M1062 da alpha.6 a conversa e Explain/Fix/Optimize da IA, o tema escuro e as configurações de aparência, o registro de erros inesperados, muitos comandos do editor, das janelas e do Object Explorer, Schema Compare, Live Query Statistics e restore paralelo/parcial; gerada pelo workflow de release no GitHub Actions com atestado de proveniência; veja as [notas da versão](release-notes.md)). Anterior: v0.1.0-alpha.6, rótulo M1062 (acrescenta índices, descrições e Export for AI nos diagramas, Query History, Script as, avisos e sugestão de índice nos planos e a escolha de tabelas do SQL assistido por IA em bancos grandes à fonte M1053 da alpha.5; compilada pelo workflow de release no GitHub Actions com atestado de proveniência de build). Marcos são identificadores internos, não garantia de identidade binária de uma recompilação local. A importação pública inicial usou M1002. Histórico operacional e provas brutas privados não são incluídos intencionalmente. A implementação importada passou anteriormente em 5.187 checks automatizados (2.115 integração PostgreSQL e 3.072 WPF), além de abertura de pacote, preservação de perfil instalado e recuperação de três rascunhos entre rollback/reinício. São observações históricas, não testes novos a cada revisão. Reproduza o comportamento atual pelos scripts públicos e informe ambiente/resultados reais. As verificações da revisão pública inicial são registradas abaixo após execução. @@ -38,6 +38,12 @@ Uma execução completa passou em 2.236 checks de integração + 3.315 WPF = 5.5 Durante o desenvolvimento, a janela foi comparada com o Query Store do SSMS 22.11 sob carga sintética idêntica, contra SQL Server LocalDB e o cluster PostgreSQL descartável. Os dois listaram os mesmos statements com contagens iguais. Diferenças encontradas na época: uma janela em vez de sete relatórios do Query Store; contadores acumulados do servidor em vez de intervalos de tempo por banco; sem gráfico, plano, leituras lógicas ou ordenação pelo cabeçalho; registros inteiros expostos como nome das linhas a leitores de tela. Ordenação pelo cabeçalho, métricas de I/O e blocos, planos genéricos, gráfico top-N, janelas de tempo e nomes curtos de linha foram acrescentados depois. Diferenças que permanecem: uma janela em vez de relatórios separados, janelas calculadas subtraindo amostras em vez de intervalos armazenados, e sem tempo de CPU por statement, que o PostgreSQL não registra. Observações físicas de DPI e leitor de tela desta janela não recebem nova certificação. +## v0.1.0-beta.1 / M1145 — 20/11/2026 + +No repositório de desenvolvimento, a fonte M1145 (o M1143 mais as pastas System Databases e System Schemas do Object Explorer) passou na regressão completa no PostgreSQL 17.11: 3.151 verificações de integração + 5.781 WPF = 8.932, na primeira tentativa, num cluster descartável em loopback com `pg_stat_statements` pré-carregado. A fonte M1143 tinha passado no 17.11 com 3.151 + 5.770 = 8.921. A fonte M1141, com as mesmas funções e os padrões anteriores, tinha passado no 16.15 (3.093 + 5.728 = 8.821), 17.11 e 18.6 (3.151 + 5.762 = 8.913 cada); as rodadas do 17.11 e do 18.6 passaram na segunda tentativa (um teste desatualizado da ordem das páginas de Options, depois atualizado, e uma exceção intermitente do driver num teste de cancelamento das estatísticas ao vivo, que passou sem mudança). O M1143 muda só padrões da interface e o M1145 só agrupa as mesmas linhas do catálogo em pastas; nenhum dos dois foi repetido no 16.15 e no 18.6. A diferença no 16.15 vem de verificações que só valem a partir do 17 (`MAINTAIN`, `pg_dump --filter`). + +Gates do beta rodados na máquina do mantenedor antes das mudanças de padrão do M1143: navegação só pelo teclado nas telas novas com teclas reais (22 verificações), Narrador ouvido pelo mantenedor, escala de 100/150/175 % em Cool Breeze, Dark e Light com inglês, coreano e japonês (200 % não era possível naquele monitor) e os cenários de desempenho do projeto. Dois limites de desempenho foram aceitos: executar uma consulta de 10.000 × 20 com cinco abas abertas pausa a interface por 350–460 ms (limite 250 ms), e restaurar cinco rascunhos recuperados leva cerca de 2,05 s (limite 2 s). O PostGIS rodou com o pacote oficial PostGIS 3.7.0 numa cópia dos binários do PostgreSQL 17.11. As funções de IA rodaram contra um provedor falso local. VM Windows limpa, outro usuário Windows e atualização sobre a alpha.7 numa máquina limpa não foram testados. As traduções são traduções automáticas conferidas por script quanto a marcadores e teclas de acesso, sem revisão de falantes nativos. + ## v0.1.0-alpha.7 / M1117 — 17/11/2026 Uma execução completa passou em 3.135 verificações de integração + 5.440 WPF = 8.575 no PostgreSQL 17.11, num cluster descartável em loopback com `pg_stat_statements` pré-carregado, na primeira tentativa. O pacote self-contained gerado localmente passou na verificação do manifesto (526 arquivos), nas conferências de guias e do arquivo, no teste de abertura e numa instalação e remoção gráfica por usuário; a instalação global não foi executada. O teste de abertura agora cancela o Connect que o PGMS abre na inicialização antes de fechar a janela principal: ele vinha falhando de forma intermitente porque o diálogo podia abrir antes do pedido de fechamento. No repositório de desenvolvimento, as funções acrescentadas desde a alpha.6 foram validadas por recortes enquanto eram construídas; a regressão completa no PostgreSQL 16.15 e 18.6 só rodou numa fonte anterior (M1066). A conversa e o Explain/Fix/Optimize da IA rodaram com um provedor falso local, não com um real. O PostGIS não foi instalado: foi usado um tipo `geometry` substituto. O tratamento de erros inesperados foi exercitado pelos mesmos métodos que os tratadores globais chamam; os tratadores não foram disparados por uma falha real. As telas novas foram exercitadas por testes automatizados e, no tema escuro e na barra de título, à mão com teclado e mouse num monitor a 100 %; não foram usados VM Windows limpa nem leitores de tela. diff --git a/installer/release.json b/installer/release.json index 8407a43..dbe0d7e 100644 --- a/installer/release.json +++ b/installer/release.json @@ -1,6 +1,6 @@ { - "Version": "0.1.0-alpha.7", - "NumericVersion": "0.1.0.7", - "Milestone": "M1117", - "ManifestSha256": "40D3EE2B8737B00DD928C14B9AFDB1B9C709512D521BDCA39083FCEBC4A5A75F" + "Version": "0.1.0-beta.1", + "NumericVersion": "0.1.0.8", + "Milestone": "M1145", + "ManifestSha256": "4303645EFF46C7C2929222B5B8800F8CECF0F2C4FAA98DDC4AB181330353DBC5" } 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/BuildInfo.cs b/src/PGMS.Desktop/BuildInfo.cs index 5a5fd6b..822849f 100644 --- a/src/PGMS.Desktop/BuildInfo.cs +++ b/src/PGMS.Desktop/BuildInfo.cs @@ -2,5 +2,5 @@ namespace PGMS.Desktop; public static class BuildInfo { - public const string Milestone = "M1117"; + public const string Milestone = "M1145"; } 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..4d2f018 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(); @@ -140,7 +157,8 @@ internal static string PathOf(CatalogNode node) CatalogKind.DataType => entry.DataTypeKind switch { "e" => "Enum", "d" => "Domain", "c" => "Composite Type", "r" => "Range Type", _ => "Data Type" }, CatalogKind.Databases or CatalogKind.Schemas or CatalogKind.Tables or CatalogKind.Views or CatalogKind.MaterializedViews or CatalogKind.Sequences or CatalogKind.Functions or CatalogKind.Procedures or CatalogKind.Columns or CatalogKind.Indexes or CatalogKind.Roles or CatalogKind.Enums or CatalogKind.Domains or CatalogKind.DatabaseDiagrams or CatalogKind.Keys or CatalogKind.Constraints or CatalogKind.Triggers or CatalogKind.Extensions - or CatalogKind.CompositeTypes or CatalogKind.ForeignServers or CatalogKind.Replication or CatalogKind.Publications or CatalogKind.Subscriptions => "Folder", + or CatalogKind.CompositeTypes or CatalogKind.ForeignServers or CatalogKind.Replication or CatalogKind.Publications or CatalogKind.Subscriptions + or CatalogKind.SystemDatabases or CatalogKind.SystemSchemas => "Folder", CatalogKind.DatabaseDiagram => "Database Diagram", _ => WordBreak().Replace(entry.Kind.ToString(), " ") }; 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..3eaa68f 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 @@ - - - - + + + + +