From af68e796497459842b1745fddd7a2aea77a8e4f8 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Thu, 12 Nov 2026 13:38:01 +0700 Subject: [PATCH 1/4] perf(windows): load restored table tabs when shown, read the row estimate first, share the editor device, stop the idle caret and drop unused Windows App SDK components --- .../fix-issue/references/platform-windows.md | 4 +- .../references/verification-windows.md | 2 +- .../fix-issue/scripts/lib/platform-windows.sh | 2 +- core/crates/ffi/src/lib.rs | 2 +- core/crates/ffi/src/session.rs | 42 ++++- core/crates/ffi/tests/browse.rs | 28 ++- .../0022-browsing-through-the-ffi.md | 2 +- windows/AGENTS.md | 4 +- windows/Directory.Packages.props | 3 + windows/TablePro.slnx | 1 + .../docs/decisions/0002-sql-editor-control.md | 3 +- windows/docs/decisions/0004-app-shell.md | 4 +- windows/docs/decisions/0005-distribution.md | 7 +- .../src/TablePro.App.Model/ObjectFolders.cs | 60 ++++-- windows/src/TablePro.App.Model/RunResults.cs | 12 +- windows/src/TablePro.App.Model/TabSession.cs | 6 + windows/src/TablePro.App.Model/TablePage.cs | 3 + windows/src/TablePro.App.Model/TableTab.cs | 123 ++++++++++-- .../TablePro.App/Strings/en-US/Resources.resw | 12 ++ windows/src/TablePro.App/TablePro.App.csproj | 5 +- .../TablePro.App/Views/ResultsPane.xaml.cs | 7 +- .../src/TablePro.App/Views/TableTabView.xaml | 1 + .../TablePro.App/Views/TableTabView.xaml.cs | 41 +++- .../TablePro.App/Views/WorkspaceView.xaml.cs | 84 +++++++-- .../TablePro.DataGrid.csproj | 2 +- .../src/TablePro.Editor.Model/CaretBlink.cs | 81 ++++++++ .../src/TablePro.Editor/Rendering/Palette.cs | 7 + .../src/TablePro.Editor/SqlEditor.Caret.cs | 129 +++++++++++++ .../src/TablePro.Editor/SqlEditor.Keyboard.cs | 1 + .../src/TablePro.Editor/SqlEditor.Pointer.cs | 1 + .../src/TablePro.Editor/SqlEditor.Render.cs | 11 +- windows/src/TablePro.Editor/SqlEditor.cs | 115 +++++++----- .../TablePro.Editor/TablePro.Editor.csproj | 6 +- .../src/TablePro.Graphics/GraphicsDevice.cs | 119 +++++++++--- windows/src/TablePro.Graphics/RenderDevice.cs | 7 + .../TablePro.Graphics.csproj | 3 +- .../src/TablePro.Interop/DatabaseSession.cs | 11 ++ .../Generated/tablepro_ffi.cs | 133 +++++++++++++ windows/src/TablePro.Interop/Mapping.cs | 8 + windows/src/TablePro.Interop/RowEstimate.cs | 4 + windows/tests/Shared/WinUiApp.cs | 133 +++++++++++++ .../DefinitionTabTests.cs | 3 + .../ObjectFoldersTests.cs | 71 ++++++- .../RunResultsTests.cs | 31 +++ .../TablePro.App.Model.Tests/TabFakes.cs | 20 ++ .../TableTabCountTests.cs | 176 ++++++++++++++++++ .../TablePro.App.Model.Tests/TableTabTests.cs | 85 +++++++++ .../TablePro.DataGrid.Tests.csproj | 4 + .../TablePro.DataGrid.Tests/WinUiHost.cs | 129 +------------ .../CaretBlinkTests.cs | 142 ++++++++++++++ .../tests/TablePro.Editor.Tests/CaretTests.cs | 68 +++++++ .../tests/TablePro.Editor.Tests/EditorHost.cs | 52 ++++++ .../TablePro.Editor.Tests/LifetimeTests.cs | 80 ++++++++ .../TablePro.Editor.Tests.csproj | 54 ++++++ .../tests/TablePro.Editor.Tests/app.manifest | 15 ++ .../TablePro.Interop.Tests/BrowseTests.cs | 16 ++ 56 files changed, 1888 insertions(+), 287 deletions(-) create mode 100644 windows/src/TablePro.Editor.Model/CaretBlink.cs create mode 100644 windows/src/TablePro.Editor/SqlEditor.Caret.cs create mode 100644 windows/src/TablePro.Interop/RowEstimate.cs create mode 100644 windows/tests/Shared/WinUiApp.cs create mode 100644 windows/tests/TablePro.App.Model.Tests/TableTabCountTests.cs create mode 100644 windows/tests/TablePro.Editor.Model.Tests/CaretBlinkTests.cs create mode 100644 windows/tests/TablePro.Editor.Tests/CaretTests.cs create mode 100644 windows/tests/TablePro.Editor.Tests/EditorHost.cs create mode 100644 windows/tests/TablePro.Editor.Tests/LifetimeTests.cs create mode 100644 windows/tests/TablePro.Editor.Tests/TablePro.Editor.Tests.csproj create mode 100644 windows/tests/TablePro.Editor.Tests/app.manifest diff --git a/.claude/skills/fix-issue/references/platform-windows.md b/.claude/skills/fix-issue/references/platform-windows.md index e7baaae3d1..d823df2775 100644 --- a/.claude/skills/fix-issue/references/platform-windows.md +++ b/.claude/skills/fix-issue/references/platform-windows.md @@ -43,8 +43,8 @@ Pass `--platform windows`, which a Windows shell (Git Bash, MSYS2, Cygwin) picks | `app` | Windows only: anything under `windows/src/TablePro.App` changed, before `ui`; the Native AOT publish CI tests | | `ui [filter]` | Windows only: the change is visible in the app, or a flow the UI tests cover changed | -- Pick tests by what you changed: `src/` has its tests in `tests/.Tests` where that folder exists. `TablePro.Graphics` is reached through `TablePro.DataGrid.Tests`, and `TablePro.Editor` and `TablePro.App` through the UI tests. A core crate has its tests in its own folder. -- On macOS or Linux, `build`, `test`, `core` and `bindings` run. `app`, `ui` and `TablePro.DataGrid.Tests` report INCONCLUSIVE there: the pull request's `windows / Windows (x64)` and `windows / Windows (Arm64)` jobs run them. +- Pick tests by what you changed: `src/` has its tests in `tests/.Tests` where that folder exists. `TablePro.Graphics` is reached through `TablePro.DataGrid.Tests` and `TablePro.Editor.Tests`, `TablePro.Editor` through `TablePro.Editor.Tests` and the UI tests, and `TablePro.App` through the UI tests. A core crate has its tests in its own folder. +- On macOS or Linux, `build`, `test`, `core` and `bindings` run. `app`, `ui`, `TablePro.DataGrid.Tests` and `TablePro.Editor.Tests` report INCONCLUSIVE there: the pull request's `windows / Windows (x64)` and `windows / Windows (Arm64)` jobs run them. - There is no lint step: `windows.yml` runs none. `build` is the lint, since `windows/Directory.Build.props` turns on the latest recommended analyzers and the `.editorconfig` style with warnings as errors. - Extra review pass: none beyond the security pass. - Traps and remedies: `references/verification-windows.md`. diff --git a/.claude/skills/fix-issue/references/verification-windows.md b/.claude/skills/fix-issue/references/verification-windows.md index 77cdcafa0a..e849cbf8f0 100644 --- a/.claude/skills/fix-issue/references/verification-windows.md +++ b/.claude/skills/fix-issue/references/verification-windows.md @@ -24,7 +24,7 @@ Read this when a `verify.sh` verdict needs interpreting for the Windows app, bef - **A filter that matches nothing exits 8**, "Zero tests ran". The wrapper reports it as INCONCLUSIVE; check the executed count anyway. - **A bare filter word matches part of a test's full name**, namespace and class included, through `--filter-method "**"`. xunit's own options go after `--`: `--filter-class`, `--filter-trait "Needs=Core"`, `--filter-query`. -- **`TablePro.DataGrid.Tests` runs on Windows only.** Its csproj turns `IsTestProject` off elsewhere, so the solution's run on a Mac compiles it and runs the other four projects: fewer cases than CI counts on Windows. +- **`TablePro.DataGrid.Tests` and `TablePro.Editor.Tests` run on Windows only.** Their csproj files turn `IsTestProject` off elsewhere, so the solution's run on a Mac compiles them and runs the other four projects: fewer cases than CI counts on Windows. - **The `Needs=Core` tests load the real core** that the build copied beside the test assembly. They run on every runner. - **Cargo exits 101 for a compile error and for a failed test.** The `core` step tells them apart by whether a test binary ran. A filter that matches nothing exits 0 with "0 passed", which the wrapper reports as INCONCLUSIVE. - **`core` passes `--target `**, as the csproj and `core.yml` do, so it reuses the build instead of compiling the core again into `target/debug`. diff --git a/.claude/skills/fix-issue/scripts/lib/platform-windows.sh b/.claude/skills/fix-issue/scripts/lib/platform-windows.sh index 76edf690e7..e53998f7cf 100644 --- a/.claude/skills/fix-issue/scripts/lib/platform-windows.sh +++ b/.claude/skills/fix-issue/scripts/lib/platform-windows.sh @@ -368,7 +368,7 @@ platform_step() { else report_dotnet_tests "$log" "$filtered" "$code" if [ -z "$project" ] && ! on_windows; then - note "TablePro.DataGrid.Tests compiled but did not run: it runs on Windows" + note "TablePro.DataGrid.Tests and TablePro.Editor.Tests compiled but did not run: they run on Windows" fi fi diagnose_environment "$log" && STATUS=INCONCLUSIVE diff --git a/core/crates/ffi/src/lib.rs b/core/crates/ffi/src/lib.rs index 7a8f4b25f1..5561e6d81c 100644 --- a/core/crates/ffi/src/lib.rs +++ b/core/crates/ffi/src/lib.rs @@ -60,7 +60,7 @@ pub use row_edits::{ }; pub use run::{QueryRun, RunEvent, RunListener, RunOutcome, TransactionStateTag, TruncationTag}; pub use safe_mode_gate::RunGate; -pub use session::{ColumnSort, DatabaseSession, FailureCauseTag, SessionHealthTag, TablePageRead}; +pub use session::{ColumnSort, DatabaseSession, FailureCauseTag, RowEstimate, SessionHealthTag, TablePageRead}; pub use statement_at::StatementSpan; pub use structure::{StructureColumn, StructureForeignKey, StructureIndex, TableStructure}; diff --git a/core/crates/ffi/src/session.rs b/core/crates/ffi/src/session.rs index 41c4c0b5a1..153d2a5313 100644 --- a/core/crates/ffi/src/session.rs +++ b/core/crates/ffi/src/session.rs @@ -3,7 +3,7 @@ use std::time::Instant; use tablepro_core::browse::{PageRequest, PagingMode, SortKey, build_count, build_page, paging_mode, read_page}; use tablepro_core::filter::FilterSet; -use tablepro_core::meta::{ObjectInfo, ObjectScope, PagePosition, RowIdentity, TableRef}; +use tablepro_core::meta::{ObjectInfo, ObjectScope, PagePosition, RowCountEstimate, RowIdentity, TableRef}; use tablepro_core::sql_syntax::{SortReference, sort_reference, with_order_by}; use tablepro_core::{ByteLimit, ColumnInfo, EditorSessionOptions, QueryResult, ResultEvent, ResultSink, Truncation}; use tablepro_session::runtime::{Tasks, catch_panic}; @@ -62,6 +62,25 @@ impl std::fmt::Debug for TablePageRead { } } +// The engine's own idea of a table's rows, read from its statistics with no scan. Exact where it keeps the count. +#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)] +pub enum RowEstimate { + Exact { rows: u64 }, + Approximate { rows: u64 }, + // No statistics for the table, as SQLite before ANALYZE. + Unknown, +} + +impl From for RowEstimate { + fn from(estimate: RowCountEstimate) -> Self { + match estimate { + RowCountEstimate::Exact(rows) => Self::Exact { rows }, + RowCountEstimate::Approximate(rows) => Self::Approximate { rows }, + RowCountEstimate::Unknown => Self::Unknown, + } + } +} + // How the session's connection is doing. A reconnect replaces it on its own; a failed one waits for reconnect(). #[derive(Debug, Clone, PartialEq, Eq, uniffi::Enum)] pub enum SessionHealthTag { @@ -263,6 +282,27 @@ impl DatabaseSession { .await } + // Of the whole table, so it says nothing exact about a filtered view; the app decides from it whether to count. + pub async fn table_row_estimate( + &self, + table: TableName, + cancel: Option>, + ) -> Result { + let session = self.session.clone(); + let cancel = token(cancel); + on_runtime(&self.tasks, async move { + let table: TableRef = table.into(); + let estimate = session + .run_cancellable(OperationKind::Metadata, &cancel, |lease, options| { + let table = table.clone(); + async move { Ok(lease.table_estimate(&table, options).await?) } + }) + .await?; + Ok(RowEstimate::from(estimate.rows)) + }) + .await + } + // The table as the server defines it now. `kind` decides whether a CREATE script belongs: a view gets none. pub async fn table_structure( &self, diff --git a/core/crates/ffi/tests/browse.rs b/core/crates/ffi/tests/browse.rs index cf6912bf32..a4b4064d32 100644 --- a/core/crates/ffi/tests/browse.rs +++ b/core/crates/ffi/tests/browse.rs @@ -11,9 +11,9 @@ use std::time::{Duration, Instant}; use secrecy::SecretString; use tablepro_ffi::{ ColumnSort, CombinatorTag, Core, CoreError, DatabaseSession, FileOpenRequest, FilterOpTag, FilterRuleArg, - FilterValueArg, HostConfig, HostSecretError, HostSecrets, ObjectEntry, ObjectKindTag, ObjectScopeArg, RunEvent, - RunListener, RunOutcome, RunSettings, SecretItemTag, SecretKindTag, TableFilterArg, TableName, TablePageRead, - TransactionStateTag, TruncationTag, + FilterValueArg, HostConfig, HostSecretError, HostSecrets, ObjectEntry, ObjectKindTag, ObjectScopeArg, RowEstimate, + RunEvent, RunListener, RunOutcome, RunSettings, SecretItemTag, SecretKindTag, TableFilterArg, TableName, + TablePageRead, TransactionStateTag, TruncationTag, }; struct NoSecrets; @@ -86,12 +86,17 @@ async fn fixture(dir: &Path, sql: &str) -> (Arc, Arc) { create: true, }; let session = core.open_file(request, None).await.unwrap(); + execute(&session, sql).await; + (core, session) +} + +// On an editor of its own, closed before the test reads through the session. +async fn execute(session: &DatabaseSession, sql: &str) { let editor = session.open_editor(None).await.unwrap(); let run = editor.run(sql.to_owned(), RunSettings::default(), Box::new(Quiet)); let outcome = run.outcome().await.unwrap(); assert!(matches!(outcome, RunOutcome::Completed { .. }), "{outcome:?}"); editor.close().await.unwrap(); - (core, session) } fn table(name: &str) -> TableName { @@ -229,6 +234,21 @@ async fn contains_finds_a_percent_sign_as_typed_and_like_keeps_the_users_wildcar assert_eq!(liked, texts(&["50% off", "500 units"])); } +#[tokio::test] +async fn a_tables_estimate_is_unknown_until_analyze_writes_its_statistics() { + let dir = tempfile::tempdir().unwrap(); + let (_core, session) = fixture(dir.path(), PEOPLE).await; + + let before = session.table_row_estimate(table("people"), None).await.unwrap(); + // ANALYZE writes sqlite_stat1, whose row for the index starts with the table's row count. + execute(&session, "CREATE INDEX people_by_age ON people (age); ANALYZE").await; + let after = session.table_row_estimate(table("people"), None).await.unwrap(); + session.close().await.unwrap(); + + assert_eq!(before, RowEstimate::Unknown); + assert_eq!(after, RowEstimate::Approximate { rows: 7 }); +} + #[tokio::test] async fn a_filter_on_a_column_the_table_lacks_is_refused_before_any_read() { let dir = tempfile::tempdir().unwrap(); diff --git a/core/docs/decisions/0022-browsing-through-the-ffi.md b/core/docs/decisions/0022-browsing-through-the-ffi.md index 54d741919a..a7a76a24d7 100644 --- a/core/docs/decisions/0022-browsing-through-the-ffi.md +++ b/core/docs/decisions/0022-browsing-through-the-ffi.md @@ -12,7 +12,7 @@ The Windows app reaches the core only through `crates/ffi`. A table tab read its The FFI exposes what the Linux app calls, and does the work the Linux app does, so an app on it builds no SQL and keeps no store of its own. - `DatabaseSession::read_table_page` reads the catalog's columns and the row identity, builds the page once with the filter so a value the column cannot take or a column the table lacks fails the call before anything is sent, then reads it with `browse::read_page` on a pooled connection (`OperationKind::Page`). The rows arrive as the run events an editor run gives (`ResultSetStarted`, `RowsAppended`, `ResultSetFinished`, `Finished` with an idle transaction), so a host shows a page and a query result the same way. `table_query` is gone, and a table tab no longer holds an editor connection. -- `table_row_count` takes the same filter. `filter_choices` gives each column's operators from `SqlDialect::filter_operators`, the engine's combinators, and whether it takes a raw SQL predicate, which `validate_raw_predicate` reads as exactly one expression. MongoDB's raw filter is a query document, not SQL, so it is not offered there yet, and raw text for an engine that is not SQL is refused (`filter.raw_unsupported`). +- `table_row_count` takes the same filter. `table_row_estimate` gives the whole table's rows from `Connection::table_estimate` as `RowEstimate` (exact, approximate or unknown), on a pooled connection (`OperationKind::Metadata`), so a host decides whether to count as the Linux pager does. `filter_choices` gives each column's operators from `SqlDialect::filter_operators`, the engine's combinators, and whether it takes a raw SQL predicate, which `validate_raw_predicate` reads as exactly one expression. MongoDB's raw filter is a query document, not SQL, so it is not offered there yet, and raw text for an engine that is not SQL is refused (`filter.raw_unsupported`). - A refused filter carries the codes of each layer: `operation.browse`, `browse.filter`, the rule's `filter.*`, and for a value the column cannot take, the parse's `edit.*` (`BrowseSqlError::codes`, `BuildFilterError::codes`). - `table_structure` reads `fetch_table_definition` and gives its columns, indexes and foreign keys as display text, and the CREATE script from `DdlDialect::create_table_script` only for a table or a partitioned table, by the kind the catalog lists it under where it has one: on some engines the script for a view would be a CREATE TABLE made from its columns. - `QueryEditor::use_database` moves an editor's connection to a database, for a definition whose text names none (MySQL's), as the Linux app opens such a definition. diff --git a/windows/AGENTS.md b/windows/AGENTS.md index 0d8b3977d5..d6e1004ef0 100644 --- a/windows/AGENTS.md +++ b/windows/AGENTS.md @@ -21,7 +21,7 @@ This is the guide for work under `windows/`. The root `AGENTS.md` holds the rule - `src/TablePro.Editor`: the `SqlEditor` control over that model: Direct2D and DirectWrite in a SwapChainPanel, TSF, the UIA text provider, and the core's lexer through `CoreSqlLexer`. - `src/TablePro.DataGrid.Model`: the grid's columns, selection, keys, cell blocks read from the core (`ResultSetData`), pending edits laid over them (`EditedGridData`) and Excel-style copy. Plain `net10.0`, so `tests/TablePro.DataGrid.Model.Tests` runs anywhere; its `Needs=Core` tests load the real core. - `src/TablePro.DataGrid`: the `DataGridView` control: ItemsRepeater rows that draw their cells with DirectWrite into composition surfaces, frozen columns, the header row, in-place cell editing with pending-change marks, and UIA peers. -- `tests/TablePro.DataGrid.Tests`: the control in a real WinUI window on a thread of its own. It runs on Windows and only compiles elsewhere. +- `tests/TablePro.DataGrid.Tests` and `tests/TablePro.Editor.Tests`: each control in a real WinUI window on a thread of its own, the app and window from `tests/Shared/WinUiApp.cs`. They run on Windows and only compile elsewhere. - `tests/TablePro.DataGrid.Gate` and `tests/TablePro.DataGrid.Gate.Uia`: the grid's timing and behavior gate, outside the solution. `ci/run-gate.ps1` builds and runs it; `.github/workflows/windows-grid-gate.yml` runs it by dispatch. - `src/TablePro.App`: the WinUI app: one window, the rail, the Connections page, the connection form window, Settings and a workspace per connection (`docs/decisions/0004-app-shell.md`). Strings are in `Strings/en-US/Resources.resw`. - `src/TablePro.App.Model`: the app's settings and session files, the library tree, the connection form's fields, the object folders, the tab and connection lifecycles over small session, editor and run interfaces, and a table tab's pending edits. Plain `net10.0`, so `tests/TablePro.App.Model.Tests` runs anywhere. @@ -41,7 +41,7 @@ This is the guide for work under `windows/`. The root `AGENTS.md` holds the rule - `QueryEditor.Run` returns at once. Read the run's events with `ReadEventsAsync` on the UI thread; rows that arrive while it is busy come as one event. - A grid reads a `ResultSet` through `ResultCursor.Fetch`, one window per visible range. A cursor belongs to one thread, and a window cannot be read after the cursor's next fetch. - `DataGridView.SetData(new ResultSetData(set, columns))` shows a set. Call the grid's `RowsChanged` after each `RowsAppended`. Sorting is the host's: the grid raises `SortRequested` and shows `Sort`. -- The core writes every sorted statement: `ReadTablePageAsync` reads a table's page with its sort and filter on a pooled connection and returns its run, `SortedQuery` writes a query result's, null when the statement cannot run again or the engine cannot name the column. `ResultSet.SortedAsync` then sorts the rows held (`core/docs/decisions/0007-sorting-a-result.md`). `ReadTablePageAsync` takes the page's offset, and `CanSeek` says whether the engine has later pages; `CountRowsAsync` counts the rows the filter picks. The filter's values are bound by the core, never written into SQL here (`core/docs/decisions/0022-browsing-through-the-ffi.md`). +- The core writes every sorted statement: `ReadTablePageAsync` reads a table's page with its sort and filter on a pooled connection and returns its run, `SortedQuery` writes a query result's, null when the statement cannot run again or the engine cannot name the column. `ResultSet.SortedAsync` then sorts the rows held (`core/docs/decisions/0007-sorting-a-result.md`). `ReadTablePageAsync` takes the page's offset, and `CanSeek` says whether the engine has later pages; `CountRowsAsync` counts the rows the filter picks, and `EstimateRowsAsync` gives the whole table's count from the engine's statistics, null where it keeps none. The filter's values are bound by the core, never written into SQL here (`core/docs/decisions/0022-browsing-through-the-ffi.md`). - `GetStructureAsync` gives a table's columns, indexes, foreign keys and CREATE script, `GetObjectDefinitionAsync` a routine's, trigger's or sequence's source, `ExportRowsAsync` and `ExportTableAsync` write a file through the core's encoders, and `TableProCore.OpenHistoryAsync` the query history, which withholds what the engine says holds a secret. - A table tab edits through `DatabaseSession.OpenTableEditorAsync`: the app sends what was typed (`CellEdit`) per row of the page's `ResultSet`, and `TableEditor.Plan` gives a `RowSave` with its statements and Safe Mode gate, which `RunAsync` saves (`core/docs/decisions/0019-row-edits-through-the-ffi.md`). - `QueryEvent.Finished.Transaction` is the transaction the editor's connection is left in. A session's `Health` is waited on with `WaitForHealthChangeAsync`, which returns once it differs from the one passed in. diff --git a/windows/Directory.Packages.props b/windows/Directory.Packages.props index 3c7dd9ddad..f91e0cad5f 100644 --- a/windows/Directory.Packages.props +++ b/windows/Directory.Packages.props @@ -8,7 +8,10 @@ + + + diff --git a/windows/TablePro.slnx b/windows/TablePro.slnx index 4d9ed824ef..bbdd1d790f 100644 --- a/windows/TablePro.slnx +++ b/windows/TablePro.slnx @@ -13,6 +13,7 @@ + diff --git a/windows/docs/decisions/0002-sql-editor-control.md b/windows/docs/decisions/0002-sql-editor-control.md index 06bce27191..0e05201569 100644 --- a/windows/docs/decisions/0002-sql-editor-control.md +++ b/windows/docs/decisions/0002-sql-editor-control.md @@ -36,8 +36,9 @@ ### Drawing - A SwapChainPanel holds a composition swap chain (flip sequential, three buffers, at most two frames waiting). A frame starts only when the swap chain can take it, through its frame latency object, so Present never blocks the UI thread. Direct3D 11 runs on the GPU, or WARP when there is none or software rendering is asked for. Direct2D draws on it, DirectWrite lays out each visible line. +- Every editor on a UI thread draws on one Direct3D and Direct2D device, as the grid's rows do (0003), and the first editor to find it lost replaces it for the rest. Each editor has its own device context and swap chain. TabView unloads a tab's content on every switch, so a hidden editor gives back its swap chain (`SetSwapChain(null)`) and keeps its layouts and brushes; showing it again makes one swap chain. - Line layouts are cached by text and colors, so lines that shift after an edit keep theirs; only the edited line is laid out again. A line over 4,096 characters is laid out in a slice around the visible columns. -- A frame is drawn on the UI thread when something changed, and many changes before it give one frame. It holds the gutter, current line band, find matches, selections, text, IME marks and carets. The caret blinks at the system rate, with the system caret width. +- A frame is drawn on the UI thread when something changed, and many changes before it give one frame. It holds the gutter, current line band, find matches, selections, text, IME marks and carets. The caret blinks at the system rate, with the system caret width, and stops after the system caret timeout (`SPI_GETCARETTIMEOUT`, 5 seconds when the call fails) with no input, shown, as a Win32 edit control's does. In an inactive window (`InputActivationListener`) it is hidden and nothing blinks, as Win32's About Carets asks. - Why a SwapChainPanel and not Composition drawing surfaces: one surface, presented when something changed, and a frame time measured from input to present; the same model as Windows Terminal. Surfaces per line would add their own management for scrolling that this cost does not need. - Colors: theme resources for the chrome. In high contrast the system colors, selected text in the highlight text color, and no syntax colors. - DPI: the buffer is in pixels and the panel's composition scale shrinks it back. Ctrl+wheel, Ctrl+= and Ctrl+- zoom. diff --git a/windows/docs/decisions/0004-app-shell.md b/windows/docs/decisions/0004-app-shell.md index 2a466b17d2..786f43b588 100644 --- a/windows/docs/decisions/0004-app-shell.md +++ b/windows/docs/decisions/0004-app-shell.md @@ -54,7 +54,7 @@ On 2026-11-05 the maintainer had the app show what the server prints, PostgreSQL - An item's icon is its engine's artwork (Engine artwork, below) in the connection's colour, with the engine's name as the item's `AutomationProperties.HelpText`. The macOS rail puts the colour in a dot on the glyph's corner; `NavigationViewItem.Icon` takes one `IconElement` and its `InfoBadge` slot carries the connecting state, so here the glyph itself takes the colour. The library's changes reach open items: a rename or a new colour shows at once. - A rail item appears at once. `NavigationViewItem.Icon` takes an `IconElement`, which cannot host a `ProgressRing`, so the item shows an attention-dot `InfoBadge` while connecting and a critical-icon `InfoBadge` after a failure, with the state in `AutomationProperties.ItemStatus` and the tooltip. The page shows the `ProgressRing`, "Connecting to name..." and Cancel. - A failure is an Error `InfoBar` with Retry, Edit connection and Copy details in its content. It is closed and opened again on each failure, since Narrator reads an InfoBar when it opens ([InfoBar](https://learn.microsoft.com/en-us/windows/apps/develop/ui/controls/infobar)). -- Cancel removes the item. At launch, only the front connection connects; another restored item connects when it is selected. +- Cancel removes the item. At launch, only the front connection connects; another restored item connects when it is selected. A restored table tab reads its first page the first time it shows (its first `Loaded`, which TabView raises only for the content it displays), so a session with many table tabs reads one table. - A connection the core holds no secret for (`keyring.secret_not_stored`, an imported one or one whose secret was removed) asks for it in a `ContentDialog`, as macOS asks: a `PasswordBox` named for the secret the error carries (`ErrorInfo.secret`) and "Save it in Credential Manager". The answer goes to that connect only (`connect_saved` takes it as a typed secret), and with the box ticked the core stores it once it has logged in (`connect_saved`'s `keep`), so a wrong one is asked for again on Retry. The core files it against the record that connect read, under the library's write lock, and drops it when an edit since then changed anything the connect reads, a delete removed it, or a secret was saved since. Closing the dialog cancels the connect. ### Commands and keys @@ -119,7 +119,7 @@ On 2026-11-05 the maintainer had the app show what the server prints, PostgreSQL - A header click on a query result does what the macOS app does: the result's statement runs again with the column's ORDER BY in place of its own and before its row limit (`DatabaseSession.SortedQuery`, the core's `with_order_by`). The ORDER BY names the column, or gives its position where a name is not unique or not a plain column (core ADR 0007). Only one statement that reads runs again. For a script, a write, SHOW or EXPLAIN, and where the engine takes no position, the core sorts the rows the result holds (`ResultSet.SortedAsync`), as macOS sorts them where they are, and the status says so. - The object pane resizes with the Windows Community Toolkit's `GridSplitter` (Sizers), set up as its [page](https://learn.microsoft.com/en-us/dotnet/communitytoolkit/windows/sizers/gridsplitter) lays it out, between 180 and 640 effective pixels; WinUI's `SplitView` has no user resize. Every workspace shares the width, which `session.json` keeps. - Reopen closed tab (File menu, Ctrl+Shift+T, which the [Tab view](https://learn.microsoft.com/en-us/windows/apps/develop/ui/controls/tab-view) page asks for): a workspace keeps its last 20 closed tabs, newest first, each with its text or its table and its place in the strip. Disconnecting forgets them; Reconnect and connecting an edited connection keep them. -- Table tabs page as macOS pages a table: a page is the default page size long (Settings, Pagination: 100, 500, 1,000, 5,000 or 10,000 rows, 1,000 unless changed, as macOS); First, Previous, Next and Last sit in the tab's `CommandBar`, and its one status words the page as the macOS status bar does, with the run's time: "1,001-2,000 of 3,503 rows · 15 ms", or "Rows 1,001-2,000 · 15 ms" until the count lands. A table that fits one page keeps "Rows: 347 · 12 ms". The core writes each page (`table_query` takes an offset, over `build_page`'s `PagePosition::Offset`) and counts the table (`table_row_count`, `build_count` as the Linux pager counts), in the background after the first full page; until the count lands, Next stays while pages come back full. A sort or a refresh goes back to the first page, and a refresh counts again. An engine that pages on the server (Cassandra) cannot seek by offset, so it has only its first page, as on macOS, and the core refuses another (`ffi.page_unsupported`). +- Table tabs page as macOS pages a table: a page is the default page size long (Settings, Pagination: 100, 500, 1,000, 5,000 or 10,000 rows, 1,000 unless changed, as macOS); First, Previous, Next and Last sit in the tab's `CommandBar`, and its one status words the page as the macOS status bar does, with the run's time: "1,001-2,000 of 3,503 rows · 15 ms", or "Rows 1,001-2,000 · 15 ms" until the count lands. A table that fits one page keeps "Rows: 347 · 12 ms". The core writes each page (`table_query` takes an offset, over `build_page`'s `PagePosition::Offset`) and counts the table (`table_row_count`, `build_count` as the Linux pager counts), in the background after the first full page; until the count lands, Next stays while pages come back full. Before it counts, it reads the engine's estimate (`table_row_estimate`, over `Connection::table_estimate`, as the Linux pager does), and decides as macOS does: an exact count the engine keeps is the total; under 100,000 rows, or with no estimate, the server counts; from 100,000 on nothing is counted, the status says "1-1,000 of about 2,000,000 rows" (no total under a filter), and Count rows in the command bar counts on request. Last page, Go to page and All rows wait for an exact count. A sort or a refresh goes back to the first page, and a refresh counts again. An engine that pages on the server (Cassandra) cannot seek by offset, so it has only its first page, as on macOS, and the core refuses another (`ffi.page_unsupported`). - Rows per page: a "1,000 rows" button before First page opens the macOS sizes, 5, 10, 20, 100, 500 and 1,000, as `RadioMenuFlyoutItem`s, then All rows..., which asks first and needs the count, and Custom..., up to 1,000,000. A new size keeps the page that holds the first row shown, as macOS does. The size belongs to the tab: `session.json` keeps it with the tab's page, and Reopen closed tab brings both back. - Go to page: between Previous and Next, "Page 3 of 36" opens a flyout with a `NumberBox` from 1 to the page count, as macOS asks in a popover. It is offered once the table is counted, as on macOS, and the box keeps a typed number inside that range (`InvalidInputOverwritten`). - An open transaction: each run's `Finished` event carries the transaction the editor's connection is left in (the core's `RunSummary.transaction_state`). The tab that holds one shows a Warning `InfoBar` above its results, "Transaction open", with Roll back, which asks first, and Commit, hidden on a read-only connection; a failed one is an Error bar with Roll back only. Both send COMMIT or ROLLBACK as typed SQL, EXEC or DISCARD for a key-value engine, as the Linux app does. Over the tabs, a bar names another tab that holds one, with Show; macOS shows its bar above every tab of the connection, and here the owning tab carries the actions, since the transaction lives on that tab's own connection. Closing a tab that holds one asks first, since closing rolls it back. Window close and Exit confirm every affected held transaction before closing any tabs; cancelling keeps them open. Then one dialog lists every query tab still running, as macOS asks before it quits, and says closing rolls back a transaction a run has open; a table tab loading a page is not asked about. Exit then hides the windows and closes every connection, each tab stopping its run, for up to 5 seconds before the process ends. While any tab holds a transaction or unsaved changes, the primary window registers a reason with `ShutdownBlockReasonCreate` ("Table changes are not saved.", "A transaction is open.") and answers `WM_QUERYENDSESSION` with FALSE once it has written the session file: a sign-out or a restart then lists TablePro with its reason and the user can cancel and save, and a Restart Manager request, as from an installer, is cancelled ([Application Shutdown Changes in Windows Vista](https://learn.microsoft.com/en-us/previous-versions/windows/desktop/ms700677(v=vs.85)); Restart Manager, [Guidelines for Applications](https://learn.microsoft.com/en-us/windows/win32/rstmgr/guidelines-for-applications)). A running query does not hold it, since stopping it is the default. A forced end cannot be held: "Sign out anyway" (`ENDSESSION_CRITICAL`) goes on to `WM_ENDSESSION`, which writes the session file again, and a forced Restart Manager close, as an update that closes the app by force, ends the process with no `WM_ENDSESSION`. Either way the unsaved changes and the transaction are lost. Disconnect, Reconnect and connecting an edited connection ask about held transactions the same way first, in the primary and in a tab window, but not about a running query, which they stop, and Reconnect and an edited connection bring the tabs back with their text on the new session. Cancelling that connect keeps the connection with Retry, so the tabs still come back. A window with a dialog already open waits for it to be dismissed before accepting a close request. WinUI opens one `ContentDialog` per thread, even across windows, so a question asked while another window shows one is declined, as Cancel would decline it (`WindowDialogs`). diff --git a/windows/docs/decisions/0005-distribution.md b/windows/docs/decisions/0005-distribution.md index 905c927c7e..87956eb78e 100644 --- a/windows/docs/decisions/0005-distribution.md +++ b/windows/docs/decisions/0005-distribution.md @@ -17,7 +17,7 @@ A release is one MSIX per architecture, built with Native AOT in the Release con - **The Windows App SDK self-contained.** Microsoft's guide for framework-dependent packaged apps says "for packaged apps that are not distributed through the Store, you as the developer are responsible for distributing the Framework package", and the Main and Singleton packages come only through the Deployment API. A self-contained package needs neither, and "packaged, self-contained" needs no initialization ([deployment overview](https://learn.microsoft.com/windows/apps/package-and-deploy/deploy-overview)). Its costs in that table, a larger download and no shared code pages, are marked "unpackaged apps only"; the remaining one is that a Windows App SDK fix ships with our next release. - **.NET self-contained.** Native AOT has no shared runtime to depend on, and .NET has no framework package for MSIX. -- **The metapackage stays, for now.** The metapackage also brings AI, ML, Search, Widgets and DWrite, and a self-contained build copies every component's binaries into the package (`Microsoft.WindowsAppSDK.SelfContained.targets` in Base 2.6.4): ONNX Runtime 1.27.1 and DirectML alone are 41.8 MB per architecture. But every Community Toolkit 8.2.251219 package depends on `Microsoft.WindowsAppSDK` 1.6.250108002 or later. With `Microsoft.WindowsAppSDK.WinUI` as the only reference, NuGet resolved that dependency to 1.6.250108002, whose WinUI targets loaded beside 2.6.4's (MSB4011), and the MSIX tooling stopped on `CustomBeforeMicrosoftCommonTargets` (run 41682292859). The Toolkit's 8.3 previews depend on `Microsoft.WindowsAppSDK.WinUI` instead; once 8.3 is stable, the app references the WinUI package alone, as 0001 chose. Meanwhile the extra components cost size and nothing else: the app never activates them, and none of their DLLs imports the VC++ redistributable (`llvm-objdump -p` over the 2.6.4 packages' x64 binaries, and the package check). +- **The WinUI component, not the metapackage.** The Windows App SDK 1.8 release notes (NuGet Metapackage): "This allows developers to choose either the metapackage or select specific component packages for their applications." The app and its libraries reference `Microsoft.WindowsAppSDK.WinUI`, which brings Foundation, InteractiveExperiences, Base and WebView2, and the app references `Microsoft.Windows.SDK.BuildTools.MSIX` itself, as the same notes ask of an app that uses component packages alone. Every Community Toolkit 8.2.251219 package still depends on the metapackage, `Microsoft.WindowsAppSDK` 1.6.250108002 or later, and each route that keeps that dependency keeps every component. Resolved alone it took 1.6.250108002, whose WinUI targets loaded beside 2.6.4's (MSB4011, run 41682292859). Pinned to 2.6.4, transitive pinning brought AI, ML, Search, Widgets, DWrite and Runtime with their props, and ML's `onnxruntime.dll`, `DirectML.dll` and `Microsoft.Windows.AI.MachineLearning.dll` as native assets; `ExcludeAssets="all"` on the metapackage hid only its own (restores on a Mac, 2026-11-12, read from `project.assets.json` and `nuget.g.props`). So the app prunes it: `PrunePackageReference` removes a package from the graph together with what only it brings ([PackageReference in project files](https://learn.microsoft.com/nuget/consume-packages/package-references-in-project-files), PrunePackageReference). The restore then holds the closure `Microsoft.WindowsAppSDK.WinUI` 2.6.4's nuspec declares and nothing else, so nothing WinUI loads is left out, and the component payload the self-contained build copies (`Microsoft.WindowsAppSDK.SelfContained.targets` in Base 2.6.4, plus ML's native assets) falls from 114.9 to 54.1 MB on x64 and from 123.1 to 61.2 MB on Arm64, uncompressed. The grid's test host and gate keep the metapackage, since they ship nothing. The prune goes once a stable Toolkit depends on the WinUI package, as 8.3's previews do. - **The hybrid CRT for the core.** Rust's MSVC targets link `vcruntime140.dll` by default, and DuckDB's C++ adds `msvcp140.dll`: a machine without the VC++ redistributable could not load `tablepro_ffi.dll`. Native AOT already links the hybrid CRT, the C++ runtime inside and the Universal CRT from Windows (`/NODEFAULTLIB:libucrt.lib /DEFAULTLIB:ucrt.lib` in `Microsoft.NETCore.Native.Windows.targets`), as the Windows App SDK guide asks of self-contained C++. The core does the same through `CoreRustFlags`: `+crt-static` makes `cc`, `cmake` and `aws-lc-sys` build with `/MT` too. The flags go into `RUSTFLAGS` because the workflows set `RUSTFLAGS`, which overrides any Cargo configuration file. - **One package per architecture, then a bundle.** The tooling would split a bundle per architecture by scale once the logos have scale variants, so `AppxBundle=Never` keeps every scale in the one package, and `makeappx bundle` joins the two that the x64 and Arm64 runners build. Signing the bundle signs the packages in it ([Sign an app package using SignTool](https://learn.microsoft.com/windows/msix/package/sign-app-package-using-signtool)). - **The version and publisher set by the workflow.** The manifest task (`WinAppSdkGenerateAppxManifest` in `Microsoft.Windows.SDK.BuildTools.MSIX` 1.7.251221100) takes the Publisher from the signing certificate only when the build signs, and Artifact Signing signs afterwards. So the workflow writes the version and `WINDOWS_PUBLISHER` into `Package.appxmanifest` before the build, as Microsoft's [desktop app workflows](https://github.com/microsoft/github-actions-for-desktop-apps/blob/main/.github/workflows/cd.yml) do. The same task writes `Windows.Desktop`'s MinVersion from `TargetPlatformMinVersion`, 10.0.17763.0, and its MaxVersionTested from the target framework's SDK, 10.0.26100.0. @@ -32,7 +32,7 @@ A release is one MSIX per architecture, built with Native AOT in the Release con - When Native AOT trimmed an object's own class, CsWinRT 2.2 wraps it as the nearest base class it kept (`TypeNameSupport.FindRcwTypeByNameCached`). No code constructed an `OverlappedPresenter`, so `AppWindow.Presenter` came back as `AppWindowPresenter` and every cast to `OverlappedPresenter` failed: a window closed maximized came back normal, no window kept its minimum size and the connection form could be minimized. Each window creates its `OverlappedPresenter` and sets it with `AppWindow.SetPresenter`. - `TheInstalledPackageStartsAndKeepsItsFilesInLocalState` is the only test of the packaged code path, where the data folder is the package's LocalState. It runs in `release-windows.yml`, not on pull requests. - A Windows App SDK servicing fix reaches users only through our next release. -- The package carries Windows App SDK components the app never loads, until the Toolkit depends on the WinUI package. +- A Windows App SDK component the app starts to use is a package reference of its own: the metapackage no longer brings it. - `WINDOWS_PUBLISHER` fixes the package family name. Changing it later makes Windows install the next version beside the old one. - The Store would need its own reserved identity, a second package family. - MSIX orders versions by four numbers, so the Windows app has no beta channel. @@ -53,5 +53,6 @@ A release is one MSIX per architecture, built with Native AOT in the Release con - **An unpackaged installer** (MSI or Inno Setup). Gives up MSIX's clean uninstall, per-user install without elevation and the LocalState folder 0004 chose, and the installer, the exe and every DLL need signing. - **A VCLibs framework dependency** instead of the hybrid CRT. A sideloaded install fails where the framework package is missing, and the unpackaged build would still need the redistributable. - **The tooling's own Azure code signing** (`AzureCodeSigningEnabled`). It signs inside the build on each runner, so the bundle would need a second signing step anyway; the maintainer chose the action. -- **`ExcludeAssets` on each unused component.** Six references that hide packages the metapackage declares, and what WinUI still needs from them at run time would rest on what the UI tests happen to reach. +- **`ExcludeAssets` on each unused component.** Seven references, one per package the metapackage and ML declare, each hiding what one of them brings, against one prune that removes them from the graph. +- **Keeping the metapackage until Toolkit 8.3 is stable.** About 60 MB of each package per architecture, uncompressed, for code the app never activates. - **The newest winget schema.** winget-pkgs asks for 1.12, and its older clients read 1.12. diff --git a/windows/src/TablePro.App.Model/ObjectFolders.cs b/windows/src/TablePro.App.Model/ObjectFolders.cs index f4b978ed4a..1251fd87ef 100644 --- a/windows/src/TablePro.App.Model/ObjectFolders.cs +++ b/windows/src/TablePro.App.Model/ObjectFolders.cs @@ -1,3 +1,4 @@ +using System.Globalization; using TablePro.Interop; namespace TablePro.App.Model; @@ -24,17 +25,18 @@ public static class ObjectFolders { public const int PageSize = 500; - public static IReadOnlyList Group(IEnumerable objects) + // The culture is passed in, since a schema's objects are sorted off the UI thread. + public static IReadOnlyList Group(IEnumerable objects, CultureInfo culture) { ArgumentNullException.ThrowIfNull(objects); + ArgumentNullException.ThrowIfNull(culture); + var names = StringComparer.Create(culture, ignoreCase: true); return [ .. objects .GroupBy(entry => Folder(entry.Kind)) .OrderBy(group => group.Key) - .Select(group => new ObjectFolder( - group.Key, - [.. group.OrderBy(entry => entry.Name, StringComparer.CurrentCultureIgnoreCase)])), + .Select(group => new ObjectFolder(group.Key, [.. group.OrderBy(entry => entry.Name, names)])), ]; } @@ -59,23 +61,55 @@ public static bool HasRows(ObjectKind kind) => kind is ObjectKind.Table or Objec // As the core's ObjectKind::has_definition: it opens as SQL to read rather than rows to page. public static bool HasDefinition(ObjectKind kind) => kind is ObjectKind.Function or ObjectKind.Procedure or ObjectKind.Sequence or ObjectKind.Trigger; +} + +// Every object of a connection in the filter's order, sorted once so that a keystroke only scans it. +public sealed class ObjectCatalog +{ + private const int CancelCheckInterval = 1024; - public static IReadOnlyList Filter(IEnumerable objects, string text) + private readonly ObjectEntry[] _sorted; + private readonly CompareInfo _compare; + + public ObjectCatalog(IEnumerable objects, CultureInfo culture) { ArgumentNullException.ThrowIfNull(objects); + ArgumentNullException.ThrowIfNull(culture); + var names = StringComparer.Create(culture, ignoreCase: true); + _compare = culture.CompareInfo; + _sorted = [.. objects.OrderBy(entry => entry.Name, names).ThenBy(entry => entry.Schema, names)]; + } + + public int Count => _sorted.Length; + + // Names that start with the text come first; both parts keep the catalog's order, so the list reads by name. + public IReadOnlyList Filter(string text, CancellationToken cancellationToken = default) + { var needle = text?.Trim() ?? string.Empty; if (needle.Length == 0) { return []; } - return - [ - .. objects - .Where(entry => entry.Name.Contains(needle, StringComparison.CurrentCultureIgnoreCase)) - .OrderBy(entry => entry.Name.StartsWith(needle, StringComparison.CurrentCultureIgnoreCase) ? 0 : 1) - .ThenBy(entry => entry.Name, StringComparer.CurrentCultureIgnoreCase) - .ThenBy(entry => entry.Schema, StringComparer.CurrentCultureIgnoreCase), - ]; + var starting = new List(); + var containing = new List(); + for (var index = 0; index < _sorted.Length; index++) + { + if (index % CancelCheckInterval == 0) + { + cancellationToken.ThrowIfCancellationRequested(); + } + + var entry = _sorted[index]; + if (_compare.IndexOf(entry.Name, needle, CompareOptions.IgnoreCase) < 0) + { + continue; + } + + (_compare.IsPrefix(entry.Name, needle, CompareOptions.IgnoreCase) ? starting : containing).Add(entry); + } + + starting.AddRange(containing); + return starting; } } diff --git a/windows/src/TablePro.App.Model/RunResults.cs b/windows/src/TablePro.App.Model/RunResults.cs index bb84f3377f..8da67d5e9c 100644 --- a/windows/src/TablePro.App.Model/RunResults.cs +++ b/windows/src/TablePro.App.Model/RunResults.cs @@ -9,6 +9,8 @@ public sealed class RunResult(int setIndex, IReadOnlyList columns) public IReadOnlyList Columns { get; } = columns; + public int Position { get; internal set; } + public long Rows { get; internal set; } // Every row the statement produced, where the engine counted past the limit. @@ -28,12 +30,16 @@ public sealed class RunResults(string label, string labelMore) { private readonly List _results = []; + // A script can return thousands of sets, and each of their events looks one up. + private readonly Dictionary _bySet = []; + public IReadOnlyList Results => _results; public RunResult Add(int setIndex, IReadOnlyList columns) { - var result = new RunResult(setIndex, columns); + var result = new RunResult(setIndex, columns) { Position = _results.Count + 1 }; _results.Add(result); + _bySet.TryAdd(setIndex, result); return result; } @@ -67,7 +73,7 @@ public RunResult Add(int setIndex, IReadOnlyList columns) public string Label(RunResult result) { ArgumentNullException.ThrowIfNull(result); - var position = _results.IndexOf(result) + 1; + var position = result.Position; return result switch { { Truncated: false } => string.Format(CultureInfo.CurrentCulture, label, position, result.Rows), @@ -76,5 +82,5 @@ public string Label(RunResult result) }; } - private RunResult? Find(int setIndex) => _results.Find(result => result.SetIndex == setIndex); + private RunResult? Find(int setIndex) => _bySet.GetValueOrDefault(setIndex); } diff --git a/windows/src/TablePro.App.Model/TabSession.cs b/windows/src/TablePro.App.Model/TabSession.cs index 12e456e188..be6b4ba2a9 100644 --- a/windows/src/TablePro.App.Model/TabSession.cs +++ b/windows/src/TablePro.App.Model/TabSession.cs @@ -24,6 +24,9 @@ Task ReadTablePageAsync( Task CountRowsAsync(TableName table, TableFilter? filter, CancellationToken cancellationToken); + // The whole table's, from the engine's statistics; null where the engine keeps none. + Task EstimateRowsAsync(TableName table, CancellationToken cancellationToken); + Task GetFilterChoicesAsync(TableName table, CancellationToken cancellationToken); Task GetStructureAsync(TableName table, ObjectKind kind, CancellationToken cancellationToken); @@ -133,6 +136,9 @@ public async Task ReadTablePageAsync( public Task CountRowsAsync(TableName table, TableFilter? filter, CancellationToken cancellationToken) => _share.Session.CountRowsAsync(table, filter, cancellationToken); + public Task EstimateRowsAsync(TableName table, CancellationToken cancellationToken) => + _share.Session.EstimateRowsAsync(table, cancellationToken); + public Task GetFilterChoicesAsync(TableName table, CancellationToken cancellationToken) => _share.Session.GetFilterChoicesAsync(table, cancellationToken); diff --git a/windows/src/TablePro.App.Model/TablePage.cs b/windows/src/TablePro.App.Model/TablePage.cs index 2cd2e192bc..c5975fa1c2 100644 --- a/windows/src/TablePro.App.Model/TablePage.cs +++ b/windows/src/TablePro.App.Model/TablePage.cs @@ -16,6 +16,9 @@ public sealed record TablePage(long Offset, int Size, long Rows, long? Total, bo public static int Clamp(int size) => Math.Clamp(size, 1, MaximumSize); + // The engine's estimate of the table, shown as about N while no count gave Total; nothing pages by it. + public long? Estimate { get; init; } + public long FirstRow => Rows == 0 ? 0 : Offset + 1; public long LastRow => Offset + Rows; diff --git a/windows/src/TablePro.App.Model/TableTab.cs b/windows/src/TablePro.App.Model/TableTab.cs index 957ff0a71d..30ce74f4f2 100644 --- a/windows/src/TablePro.App.Model/TableTab.cs +++ b/windows/src/TablePro.App.Model/TableTab.cs @@ -129,6 +129,9 @@ public sealed class TableTab : IWorkspaceTab "ffi.not_connected", }; + // From this estimate on the server counts only when asked, as macOS's default threshold. + private const long CountsBelow = 100_000; + private readonly ITabSession _session; private readonly ITableTabView _view; private readonly IResultsView _results; @@ -151,6 +154,15 @@ public sealed class TableTab : IWorkspaceTab private int? _chosenSize; private CancellationTokenSource? _counting; + // Count rows started the count in flight, which then shows as running rather than hides. + private bool _countAsked; + + // The estimate held the count back for the filter shown; only a read that counts again asks it again. + private bool _countHeldBack; + + // A restored tab reads nothing until it first shows; any read before that counts as its first show. + private bool _shown; + // The set the edits name rows of, which the core reads each key and stored value from. private ResultSet? _editsRows; private EditLock? _pageLock; @@ -229,6 +241,13 @@ public TableTab( // Null until a run has read the page; a count that arrives later adds the total, as on macOS. public PageRun? Finished { get; private set; } + public bool IsCounting => _counting is not null; + + // Only an exact total pages to the end; a count the tab runs by itself is on its way, so Count rows waits for it. + public bool OffersCount => _page.Total is null && _page.IsPaged && (_counting is null || _countAsked); + + public bool CanCountRows => OffersCount && !IsCounting && !IsRunning && !IsSaving && !_work.IsClosed; + // The rows of the page shown, which are what an edit of the page changes. public ResultSet? ShownRows => _results.ShownSet; @@ -327,12 +346,24 @@ public async Task RunAsync() } } + // The first time only, with nothing held yet to ask about; later shows keep what the tab read. + public Task ShowAsync() => _shown ? Task.CompletedTask : LoadAsync(_page.Offset); + + // The exact count the estimate held back, or one that failed; a read that counts again takes its place. + public async Task CountRowsAsync() + { + if (CanCountRows) + { + await _work.RunAsync(token => CountAsync(asked: true, token)).ConfigureAwait(true); + } + } + // A refresh counts the table again and reads its columns again; its structure and filter choices go stale. public async Task RefreshAsync() { if (await MayReloadNowAsync(ReloadReason.Refresh).ConfigureAwait(true)) { - _page = _page with { Total = null }; + _page = _page with { Total = null, Estimate = null }; _reopenTableEditor = true; _structure.MarkStale(); _choices.MarkStale(); @@ -672,6 +703,7 @@ private async Task ResizeToAsync(TablePage page, int chosen) // Recount after a filter, a refresh or a save, which can change the total; it is counted once the page is read. private async Task LoadAsync(long offset, bool recount = false) { + _shown = true; if (!IsRunning) { await _work.RunAsync(token => LoadPageAsync(offset, recount, token)).ConfigureAwait(true); @@ -714,12 +746,18 @@ private async Task LoadPageAsync(long offset, bool recount, CancellationToken ca // A count of what was read before would land as this page's total. _counting?.Cancel(); _counting = null; + _countHeldBack = false; } _run?.Dispose(); _run = read.Run; var shownPage = _page; - _page = page with { CanSeek = read.CanSeek, Total = recount ? null : _page.Total }; + _page = page with + { + CanSeek = read.CanSeek, + Total = recount ? null : _page.Total, + Estimate = recount ? null : _page.Estimate, + }; await _results.ShowRunAsync(_run, _sort, read.VisibleColumns, cancellationToken).ConfigureAwait(true); if (_work.IsClosed) { @@ -1057,7 +1095,7 @@ private async Task AfterSaveAsync( if (reload) { // Rows came and went, so the page is read again and the table counted again, without asking. - _page = _page with { Total = null }; + _page = _page with { Total = null, Estimate = null }; await LoadAsync(_page.Offset, recount: true).ConfigureAwait(true); } @@ -1097,39 +1135,48 @@ private void SetSaving(bool saving) StateChanged?.Invoke(this, EventArgs.Empty); } - private async void CountIfNeeded() => await _work.RunAsync(CountAsync).ConfigureAwait(true); + private async void CountIfNeeded() => + await _work.RunAsync(token => CountAsync(asked: false, token)).ConfigureAwait(true); - // A first page that is not full holds the whole table; otherwise the server counts it, in the background. - private async Task CountAsync(CancellationToken closing) + // A first page that is not full holds the whole table; otherwise the estimate decides, then the server counts. + private async Task CountAsync(bool asked, CancellationToken closing) { - if (_page.Total is not null || !_page.CanSeek) + if (!asked && (_page.Total is not null || !_page.CanSeek || _countHeldBack)) { _view.UpdatePager(); return; } - if (_page.Offset == 0 && _page.Rows < _page.Size) + if (!asked && _page.Offset == 0 && _page.Rows < _page.Size) { _page = _page with { Total = _page.Rows }; _view.UpdatePager(); return; } - _view.UpdatePager(); _counting?.Cancel(); using var counting = CancellationTokenSource.CreateLinkedTokenSource(closing); _counting = counting; + _countAsked = asked; + _view.UpdatePager(); + var filter = _shownFilter; try { - var total = await _session.CountRowsAsync(Table, _shownFilter, counting.Token).ConfigureAwait(true); - // A count that lands as the tab closes, or once a read that counts again took its place, is not shown. - if (_work.IsClosed || !ReferenceEquals(_counting, counting)) + if (!asked) { - return; + if (!await CountsAfterEstimateAsync(filter, counting).ConfigureAwait(true)) + { + return; + } + + _view.UpdatePager(); } - _page = _page with { Total = total }; - _view.UpdatePager(); + var total = await _session.CountRowsAsync(Table, filter, counting.Token).ConfigureAwait(true); + if (Owns(counting)) + { + _page = _page with { Total = total }; + } } catch (Exception exception) when (exception is TableProException or OperationCanceledException) { @@ -1140,10 +1187,56 @@ private async Task CountAsync(CancellationToken closing) if (ReferenceEquals(_counting, counting)) { _counting = null; + if (!_work.IsClosed) + { + _view.UpdatePager(); + } } } } + // As macOS decides; under a filter the whole table's estimate is no total, so it only decides whether to count. + private async Task CountsAfterEstimateAsync(TableFilter? filter, CancellationTokenSource counting) + { + RowEstimate? estimate; + try + { + estimate = await _session.EstimateRowsAsync(Table, counting.Token).ConfigureAwait(true); + } + catch (TableProException) + { + // Without an estimate the server counts, as it did before there was one. + estimate = null; + } + + if (!Owns(counting)) + { + return false; + } + + if (estimate is { } known && filter is null) + { + if (known.IsExact) + { + _page = _page with { Total = known.Rows }; + return false; + } + + _page = _page with { Estimate = known.Rows }; + } + + if (estimate is { Rows: >= CountsBelow }) + { + _countHeldBack = true; + return false; + } + + return true; + } + + // A count or estimate that lands as the tab closes, or once a read that counts again took its place, is not shown. + private bool Owns(CancellationTokenSource counting) => !_work.IsClosed && ReferenceEquals(_counting, counting); + private void SetRunning(bool running) { IsRunning = running; diff --git a/windows/src/TablePro.App/Strings/en-US/Resources.resw b/windows/src/TablePro.App/Strings/en-US/Resources.resw index a095e59f46..9a97f88066 100644 --- a/windows/src/TablePro.App/Strings/en-US/Resources.resw +++ b/windows/src/TablePro.App/Strings/en-US/Resources.resw @@ -1371,6 +1371,9 @@ {0:N0}-{1:N0} of {2:N0} rows · {3:N0} ms + + {0:N0}-{1:N0} of about {2:N0} rows · {3:N0} ms + Move tab to new window @@ -1425,6 +1428,15 @@ Page {0:N0} + + Count rows + + + Counting rows... + + + Count every row, for Last page and Go to page + Go to page diff --git a/windows/src/TablePro.App/TablePro.App.csproj b/windows/src/TablePro.App/TablePro.App.csproj index 4595fa9984..f5b3186faf 100644 --- a/windows/src/TablePro.App/TablePro.App.csproj +++ b/windows/src/TablePro.App/TablePro.App.csproj @@ -43,8 +43,11 @@ - + + + + diff --git a/windows/src/TablePro.App/Views/ResultsPane.xaml.cs b/windows/src/TablePro.App/Views/ResultsPane.xaml.cs index 9a64ed3c27..e5e7b26a51 100644 --- a/windows/src/TablePro.App/Views/ResultsPane.xaml.cs +++ b/windows/src/TablePro.App/Views/ResultsPane.xaml.cs @@ -138,6 +138,7 @@ public async Task ShowRunAsync(ITabRun run, GridSort sort, int visibleColumns, C _pickedView = null; var results = new RunResults(Strings.Get("ResultSetItem"), Strings.Get("ResultSetItemMore")); var incoming = new List(); + var heldBy = new Dictionary(); var adopted = false; long? affected = null; // Only the counts a statement reported, so a run where none did keeps none. @@ -169,7 +170,9 @@ void Adopt() { var result = results.Add(started.SetIndex, started.Columns.Take(visibleColumns).ToList()); var item = new ComboBoxItem { Content = results.Label(result) }; - incoming.Add(new HeldSet(result, set, item)); + var held = new HeldSet(result, set, item); + incoming.Add(held); + heldBy.Add(result, held); if (ReferenceEquals(_held, incoming)) { ListInPicker(item); @@ -182,7 +185,7 @@ or QueryEvent.RowLimitReached or QueryEvent.ByteLimitReached or QueryEvent.ResultSetFinished: if (results.Apply(queryEvent) is { } changed - && incoming.Find(entry => ReferenceEquals(entry.Result, changed)) is { } grown) + && heldBy.GetValueOrDefault(changed) is { } grown) { grown.Item.Content = results.Label(changed); if (queryEvent is QueryEvent.RowsAppended or QueryEvent.ResultSetFinished) diff --git a/windows/src/TablePro.App/Views/TableTabView.xaml b/windows/src/TablePro.App/Views/TableTabView.xaml index f8470e3824..64e6e663df 100644 --- a/windows/src/TablePro.App/Views/TableTabView.xaml +++ b/windows/src/TablePro.App/Views/TableTabView.xaml @@ -67,6 +67,7 @@ + diff --git a/windows/src/TablePro.App/Views/TableTabView.xaml.cs b/windows/src/TablePro.App/Views/TableTabView.xaml.cs index 7f547789c2..0e065675ff 100644 --- a/windows/src/TablePro.App/Views/TableTabView.xaml.cs +++ b/windows/src/TablePro.App/Views/TableTabView.xaml.cs @@ -63,13 +63,10 @@ internal TableTabView( grid.CellEditCommitting += OnCellEditCommitting; grid.DeleteRequested += (_, _) => DeleteRows(); grid.ContextRequested += OnGridContextRequested; + // TabView loads only the content it shows, so a restored tab reads nothing until it first shows. + Loaded += OnFirstLoaded; UpdatePager(); UpdateEditing(); - // A restored filter shows in its bar, as one applied here does. - if (_model.Filter is not null) - { - ShowFilter(true, focus: false); - } } public event EventHandler? StateChanged; @@ -420,6 +417,9 @@ private void UpdatePager() ? Strings.Format("PageOf", page.Number, count) : Strings.Format("PageNumber", page.Number); GoToPageButton.IsEnabled = !busy && page.Count is > 1; + CountRowsButton.Visibility = _model.OffersCount ? Visibility.Visible : Visibility.Collapsed; + CountRowsButton.IsEnabled = _model.CanCountRows; + CountRowsButton.Label = Strings.Get(_model.IsCounting ? "CountingRows" : "CountRows"); if (!_model.IsSaving && RowsStatus() is { } status) { StatusText.Text = status; @@ -440,11 +440,35 @@ private void UpdatePager() return Strings.Format(run.Truncated ? "StatusRowsLimited" : "StatusRows", page.Rows, run.Milliseconds); } - return page.Total is { } total - ? Strings.Format("StatusPageOf", page.FirstRow, page.LastRow, total, run.Milliseconds) + if (page.Total is { } total) + { + return Strings.Format("StatusPageOf", page.FirstRow, page.LastRow, total, run.Milliseconds); + } + + return page.Estimate is { } estimate + ? Strings.Format("StatusPageOfAbout", page.FirstRow, page.LastRow, estimate, run.Milliseconds) : Strings.Format("StatusPage", page.FirstRow, page.LastRow, run.Milliseconds); } + // The first page, and a restored filter's bar with its choices, wait for the first show. + private async void OnFirstLoaded(object sender, RoutedEventArgs e) + { + // Selected only in passing, as each restored tab is, a tab may hear Loaded once it has left the tree. + if (!IsLoaded) + { + return; + } + + Loaded -= OnFirstLoaded; + // A restored filter shows in its bar, as one applied here does. + if (_model.Filter is not null && !ShowsFilter) + { + ShowFilter(true, focus: false); + } + + await _model.ShowAsync().ConfigureAwait(true); + } + // An editor opening or closing counts as a change for Save and the menus. private void EditStateMayHaveChanged() { @@ -654,6 +678,9 @@ private async void OnPreviousPage(object sender, RoutedEventArgs e) => private async void OnLastPage(object sender, RoutedEventArgs e) => await _model.LastPageAsync().ConfigureAwait(true); + private async void OnCountRows(object sender, RoutedEventArgs e) => + await _model.CountRowsAsync().ConfigureAwait(true); + private async void OnRefresh(object sender, RoutedEventArgs e) { await _model.RefreshAsync().ConfigureAwait(true); diff --git a/windows/src/TablePro.App/Views/WorkspaceView.xaml.cs b/windows/src/TablePro.App/Views/WorkspaceView.xaml.cs index 0d83f3fbd7..f3f851f618 100644 --- a/windows/src/TablePro.App/Views/WorkspaceView.xaml.cs +++ b/windows/src/TablePro.App/Views/WorkspaceView.xaml.cs @@ -1,4 +1,5 @@ using System.Collections.ObjectModel; +using System.Globalization; using System.Runtime.InteropServices; using Microsoft.UI; using Microsoft.UI.Xaml; @@ -26,10 +27,11 @@ public sealed partial class WorkspaceView : UserControl, IWorkspaceTabsView _tabs; private SessionShare? _share; private DatabaseSession? _session; - private IReadOnlyList? _everyObject; + private ObjectCatalog? _everyObject; private bool _singleSchema; private string _failureDetails = string.Empty; private int _filterGeneration; + private CancellationTokenSource? _filtering; // Schemas a refresh reads again, the next time each one opens. private readonly HashSet _stale = []; @@ -294,6 +296,8 @@ public async Task CloseTabsAsync(bool keepClosed = false) _watching = null; _loadingTree?.Cancel(); _loadingTree = null; + _filtering?.Cancel(); + _filtering = null; HealthBar.IsOpen = false; ElsewhereBar.IsOpen = false; HideChangesOnConnect(); @@ -344,9 +348,9 @@ private void AddQuery(string? sql, string title, int? index, string? database = return null; } + // Its first page is read when the tab first shows, so a restored session reads only the tab it shows. var table = new TableTabView(_workbench, _share, schema, name, kind, restore); AddTab(table, IconOf(kind), index); - table.Run(); return table; } @@ -1148,7 +1152,9 @@ private async Task LoadTreeAsync(bool refresh = false) : await session.GetObjectsAsync(ObjectScope.DefaultSchema, loading.Token).ConfigureAwait(true); // The core may answer after the cancel, and its answer then is the replaced load's. loading.Token.ThrowIfCancellationRequested(); - AddFolders(Objects, shown.FirstOrDefault()?.Name, objects); + var folders = await GroupAsync(objects).ConfigureAwait(true); + loading.Token.ThrowIfCancellationRequested(); + AddFolders(Objects, shown.FirstOrDefault()?.Name, folders); foreach (var folder in Objects.Where(node => node.Folder?.Kind == FolderKind.Tables)) { RealizeFolder(folder); @@ -1215,18 +1221,26 @@ private async Task RealizeSchemaAsync(ObjectNode node) var objects = _stale.Remove(node.Schema) ? await _session.RefreshObjectsAsync(scope).ConfigureAwait(true) : await _session.GetObjectsAsync(scope).ConfigureAwait(true); + var folders = await GroupAsync(objects).ConfigureAwait(true); node.Children.Clear(); - AddFolders(node.Children, node.Schema, objects); + AddFolders(node.Children, node.Schema, folders); + } + + // A schema can hold tens of thousands of objects, and a culture-aware sort of them would stall the UI thread. + private static Task> GroupAsync(IReadOnlyList objects) + { + var culture = CultureInfo.CurrentCulture; + return Task.Run(() => ObjectFolders.Group(objects, culture)); } - private static void AddFolders(ObservableCollection target, string? schema, IReadOnlyList objects) + private static void AddFolders(ObservableCollection target, string? schema, IReadOnlyList folders) { - foreach (var folder in ObjectFolders.Group(objects)) + foreach (var folder in folders) { target.Add(new ObjectNode(ObjectNodeKind.Folder, Strings.Get("Folder_" + folder.Kind)) { Icon = Symbol.Folder, - Detail = folder.Objects.Count.ToString(System.Globalization.CultureInfo.CurrentCulture), + Detail = folder.Objects.Count.ToString(CultureInfo.CurrentCulture), Schema = schema, Folder = folder, HasUnrealizedChildren = folder.Objects.Count > 0, @@ -1451,43 +1465,73 @@ internal static void CopyText(string text) } } + // Each keystroke scans the catalog on the thread pool and stops the scan it replaces. private async void OnFilterChanged(AutoSuggestBox sender, AutoSuggestBoxTextChangedEventArgs args) { var text = sender.Text; var generation = ++_filterGeneration; + _filtering?.Cancel(); + _filtering = null; if (string.IsNullOrWhiteSpace(text)) { ShowTree(); return; } - if (_session is null) + if (_session is not { } session) { return; } + using var filtering = new CancellationTokenSource(); + _filtering = filtering; try { - _everyObject ??= await _session - .GetObjectsAsync(_singleSchema ? ObjectScope.DefaultSchema : ObjectScope.AllSchemas) + var catalog = _everyObject; + if (catalog is null) + { + var objects = await session + .GetObjectsAsync(_singleSchema ? ObjectScope.DefaultSchema : ObjectScope.AllSchemas) + .ConfigureAwait(true); + var culture = CultureInfo.CurrentCulture; + catalog = await Task.Run(() => new ObjectCatalog(objects, culture)).ConfigureAwait(true); + _everyObject ??= catalog; + } + + // Typing on while the catalog loads leaves only the newest text to show. + if (generation != _filterGeneration) + { + return; + } + + var showSchema = !_singleSchema; + var token = filtering.Token; + var nodes = await Task.Run( + () => catalog.Filter(text, token).Select(entry => EntryNode(entry, showSchema)).ToList(), + token) .ConfigureAwait(true); + if (generation != _filterGeneration || token.IsCancellationRequested) + { + return; + } + + ShowList(nodes, Strings.Format("FilterMatches", nodes.Count)); + } + catch (OperationCanceledException) when (filtering.IsCancellationRequested) + { + // A newer keystroke took over the list. } catch (TableProException exception) { ShowListMessage(Strings.Error(exception.Error)); - return; } - - // Typing on while the catalog loads leaves only the newest text to show. - if (generation != _filterGeneration) + finally { - return; + if (ReferenceEquals(_filtering, filtering)) + { + _filtering = null; + } } - - var matches = ObjectFolders.Filter(_everyObject, text); - ShowList( - [.. matches.Select(entry => EntryNode(entry, showSchema: !_singleSchema))], - Strings.Format("FilterMatches", matches.Count)); } private void OnBackToTree(object sender, RoutedEventArgs e) diff --git a/windows/src/TablePro.DataGrid/TablePro.DataGrid.csproj b/windows/src/TablePro.DataGrid/TablePro.DataGrid.csproj index 17891fea5f..12f1a17c6c 100644 --- a/windows/src/TablePro.DataGrid/TablePro.DataGrid.csproj +++ b/windows/src/TablePro.DataGrid/TablePro.DataGrid.csproj @@ -21,7 +21,7 @@ - + diff --git a/windows/src/TablePro.Editor.Model/CaretBlink.cs b/windows/src/TablePro.Editor.Model/CaretBlink.cs new file mode 100644 index 0000000000..1682da8600 --- /dev/null +++ b/windows/src/TablePro.Editor.Model/CaretBlink.cs @@ -0,0 +1,81 @@ +namespace TablePro.Editor.Model; + +// As a Windows edit control: it blinks until the caret timeout passes with no input, and an inactive window has none. +public sealed class CaretBlink +{ + private readonly TimeProvider _clock; + private long _lastInput; + private bool _on = true; + private bool _focused; + private bool _active = true; + + public CaretBlink() + : this(TimeProvider.System) + { + } + + public CaretBlink(TimeProvider clock) + { + ArgumentNullException.ThrowIfNull(clock); + _clock = clock; + _lastInput = clock.GetTimestamp(); + } + + // What Windows uses when SPI_GETCARETTIMEOUT has no answer. + public static TimeSpan DefaultTimeout { get; } = TimeSpan.FromSeconds(5); + + // Zero when the user turned blinking off. + public TimeSpan Interval { get; set; } + + // Negative never stops. + public TimeSpan Timeout { get; set; } = DefaultTimeout; + + // Whether the timer should run. + public bool IsBlinking { get; private set; } + + public bool CaretVisible => _focused && _active && _on; + + // These return true when CaretVisible changed, so the caller draws only then. + public bool SetFocused(bool focused) + { + var was = CaretVisible; + _focused = focused; + Restart(); + return was != CaretVisible; + } + + public bool SetActive(bool active) + { + var was = CaretVisible; + _active = active; + Restart(); + return was != CaretVisible; + } + + // A key, a click, a selection change or a composition update. + public bool Restart() + { + var was = CaretVisible; + _on = true; + _lastInput = _clock.GetTimestamp(); + IsBlinking = _focused && _active && Interval > TimeSpan.Zero; + return was != CaretVisible; + } + + public bool Tick() + { + if (!IsBlinking) + { + return false; + } + if (Timeout >= TimeSpan.Zero && _clock.GetElapsedTime(_lastInput) >= Timeout) + { + IsBlinking = false; + var was = _on; + _on = true; + return !was; + } + _on = !_on; + return true; + } +} diff --git a/windows/src/TablePro.Editor/Rendering/Palette.cs b/windows/src/TablePro.Editor/Rendering/Palette.cs index 5e09407e95..f739c42444 100644 --- a/windows/src/TablePro.Editor/Rendering/Palette.cs +++ b/windows/src/TablePro.Editor/Rendering/Palette.cs @@ -33,6 +33,13 @@ internal sealed class Palette // Indexed by TablePro.Interop.SyntaxKind. public Color?[] Syntax { get; private init; } = []; + // Next to the fields, so a new color is compared too: a tab shown again rebuilds its brushes only when one changed. + public bool SameAs(Palette other) => + other.HighContrast == HighContrast && other.Dark == Dark && other.Background == Background && other.Text == Text + && other.LineNumber == LineNumber && other.CurrentLine == CurrentLine && other.Selection == Selection + && other.SelectionText == SelectionText && other.Caret == Caret && other.FindMatch == FindMatch + && other.Syntax.SequenceEqual(Syntax); + public static Palette Resolve(ElementTheme theme) { var highContrast = new AccessibilitySettings().HighContrast; diff --git a/windows/src/TablePro.Editor/SqlEditor.Caret.cs b/windows/src/TablePro.Editor/SqlEditor.Caret.cs new file mode 100644 index 0000000000..28bad833fe --- /dev/null +++ b/windows/src/TablePro.Editor/SqlEditor.Caret.cs @@ -0,0 +1,129 @@ +using Microsoft.UI.Dispatching; +using Microsoft.UI.Input; +using TablePro.Editor.Model; +using Windows.UI.ViewManagement; +using static TerraFX.Interop.Windows.SPI; +using static TerraFX.Interop.Windows.Windows; + +namespace TablePro.Editor; + +public sealed partial class SqlEditor +{ + private readonly CaretBlink _blink = new(); + private DispatcherQueueTimer? _blinkTimer; + private InputActivationListener? _activation; + private bool _hooked; + + internal bool IsCaretBlinking => _blink.IsBlinking; + + internal bool WatchesWindowActivation => _activation is not null; + + internal bool IsInActiveWindow => _activation?.State == InputActivationState.Activated; + + // Only while loaded: UISettings, the window's listener and the timer would hold the editor through its handlers. + private void Hook() + { + if (_hooked) + { + return; + } + _hooked = true; + _uiSettings.ColorValuesChanged += OnColorValuesChanged; + // The window the editor is in now, since a tab can be dragged to another one. + if (XamlRoot?.ContentIslandEnvironment?.AppWindowId is { Value: not 0 } window) + { + _activation = InputActivationListener.GetForWindowId(window); + } + if (_activation is not null) + { + _activation.InputActivationChanged += OnInputActivationChanged; + } + _blinkTimer ??= DispatcherQueue.CreateTimer(); + _blinkTimer.Tick += OnBlinkTick; + ReadCaretSettings(); + _blink.SetActive(_activation?.State != InputActivationState.Deactivated); + SyncBlinkTimer(); + } + + private void Unhook() + { + if (!_hooked) + { + return; + } + _hooked = false; + _uiSettings.ColorValuesChanged -= OnColorValuesChanged; + if (_activation is not null) + { + _activation.InputActivationChanged -= OnInputActivationChanged; + _activation = null; + } + if (_blinkTimer is not null) + { + _blinkTimer.Stop(); + _blinkTimer.Tick -= OnBlinkTick; + } + } + + // Input shows the caret and starts its timeout again. + private void RestartBlink() + { + if (_blink.Restart()) + { + Invalidate(); + } + SyncBlinkTimer(); + } + + // Started again on each change, so the next blink is a full interval after it. + private void SyncBlinkTimer() + { + if (_blinkTimer is null) + { + return; + } + _blinkTimer.Stop(); + if (_hooked && _blink.IsBlinking) + { + _blinkTimer.Interval = _blink.Interval; + _blinkTimer.Start(); + } + } + + private void OnBlinkTick(DispatcherQueueTimer sender, object args) + { + if (_blink.Tick()) + { + Invalidate(); + } + if (!_blink.IsBlinking) + { + sender.Stop(); + } + } + + private void OnInputActivationChanged(InputActivationListener sender, + InputActivationListenerActivationChangedEventArgs args) + { + if (_blink.SetActive(sender.State != InputActivationState.Deactivated)) + { + Invalidate(); + } + SyncBlinkTimer(); + } + + // AccessibilitySettings.HighContrastChanged needs a CoreWindow, and this one fires for contrast themes too. + private void OnColorValuesChanged(UISettings sender, object args) => DispatcherQueue.TryEnqueue(RebuildBrushes); + + private unsafe void ReadCaretSettings() + { + var blink = GetCaretBlinkTime(); + // INFINITE is blinking turned off, and 0 a failed call. + _blink.Interval = blink is > 0 and < uint.MaxValue ? TimeSpan.FromMilliseconds(blink) : TimeSpan.Zero; + uint timeout; + // A system that does not know SPI_GETCARETTIMEOUT fails the call; Windows' default stands in. + _blink.Timeout = SystemParametersInfoW(SPI_GETCARETTIMEOUT, 0, &timeout, 0) + ? TimeSpan.FromMilliseconds(timeout) + : CaretBlink.DefaultTimeout; + } +} diff --git a/windows/src/TablePro.Editor/SqlEditor.Keyboard.cs b/windows/src/TablePro.Editor/SqlEditor.Keyboard.cs index 11286107cf..06a6b5fe84 100644 --- a/windows/src/TablePro.Editor/SqlEditor.Keyboard.cs +++ b/windows/src/TablePro.Editor/SqlEditor.Keyboard.cs @@ -21,6 +21,7 @@ protected override void OnKeyDown(KeyRoutedEventArgs e) base.OnKeyDown(e); return; } + RestartBlink(); _tsf?.FlushPendingComposition(); // While the IME composes, its keys are its own; it hands back the ones it does not use after. if (IsComposing || e.Key == (VirtualKey)229) diff --git a/windows/src/TablePro.Editor/SqlEditor.Pointer.cs b/windows/src/TablePro.Editor/SqlEditor.Pointer.cs index 7a24334fb7..34b4557f03 100644 --- a/windows/src/TablePro.Editor/SqlEditor.Pointer.cs +++ b/windows/src/TablePro.Editor/SqlEditor.Pointer.cs @@ -57,6 +57,7 @@ private void OnPointerPressed(object sender, PointerRoutedEventArgs e) return; } Focus(FocusState.Pointer); + RestartBlink(); var position = point.Position; CountClick(point.Timestamp, position); var offset = OffsetAt(position); diff --git a/windows/src/TablePro.Editor/SqlEditor.Render.cs b/windows/src/TablePro.Editor/SqlEditor.Render.cs index caecdb6729..6506c29143 100644 --- a/windows/src/TablePro.Editor/SqlEditor.Render.cs +++ b/windows/src/TablePro.Editor/SqlEditor.Render.cs @@ -26,6 +26,12 @@ private unsafe void Render() { return; } + // Another editor on this thread found the shared device lost. + if (!_device.IsCurrent) + { + RecoverDevice(lost: false); + return; + } if (!_device.TryBeginFrame()) { RenderOnNextTick(); @@ -107,7 +113,7 @@ private unsafe void Render() var matches = FindMatchesIn(first, last); var spanIndex = 0; var primaryLine = Document.GetLineFromOffset(_model.Primary.Active); - var caretOn = _focused && _caretOn; + var caretOn = _blink.CaretVisible; var caretWidth = CaretWidth(); for (var line = first; line <= last; line++) { @@ -207,8 +213,7 @@ private unsafe void Render() var created = _layouts.CreatedThisFrame; if (!_device.EndDrawAndPresent()) { - ReleaseDevice(); - CreateDevice(); + RecoverDevice(lost: true); return; } _layouts.EndFrame(); diff --git a/windows/src/TablePro.Editor/SqlEditor.cs b/windows/src/TablePro.Editor/SqlEditor.cs index 102c358248..fa336ee0f5 100644 --- a/windows/src/TablePro.Editor/SqlEditor.cs +++ b/windows/src/TablePro.Editor/SqlEditor.cs @@ -12,7 +12,6 @@ using TablePro.Editor.Rendering; using TablePro.Graphics; using Windows.UI.ViewManagement; -using static TerraFX.Interop.Windows.Windows; namespace TablePro.Editor; @@ -45,12 +44,11 @@ public sealed partial class SqlEditor : UserControl, IDisposable private TextLayouts? _layouts; private Brushes? _brushes; private TsfInput? _tsf; - private DispatcherQueueTimer? _blinkTimer; private FindBar? _findBar; private SqlEditorAutomationPeer? _peer; private bool _renderQueued; - private bool _caretOn = true; - private bool _focused; + private bool _loaded; + private float _fontSize = DefaultFontSize; private float _zoom = 1; private string _composition = string.Empty; private int _compositionCaret; @@ -82,8 +80,6 @@ public SqlEditor() _verticalBar.ValueChanged += (_, e) => ScrollFromBar(vertical: true, e.NewValue); _horizontalBar.ValueChanged += (_, e) => ScrollFromBar(vertical: false, e.NewValue); ActualThemeChanged += (_, _) => RebuildBrushes(); - // AccessibilitySettings.HighContrastChanged needs a CoreWindow, and this one fires for contrast themes too. - _uiSettings.ColorValuesChanged += (_, _) => DispatcherQueue.TryEnqueue(RebuildBrushes); GotFocus += (_, _) => OnFocusChanged(true); LostFocus += (_, _) => OnFocusChanged(false); CharacterReceived += OnCharacterReceived; @@ -125,11 +121,23 @@ public ISyntaxLexer? Lexer public string AdapterName => _device?.AdapterName ?? string.Empty; + internal bool HoldsSwapChain => _device?.HasSwapChain == true; + public bool HasTextServices => _tsf is not null; public bool IsComposing => _tsf?.HasActiveComposition == true || _composition.Length > 0; - public float EditorFontSize { get; set; } = DefaultFontSize; + public float EditorFontSize + { + get => _fontSize; + set + { + _fontSize = value; + _layouts?.Configure(_fontSize * _zoom, _model.Options.TabSize); + UpdateScrollBars(); + Invalidate(); + } + } public float Zoom { @@ -172,11 +180,11 @@ public void Dispose() return; } _disposed = true; + Unhook(); _highlighter?.Dispose(); ReleaseDevice(); _tsf?.Dispose(); _tsf = null; - _blinkTimer?.Stop(); } protected override AutomationPeer OnCreateAutomationPeer() => _peer = new SqlEditorAutomationPeer(this); @@ -217,51 +225,71 @@ private void OnSelectionsChanged() private void OnLoaded(object sender, RoutedEventArgs e) { + if (_disposed) + { + return; + } // A flyout keeps the window it first opened in (microsoft/microsoft-ui-xaml#10207); a tab can move the editor. if (ContextFlyout?.XamlRoot is { } shown && !ReferenceEquals(shown, XamlRoot)) { ContextFlyout = BuildContextMenu(); } - CreateDevice(); + _loaded = true; + Hook(); + PrepareDevice(); + AttachSwapChain(); _tsf ??= TsfInput.Create(new TsfHost(this)); - var blink = GetCaretBlinkTime(); - if (_blinkTimer is null && blink is > 0 and < uint.MaxValue) - { - _blinkTimer = DispatcherQueue.CreateTimer(); - _blinkTimer.Interval = TimeSpan.FromMilliseconds(blink); - _blinkTimer.Tick += (_, _) => - { - _caretOn = !_caretOn; - Invalidate(); - }; - } - if (_focused) - { - _blinkTimer?.Start(); - } } + // TabView unloads a tab's content on every switch; a hidden tab keeps its layouts and brushes. private void OnUnloaded(object sender, RoutedEventArgs e) { - _blinkTimer?.Stop(); - ReleaseDevice(); + _loaded = false; + Unhook(); + _device?.Detach(); + } + + private unsafe void PrepareDevice() + { + if (_device is null) + { + _device = new GraphicsDevice(PreferSoftwareRendering); + _layouts = new TextLayouts(_device.DWrite, EditorFontSize * _zoom, _model.Options.TabSize); + RebuildBrushes(); + UpdateScrollBars(); + } + // ColorValuesChanged is watched only while loaded, so the colors may have changed while the tab was hidden. + else if (_device.IsCurrent && (_brushes is null || !_brushes.Palette.SameAs(Palette.Resolve(ActualTheme)))) + { + RebuildBrushes(); + } } - private unsafe void CreateDevice() + private void AttachSwapChain() { - if (_device is not null || _panel.ActualWidth < 1 || _panel.ActualHeight < 1) + if (!_loaded || _device is null || _device.HasSwapChain || _panel.ActualWidth < 1 || _panel.ActualHeight < 1) { return; } - _device = new GraphicsDevice(PreferSoftwareRendering); - _layouts = new TextLayouts(_device.DWrite, EditorFontSize * _zoom, _model.Options.TabSize); + if (!_device.IsCurrent) + { + _device.Recover(lost: false); + RebuildBrushes(); + } _device.Attach(_panel, PixelWidth(), PixelHeight(), _panel.CompositionScaleX, _panel.CompositionScaleY); - RebuildBrushes(); UpdateScrollBars(); Invalidate(); } + // Brushes are made on the device, and the cached layouts hold them as drawing effects. + private void RecoverDevice(bool lost) + { + _device!.Recover(lost); + RebuildBrushes(); + AttachSwapChain(); + } + private void ReleaseDevice() { _brushes?.Dispose(); @@ -274,9 +302,15 @@ private void ReleaseDevice() private void OnViewResized() { - if (_device is null) + if (_device is null || !_device.HasSwapChain) + { + AttachSwapChain(); + return; + } + // A swap chain on a removed device fails ResizeBuffers; the new one is made at the new size. + if (!_device.IsCurrent) { - CreateDevice(); + RecoverDevice(lost: false); return; } _device.Resize(PixelWidth(), PixelHeight(), _panel.CompositionScaleX, _panel.CompositionScaleY); @@ -298,31 +332,20 @@ private unsafe void RebuildBrushes() private void OnFocusChanged(bool focused) { - _focused = focused; + _blink.SetFocused(focused); + SyncBlinkTimer(); if (focused) { _tsf?.Focus(); - RestartBlink(); } else { _tsf?.Unfocus(); - _blinkTimer?.Stop(); _model.Document.Undo.BreakJoin(); } Invalidate(); } - private void RestartBlink() - { - _caretOn = true; - if (_blinkTimer is not null && _focused) - { - _blinkTimer.Stop(); - _blinkTimer.Start(); - } - } - private int PixelWidth() => (int)Math.Ceiling(_panel.ActualWidth * _panel.CompositionScaleX); private int PixelHeight() => (int)Math.Ceiling(_panel.ActualHeight * _panel.CompositionScaleY); diff --git a/windows/src/TablePro.Editor/TablePro.Editor.csproj b/windows/src/TablePro.Editor/TablePro.Editor.csproj index 657a4463a0..aa9d1625d3 100644 --- a/windows/src/TablePro.Editor/TablePro.Editor.csproj +++ b/windows/src/TablePro.Editor/TablePro.Editor.csproj @@ -16,7 +16,11 @@ - + + + + + diff --git a/windows/src/TablePro.Graphics/GraphicsDevice.cs b/windows/src/TablePro.Graphics/GraphicsDevice.cs index 4e9964f3c4..4641335298 100644 --- a/windows/src/TablePro.Graphics/GraphicsDevice.cs +++ b/windows/src/TablePro.Graphics/GraphicsDevice.cs @@ -24,21 +24,32 @@ internal sealed unsafe class GraphicsDevice : IDisposable // WinUI 3's ISwapChainPanelNative IID (microsoft.ui.xaml.media.dxinterop.h); TerraFX has only the vtable. private static readonly Guid SwapChainPanelNativeIid = new("63aad0b8-7c24-40ff-85a8-640d944cc325"); - private readonly RenderDevice _device; + // Every editor on a UI thread draws on one device, as the grid's rows do, so showing a tab makes none. + [ThreadStatic] + private static RenderDevice? s_hardware; + + [ThreadStatic] + private static RenderDevice? s_software; + + [ThreadStatic] + private static int s_swapChainsCreated; + + private readonly bool _forceSoftware; + private RenderDevice _device; private ID2D1DeviceContext* _context; private IDXGISwapChain1* _swapChain; private ID2D1Bitmap1* _target; private IDWriteFactory* _dwrite; private HANDLE _frameReady; + private SwapChainPanel? _panel; private float _scaleX = 1; private float _scaleY = 1; public GraphicsDevice(bool forceSoftware) { - _device = new RenderDevice(forceSoftware); - ID2D1DeviceContext* context; - NativeCom.Check(_device.Direct2D->CreateDeviceContext(D2D1_DEVICE_CONTEXT_OPTIONS_NONE, &context)); - _context = context; + _forceSoftware = forceSoftware; + _device = Shared(forceSoftware); + _context = CreateContext(_device); IDWriteFactory* dwrite; NativeCom.Check(DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED, NativeCom.Iid(), (IUnknown**)&dwrite)); _dwrite = dwrite; @@ -56,8 +67,15 @@ public GraphicsDevice(bool forceSoftware) public IDWriteFactory* DWrite => _dwrite; + public bool HasSwapChain => _swapChain is not null; + public bool HasTarget => _target is not null; + // False once another editor found the shared device lost and replaced it. + public bool IsCurrent => ReferenceEquals(_device, _forceSoftware ? s_software : s_hardware); + + internal static int SwapChainsCreated => s_swapChainsCreated; + public void Attach(SwapChainPanel panel, int pixelWidth, int pixelHeight, float scaleX, float scaleY) { PixelWidth = Math.Max(1, pixelWidth); @@ -81,6 +99,7 @@ public void Attach(SwapChainPanel panel, int pixelWidth, int pixelHeight, float NativeCom.Check(_device.DxgiFactory->CreateSwapChainForComposition((IUnknown*)_device.Direct3D, &description, null, &swapChain)); _swapChain = swapChain; + s_swapChainsCreated++; // A frame starts only when the swap chain can take it, so Present never blocks the UI thread. IDXGISwapChain2* swapChain2; NativeCom.Check(_swapChain->QueryInterface(NativeCom.Iid(), (void**)&swapChain2)); @@ -88,19 +107,51 @@ public void Attach(SwapChainPanel panel, int pixelWidth, int pixelHeight, float _frameReady = swapChain2->GetFrameLatencyWaitableObject(); swapChain2->Release(); ApplyScale(); + SetSwapChain(panel, (IDXGISwapChain*)_swapChain); + _panel = panel; + CreateTarget(); + } - var inspectable = ((WinRT.IWinRTObject)panel).NativeObject.ThisPtr; - var iid = SwapChainPanelNativeIid; - Marshal.ThrowExceptionForHR(Marshal.QueryInterface(inspectable, in iid, out var native)); - try + // A hidden editor gives back its three window-sized buffers; its context and what it made on it stay. + public void Detach() + { + if (_frameReady != HANDLE.NULL) + { + CloseHandle(_frameReady); + _frameReady = HANDLE.NULL; + } + if (_context is not null) { - NativeCom.Check(((TerraFX.Interop.WinRT.ISwapChainPanelNative*)native)->SetSwapChain((IDXGISwapChain*)_swapChain)); + _context->SetTarget(null); } - finally + NativeCom.Release(ref _target); + if (_panel is not null) { - Marshal.Release(native); + SetSwapChain(_panel, null); + _panel = null; } - CreateTarget(); + NativeCom.Release(ref _swapChain); + } + + // The first editor to see the loss replaces the shared device; the caller then remakes its brushes and swap chain. + public void Recover(bool lost) + { + Detach(); + NativeCom.Release(ref _context); + if (lost && IsCurrent) + { + if (_forceSoftware) + { + s_software = null; + } + else + { + s_hardware = null; + } + _device.Dispose(); + } + _device = Shared(_forceSoftware); + _context = CreateContext(_device); } public void Resize(int pixelWidth, int pixelHeight, float scaleX, float scaleY) @@ -150,22 +201,44 @@ public bool EndDrawAndPresent() return true; } + // The shared device stays for the thread's other editors. public void Dispose() { - if (_frameReady != HANDLE.NULL) + Detach(); + NativeCom.Release(ref _context); + NativeCom.Release(ref _dwrite); + } + + private static RenderDevice Shared(bool forceSoftware) + { + if (forceSoftware) { - CloseHandle(_frameReady); - _frameReady = HANDLE.NULL; + return s_software ??= new RenderDevice(forceSoftware: true); } - if (_context is not null) + return s_hardware ??= new RenderDevice(forceSoftware: false); + } + + private static ID2D1DeviceContext* CreateContext(RenderDevice device) + { + ID2D1DeviceContext* context; + NativeCom.Check(device.Direct2D->CreateDeviceContext(D2D1_DEVICE_CONTEXT_OPTIONS_NONE, &context)); + return context; + } + + // Null takes the swap chain off the panel. + private static void SetSwapChain(SwapChainPanel panel, IDXGISwapChain* swapChain) + { + var inspectable = ((WinRT.IWinRTObject)panel).NativeObject.ThisPtr; + var iid = SwapChainPanelNativeIid; + Marshal.ThrowExceptionForHR(Marshal.QueryInterface(inspectable, in iid, out var native)); + try { - _context->SetTarget(null); + NativeCom.Check(((TerraFX.Interop.WinRT.ISwapChainPanelNative*)native)->SetSwapChain(swapChain)); + } + finally + { + Marshal.Release(native); } - NativeCom.Release(ref _target); - NativeCom.Release(ref _swapChain); - NativeCom.Release(ref _context); - _device.Dispose(); - NativeCom.Release(ref _dwrite); } // The panel shows the buffer at its own scale, so the buffer is drawn in pixels and shrunk back by the scale. diff --git a/windows/src/TablePro.Graphics/RenderDevice.cs b/windows/src/TablePro.Graphics/RenderDevice.cs index 781c708b95..80dec74f65 100644 --- a/windows/src/TablePro.Graphics/RenderDevice.cs +++ b/windows/src/TablePro.Graphics/RenderDevice.cs @@ -11,6 +11,10 @@ namespace TablePro.Graphics; // The Basic Render Driver is WARP behind a hardware device type, as on VMs and CI runners without a GPU. internal sealed unsafe class RenderDevice : IDisposable { + // Per thread, so a test on the UI thread does not count the font warm-up's device on a pool thread. + [ThreadStatic] + private static int s_created; + private ID3D11Device* _d3d; private IDXGIFactory2* _dxgiFactory; private ID2D1Factory1* _d2dFactory; @@ -61,8 +65,11 @@ public RenderDevice(bool forceSoftware, bool multithreaded = false) { dxgiDevice->Release(); } + s_created++; } + internal static int CreatedOnThisThread => s_created; + public bool IsSoftware { get; } public string AdapterName { get; } = string.Empty; diff --git a/windows/src/TablePro.Graphics/TablePro.Graphics.csproj b/windows/src/TablePro.Graphics/TablePro.Graphics.csproj index 39bbc67006..190a023fac 100644 --- a/windows/src/TablePro.Graphics/TablePro.Graphics.csproj +++ b/windows/src/TablePro.Graphics/TablePro.Graphics.csproj @@ -19,10 +19,11 @@ + - + diff --git a/windows/src/TablePro.Interop/DatabaseSession.cs b/windows/src/TablePro.Interop/DatabaseSession.cs index 3109d01aa4..8e0a36145c 100644 --- a/windows/src/TablePro.Interop/DatabaseSession.cs +++ b/windows/src/TablePro.Interop/DatabaseSession.cs @@ -126,6 +126,17 @@ public async Task CountRowsAsync( return Mapping.Count(count); } + // The whole table's, from the engine's statistics, so it costs no count; null where the engine keeps none. + public async Task EstimateRowsAsync(TableName table, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(table); + var estimate = await CoreCall.RunAsync( + token => _session.TableRowEstimate(Mapping.Table(table), token), + cancellationToken) + .ConfigureAwait(false); + return Mapping.Estimate(estimate); + } + // Kind decides whether a CREATE script belongs: a view gets none. public async Task GetStructureAsync( TableName table, diff --git a/windows/src/TablePro.Interop/Generated/tablepro_ffi.cs b/windows/src/TablePro.Interop/Generated/tablepro_ffi.cs index 1291135e3e..7d7351609b 100644 --- a/windows/src/TablePro.Interop/Generated/tablepro_ffi.cs +++ b/windows/src/TablePro.Interop/Generated/tablepro_ffi.cs @@ -1080,6 +1080,8 @@ public struct UniffiVTableCallbackInterfaceRunListener + + @@ -2237,6 +2239,17 @@ public static extern ulong uniffi_tablepro_ffi_fn_method_databasesession_table_row_count(ulong @ptr,RustBuffer @table,RustBuffer @filter,RustBuffer @cancel ); + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ulong uniffi_tablepro_ffi_fn_method_databasesession_table_row_estimate(ulong @ptr,RustBuffer @table,RustBuffer @cancel + ); + #if NET8_0_OR_GREATER [LibraryImport("tablepro_ffi")] [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] @@ -3821,6 +3834,17 @@ public static extern ushort uniffi_tablepro_ffi_checksum_method_databasesession_table_row_count( ); + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_databasesession_table_row_estimate( + ); + #if NET8_0_OR_GREATER [LibraryImport("tablepro_ffi")] [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] @@ -4520,6 +4544,12 @@ static void uniffiCheckApiChecksums() { throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_databasesession_table_row_count` checksum `47733`, library returned `{checksum}`"); } } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_databasesession_table_row_estimate(); + if (checksum != 301) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_databasesession_table_row_estimate` checksum `301`, library returned `{checksum}`"); + } + } { var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_databasesession_table_structure(); if (checksum != 41263) { @@ -5805,6 +5835,8 @@ internal interface IDatabaseSession { /// Task TableRowCount(TableName @table, TableFilterArg? @filter, CancelToken? @cancel); /// + Task TableRowEstimate(TableName @table, CancelToken? @cancel); + /// Task TableStructure(TableName @table, ObjectKindTag @kind, CancelToken? @cancel); } internal class DatabaseSession : IDatabaseSession, IDisposable { @@ -6282,6 +6314,28 @@ public async Task TableRowCount(TableName @table, TableFilterArg? @filter ); } + /// + public async Task TableRowEstimate(TableName @table, CancelToken? @cancel) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_table_row_estimate(thisPtr, FfiConverterTypeTableName.INSTANCE.Lower(@table), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + // Lift + (result) => FfiConverterTypeRowEstimate.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + /// public async Task TableStructure(TableName @table, ObjectKindTag @kind, CancelToken? @cancel) { return await _UniFFIAsync.UniffiRustCallAsync( @@ -11082,6 +11136,85 @@ public override void Write(RowEdit value, BigEndianStream stream) { +internal record RowEstimate { + + public record Exact ( + ulong Rows + ) : RowEstimate {} + + public record Approximate ( + ulong Rows + ) : RowEstimate {} + + public record Unknown: RowEstimate {} + + + + +} + +class FfiConverterTypeRowEstimate : FfiConverterRustBuffer{ + public static FfiConverterRustBuffer INSTANCE = new FfiConverterTypeRowEstimate(); + + public override RowEstimate Read(BigEndianStream stream) { + var value = stream.ReadInt(); + switch (value) { + case 1: + return new RowEstimate.Exact( + FfiConverterUInt64.INSTANCE.Read(stream) + ); + case 2: + return new RowEstimate.Approximate( + FfiConverterUInt64.INSTANCE.Read(stream) + ); + case 3: + return new RowEstimate.Unknown( + ); + default: + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeRowEstimate.Read()", value)); + } + } + + public override int AllocationSize(RowEstimate value) { + switch (value) { + case RowEstimate.Exact variant_value: + return 4 + + FfiConverterUInt64.INSTANCE.AllocationSize(variant_value.Rows); + case RowEstimate.Approximate variant_value: + return 4 + + FfiConverterUInt64.INSTANCE.AllocationSize(variant_value.Rows); + case RowEstimate.Unknown variant_value: + return 4; + default: + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeRowEstimate.AllocationSize()", value)); + } + } + + public override void Write(RowEstimate value, BigEndianStream stream) { + switch (value) { + case RowEstimate.Exact variant_value: + stream.WriteInt(1); + FfiConverterUInt64.INSTANCE.Write(variant_value.Rows, stream); + break; + case RowEstimate.Approximate variant_value: + stream.WriteInt(2); + FfiConverterUInt64.INSTANCE.Write(variant_value.Rows, stream); + break; + case RowEstimate.Unknown variant_value: + stream.WriteInt(3); + break; + default: + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeRowEstimate.Write()", value)); + } + } +} + + + + + + + internal record RowSaveOutcome { public record Saved ( diff --git a/windows/src/TablePro.Interop/Mapping.cs b/windows/src/TablePro.Interop/Mapping.cs index cc977d9a1e..37f4fd862a 100644 --- a/windows/src/TablePro.Interop/Mapping.cs +++ b/windows/src/TablePro.Interop/Mapping.cs @@ -189,6 +189,14 @@ [.. structure.Indexes.Select(index => key.OnUpdate))], structure.Ddl); + // Null where the engine keeps no statistics for the table, as SQLite before ANALYZE. + public static RowEstimate? Estimate(Native.RowEstimate estimate) => estimate switch + { + Native.RowEstimate.Exact exact => new RowEstimate(Count(exact.Rows), IsExact: true), + Native.RowEstimate.Approximate approximate => new RowEstimate(Count(approximate.Rows), IsExact: false), + _ => null, + }; + public static ObjectSource Source(Native.ObjectSource source) => new(source.Sql, source.Database, source.OpensInEditor); diff --git a/windows/src/TablePro.Interop/RowEstimate.cs b/windows/src/TablePro.Interop/RowEstimate.cs new file mode 100644 index 0000000000..4cc5819419 --- /dev/null +++ b/windows/src/TablePro.Interop/RowEstimate.cs @@ -0,0 +1,4 @@ +namespace TablePro.Interop; + +// The engine's own idea of a table's rows, read from its statistics with no scan; exact where it keeps the count. +public sealed record RowEstimate(long Rows, bool IsExact); diff --git a/windows/tests/Shared/WinUiApp.cs b/windows/tests/Shared/WinUiApp.cs new file mode 100644 index 0000000000..ba391db0a3 --- /dev/null +++ b/windows/tests/Shared/WinUiApp.cs @@ -0,0 +1,133 @@ +using Microsoft.UI.Dispatching; +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Controls; +using Microsoft.UI.Xaml.Markup; +using Microsoft.UI.Xaml.Media; +using Microsoft.UI.Xaml.XamlTypeInfo; +using Windows.Graphics; + +namespace TablePro.Testing; + +// One WinUI app per test run, on an STA thread of its own, in the gate's 1440 x 900 window. +internal static class WinUiApp +{ + private static readonly Lazy> s_queue = new(StartAsync); + + public static Window Window { get; private set; } = null!; + + // An exception XAML raised on the UI thread during the test, which would otherwise end the process. + public static Exception? Unhandled { get; set; } + + public static async Task RunAsync(Func body) + { + var queue = await s_queue.Value.WaitAsync(TimeSpan.FromSeconds(90)); + var done = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + queue.TryEnqueue(async () => + { + try + { + Unhandled = null; + await body(); + if (Unhandled is { } error) + { + throw new InvalidOperationException("XAML raised an unhandled exception", error); + } + done.SetResult(); + } + catch (Exception ex) + { + done.SetException(ex); + } + }); + await done.Task.WaitAsync(TimeSpan.FromMinutes(5)); + } + + public static Task NextFrameAsync() + { + var tcs = new TaskCompletionSource(); + EventHandler? handler = null; + handler = (_, _) => + { + CompositionTarget.Rendering -= handler; + tcs.TrySetResult(); + }; + CompositionTarget.Rendering += handler; + return tcs.Task; + } + + private static Task StartAsync() + { + var ready = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var thread = new Thread(() => + { + try + { + WinRT.ComWrappersSupport.InitializeComWrappers(); + Application.Start(callback => + { + var queue = DispatcherQueue.GetForCurrentThread(); + SynchronizationContext.SetSynchronizationContext(new DispatcherQueueSynchronizationContext(queue)); + _ = new TestApp(window => + { + Window = window; + ready.TrySetResult(queue); + }, error => ready.TrySetException(error)); + }); + } + catch (Exception ex) + { + ready.TrySetException(ex); + } + }) + { + IsBackground = true, + Name = "WinUI", + }; + thread.SetApartmentState(ApartmentState.STA); + thread.Start(); + return ready.Task; + } +} + +// An app with no XAML files, so the WinUI controls' types come from their own metadata provider. +internal sealed partial class TestApp : Application, IXamlMetadataProvider +{ + private readonly XamlControlsXamlMetaDataProvider _provider; + private readonly Action _ready; + private readonly Action _failed; + + public TestApp(Action ready, Action failed) + { + _ready = ready; + _failed = failed; + XamlControlsXamlMetaDataProvider.Initialize(); + _provider = new XamlControlsXamlMetaDataProvider(); + UnhandledException += (_, e) => + { + e.Handled = true; + WinUiApp.Unhandled ??= e.Exception; + }; + } + + public IXamlType GetXamlType(Type type) => _provider.GetXamlType(type); + + public IXamlType GetXamlType(string fullName) => _provider.GetXamlType(fullName); + + public XmlnsDefinition[] GetXmlnsDefinitions() => _provider.GetXmlnsDefinitions(); + + protected override void OnLaunched(LaunchActivatedEventArgs args) + { + try + { + Resources.MergedDictionaries.Add(new XamlControlsResources()); + var window = new Window { Title = typeof(TestApp).Assembly.GetName().Name ?? nameof(TestApp) }; + window.AppWindow.MoveAndResize(new RectInt32(40, 40, 1440, 900)); + window.Activate(); + _ready(window); + } + catch (Exception ex) + { + _failed(ex); + } + } +} diff --git a/windows/tests/TablePro.App.Model.Tests/DefinitionTabTests.cs b/windows/tests/TablePro.App.Model.Tests/DefinitionTabTests.cs index f0a6a091d0..42d8785e79 100644 --- a/windows/tests/TablePro.App.Model.Tests/DefinitionTabTests.cs +++ b/windows/tests/TablePro.App.Model.Tests/DefinitionTabTests.cs @@ -248,6 +248,9 @@ public Task ReadTablePageAsync( public Task CountRowsAsync(TableName table, TableFilter? filter, CancellationToken cancellationToken) => throw new NotSupportedException(); + public Task EstimateRowsAsync(TableName table, CancellationToken cancellationToken) => + throw new NotSupportedException(); + public Task GetFilterChoicesAsync(TableName table, CancellationToken cancellationToken) => throw new NotSupportedException(); diff --git a/windows/tests/TablePro.App.Model.Tests/ObjectFoldersTests.cs b/windows/tests/TablePro.App.Model.Tests/ObjectFoldersTests.cs index e776a76e24..911251680a 100644 --- a/windows/tests/TablePro.App.Model.Tests/ObjectFoldersTests.cs +++ b/windows/tests/TablePro.App.Model.Tests/ObjectFoldersTests.cs @@ -1,3 +1,4 @@ +using System.Globalization; using TablePro.Interop; namespace TablePro.App.Model.Tests; @@ -11,10 +12,11 @@ private static ObjectEntry Entry(string name, ObjectKind kind = ObjectKind.Table public void ObjectsGoIntoOneFolderPerKindInTheFixedOrderSortedByName() { var folders = ObjectFolders.Group( - [ - Entry("zeta"), Entry("v_people", ObjectKind.View), Entry("alpha"), Entry("parts", ObjectKind.PartitionedTable), - Entry("next_id", ObjectKind.Sequence), - ]); + [ + Entry("zeta"), Entry("v_people", ObjectKind.View), Entry("alpha"), Entry("parts", ObjectKind.PartitionedTable), + Entry("next_id", ObjectKind.Sequence), + ], + CultureInfo.InvariantCulture); Assert.Equal([FolderKind.Tables, FolderKind.Views, FolderKind.Sequences], folders.Select(folder => folder.Kind)); Assert.Equal(["alpha", "parts", "zeta"], folders[0].Objects.Select(entry => entry.Name)); @@ -23,9 +25,7 @@ public void ObjectsGoIntoOneFolderPerKindInTheFixedOrderSortedByName() [Fact] public void AFilterRanksNamesThatStartWithTheTextFirst() { - var matches = ObjectFolders.Filter( - [Entry("user_roles"), Entry("audit_users"), Entry("Users"), Entry("orders")], - "USER"); + var matches = Catalog(Entry("user_roles"), Entry("audit_users"), Entry("Users"), Entry("orders")).Filter("USER", TestContext.Current.CancellationToken); Assert.Equal(["user_roles", "Users", "audit_users"], matches.Select(entry => entry.Name)); } @@ -33,9 +33,64 @@ public void AFilterRanksNamesThatStartWithTheTextFirst() [Fact] public void AnEmptyFilterMatchesNothing() { - Assert.Empty(ObjectFolders.Filter([Entry("a")], " ")); + Assert.Empty(Catalog(Entry("a")).Filter(" ", TestContext.Current.CancellationToken)); } + // The order the list showed when each keystroke sorted its matches: starts-with first, then name, then schema. + [Theory] + [InlineData("en-US")] + [InlineData("vi-VN")] + [InlineData("de-DE")] + [InlineData("tr-TR")] + public void TheCatalogFiltersInTheOrderAPerKeystrokeSortGave(string name) + { + var culture = CultureInfo.GetCultureInfo(name); + var names = new[] + { + "users", "Users", "user_roles", "audit_users", "đơn_hàng", "Đơn_Hàng_cũ", "khách_hàng", "ıncome", "Income", + "INCOME_tax", "straße", "STRASSE", "orders", "order_items", "s_user", "USER", "zuser", "a_user_b", + }; + var entries = names + .SelectMany(each => new[] { Entry(each, schema: "public"), Entry(each, schema: "archive"), Entry(each) }) + .ToList(); + var catalog = new ObjectCatalog(entries, culture); + var shown = CultureInfo.CurrentCulture; + CultureInfo.CurrentCulture = culture; + try + { + foreach (var text in new[] { "user", "USER", "đơn", "hàng", "income", "İNCOME", "strasse", "ß", "o", " r " }) + { + var needle = text.Trim(); + List expected = + [ + .. entries + .Where(entry => entry.Name.Contains(needle, StringComparison.CurrentCultureIgnoreCase)) + .OrderBy(entry => entry.Name.StartsWith(needle, StringComparison.CurrentCultureIgnoreCase) ? 0 : 1) + .ThenBy(entry => entry.Name, StringComparer.CurrentCultureIgnoreCase) + .ThenBy(entry => entry.Schema, StringComparer.CurrentCultureIgnoreCase), + ]; + + Assert.Equal(expected, catalog.Filter(text, TestContext.Current.CancellationToken)); + } + } + finally + { + CultureInfo.CurrentCulture = shown; + } + } + + [Fact] + public void AFilterStoppedMidwayThrowsInsteadOfReturningPartOfTheMatches() + { + var catalog = Catalog([.. Enumerable.Range(0, 5_000).Select(index => Entry($"t{index}"))]); + using var stopped = new CancellationTokenSource(); + stopped.Cancel(); + + Assert.Throws(() => catalog.Filter("t", stopped.Token)); + } + + private static ObjectCatalog Catalog(params ObjectEntry[] entries) => new(entries, CultureInfo.InvariantCulture); + [Fact] public void OnlyTablesAndViewsHaveRowsToShow() { diff --git a/windows/tests/TablePro.App.Model.Tests/RunResultsTests.cs b/windows/tests/TablePro.App.Model.Tests/RunResultsTests.cs index 407dddb3c7..de9484875f 100644 --- a/windows/tests/TablePro.App.Model.Tests/RunResultsTests.cs +++ b/windows/tests/TablePro.App.Model.Tests/RunResultsTests.cs @@ -91,6 +91,37 @@ public void EventsAboutNoListedSetChangeNothing() Assert.Equal(0, only.Rows); } + // A script of one statement per sequence returns a set per statement, and each event finds its own. + [Fact] + public void TenThousandSetsEachTakeTheirOwnRowsAndPlace() + { + var results = New(); + var sets = Enumerable.Range(0, 10_000).Select(index => results.Add(index * 2, Columns)).ToList(); + + foreach (var index in Enumerable.Range(0, sets.Count).Reverse()) + { + results.Apply(new QueryEvent.RowsAppended(index * 2, index)); + results.Apply(new QueryEvent.ResultSetFinished(index * 2, index + 1, null, Truncation.Complete)); + } + + Assert.Null(results.Apply(new QueryEvent.RowsAppended(1, 5))); + Assert.Equal(Enumerable.Range(1, sets.Count).Select(rows => (long)rows), sets.Select(set => set.Rows)); + Assert.Equal("Result 1 (1)", results.Label(sets[0])); + Assert.Equal("Result 10000 (10000)", results.Label(sets[^1])); + } + + [Fact] + public void TwoSetsWithOneIndexLeaveTheEventsToTheFirst() + { + var results = New(); + var first = results.Add(3, Columns); + var second = results.Add(3, Columns); + + Assert.Same(first, results.Apply(new QueryEvent.RowsAppended(3, 8))); + Assert.Equal(0, second.Rows); + Assert.Equal("Result 2 (0)", results.Label(second)); + } + // No number format, so the labels read the same under every culture. private static RunResults New() => new("Result {0} ({1})", "Result {0} ({1}+)"); } diff --git a/windows/tests/TablePro.App.Model.Tests/TabFakes.cs b/windows/tests/TablePro.App.Model.Tests/TabFakes.cs index aedb042878..8477ebeb3c 100644 --- a/windows/tests/TablePro.App.Model.Tests/TabFakes.cs +++ b/windows/tests/TablePro.App.Model.Tests/TabFakes.cs @@ -52,6 +52,15 @@ internal sealed class FakeSession : ITabSession public Gate? Counting { get; set; } + public Gate? Estimating { get; set; } + + // None by default, as an engine without statistics gives, so the server counts as it did before estimates. + public RowEstimate? Estimate { get; set; } + + public CoreError? EstimateFailure { get; set; } + + public int Estimates { get; private set; } + // Waited at by the run of each page read. public Gate? PageReading { get; set; } @@ -210,6 +219,17 @@ public async Task CountRowsAsync(TableName table, TableFilter? filter, Can return RowsPicked(filter); } + public async Task EstimateRowsAsync(TableName table, CancellationToken cancellationToken) + { + Estimates++; + if (Estimating is { } estimating) + { + await estimating.PassAsync(cancellationToken); + } + + return EstimateFailure is { } failure ? throw new TableProException(failure) : Estimate; + } + public Task GetFilterChoicesAsync(TableName table, CancellationToken cancellationToken) { ChoicesReads++; diff --git a/windows/tests/TablePro.App.Model.Tests/TableTabCountTests.cs b/windows/tests/TablePro.App.Model.Tests/TableTabCountTests.cs new file mode 100644 index 0000000000..6a755d57c2 --- /dev/null +++ b/windows/tests/TablePro.App.Model.Tests/TableTabCountTests.cs @@ -0,0 +1,176 @@ +using TablePro.Interop; + +namespace TablePro.App.Model.Tests; + +public sealed class TableTabCountTests +{ + private static readonly TableFilter ByName = new( + FilterCombinator.And, + [new FilterRule("Name", FilterOperator.Contains, new FilterValue.One("AC"))], + null); + + private readonly FakeSession _session = new() { TableRows = 2_000_123, FilteredRows = 1_200 }; + private readonly FakeTableView _view = new(); + private readonly FakeResults _results = new(); + private AppSettings _settings = new(); + + [Fact] + public async Task AnEstimateOfTwoMillionRowsShowsWithNoCountAndLeavesLastAndGoToPageOff() + { + _session.Estimate = new RowEstimate(2_000_000, IsExact: false); + var tab = New(); + + await tab.RunAsync(); + + Assert.Equal(0, _session.Counts); + Assert.Equal(2_000_000, tab.Page.Estimate); + Assert.Null(tab.Page.Total); + Assert.Null(tab.Page.Count); + Assert.True(tab.Page.HasNext); + Assert.False(tab.Page.HasLast); + Assert.False(tab.Page.Accepts(2)); + Assert.True(tab.OffersCount); + Assert.True(tab.CanCountRows); + + await tab.ShowAllRowsAsync(); + await tab.NextPageAsync(); + + Assert.Equal(1_000, tab.Page.Size); + Assert.Equal(1_000, tab.Page.Offset); + Assert.Equal(2_000_000, tab.Page.Estimate); + Assert.Equal(1, _session.Estimates); + Assert.Equal(0, _session.Counts); + } + + [Theory] + [InlineData(50_000L, 1)] + [InlineData(99_999L, 1)] + [InlineData(100_000L, 0)] + [InlineData(2_000_000L, 0)] + public async Task TheServerCountsByItselfOnlyATableEstimatedUnderAHundredThousandRows(long estimate, int counts) + { + _session.Estimate = new RowEstimate(estimate, IsExact: false); + var tab = New(); + + await tab.RunAsync(); + + long? total = counts == 1 ? 2_000_123 : null; + Assert.Equal(counts, _session.Counts); + Assert.Equal(total, tab.Page.Total); + Assert.Equal(estimate, tab.Page.Estimate); + } + + [Fact] + public async Task AnExactEstimateOfTheWholeTableIsItsTotalWithNoCount() + { + _settings = new AppSettings { PageSize = 5 }; + _session.TableRows = 7; + _session.Estimate = new RowEstimate(7, IsExact: true); + var tab = New(); + + await tab.RunAsync(); + + Assert.Equal(0, _session.Counts); + Assert.Equal(7, tab.Page.Total); + Assert.Equal(2, tab.Page.Count); + Assert.True(tab.Page.HasLast); + Assert.False(tab.OffersCount); + } + + [Fact] + public async Task UnderAFilterTheTablesEstimateOfTwoMillionCountsNothingAndShowsNoTotal() + { + _session.Estimate = new RowEstimate(2_000_000, IsExact: false); + var tab = New(); + await tab.RunAsync(); + + await tab.ApplyFilterAsync(ByName); + + Assert.Equal(2, _session.Estimates); + Assert.Equal(0, _session.Counts); + Assert.Null(tab.Page.Total); + Assert.Null(tab.Page.Estimate); + Assert.True(tab.OffersCount); + } + + [Fact] + public async Task WithNoEstimateTheServerCountsAsBefore() + { + var tab = New(); + + await tab.RunAsync(); + + Assert.Equal(1, _session.Estimates); + Assert.Equal(1, _session.Counts); + Assert.Equal(2_000_123, tab.Page.Total); + Assert.Null(tab.Page.Estimate); + } + + [Fact] + public async Task AnEstimateThatFailsLeavesTheCountToTheServer() + { + _session.EstimateFailure = Errors.Of("operation.timeout"); + var tab = New(); + + await tab.RunAsync(); + + Assert.Equal(1, _session.Estimates); + Assert.Equal(1, _session.Counts); + Assert.Equal(2_000_123, tab.Page.Total); + } + + [Fact] + public async Task CountRowsCountsTheTableTheEstimateHeldBack() + { + _session.Estimate = new RowEstimate(2_000_000, IsExact: false); + var tab = New(); + await tab.RunAsync(); + + await tab.CountRowsAsync(); + + Assert.Equal(1, _session.Estimates); + Assert.Equal(1, _session.Counts); + Assert.Equal(2_000_123, tab.Page.Total); + Assert.True(tab.Page.HasLast); + Assert.False(tab.OffersCount); + Assert.False(tab.IsCounting); + } + + [Fact] + public async Task AnEstimateThatLandsAsTheTabClosesShowsNothingAndCountsNothing() + { + var estimating = new Gate(honorsCancel: false); + _session.Estimating = estimating; + _session.Estimate = new RowEstimate(2_000_000, IsExact: false); + var tab = New(); + await tab.RunAsync(); + await estimating.Reached; + var pagers = _view.Pagers.Count; + + var closing = tab.CloseAsync(); + var waited = !closing.IsCompleted; + estimating.Open(); + await closing; + + Assert.True(waited); + Assert.Null(tab.Page.Estimate); + Assert.Null(tab.Page.Total); + Assert.Equal(0, _session.Counts); + Assert.Equal(pagers, _view.Pagers.Count); + Assert.Equal(1, _session.Releases); + } + + private TableTab New() + { + var tab = new TableTab( + _session, + _view, + _results, + new TableName(null, "Artist"), + ObjectKind.Table, + () => _settings, + null); + _view.Tab = tab; + return tab; + } +} diff --git a/windows/tests/TablePro.App.Model.Tests/TableTabTests.cs b/windows/tests/TablePro.App.Model.Tests/TableTabTests.cs index 7f334ed14f..ca29c8e878 100644 --- a/windows/tests/TablePro.App.Model.Tests/TableTabTests.cs +++ b/windows/tests/TablePro.App.Model.Tests/TableTabTests.cs @@ -133,6 +133,91 @@ public void ARestoredTabStartsAtThePageHoldingItsFirstRow() Assert.False(tab.Shows("main", "Artist")); } + [Fact] + public async Task OfTenRestoredTableTabsOnlyTheOneThatShowsReadsItsTable() + { + var saved = Enumerable.Range(1, 10) + .Select(index => new SessionTab { Kind = TabKind.Table, Title = $"T{index}", Table = $"T{index}" }) + .ToList(); + var (restored, selected) = SessionTabs.Persisted(saved, 4); + var tabs = restored + .Select(tab => new TableTab( + _session, + new FakeTableView(), + new FakeResults(), + new TableName(tab.Schema, tab.Table!), + tab.ObjectKindOr(ObjectKind.Table), + () => _settings, + tab)) + .ToList(); + + await tabs[selected].ShowAsync(); + + Assert.Equal(10, tabs.Count); + Assert.Single(_session.Pages); + Assert.Equal(1, _session.TableEditorOpens); + Assert.Equal(1, _session.Counts); + Assert.Equal(1_000, tabs[selected].Page.Rows); + } + + [Fact] + public async Task ATabReadsItsPageTheFirstTimeItShowsAndNotAgain() + { + await _tab.ShowAsync(); + await _tab.ShowAsync(); + + Assert.Single(_session.Queries); + Assert.Equal(1, _session.TableEditorOpens); + Assert.Equal(1, _session.Counts); + } + + [Fact] + public async Task ARunBeforeTheTabFirstShowsCountsAsItsShow() + { + await _tab.RunAsync(); + await _tab.ShowAsync(); + + Assert.Single(_session.Queries); + } + + [Fact] + public void ATabThatNeverShowedSavesThePageSizeOffsetAndFilterItWasRestoredWith() + { + var filter = new TableFilter( + FilterCombinator.And, + [new FilterRule("Name", FilterOperator.Contains, new FilterValue.One("AC"))], + null); + var tab = New(new SessionTab + { + Kind = TabKind.Table, + Title = "Artist", + Table = "Artist", + PageSize = 20, + Offset = 40, + Filter = SavedFilter.From(filter), + }); + + var snapshot = tab.Snapshot(); + + Assert.Equal(20, snapshot.PageSize); + Assert.Equal(40, snapshot.Offset); + Assert.Equal(FilterText.Of(filter), FilterText.Of(snapshot.Filter?.ToFilter())); + Assert.Empty(_session.Queries); + } + + [Fact] + public async Task ATabClosedBeforeItShowedLetsItsSessionGoOnceAndReadsNothing() + { + await _tab.CloseAsync(); + await _tab.ShowAsync(); + + Assert.Equal(1, _session.Releases); + Assert.Empty(_session.Queries); + Assert.Equal(0, _session.TableEditorOpens); + Assert.Equal(0, _session.Counts); + Assert.Equal(0, _session.Estimates); + } + [Fact] public async Task ASortReadsTheFirstPageInOrderAndARefusedOneKeepsTheShownSort() { diff --git a/windows/tests/TablePro.DataGrid.Tests/TablePro.DataGrid.Tests.csproj b/windows/tests/TablePro.DataGrid.Tests/TablePro.DataGrid.Tests.csproj index aeda957e25..23e18c145d 100644 --- a/windows/tests/TablePro.DataGrid.Tests/TablePro.DataGrid.Tests.csproj +++ b/windows/tests/TablePro.DataGrid.Tests/TablePro.DataGrid.Tests.csproj @@ -41,6 +41,10 @@ + + + + diff --git a/windows/tests/TablePro.DataGrid.Tests/WinUiHost.cs b/windows/tests/TablePro.DataGrid.Tests/WinUiHost.cs index 18dc7f2c73..2e6c1b4268 100644 --- a/windows/tests/TablePro.DataGrid.Tests/WinUiHost.cs +++ b/windows/tests/TablePro.DataGrid.Tests/WinUiHost.cs @@ -1,51 +1,21 @@ using System.Globalization; -using Microsoft.UI.Dispatching; -using Microsoft.UI.Windowing; using Microsoft.UI.Xaml; -using Microsoft.UI.Xaml.Controls; -using Microsoft.UI.Xaml.Markup; using Microsoft.UI.Xaml.Media; -using Microsoft.UI.Xaml.XamlTypeInfo; using TablePro.DataGrid.Model; -using Windows.Graphics; +using TablePro.Testing; [assembly: CollectionBehavior(CollectionBehavior.CollectionPerAssembly)] namespace TablePro.DataGrid.Tests; -// One WinUI app per test run, on an STA thread of its own, in the gate's 1440 x 900 window. +// The grid's side of the shared WinUI app in tests/Shared/WinUiApp.cs. internal static class WinUiHost { - private static readonly Lazy> s_queue = new(StartAsync); + public static Window Window => WinUiApp.Window; - public static Window Window { get; private set; } = null!; + public static Task RunAsync(Func body) => WinUiApp.RunAsync(body); - // An exception XAML raised on the UI thread during the test, which would otherwise end the process. - public static Exception? Unhandled { get; set; } - - public static async Task RunAsync(Func body) - { - var queue = await s_queue.Value.WaitAsync(TimeSpan.FromSeconds(90)); - var done = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - queue.TryEnqueue(async () => - { - try - { - Unhandled = null; - await body(); - if (Unhandled is { } error) - { - throw new InvalidOperationException("XAML raised an unhandled exception", error); - } - done.SetResult(); - } - catch (Exception ex) - { - done.SetException(ex); - } - }); - await done.Task.WaitAsync(TimeSpan.FromMinutes(5)); - } + public static Task NextFrameAsync() => WinUiApp.NextFrameAsync(); // A grid with data in the window, laid out and drawn. public static async Task ShowAsync(IGridData data, int frozen = 0, bool sizeToContent = false) @@ -65,95 +35,6 @@ public static async Task ShowAsync(IGridData data, int frozen = 0, await NextFrameAsync(); return grid; } - - public static Task NextFrameAsync() - { - var tcs = new TaskCompletionSource(); - EventHandler? handler = null; - handler = (_, _) => - { - CompositionTarget.Rendering -= handler; - tcs.TrySetResult(); - }; - CompositionTarget.Rendering += handler; - return tcs.Task; - } - - private static Task StartAsync() - { - var ready = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - var thread = new Thread(() => - { - try - { - WinRT.ComWrappersSupport.InitializeComWrappers(); - Application.Start(callback => - { - var queue = DispatcherQueue.GetForCurrentThread(); - SynchronizationContext.SetSynchronizationContext(new DispatcherQueueSynchronizationContext(queue)); - _ = new TestApp(window => - { - Window = window; - ready.TrySetResult(queue); - }, error => ready.TrySetException(error)); - }); - } - catch (Exception ex) - { - ready.TrySetException(ex); - } - }) - { - IsBackground = true, - Name = "WinUI", - }; - thread.SetApartmentState(ApartmentState.STA); - thread.Start(); - return ready.Task; - } -} - -// An app with no XAML files, so the WinUI controls' types come from their own metadata provider. -internal sealed partial class TestApp : Application, IXamlMetadataProvider -{ - private readonly XamlControlsXamlMetaDataProvider _provider; - private readonly Action _ready; - private readonly Action _failed; - - public TestApp(Action ready, Action failed) - { - _ready = ready; - _failed = failed; - XamlControlsXamlMetaDataProvider.Initialize(); - _provider = new XamlControlsXamlMetaDataProvider(); - UnhandledException += (_, e) => - { - e.Handled = true; - WinUiHost.Unhandled ??= e.Exception; - }; - } - - public IXamlType GetXamlType(Type type) => _provider.GetXamlType(type); - - public IXamlType GetXamlType(string fullName) => _provider.GetXamlType(fullName); - - public XmlnsDefinition[] GetXmlnsDefinitions() => _provider.GetXmlnsDefinitions(); - - protected override void OnLaunched(LaunchActivatedEventArgs args) - { - try - { - Resources.MergedDictionaries.Add(new XamlControlsResources()); - var window = new Window { Title = "TablePro.DataGrid.Tests" }; - window.AppWindow.MoveAndResize(new RectInt32(40, 40, 1440, 900)); - window.Activate(); - _ready(window); - } - catch (Exception ex) - { - _failed(ex); - } - } } // Column 3 is NULL every seventh row, column 5 past the cap, column 7 Arabic and column 9 an emoji. diff --git a/windows/tests/TablePro.Editor.Model.Tests/CaretBlinkTests.cs b/windows/tests/TablePro.Editor.Model.Tests/CaretBlinkTests.cs new file mode 100644 index 0000000000..193c8ca853 --- /dev/null +++ b/windows/tests/TablePro.Editor.Model.Tests/CaretBlinkTests.cs @@ -0,0 +1,142 @@ +namespace TablePro.Editor.Model.Tests; + +// Windows' defaults: a 530 ms blink and a 5,000 ms caret timeout. +public sealed class CaretBlinkTests +{ + private static readonly TimeSpan Blink = TimeSpan.FromMilliseconds(530); + private static readonly TimeSpan Minute = TimeSpan.FromMinutes(1); + + [Fact] + public void AnIdleMinuteBlinksForTheTimeoutThenLeavesTheCaretShown() + { + var clock = new ManualClock(); + var blink = Focused(clock); + + // Nine blinks fit in 5 s, then one draw leaves the caret shown; with no timeout it was 113. + Assert.Equal(10, Run(blink, clock, Minute)); + Assert.False(blink.IsBlinking); + Assert.True(blink.CaretVisible); + } + + [Fact] + public void WithNoTimeoutItBlinksTheWholeMinute() + { + var clock = new ManualClock(); + var blink = Focused(clock, timeout: TimeSpan.FromMilliseconds(-1)); + + Assert.Equal(113, Run(blink, clock, Minute)); + Assert.True(blink.IsBlinking); + } + + [Fact] + public void InputAfterTheTimeoutBlinksAgain() + { + var clock = new ManualClock(); + var blink = Focused(clock); + Run(blink, clock, Minute); + + blink.Restart(); + + Assert.True(blink.IsBlinking); + Assert.True(blink.CaretVisible); + Assert.Equal(10, Run(blink, clock, Minute)); + } + + [Fact] + public void InputWhileBlinkingStartsTheTimeoutAgain() + { + var clock = new ManualClock(); + var blink = Focused(clock); + Assert.Equal(7, Run(blink, clock, TimeSpan.FromMilliseconds(4000))); + + blink.Restart(); + + Assert.True(blink.CaretVisible); + Assert.Equal(10, Run(blink, clock, Minute)); + } + + [Fact] + public void AnInactiveWindowShowsNoCaretAndNeverBlinks() + { + var clock = new ManualClock(); + var blink = Focused(clock); + + Assert.True(blink.SetActive(false)); + + Assert.False(blink.CaretVisible); + Assert.False(blink.IsBlinking); + Assert.Equal(0, Run(blink, clock, Minute)); + } + + [Fact] + public void TheWindowActiveAgainShowsTheCaretAndBlinks() + { + var clock = new ManualClock(); + var blink = Focused(clock); + blink.SetActive(false); + Run(blink, clock, Minute); + + Assert.True(blink.SetActive(true)); + + Assert.True(blink.CaretVisible); + Assert.Equal(10, Run(blink, clock, Minute)); + } + + [Fact] + public void LosingFocusHidesTheCaretAndStops() + { + var clock = new ManualClock(); + var blink = Focused(clock); + + Assert.True(blink.SetFocused(false)); + + Assert.False(blink.CaretVisible); + Assert.False(blink.IsBlinking); + Assert.Equal(0, Run(blink, clock, Minute)); + } + + [Fact] + public void BlinkingTurnedOffShowsASteadyCaret() + { + var clock = new ManualClock(); + var blink = new CaretBlink(clock) { Interval = TimeSpan.Zero }; + blink.SetFocused(true); + + Assert.True(blink.CaretVisible); + Assert.False(blink.IsBlinking); + Assert.Equal(0, Run(blink, clock, Minute)); + } + + private static CaretBlink Focused(ManualClock clock, TimeSpan? timeout = null) + { + var blink = new CaretBlink(clock) { Interval = Blink, Timeout = timeout ?? CaretBlink.DefaultTimeout }; + blink.SetFocused(true); + return blink; + } + + // A timer at the blink interval that nobody stopped; returns the ticks that changed the caret, each one a frame. + private static int Run(CaretBlink blink, ManualClock clock, TimeSpan duration) + { + var changes = 0; + for (var elapsed = Blink; elapsed <= duration; elapsed += Blink) + { + clock.Advance(Blink); + if (blink.Tick()) + { + changes++; + } + } + return changes; + } + + private sealed class ManualClock : TimeProvider + { + private long _milliseconds; + + public override long TimestampFrequency => 1000; + + public override long GetTimestamp() => _milliseconds; + + public void Advance(TimeSpan by) => _milliseconds += (long)by.TotalMilliseconds; + } +} diff --git a/windows/tests/TablePro.Editor.Tests/CaretTests.cs b/windows/tests/TablePro.Editor.Tests/CaretTests.cs new file mode 100644 index 0000000000..34c9b1b03b --- /dev/null +++ b/windows/tests/TablePro.Editor.Tests/CaretTests.cs @@ -0,0 +1,68 @@ +using System.Diagnostics; +using Microsoft.UI.Xaml; +using TablePro.Testing; +using TerraFX.Interop.Windows; +using static TerraFX.Interop.Windows.Windows; + +namespace TablePro.Editor.Tests; + +public sealed class CaretTests +{ + private static readonly TimeSpan LongestTimeout = TimeSpan.FromSeconds(15); + + // A Win32 edit control stops blinking after the caret timeout; the editor drew a frame per blink for ever. + [Fact] + public Task TheCaretStopsBlinkingAfterTheCaretTimeoutAndNoFrameFollows() + { + var blink = GetCaretBlinkTime(); + Assert.SkipWhen(blink is 0 or uint.MaxValue, "Caret blinking is off on this machine."); + var timeout = CaretTimeout(); + Assert.SkipWhen(timeout > LongestTimeout, $"The caret timeout here is {timeout}."); + var cancel = TestContext.Current.CancellationToken; + return WinUiApp.RunAsync(async () => + { + var editor = new SqlEditor { Text = "SELECT 1;" }; + try + { + Assert.True(await EditorHost.ShowAsync(editor), "the editor drew no frame"); + WinUiApp.Window.Activate(); + await WinUiApp.NextFrameAsync(); + Assert.True(editor.WatchesWindowActivation, "no InputActivationListener for the editor's window"); + Assert.SkipUnless(editor.IsInActiveWindow, "The test window is not the active window."); + var frames = 0; + editor.FramePresented += (_, _) => frames++; + + var focused = Stopwatch.StartNew(); + Assert.True(editor.Focus(FocusState.Programmatic)); + await WinUiApp.NextFrameAsync(); + Assert.True(editor.IsCaretBlinking); + while (editor.IsCaretBlinking && focused.Elapsed < timeout + TimeSpan.FromSeconds(3)) + { + await Task.Delay(50, cancel); + } + + Assert.False(editor.IsCaretBlinking, $"still blinking {focused.ElapsedMilliseconds} ms after focus"); + Assert.True(focused.Elapsed >= timeout, $"stopped after {focused.ElapsedMilliseconds} ms"); + Assert.True(frames >= 2, $"{frames} frames while it blinked"); + await WinUiApp.NextFrameAsync(); + await WinUiApp.NextFrameAsync(); + frames = 0; + await Task.Delay(1000, cancel); + Assert.Equal(0, frames); + } + finally + { + EditorHost.Clear(); + editor.Dispose(); + } + }); + } + + private static unsafe TimeSpan CaretTimeout() + { + uint milliseconds; + return SystemParametersInfoW(SPI.SPI_GETCARETTIMEOUT, 0, &milliseconds, 0) + ? TimeSpan.FromMilliseconds(milliseconds) + : TimeSpan.FromSeconds(5); + } +} diff --git a/windows/tests/TablePro.Editor.Tests/EditorHost.cs b/windows/tests/TablePro.Editor.Tests/EditorHost.cs new file mode 100644 index 0000000000..b95fae4186 --- /dev/null +++ b/windows/tests/TablePro.Editor.Tests/EditorHost.cs @@ -0,0 +1,52 @@ +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Controls; +using Microsoft.UI.Xaml.Media; +using TablePro.Testing; + +[assembly: CollectionBehavior(CollectionBehavior.CollectionPerAssembly)] + +namespace TablePro.Editor.Tests; + +// The editor's side of the shared WinUI app in tests/Shared/WinUiApp.cs; one panel swaps its child as TabView does. +internal static class EditorHost +{ + private static Grid? s_host; + + // False when the editor drew no frame. + public static async Task ShowAsync(SqlEditor editor) + { + var presented = false; + void OnFrame(object? sender, EditorFrame frame) => presented = true; + editor.FramePresented += OnFrame; + try + { + var host = Host(); + host.Children.Clear(); + host.Children.Add(editor); + for (var i = 0; i < 300 && !presented; i++) + { + await WinUiApp.NextFrameAsync(); + } + return presented; + } + finally + { + editor.FramePresented -= OnFrame; + } + } + + public static void Clear() => Host().Children.Clear(); + + private static Grid Host() + { + if (s_host is null || !ReferenceEquals(WinUiApp.Window.Content, s_host)) + { + s_host = new Grid + { + Background = (Brush)Application.Current.Resources["ApplicationPageBackgroundThemeBrush"], + }; + WinUiApp.Window.Content = s_host; + } + return s_host; + } +} diff --git a/windows/tests/TablePro.Editor.Tests/LifetimeTests.cs b/windows/tests/TablePro.Editor.Tests/LifetimeTests.cs new file mode 100644 index 0000000000..a7a0815774 --- /dev/null +++ b/windows/tests/TablePro.Editor.Tests/LifetimeTests.cs @@ -0,0 +1,80 @@ +using System.Runtime.CompilerServices; +using TablePro.Graphics; +using TablePro.Testing; + +namespace TablePro.Editor.Tests; + +public sealed class LifetimeTests +{ + // UISettings held its ColorValuesChanged handler, and through it the editor of every closed query tab. + [Fact] + public Task AnEditorRemovedAndDisposedIsCollected() + { + var cancel = TestContext.Current.CancellationToken; + return WinUiApp.RunAsync(async () => + { + var editor = await ShowAndCloseAsync(); + for (var round = 0; round < 10 && editor.IsAlive; round++) + { + await WinUiApp.NextFrameAsync(); + // Off the UI thread, so whatever is released in its apartment can get back to it. + await Task.Run(() => + { + GC.Collect(); + GC.WaitForPendingFinalizers(); + GC.Collect(); + }, cancel); + } + Assert.False(editor.IsAlive, "the editor is still reachable after it was removed and disposed"); + }); + } + + // TabView unloads a tab's content on every switch; each show was a new Direct3D device, factories and swap chain. + [Fact] + public Task SwitchingBetweenEditorsMakesOneSwapChainPerShowOnOneDevice() => WinUiApp.RunAsync(async () => + { + string[] texts = ["SELECT 1;", "SELECT 2;", "SELECT 3;"]; + var editors = texts.Select(text => new SqlEditor { Text = text }).ToArray(); + try + { + var devices = RenderDevice.CreatedOnThisThread; + var swapChains = GraphicsDevice.SwapChainsCreated; + for (var round = 0; round < 10; round++) + { + foreach (var editor in editors) + { + Assert.True(await EditorHost.ShowAsync(editor), $"no frame after the switch in round {round}"); + } + } + await WinUiApp.NextFrameAsync(); + await WinUiApp.NextFrameAsync(); + + // None when an earlier test already made this thread's device. + Assert.InRange(RenderDevice.CreatedOnThisThread - devices, 0, 1); + Assert.Equal(30, GraphicsDevice.SwapChainsCreated - swapChains); + Assert.False(editors[0].HoldsSwapChain); + Assert.False(editors[1].HoldsSwapChain); + Assert.True(editors[2].HoldsSwapChain); + } + finally + { + EditorHost.Clear(); + foreach (var editor in editors) + { + editor.Dispose(); + } + } + }); + + [MethodImpl(MethodImplOptions.NoInlining)] + private static async Task ShowAndCloseAsync() + { + var editor = new SqlEditor { Text = "SELECT 1;" }; + Assert.True(await EditorHost.ShowAsync(editor), "the editor drew no frame"); + EditorHost.Clear(); + await WinUiApp.NextFrameAsync(); + await WinUiApp.NextFrameAsync(); + editor.Dispose(); + return new WeakReference(editor); + } +} diff --git a/windows/tests/TablePro.Editor.Tests/TablePro.Editor.Tests.csproj b/windows/tests/TablePro.Editor.Tests/TablePro.Editor.Tests.csproj new file mode 100644 index 0000000000..043b6c296a --- /dev/null +++ b/windows/tests/TablePro.Editor.Tests/TablePro.Editor.Tests.csproj @@ -0,0 +1,54 @@ + + + + + net10.0-windows10.0.26100.0 + 10.0.17763.0 + 10.0.17763.0 + Exe + false + TablePro.Editor.Tests + app.manifest + x64;ARM64 + win-x64;win-arm64 + true + true + None + true + true + + + + true + $(NETCoreSdkRuntimeIdentifier) + true + + + + false + false + false + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/windows/tests/TablePro.Editor.Tests/app.manifest b/windows/tests/TablePro.Editor.Tests/app.manifest new file mode 100644 index 0000000000..5e175b6dfe --- /dev/null +++ b/windows/tests/TablePro.Editor.Tests/app.manifest @@ -0,0 +1,15 @@ + + + + + + + + + + + true/PM + PerMonitorV2, PerMonitor + + + diff --git a/windows/tests/TablePro.Interop.Tests/BrowseTests.cs b/windows/tests/TablePro.Interop.Tests/BrowseTests.cs index d4083de98d..c9d10c2077 100644 --- a/windows/tests/TablePro.Interop.Tests/BrowseTests.cs +++ b/windows/tests/TablePro.Interop.Tests/BrowseTests.cs @@ -89,6 +89,22 @@ public async Task AFilterTheEngineCannotTakeThrowsBeforeAnyRead() Assert.Equal(SqliteDatabase.PeopleRows, stillThere); } + [Fact] + public async Task AnEstimateIsNoneUntilAnalyzeWritesTheTablesStatistics() + { + var cancellationToken = TestContext.Current.CancellationToken; + await using var database = await SqliteDatabase.CreateAsync(); + + var before = await database.Session.EstimateRowsAsync(People, cancellationToken); + // ANALYZE writes sqlite_stat1, whose row for the index starts with the table's row count. + await database.ExecuteAsync("CREATE INDEX people_by_name ON people (name)"); + await database.ExecuteAsync("ANALYZE"); + var after = await database.Session.EstimateRowsAsync(People, cancellationToken); + + Assert.Null(before); + Assert.Equal(new RowEstimate(SqliteDatabase.PeopleRows, IsExact: false), after); + } + [Fact] public async Task TheChoicesAreWhatTheEngineEvaluatesOnEachColumn() { From 240fe609dc2003d052db4250cc01532aaa5515ed Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Thu, 12 Nov 2026 14:09:19 +0700 Subject: [PATCH 2/4] fix(windows): find a removed editor device before its swap chain, keep an asked count and a fresh catalog, hide stale estimates --- windows/Directory.Packages.props | 6 ++- windows/src/TablePro.App.Model/TablePage.cs | 3 ++ windows/src/TablePro.App.Model/TableTab.cs | 3 +- windows/src/TablePro.App/TablePro.App.csproj | 2 +- .../TablePro.App/Views/TableTabView.xaml.cs | 2 +- .../TablePro.App/Views/WorkspaceView.xaml.cs | 31 ++++++++++--- .../src/TablePro.Editor/SqlEditor.Render.cs | 19 +++++++- windows/src/TablePro.Editor/SqlEditor.cs | 43 +++++++++++++++---- .../src/TablePro.Graphics/GraphicsDevice.cs | 17 +++++++- windows/src/TablePro.Graphics/RenderDevice.cs | 6 +++ .../TablePro.App.Model.Tests/TabFakes.cs | 4 +- .../TableTabCountTests.cs | 37 ++++++++++++++++ .../tests/TablePro.Editor.Tests/CaretTests.cs | 8 +++- .../TablePro.Editor.Tests/LifetimeTests.cs | 27 ++++++++++++ 14 files changed, 183 insertions(+), 25 deletions(-) diff --git a/windows/Directory.Packages.props b/windows/Directory.Packages.props index f91e0cad5f..dc096c423c 100644 --- a/windows/Directory.Packages.props +++ b/windows/Directory.Packages.props @@ -2,6 +2,8 @@ true true + + 2.6.4 @@ -10,8 +12,8 @@ - - + + diff --git a/windows/src/TablePro.App.Model/TablePage.cs b/windows/src/TablePro.App.Model/TablePage.cs index c5975fa1c2..c8dba4939a 100644 --- a/windows/src/TablePro.App.Model/TablePage.cs +++ b/windows/src/TablePro.App.Model/TablePage.cs @@ -19,6 +19,9 @@ public sealed record TablePage(long Offset, int Size, long Rows, long? Total, bo // The engine's estimate of the table, shown as about N while no count gave Total; nothing pages by it. public long? Estimate { get; init; } + // Statistics can lag far behind the table, as MySQL's cached TABLE_ROWS or a table never analysed reading 0. + public long? ShownEstimate => Estimate is { } estimate && estimate > LastRow ? estimate : null; + public long FirstRow => Rows == 0 ? 0 : Offset + 1; public long LastRow => Offset + Rows; diff --git a/windows/src/TablePro.App.Model/TableTab.cs b/windows/src/TablePro.App.Model/TableTab.cs index 30ce74f4f2..7a04059828 100644 --- a/windows/src/TablePro.App.Model/TableTab.cs +++ b/windows/src/TablePro.App.Model/TableTab.cs @@ -1141,7 +1141,8 @@ private async void CountIfNeeded() => // A first page that is not full holds the whole table; otherwise the estimate decides, then the server counts. private async Task CountAsync(bool asked, CancellationToken closing) { - if (!asked && (_page.Total is not null || !_page.CanSeek || _countHeldBack)) + // A page turn, sort or resize leaves a count the user asked for to finish. + if (!asked && (_page.Total is not null || !_page.CanSeek || _countHeldBack || (_counting is not null && _countAsked))) { _view.UpdatePager(); return; diff --git a/windows/src/TablePro.App/TablePro.App.csproj b/windows/src/TablePro.App/TablePro.App.csproj index f5b3186faf..c9bd46f362 100644 --- a/windows/src/TablePro.App/TablePro.App.csproj +++ b/windows/src/TablePro.App/TablePro.App.csproj @@ -47,7 +47,7 @@ - + diff --git a/windows/src/TablePro.App/Views/TableTabView.xaml.cs b/windows/src/TablePro.App/Views/TableTabView.xaml.cs index 0e065675ff..58981eaee0 100644 --- a/windows/src/TablePro.App/Views/TableTabView.xaml.cs +++ b/windows/src/TablePro.App/Views/TableTabView.xaml.cs @@ -445,7 +445,7 @@ private void UpdatePager() return Strings.Format("StatusPageOf", page.FirstRow, page.LastRow, total, run.Milliseconds); } - return page.Estimate is { } estimate + return page.ShownEstimate is { } estimate ? Strings.Format("StatusPageOfAbout", page.FirstRow, page.LastRow, estimate, run.Milliseconds) : Strings.Format("StatusPage", page.FirstRow, page.LastRow, run.Milliseconds); } diff --git a/windows/src/TablePro.App/Views/WorkspaceView.xaml.cs b/windows/src/TablePro.App/Views/WorkspaceView.xaml.cs index f3f851f618..0221883889 100644 --- a/windows/src/TablePro.App/Views/WorkspaceView.xaml.cs +++ b/windows/src/TablePro.App/Views/WorkspaceView.xaml.cs @@ -28,6 +28,9 @@ public sealed partial class WorkspaceView : UserControl, IWorkspaceTabsView? _share; private DatabaseSession? _session; private ObjectCatalog? _everyObject; + + // Bumped as the catalog is dropped, so a read started before a refresh or a reconnect is not kept. + private int _catalogGeneration; private bool _singleSchema; private string _failureDetails = string.Empty; private int _filterGeneration; @@ -181,7 +184,7 @@ internal void ShowConnected(SessionShare share, SessionConnecti { _share = share; _session = share.Session; - _everyObject = null; + ForgetCatalog(); ConnectingRing.IsActive = false; ConnectingPanel.Visibility = Visibility.Collapsed; FailedPanel.Visibility = Visibility.Collapsed; @@ -306,7 +309,7 @@ public async Task CloseTabsAsync(bool keepClosed = false) _snapshots.Clear(); Objects.Clear(); ObjectList.ItemsSource = null; - _everyObject = null; + ForgetCatalog(); WorkspaceGrid.Visibility = Visibility.Collapsed; CommandsChanged?.Invoke(this, EventArgs.Empty); SessionChanged?.Invoke(this, EventArgs.Empty); @@ -625,7 +628,7 @@ public async Task RefreshAsync() return; } - _everyObject = null; + ForgetCatalog(); await LoadTreeAsync(refresh: true).ConfigureAwait(true); } @@ -1488,14 +1491,24 @@ private async void OnFilterChanged(AutoSuggestBox sender, AutoSuggestBoxTextChan try { var catalog = _everyObject; - if (catalog is null) + while (catalog is null) { + var reading = _catalogGeneration; var objects = await session .GetObjectsAsync(_singleSchema ? ObjectScope.DefaultSchema : ObjectScope.AllSchemas) .ConfigureAwait(true); var culture = CultureInfo.CurrentCulture; - catalog = await Task.Run(() => new ObjectCatalog(objects, culture)).ConfigureAwait(true); - _everyObject ??= catalog; + var read = await Task.Run(() => new ObjectCatalog(objects, culture)).ConfigureAwait(true); + if (filtering.IsCancellationRequested || !ReferenceEquals(_session, session)) + { + return; + } + + // A refresh during the read dropped the catalog, so the one it reads now is the one to keep. + if (reading == _catalogGeneration) + { + catalog = _everyObject ??= read; + } } // Typing on while the catalog loads leaves only the newest text to show. @@ -1534,6 +1547,12 @@ private async void OnFilterChanged(AutoSuggestBox sender, AutoSuggestBoxTextChan } } + private void ForgetCatalog() + { + _everyObject = null; + _catalogGeneration++; + } + private void OnBackToTree(object sender, RoutedEventArgs e) { ObjectFilter.Text = string.Empty; diff --git a/windows/src/TablePro.Editor/SqlEditor.Render.cs b/windows/src/TablePro.Editor/SqlEditor.Render.cs index 6506c29143..2062ddcd4c 100644 --- a/windows/src/TablePro.Editor/SqlEditor.Render.cs +++ b/windows/src/TablePro.Editor/SqlEditor.Render.cs @@ -26,8 +26,8 @@ private unsafe void Render() { return; } - // Another editor on this thread found the shared device lost. - if (!_device.IsCurrent) + // Another editor on this thread found the shared device lost, or the driver removed it. + if (_device.NeedsRecovery) { RecoverDevice(lost: false); return; @@ -259,6 +259,21 @@ private void OnRenderingTick(object? sender, object e) Invalidate(); } + // The frame's map points at layouts the cache owns, so it goes whenever they do. + private void ForgetLayouts() + { + _layouts?.Clear(); + _frameLayouts.Clear(); + _frameVersion = -1; + } + + private void ConfigureLayouts() + { + _layouts?.Configure(_fontSize * _zoom, _model.Options.TabSize); + _frameLayouts.Clear(); + _frameVersion = -1; + } + private LineLayout LayoutFor(int line, string text) { if (_frameVersion == Document.Version && _frameLayouts.TryGetValue(line, out var drawn)) diff --git a/windows/src/TablePro.Editor/SqlEditor.cs b/windows/src/TablePro.Editor/SqlEditor.cs index fa336ee0f5..e833735303 100644 --- a/windows/src/TablePro.Editor/SqlEditor.cs +++ b/windows/src/TablePro.Editor/SqlEditor.cs @@ -1,4 +1,5 @@ using System.Diagnostics; +using System.Runtime.InteropServices; using Microsoft.UI; using Microsoft.UI.Dispatching; using Microsoft.UI.Xaml; @@ -109,7 +110,7 @@ public ISyntaxLexer? Lexer _lexer = value; _highlighter?.Dispose(); _highlighter = value is null ? null : new SyntaxHighlighter(Document, value); - _layouts?.Clear(); + ForgetLayouts(); Invalidate(); } } @@ -133,7 +134,7 @@ public float EditorFontSize set { _fontSize = value; - _layouts?.Configure(_fontSize * _zoom, _model.Options.TabSize); + ConfigureLayouts(); UpdateScrollBars(); Invalidate(); } @@ -145,7 +146,7 @@ public float Zoom set { _zoom = Math.Clamp(value, 0.5f, 3f); - _layouts?.Configure(EditorFontSize * _zoom, _model.Options.TabSize); + ConfigureLayouts(); UpdateScrollBars(); Invalidate(); } @@ -209,7 +210,7 @@ private void OnDocumentReset() _scrollX = 0; _scrollY = 0; _widest = 0; - _layouts?.Clear(); + ForgetLayouts(); UpdateScrollBars(); Invalidate(); TextChanged?.Invoke(this, EventArgs.Empty); @@ -245,6 +246,11 @@ private void OnLoaded(object sender, RoutedEventArgs e) // TabView unloads a tab's content on every switch; a hidden tab keeps its layouts and brushes. private void OnUnloaded(object sender, RoutedEventArgs e) { + // A tab moved to another window can hear its old window's Unloaded after the new one's Loaded. + if (IsLoaded) + { + return; + } _loaded = false; Unhook(); _device?.Detach(); @@ -272,12 +278,22 @@ private void AttachSwapChain() { return; } - if (!_device.IsCurrent) + if (_device.NeedsRecovery) { _device.Recover(lost: false); RebuildBrushes(); } - _device.Attach(_panel, PixelWidth(), PixelHeight(), _panel.CompositionScaleX, _panel.CompositionScaleY); + try + { + _device.Attach(_panel, PixelWidth(), PixelHeight(), _panel.CompositionScaleX, _panel.CompositionScaleY); + } + catch (COMException exception) when (GraphicsDevice.IsDeviceLoss(exception.HResult)) + { + // Lost between the check and the call; a new device takes it. + _device.Recover(lost: true); + RebuildBrushes(); + _device.Attach(_panel, PixelWidth(), PixelHeight(), _panel.CompositionScaleX, _panel.CompositionScaleY); + } UpdateScrollBars(); Invalidate(); } @@ -294,6 +310,7 @@ private void ReleaseDevice() { _brushes?.Dispose(); _brushes = null; + ForgetLayouts(); _layouts?.Dispose(); _layouts = null; _device?.Dispose(); @@ -308,12 +325,20 @@ private void OnViewResized() return; } // A swap chain on a removed device fails ResizeBuffers; the new one is made at the new size. - if (!_device.IsCurrent) + if (_device.NeedsRecovery) { RecoverDevice(lost: false); return; } - _device.Resize(PixelWidth(), PixelHeight(), _panel.CompositionScaleX, _panel.CompositionScaleY); + try + { + _device.Resize(PixelWidth(), PixelHeight(), _panel.CompositionScaleX, _panel.CompositionScaleY); + } + catch (COMException exception) when (GraphicsDevice.IsDeviceLoss(exception.HResult)) + { + RecoverDevice(lost: true); + return; + } UpdateScrollBars(); RenderNow(); } @@ -326,7 +351,7 @@ private unsafe void RebuildBrushes() } _brushes?.Dispose(); _brushes = new Brushes(_device.Context, Palette.Resolve(ActualTheme)); - _layouts?.Clear(); + ForgetLayouts(); Invalidate(); } diff --git a/windows/src/TablePro.Graphics/GraphicsDevice.cs b/windows/src/TablePro.Graphics/GraphicsDevice.cs index 4641335298..a018d277ab 100644 --- a/windows/src/TablePro.Graphics/GraphicsDevice.cs +++ b/windows/src/TablePro.Graphics/GraphicsDevice.cs @@ -74,8 +74,23 @@ public GraphicsDevice(bool forceSoftware) // False once another editor found the shared device lost and replaced it. public bool IsCurrent => ReferenceEquals(_device, _forceSoftware ? s_software : s_hardware); + // Checked before a swap chain is made or resized, since a hidden tab or an idle caret draws nothing to find the loss. + public bool NeedsRecovery => !IsCurrent || _device.IsLost; + internal static int SwapChainsCreated => s_swapChainsCreated; + internal static void SimulateLoss(bool software) + { + if ((software ? s_software : s_hardware) is { } device) + { + device.SimulatedLoss = true; + } + } + + // DXGI's answer when the device went away under the call. + public static bool IsDeviceLoss(int result) => + result == DXGI_ERROR_DEVICE_REMOVED || result == DXGI_ERROR_DEVICE_RESET; + public void Attach(SwapChainPanel panel, int pixelWidth, int pixelHeight, float scaleX, float scaleY) { PixelWidth = Math.Max(1, pixelWidth); @@ -138,7 +153,7 @@ public void Recover(bool lost) { Detach(); NativeCom.Release(ref _context); - if (lost && IsCurrent) + if (IsCurrent && (lost || _device.IsLost)) { if (_forceSoftware) { diff --git a/windows/src/TablePro.Graphics/RenderDevice.cs b/windows/src/TablePro.Graphics/RenderDevice.cs index 80dec74f65..832375ace1 100644 --- a/windows/src/TablePro.Graphics/RenderDevice.cs +++ b/windows/src/TablePro.Graphics/RenderDevice.cs @@ -70,6 +70,12 @@ public RenderDevice(bool forceSoftware, bool multithreaded = false) internal static int CreatedOnThisThread => s_created; + // A driver update or a TDR removes the device while nothing draws; what is made on it next fails. + public bool IsLost => _d3d is null || SimulatedLoss || _d3d->GetDeviceRemovedReason().FAILED; + + // For the tests, as the grid's FailNextDraw. + internal bool SimulatedLoss { get; set; } + public bool IsSoftware { get; } public string AdapterName { get; } = string.Empty; diff --git a/windows/tests/TablePro.App.Model.Tests/TabFakes.cs b/windows/tests/TablePro.App.Model.Tests/TabFakes.cs index 8477ebeb3c..84fc9d2bc0 100644 --- a/windows/tests/TablePro.App.Model.Tests/TabFakes.cs +++ b/windows/tests/TablePro.App.Model.Tests/TabFakes.cs @@ -59,6 +59,8 @@ internal sealed class FakeSession : ITabSession public CoreError? EstimateFailure { get; set; } + public CoreError? CountFailure { get; set; } + public int Estimates { get; private set; } // Waited at by the run of each page read. @@ -216,7 +218,7 @@ public async Task CountRowsAsync(TableName table, TableFilter? filter, Can await counting.PassAsync(cancellationToken); } - return RowsPicked(filter); + return CountFailure is { } failure ? throw new TableProException(failure) : RowsPicked(filter); } public async Task EstimateRowsAsync(TableName table, CancellationToken cancellationToken) diff --git a/windows/tests/TablePro.App.Model.Tests/TableTabCountTests.cs b/windows/tests/TablePro.App.Model.Tests/TableTabCountTests.cs index 6a755d57c2..24e3a939bd 100644 --- a/windows/tests/TablePro.App.Model.Tests/TableTabCountTests.cs +++ b/windows/tests/TablePro.App.Model.Tests/TableTabCountTests.cs @@ -136,6 +136,43 @@ public async Task CountRowsCountsTheTableTheEstimateHeldBack() Assert.False(tab.IsCounting); } + // MySQL keeps TABLE_ROWS for a day and an unanalysed table can read 0, so an estimate under the rows read is no total. + [Theory] + [InlineData(0L, null)] + [InlineData(1_000L, null)] + [InlineData(1_001L, 1_001L)] + public void AnEstimateShowsOnlyWhenItIsMoreThanTheRowsShown(long estimate, long? shown) + { + var page = TablePage.First(1_000) with { Rows = 1_000, Estimate = estimate }; + + Assert.Equal(shown, page.ShownEstimate); + } + + [Fact] + public async Task APageTurnLeavesTheCountTheUserAskedForRunning() + { + // No estimate, and the count the tab ran by itself timed out, so Count rows is offered. + _session.CountFailure = Errors.Of("operation.timeout"); + var tab = New(); + await tab.RunAsync(); + Assert.True(tab.CanCountRows); + _session.CountFailure = null; + + var asked = new Gate(); + _session.Counting = asked; + var count = tab.CountRowsAsync(); + await asked.Reached; + await tab.NextPageAsync(); + + Assert.True(tab.IsCounting); + asked.Open(); + await count; + + Assert.Equal(2, _session.Counts); + Assert.Equal(2_000_123, tab.Page.Total); + Assert.Equal(1_000, tab.Page.Offset); + } + [Fact] public async Task AnEstimateThatLandsAsTheTabClosesShowsNothingAndCountsNothing() { diff --git a/windows/tests/TablePro.Editor.Tests/CaretTests.cs b/windows/tests/TablePro.Editor.Tests/CaretTests.cs index 34c9b1b03b..8c80af7ce7 100644 --- a/windows/tests/TablePro.Editor.Tests/CaretTests.cs +++ b/windows/tests/TablePro.Editor.Tests/CaretTests.cs @@ -36,11 +36,17 @@ public Task TheCaretStopsBlinkingAfterTheCaretTimeoutAndNoFrameFollows() Assert.True(editor.Focus(FocusState.Programmatic)); await WinUiApp.NextFrameAsync(); Assert.True(editor.IsCaretBlinking); + var undisturbed = true; while (editor.IsCaretBlinking && focused.Elapsed < timeout + TimeSpan.FromSeconds(3)) { - await Task.Delay(50, cancel); + await Task.Delay(20, cancel); + undisturbed &= editor.IsInActiveWindow && editor.FocusState != FocusState.Unfocused; } + // Before desktop.ps1 runs, a runner's own windows take the activation now and then, which stops the blink too. + Assert.SkipUnless( + undisturbed && editor.IsInActiveWindow && editor.FocusState != FocusState.Unfocused, + $"The window lost activation or the editor its focus {focused.ElapsedMilliseconds} ms after focus."); Assert.False(editor.IsCaretBlinking, $"still blinking {focused.ElapsedMilliseconds} ms after focus"); Assert.True(focused.Elapsed >= timeout, $"stopped after {focused.ElapsedMilliseconds} ms"); Assert.True(frames >= 2, $"{frames} frames while it blinked"); diff --git a/windows/tests/TablePro.Editor.Tests/LifetimeTests.cs b/windows/tests/TablePro.Editor.Tests/LifetimeTests.cs index a7a0815774..50c23aad89 100644 --- a/windows/tests/TablePro.Editor.Tests/LifetimeTests.cs +++ b/windows/tests/TablePro.Editor.Tests/LifetimeTests.cs @@ -66,6 +66,33 @@ public Task SwitchingBetweenEditorsMakesOneSwapChainPerShowOnOneDevice() => WinU } }); + // A driver update or a TDR removes the device while nothing draws, so the next tab shown must not make its swap chain on it. + [Fact] + public Task ATabShownAfterTheDeviceWasLostDrawsOnANewDevice() => WinUiApp.RunAsync(async () => + { + var first = new SqlEditor { Text = "SELECT 1;" }; + var second = new SqlEditor { Text = "SELECT 2;" }; + try + { + Assert.True(await EditorHost.ShowAsync(first), "no first frame"); + Assert.True(await EditorHost.ShowAsync(second), "no first frame on the second editor"); + var devices = RenderDevice.CreatedOnThisThread; + + GraphicsDevice.SimulateLoss(software: false); + + Assert.True(await EditorHost.ShowAsync(first), "no frame on the tab shown after the loss"); + Assert.Equal(1, RenderDevice.CreatedOnThisThread - devices); + Assert.True(await EditorHost.ShowAsync(second), "no frame on the other tab after the loss"); + Assert.Equal(1, RenderDevice.CreatedOnThisThread - devices); + } + finally + { + EditorHost.Clear(); + first.Dispose(); + second.Dispose(); + } + }); + [MethodImpl(MethodImplOptions.NoInlining)] private static async Task ShowAndCloseAsync() { From 6b6db5683adc6be2f26508fe6487bca12011c7cc Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Thu, 12 Nov 2026 14:14:36 +0700 Subject: [PATCH 3/4] fix(windows): rebind a moved editor to its new window and never hand out a removed device --- windows/src/TablePro.Editor/SqlEditor.cs | 2 ++ windows/src/TablePro.Graphics/GraphicsDevice.cs | 16 ++++++++++++++-- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/windows/src/TablePro.Editor/SqlEditor.cs b/windows/src/TablePro.Editor/SqlEditor.cs index e833735303..8aae4ad7c7 100644 --- a/windows/src/TablePro.Editor/SqlEditor.cs +++ b/windows/src/TablePro.Editor/SqlEditor.cs @@ -237,6 +237,8 @@ private void OnLoaded(object sender, RoutedEventArgs e) } _loaded = true; + // A tab moved to another window can load there before its old window unloads it, still bound to the old one. + Unhook(); Hook(); PrepareDevice(); AttachSwapChain(); diff --git a/windows/src/TablePro.Graphics/GraphicsDevice.cs b/windows/src/TablePro.Graphics/GraphicsDevice.cs index a018d277ab..5b612c815c 100644 --- a/windows/src/TablePro.Graphics/GraphicsDevice.cs +++ b/windows/src/TablePro.Graphics/GraphicsDevice.cs @@ -224,13 +224,25 @@ public void Dispose() NativeCom.Release(ref _dwrite); } + // A device removed while no editor drew is not handed to a new one; editors still holding it find it no longer current. private static RenderDevice Shared(bool forceSoftware) { + var device = forceSoftware ? s_software : s_hardware; + if (device is { IsLost: true }) + { + device.Dispose(); + device = null; + } + device ??= new RenderDevice(forceSoftware); if (forceSoftware) { - return s_software ??= new RenderDevice(forceSoftware: true); + s_software = device; + } + else + { + s_hardware = device; } - return s_hardware ??= new RenderDevice(forceSoftware: false); + return device; } private static ID2D1DeviceContext* CreateContext(RenderDevice device) From 2df9239b1034443bc9ccc08073932173b58525d8 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Thu, 12 Nov 2026 14:31:52 +0700 Subject: [PATCH 4/4] docs(windows): record the MSIX sizes with the WinUI component --- windows/docs/decisions/0005-distribution.md | 1 + 1 file changed, 1 insertion(+) diff --git a/windows/docs/decisions/0005-distribution.md b/windows/docs/decisions/0005-distribution.md index 87956eb78e..66af1e13c7 100644 --- a/windows/docs/decisions/0005-distribution.md +++ b/windows/docs/decisions/0005-distribution.md @@ -46,6 +46,7 @@ A release is one MSIX per architecture, built with Native AOT in the Release con - The run passed the unsigned path's version and signing check. The temporary runs were cancelled when verification moved to the Mac. The x64 package, bundle, install/start tests and Windows winget validation remain unverified. Artifact Signing has not run with production credentials. - PR run [41705662121](https://github.com/TableProApp/TablePro/actions/runs/41705662121) built the Native AOT app on both architectures, then exposed missing engine rows and failures during resizing and library navigation. A local probe with the shipped SDK projection 10.0.26100.57 confirmed that explicit registrations add the two missing list adapters; its baseline generated only the outer engine-group list. The Windows UI tests check their runtime behavior. - In the Native AOT build, `AppWindow.Presenter` logged as `AppWindowPresenter` with `Kind` `Overlapped`, and `TheWindowComesBackWhereItStood` came back Normal on x64 (run 41844628365). A build that also called `OverlappedPresenter.Create()` logged `OverlappedPresenter` and came back maximized (run 41837948701). With each window's own presenter, the UI tests passed on both runners (run 41841130888). +- With the WinUI component and the prune, `release-windows.yml` by dispatch made the x64 MSIX 60.1 MiB and the Arm64 one 59.6 MiB, 331 files each and no ONNX Runtime, DirectML, Search, Widgets or DWriteCore (run [43169528630](https://github.com/TableProApp/TablePro/actions/runs/43169528630)), against 84.9 and 83.8 MiB with 386 and 382 files from main the same day (run [43164825446](https://github.com/TableProApp/TablePro/actions/runs/43164825446)). Both packages installed and started on Windows Server 2022 x64 and Windows 11 Arm64 in the same run, and the Native AOT build passed the UI tests on Arm64 (run [43169524642](https://github.com/TableProApp/TablePro/actions/runs/43169524642)). ## Alternatives considered