From 63658ed34e67117d58c69d886c96cd40f6397567 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Fri, 13 Nov 2026 02:05:52 +0700 Subject: [PATCH 1/3] perf(windows): draw the caret as its own visual and add the row count and results per run settings --- core/crates/ffi/src/run/query_run.rs | 5 + core/crates/ffi/src/run/run_state.rs | 74 ++++++++- .../docs/decisions/0002-sql-editor-control.md | 2 +- windows/docs/decisions/0004-app-shell.md | 6 +- windows/src/TablePro.App.Model/AppSettings.cs | 19 +++ .../src/TablePro.App.Model/IResultsView.cs | 4 +- windows/src/TablePro.App.Model/QueryTab.cs | 6 +- windows/src/TablePro.App.Model/RunResults.cs | 23 ++- windows/src/TablePro.App.Model/TabSession.cs | 5 + windows/src/TablePro.App.Model/TableTab.cs | 8 +- .../TablePro.App/Strings/en-US/Resources.resw | 36 +++++ .../TablePro.App/Views/ResultsPane.xaml.cs | 105 ++++++++++++- .../src/TablePro.App/Views/SettingsView.xaml | 8 + .../TablePro.App/Views/SettingsView.xaml.cs | 43 ++++++ .../src/TablePro.Editor/Rendering/Brushes.cs | 3 - .../src/TablePro.Editor/SqlEditor.Caret.cs | 141 ++++++++++++++++-- .../src/TablePro.Editor/SqlEditor.Render.cs | 44 ++---- windows/src/TablePro.Editor/SqlEditor.cs | 8 +- .../Generated/tablepro_ffi.cs | 46 ++++++ windows/src/TablePro.Interop/QueryRun.cs | 13 ++ .../TablePro.App.Model.Tests/QueryTabTests.cs | 15 ++ .../RunResultsTests.cs | 85 +++++++++-- .../TablePro.App.Model.Tests/StoreTests.cs | 31 ++++ .../TablePro.App.Model.Tests/TabFakes.cs | 10 +- .../TableTabCountTests.cs | 35 +++++ .../TablePro.App.UITests/RunStatementTests.cs | 28 ++++ .../tests/TablePro.Editor.Tests/CaretTests.cs | 120 ++++++++++++++- .../RunDisposalTests.cs | 22 +++ 28 files changed, 850 insertions(+), 95 deletions(-) diff --git a/core/crates/ffi/src/run/query_run.rs b/core/crates/ffi/src/run/query_run.rs index 17cbee7def..41b18d632f 100644 --- a/core/crates/ffi/src/run/query_run.rs +++ b/core/crates/ffi/src/run/query_run.rs @@ -40,6 +40,11 @@ impl QueryRun { .map(|store| Arc::new(ResultSet::new(index, store))) } + /// The app shows this set no more, so the run lets go of its rows; they go once no `ResultSet` holds them. + pub fn release_set(&self, index: u32) { + self.state.release_set(index); + } + pub fn cancel(&self) { self.state.cancel.cancel(); } diff --git a/core/crates/ffi/src/run/run_state.rs b/core/crates/ffi/src/run/run_state.rs index d073acd62a..1ce87835a1 100644 --- a/core/crates/ffi/src/run/run_state.rs +++ b/core/crates/ffi/src/run/run_state.rs @@ -1,6 +1,6 @@ use std::panic::{AssertUnwindSafe, catch_unwind}; use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::{Arc, Mutex, PoisonError}; +use std::sync::{Arc, Mutex, PoisonError, Weak}; use tokio::sync::watch; use tokio_util::sync::CancellationToken; @@ -20,7 +20,14 @@ pub(crate) struct RunState { #[derive(Default)] struct Queue { events: Vec, - sets: Vec>, + // A released set keeps its slot, so every later set keeps its index. + sets: Vec, +} + +enum Slot { + Held(Arc), + // Weak, so a `ResultSet` the app still holds is finished with the run. + Released(Weak), } impl RunState { @@ -36,12 +43,34 @@ impl RunState { pub(crate) fn add_set(&self, store: Arc) -> u32 { let mut queue = self.lock(); - queue.sets.push(store); + queue.sets.push(Slot::Held(store)); u32::try_from(queue.sets.len() - 1).unwrap_or(u32::MAX) } pub(crate) fn set(&self, index: u32) -> Option> { - self.lock().sets.get(usize::try_from(index).ok()?).cloned() + match self.lock().sets.get(usize::try_from(index).ok()?)? { + Slot::Held(store) => Some(store.clone()), + Slot::Released(_) => None, + } + } + + pub(crate) fn release_set(&self, index: u32) { + let Ok(index) = usize::try_from(index) else { + return; + }; + let released = { + let mut queue = self.lock(); + let Some(slot) = queue.sets.get_mut(index) else { + return; + }; + let Slot::Held(store) = slot else { + return; + }; + let weak = Arc::downgrade(store); + std::mem::replace(slot, Slot::Released(weak)) + }; + // Outside the lock: freeing a large set's rows takes a while, and the reader posts under it. + drop(released); } // Called on a runtime thread. @@ -84,7 +113,15 @@ impl RunState { // Every set holds what it will, and `Finished` is the last event. pub(crate) fn finish(&self, outcome: RunOutcome, transaction: TransactionStateTag) { - let sets = self.lock().sets.clone(); + let sets: Vec<_> = self + .lock() + .sets + .iter() + .filter_map(|slot| match slot { + Slot::Held(store) => Some(store.clone()), + Slot::Released(store) => store.upgrade(), + }) + .collect(); sets.iter().for_each(|store| store.finish()); self.enqueue(RunEvent::Finished { outcome: outcome.clone(), @@ -226,6 +263,33 @@ mod tests { assert_eq!(state.drain(), [rows(0, 3)]); } + #[test] + fn a_released_set_is_gone_from_the_run_and_the_later_sets_keep_their_index() { + let state = RunState::new(Box::new(CountingListener::default())); + let first = Arc::new(ResultStore::new(Vec::new().into())); + let second = Arc::new(ResultStore::new(Vec::new().into())); + let third = Arc::new(ResultStore::new(Vec::new().into())); + let dropped = Arc::downgrade(&third); + assert_eq!(state.add_set(first.clone()), 0); + assert_eq!(state.add_set(second.clone()), 1); + assert_eq!(state.add_set(third), 2); + + state.release_set(0); + state.release_set(0); + state.release_set(2); + state.release_set(7); + + assert!(state.set(0).is_none()); + assert!(Arc::ptr_eq(&state.set(1).unwrap(), &second)); + assert_eq!(Arc::strong_count(&first), 1); + assert!(dropped.upgrade().is_none()); + assert_eq!(state.add_set(Arc::new(ResultStore::new(Vec::new().into()))), 3); + state.finish(RunOutcome::Cancelled, TransactionStateTag::Idle); + assert!(second.is_finished()); + // The app may still read a set it released, and it ends with the run. + assert!(first.is_finished()); + } + #[derive(Clone, Default)] struct OutcomeAtWake { outcome: Arc>>>, diff --git a/windows/docs/decisions/0002-sql-editor-control.md b/windows/docs/decisions/0002-sql-editor-control.md index 0e05201569..c4068cb408 100644 --- a/windows/docs/decisions/0002-sql-editor-control.md +++ b/windows/docs/decisions/0002-sql-editor-control.md @@ -38,7 +38,7 @@ - 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, 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. +- 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 and IME marks. The carets are a composition visual of their own over the swap chain, one sprite per visible caret, as WinUI's TextBox keeps its caret in an element of its own (`TextBoxView.cpp`, `EnsureCaretElement`). SwapChainPanel draws its swap chain first (`SwapChainPanel.cpp`, `GetChildrenInRenderOrder`), so the panel's child visual lies above it. A frame places the sprites at the positions it laid out, snapped to pixels; a blink, focus or the window's activation only shows or hides the visual, with no frame. On `windows-2025` (run 43277097648) focus and a 5 second blink of 10 toggles presented 11 frames when the frame held the caret, and 0 with the visual. 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 786f43b588..ea007553f5 100644 --- a/windows/docs/decisions/0004-app-shell.md +++ b/windows/docs/decisions/0004-app-shell.md @@ -113,13 +113,13 @@ On 2026-11-05 the maintainer had the app show what the server prints, PostgreSQL - Invoking a table or view opens its table tab, or brings the open one forward. The core reads the page (`DatabaseSession.ReadTablePageAsync`, over the core's `read_page`), quoted, ordered, filtered and limited as the engine writes it, on one of the session's pooled connections (amended by 0007). - A query tab is the SQL editor over the run's results, on its own editor connection opened on first use; a table tab is the results alone, read on the session's pooled connections (0007). - Run statement (Query menu, Ctrl+Shift+Enter, as on Linux): the core picks the statement the cursor is in, or the last one before it, with the session's own grammar (`DatabaseSession.statement_at`, over `ScriptPlan::statement_at`, in UTF-16 offsets). The editor selects it, so the tab shows which statement ran, and Safe Mode judges that text alone. -- Results: the run's first result set in `DataGridView` (ADR 0003), given to the grid once it has its first rows, or once it ends empty, and grown on each `RowsAppended`. The rows shown stay until then, so a sort or a refresh never shows an empty grid between the two results. A run with more than one set shows a `ComboBox` over the grid, "Result 1 (3)", "Result 2 (50)", as the Linux app labels them, with the count the engine gave or a plus when the row limit cut a set short; picking one shows its rows in arrival order and its count in the status. The pane holds every set of the run until the next run's first set replaces them. Columns are sized to their content, and a sort or a refresh keeps their widths. Copy and Select All in the Edit menu reach the grid when it had focus last. +- Results: the run's first result set in `DataGridView` (ADR 0003), given to the grid once it has its first rows, or once it ends empty, and grown on each `RowsAppended`. The rows shown stay until then, so a sort or a refresh never shows an empty grid between the two results. A run with more than one set shows a `ComboBox` over the grid, "Result 1 (3)", "Result 2 (50)", as the Linux app labels them, with the count the engine gave or a plus when the row limit cut a set short; picking one shows its rows in arrival order and its count in the status. The pane holds every set of the run until the next run's first set replaces them, unless Settings, Queries, Results kept per run sets a limit (10 to 1,000, as macOS): past it the run keeps its newest sets, lets go of the rest in the core (`QueryRun::release_set`), and its status ends with "N earlier results were dropped.". A dropped set the grid still shows stays until another is picked or the run ends, when the first set kept takes its place. Columns are sized to their content, and a sort or a refresh keeps their widths. Copy and Select All in the Edit menu reach the grid when it had focus last. - Messages: a run the server printed something in gets a `SelectorBar`, Results | Messages, over its results. Messages is a read-only monospace `TextBox` with one line per notice, `{severity}: {message}`, as the Linux app prints the same core's notices, set once per batch of events rather than per notice. A run with no rows opens on Messages, one with rows on Results unless Messages was picked while it ran. Past the 10,000 notices the core keeps per run (`NoticeLimitReached`), the text ends with "The output was cut short." - A header click on a table tab runs the table's query again with the sort: `build_page` writes the ORDER BY, with the row key as the tiebreak, so it orders the whole table, not the rows already read. A row address the engine adds for edits (SQLite's rowid, PostgreSQL's ctid) follows the visible columns and is not shown. An engine that pages in its own order refuses the sort, and the grid keeps the shown one. - 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. 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`). +- 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 the threshold (Settings, Pagination, Count rows if estimate less than: 1,000, 10,000, 100,000, 1,000,000 or Always count, 100,000 unless changed, as macOS), or with no estimate, the server counts; from the threshold 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`). @@ -130,7 +130,7 @@ On 2026-11-05 the maintainer had the app show what the server prints, PostgreSQL ### Settings -A page in the window, built from `SettingsCard` and `SettingsExpander`: Appearance (theme, with a link to Windows color settings), Startup (reopen the previous session), Editor (font size), Queries (row limit, query timeout), Pagination (default page size), About (version, documentation, report an issue, the data folder). A change applies at once; there is no Save ([App settings guidelines](https://learn.microsoft.com/en-us/windows/apps/design/app-settings/guidelines-for-app-settings)). +A page in the window, built from `SettingsCard` and `SettingsExpander`: Appearance (theme, with a link to Windows color settings), Startup (reopen the previous session), Editor (font size), Queries (row limit, results kept per run, query timeout), Pagination (default page size, count rows if estimate less than), About (version, documentation, report an issue, the data folder). A change applies at once; there is no Save ([App settings guidelines](https://learn.microsoft.com/en-us/windows/apps/design/app-settings/guidelines-for-app-settings)). ### Where things are kept diff --git a/windows/src/TablePro.App.Model/AppSettings.cs b/windows/src/TablePro.App.Model/AppSettings.cs index 576f20a721..5d7f2d10db 100644 --- a/windows/src/TablePro.App.Model/AppSettings.cs +++ b/windows/src/TablePro.App.Model/AppSettings.cs @@ -16,9 +16,20 @@ public sealed record AppSettings public const int DefaultPageSize = 1_000; + public const long DefaultCountRowsBelow = 100_000; + + // Counts every table whatever its estimate, as macOS's "Always count". + public const long AlwaysCount = long.MaxValue; + // The sizes the Settings page offers for a new table tab, as macOS offers them. public static IReadOnlyList PageSizeChoices { get; } = [100, 500, 1_000, 5_000, 10_000]; + // The thresholds the Settings page offers, as macOS offers them. + public static IReadOnlyList CountThresholdChoices { get; } = [1_000, 10_000, 100_000, 1_000_000, AlwaysCount]; + + // As macOS offers them; 0 keeps every result. + public static IReadOnlyList ResultsKeptChoices { get; } = [0, 10, 20, 50, 100, 200, 500, 1_000]; + public AppTheme Theme { get; set; } = AppTheme.System; public bool ReopenSession { get; set; } = true; @@ -33,6 +44,12 @@ public sealed record AppSettings // Zero leaves the statement to the connection's own limit. public int QueryTimeoutSeconds { get; set; } + // A table tab whose table the engine estimates at this many rows or more counts them only when asked. + public long CountRowsIfEstimateLessThan { get; set; } = DefaultCountRowsBelow; + + // Results with rows a run keeps, the newest; 0 keeps them all. + public int ResultSetsKeptPerRun { get; set; } + public AppSettings Normalized() => this with { Theme = Enum.IsDefined(Theme) ? Theme : AppTheme.System, @@ -40,6 +57,8 @@ public AppSettings Normalized() => this with RowLimit = Math.Clamp(RowLimit, 1, 1_000_000), PageSize = Math.Clamp(PageSize, 10, 100_000), QueryTimeoutSeconds = Math.Clamp(QueryTimeoutSeconds, 0, 86_400), + CountRowsIfEstimateLessThan = Math.Max(0, CountRowsIfEstimateLessThan), + ResultSetsKeptPerRun = Math.Max(0, ResultSetsKeptPerRun), }; } diff --git a/windows/src/TablePro.App.Model/IResultsView.cs b/windows/src/TablePro.App.Model/IResultsView.cs index 504cc764f7..2894ec52ba 100644 --- a/windows/src/TablePro.App.Model/IResultsView.cs +++ b/windows/src/TablePro.App.Model/IResultsView.cs @@ -30,7 +30,9 @@ public interface IResultsView event EventHandler? ShownSetChanged; - Task ShowRunAsync(ITabRun run, GridSort sort, int visibleColumns, CancellationToken cancellationToken); + // keptSets past 0 keeps only the run's newest sets, as Settings asks; it applies from this run on. + Task ShowRunAsync( + ITabRun run, GridSort sort, int visibleColumns, int keptSets, CancellationToken cancellationToken); // False when no set is shown, or a run or a pick replaced it while the rows were being sorted. Task SortHeldRowsAsync(GridSort sort); diff --git a/windows/src/TablePro.App.Model/QueryTab.cs b/windows/src/TablePro.App.Model/QueryTab.cs index 7a8833b3e7..178cf4739f 100644 --- a/windows/src/TablePro.App.Model/QueryTab.cs +++ b/windows/src/TablePro.App.Model/QueryTab.cs @@ -291,8 +291,10 @@ private async Task RunOnEditorAsync(string sql, bool record, CancellationToken c _run?.Dispose(); var startedAt = DateTimeOffset.Now; var started = Stopwatch.GetTimestamp(); - _run = _editor.Run(sql, RunOptions(_settings()), cancellationToken); - await _results.ShowRunAsync(_run, _sort, int.MaxValue, cancellationToken).ConfigureAwait(true); + var settings = _settings(); + _run = _editor.Run(sql, RunOptions(settings), cancellationToken); + await _results.ShowRunAsync(_run, _sort, int.MaxValue, settings.ResultSetsKeptPerRun, cancellationToken) + .ConfigureAwait(true); if (!_work.IsClosed) { if (record) diff --git a/windows/src/TablePro.App.Model/RunResults.cs b/windows/src/TablePro.App.Model/RunResults.cs index 8da67d5e9c..af7cc9bc23 100644 --- a/windows/src/TablePro.App.Model/RunResults.cs +++ b/windows/src/TablePro.App.Model/RunResults.cs @@ -26,7 +26,7 @@ public sealed class RunResult(int setIndex, IReadOnlyList columns) } // Each result set of a run in the order it started, labelled "Result {n} ({rows})" as the Linux app lists them. -public sealed class RunResults(string label, string labelMore) +public sealed class RunResults(string label, string labelMore, int kept = 0) { private readonly List _results = []; @@ -35,11 +35,28 @@ public sealed class RunResults(string label, string labelMore) public IReadOnlyList Results => _results; - public RunResult Add(int setIndex, IReadOnlyList columns) + // Earlier sets the limit let go of. + public int Dropped { get; private set; } + + // Past a limit the oldest set goes, as macOS keeps the newest, and the caller lets go of what it holds for it. + public RunResult Add(int setIndex, IReadOnlyList columns, out RunResult? dropped) { - var result = new RunResult(setIndex, columns) { Position = _results.Count + 1 }; + var result = new RunResult(setIndex, columns) { Position = Dropped + _results.Count + 1 }; _results.Add(result); _bySet.TryAdd(setIndex, result); + dropped = null; + if (kept > 0 && _results.Count > kept) + { + dropped = _results[0]; + _results.RemoveAt(0); + if (_bySet.TryGetValue(dropped.SetIndex, out var listed) && ReferenceEquals(listed, dropped)) + { + _bySet.Remove(dropped.SetIndex); + } + + Dropped++; + } + return result; } diff --git a/windows/src/TablePro.App.Model/TabSession.cs b/windows/src/TablePro.App.Model/TabSession.cs index be6b4ba2a9..05587b0387 100644 --- a/windows/src/TablePro.App.Model/TabSession.cs +++ b/windows/src/TablePro.App.Model/TabSession.cs @@ -97,6 +97,9 @@ public interface ITabRun : IDisposable ResultSet? GetResultSet(int index); + // The tab shows the set no more, so the core lets go of its rows. + void ReleaseSet(int index); + void Cancel(); } @@ -226,6 +229,8 @@ public IAsyncEnumerable ReadEventsAsync(CancellationToken cancellati public ResultSet? GetResultSet(int index) => run.GetResultSet(index); + public void ReleaseSet(int index) => run.ReleaseSet(index); + public void Cancel() => run.Cancel(); public void Dispose() => run.Dispose(); diff --git a/windows/src/TablePro.App.Model/TableTab.cs b/windows/src/TablePro.App.Model/TableTab.cs index 7a04059828..11e836bde1 100644 --- a/windows/src/TablePro.App.Model/TableTab.cs +++ b/windows/src/TablePro.App.Model/TableTab.cs @@ -129,9 +129,6 @@ 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; @@ -758,7 +755,8 @@ private async Task LoadPageAsync(long offset, bool recount, CancellationToken ca Total = recount ? null : _page.Total, Estimate = recount ? null : _page.Estimate, }; - await _results.ShowRunAsync(_run, _sort, read.VisibleColumns, cancellationToken).ConfigureAwait(true); + await _results.ShowRunAsync(_run, _sort, read.VisibleColumns, keptSets: 0, cancellationToken) + .ConfigureAwait(true); if (_work.IsClosed) { return; @@ -1226,7 +1224,7 @@ private async Task CountsAfterEstimateAsync(TableFilter? filter, Cancellat _page = _page with { Estimate = known.Rows }; } - if (estimate is { Rows: >= CountsBelow }) + if (estimate is { } held && held.Rows >= _settings().CountRowsIfEstimateLessThan) { _countHeldBack = true; return false; diff --git a/windows/src/TablePro.App/Strings/en-US/Resources.resw b/windows/src/TablePro.App/Strings/en-US/Resources.resw index 9a97f88066..b95bdd1167 100644 --- a/windows/src/TablePro.App/Strings/en-US/Resources.resw +++ b/windows/src/TablePro.App/Strings/en-US/Resources.resw @@ -432,6 +432,27 @@ Row limit + + Results kept per run + + + A run that returns more results with rows keeps only the newest. + + + Results kept per run + + + No limit + + + {0:N0} + + + {0} · 1 earlier result was dropped. + + + {0} · {1:N0} earlier results were dropped. + Query timeout @@ -1458,6 +1479,21 @@ Default page size + + Count rows if estimate less than + + + Tables with more estimated rows use approximate counts to avoid slow COUNT(*) queries + + + Count rows if estimate less than + + + {0:N0} + + + Always count + Trust this SSH server? diff --git a/windows/src/TablePro.App/Views/ResultsPane.xaml.cs b/windows/src/TablePro.App/Views/ResultsPane.xaml.cs index e5e7b26a51..6aba8874f8 100644 --- a/windows/src/TablePro.App/Views/ResultsPane.xaml.cs +++ b/windows/src/TablePro.App/Views/ResultsPane.xaml.cs @@ -14,6 +14,10 @@ public sealed partial class ResultsPane : UserControl, IResultsView private readonly RunMessages _messages = new(Strings.Get("MessagesCutShort")); private List _held = []; private HeldSet? _picked; + + // A set the limit dropped while the grid showed it, kept in _held and the picker until the run lets it go. + private HeldSet? _leaving; + private int _droppedSets; private ResultSet? _sorted; private ResultSet? _shown; private long? _milliseconds; @@ -124,19 +128,21 @@ public void Clear() } // The sets shown stay until the new run's first set has rows or ends, so a sort or a refresh never blanks the grid. - public async Task ShowRunAsync(ITabRun run, GridSort sort, int visibleColumns, CancellationToken cancellationToken) + public async Task ShowRunAsync(ITabRun run, GridSort sort, int visibleColumns, int keptSets, + CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(run); ErrorBar.IsOpen = false; Status(Strings.Get("StatusRunning")); ResultSetCount = 0; + _droppedSets = 0; Outcome = null; RowsAffected = null; _milliseconds = null; // The last run's messages stay on screen until this one's arrive or it ends, as its rows do. _messages.Reset(); _pickedView = null; - var results = new RunResults(Strings.Get("ResultSetItem"), Strings.Get("ResultSetItemMore")); + var results = new RunResults(Strings.Get("ResultSetItem"), Strings.Get("ResultSetItemMore"), keptSets); var incoming = new List(); var heldBy = new Dictionary(); var adopted = false; @@ -168,7 +174,8 @@ void Adopt() ResultSetCount++; if (run.GetResultSet(started.SetIndex) is { } set) { - var result = results.Add(started.SetIndex, started.Columns.Take(visibleColumns).ToList()); + var result = results.Add( + started.SetIndex, started.Columns.Take(visibleColumns).ToList(), out var dropped); var item = new ComboBoxItem { Content = results.Label(result) }; var held = new HeldSet(result, set, item); incoming.Add(held); @@ -177,6 +184,13 @@ void Adopt() { ListInPicker(item); } + + LetGoOfLeaving(); + if (dropped is not null && heldBy.Remove(dropped, out var gone)) + { + run.ReleaseSet(gone.Result.SetIndex); + Drop(incoming, gone); + } } break; @@ -209,6 +223,9 @@ or QueryEvent.ByteLimitReached break; case QueryEvent.Finished finished: Adopt(); + ShowFirstKept(); + LetGoOfLeaving(); + _droppedSets = results.Dropped; RowCount = adopted ? (_picked?.Result.Rows ?? 0) : 0; Transaction = finished.Transaction; Outcome = finished.Outcome; @@ -256,6 +273,7 @@ private void ShowRun(List incoming, GridSort sort) var first = incoming[0]; _held = incoming; _picked = first; + _leaving = null; _sorted = null; Columns = first.Result.Columns; ResultGrid.SetData(GridData(first.Set, first.Result.Columns)); @@ -286,6 +304,67 @@ private void Pick(HeldSet held) ResultPicked?.Invoke(this, EventArgs.Empty); } + // Once the run is shown the grid reads the set it shows, so that one stays until the run lets it go. + private void Drop(List incoming, HeldSet gone) + { + if (ReferenceEquals(gone, _picked)) + { + _leaving = gone; + return; + } + + incoming.Remove(gone); + if (ReferenceEquals(_held, incoming)) + { + RemoveFromPicker(gone.Item); + } + + gone.Set.Dispose(); + } + + // At the run's end the first set kept takes the place of a dropped one still shown, as a run shows its first set. + private void ShowFirstKept() + { + if (_leaving is not { } leaving + || !ReferenceEquals(leaving, _picked) + || _held.Find(entry => !ReferenceEquals(entry, leaving)) is not { } first) + { + return; + } + + Pick(first); + ShowPickedLabel(); + } + + // Called from the run's events, never from the picker's own, so its list never changes while it takes a pick. + private void LetGoOfLeaving() + { + if (_leaving is not { } leaving || ReferenceEquals(leaving, _picked)) + { + return; + } + + _leaving = null; + _held.Remove(leaving); + RemoveFromPicker(leaving.Item); + leaving.Set.Dispose(); + } + + private void RemoveFromPicker(ComboBoxItem item) + { + _picking = true; + try + { + ResultPicker.Items.Remove(item); + } + finally + { + _picking = false; + } + + ResultPicker.Visibility = _held.Count > 1 ? Visibility.Visible : Visibility.Collapsed; + } + private void Release() { var (held, sorted) = (_held, _sorted); @@ -294,6 +373,7 @@ private void Release() Placeholder.Visibility = Visibility.Visible; _held = []; _picked = null; + _leaving = null; _sorted = null; Columns = []; DisposeSets(held, sorted); @@ -391,6 +471,11 @@ private void OnResultPicked(object sender, SelectionChangedEventArgs e) } Pick(picked); + if (_leaving is not null) + { + // After the picker has taken the pick, since its list changes. + DispatcherQueue.TryEnqueue(LetGoOfLeaving); + } } private void Finish(QueryOutcome outcome, bool hasRows, long? affected) @@ -426,12 +511,22 @@ private void Finish(QueryOutcome outcome, bool hasRows, long? affected) ShowError(Strings.Get("StatusTimedOut")); break; default: - Status(Strings.Get("StatusCancelled")); + Status(WithDropped(Strings.Get("StatusCancelled"))); break; } } - private string RowsText(RunResult result, long milliseconds) => + private string RowsText(RunResult result, long milliseconds) => WithDropped(SetText(result, milliseconds)); + + // One line says how many earlier sets the limit dropped, after the status of its own. + private string WithDropped(string status) => _droppedSets switch + { + 0 => status, + 1 => Strings.Format("ResultsDroppedOne", status), + _ => Strings.Format("ResultsDroppedOther", status, _droppedSets), + }; + + private string SetText(RunResult result, long milliseconds) => RowsStatus?.Invoke(result.Rows, milliseconds, result.Truncated) ?? Strings.Format( result switch diff --git a/windows/src/TablePro.App/Views/SettingsView.xaml b/windows/src/TablePro.App/Views/SettingsView.xaml index 7ff758936a..657ab6910d 100644 --- a/windows/src/TablePro.App/Views/SettingsView.xaml +++ b/windows/src/TablePro.App/Views/SettingsView.xaml @@ -62,6 +62,10 @@ SpinButtonPlacementMode="Compact" ValueChanged="OnRowLimitChanged" /> + + + + + + + + diff --git a/windows/src/TablePro.App/Views/SettingsView.xaml.cs b/windows/src/TablePro.App/Views/SettingsView.xaml.cs index 40f57936bc..3858ae2db0 100644 --- a/windows/src/TablePro.App/Views/SettingsView.xaml.cs +++ b/windows/src/TablePro.App/Views/SettingsView.xaml.cs @@ -54,9 +54,36 @@ private void Load() PageSizeBox.SelectedItem = PageSizeBox.Items .OfType() .First(item => item.Tag is int size && size == settings.PageSize); + ResultsKeptBox.Items.Clear(); + foreach (var kept in AppSettings.ResultsKeptChoices.Append(settings.ResultSetsKeptPerRun).Distinct().Order()) + { + ResultsKeptBox.Items.Add(new ComboBoxItem { Content = ResultsKeptLabel(kept), Tag = kept }); + } + + ResultsKeptBox.SelectedItem = ResultsKeptBox.Items + .OfType() + .First(item => item.Tag is int kept && kept == settings.ResultSetsKeptPerRun); + CountThresholdBox.Items.Clear(); + var thresholds = AppSettings.CountThresholdChoices.Append(settings.CountRowsIfEstimateLessThan); + foreach (var threshold in thresholds.Distinct().Order()) + { + CountThresholdBox.Items.Add(new ComboBoxItem { Content = ThresholdLabel(threshold), Tag = threshold }); + } + + CountThresholdBox.SelectedItem = CountThresholdBox.Items + .OfType() + .First(item => item.Tag is long threshold && threshold == settings.CountRowsIfEstimateLessThan); _loading = false; } + private static string ResultsKeptLabel(int kept) => kept == 0 + ? Strings.Get("ResultsKeptNoLimit") + : Strings.Format("ResultsKeptOption", kept); + + private static string ThresholdLabel(long threshold) => threshold == AppSettings.AlwaysCount + ? Strings.Get("CountThresholdAlways") + : Strings.Format("CountThresholdOption", threshold); + private void OnThemeChanged(object sender, SelectionChangedEventArgs e) { if (_loading || ThemeBox.SelectedItem is not ComboBoxItem { Tag: string tag }) @@ -101,6 +128,22 @@ private void OnPageSizeChanged(object sender, SelectionChangedEventArgs e) } } + private void OnResultsKeptChanged(object sender, SelectionChangedEventArgs e) + { + if (!_loading && ResultsKeptBox.SelectedItem is ComboBoxItem { Tag: int kept }) + { + _workbench.UpdateSettings(settings => settings with { ResultSetsKeptPerRun = kept }); + } + } + + private void OnCountThresholdChanged(object sender, SelectionChangedEventArgs e) + { + if (!_loading && CountThresholdBox.SelectedItem is ComboBoxItem { Tag: long threshold }) + { + _workbench.UpdateSettings(settings => settings with { CountRowsIfEstimateLessThan = threshold }); + } + } + private void OnTimeoutChanged(NumberBox sender, NumberBoxValueChangedEventArgs args) { if (!_loading && !double.IsNaN(args.NewValue)) diff --git a/windows/src/TablePro.Editor/Rendering/Brushes.cs b/windows/src/TablePro.Editor/Rendering/Brushes.cs index 95a6dc81ff..d4629f1430 100644 --- a/windows/src/TablePro.Editor/Rendering/Brushes.cs +++ b/windows/src/TablePro.Editor/Rendering/Brushes.cs @@ -19,7 +19,6 @@ public Brushes(ID2D1DeviceContext* context, Palette palette) CurrentLine = Create(context, palette.CurrentLine); Selection = Create(context, palette.Selection); SelectionText = palette.SelectionText is Color selected ? Create(context, selected) : null; - Caret = Create(context, palette.Caret); FindMatch = Create(context, palette.FindMatch); _syntax = new ID2D1Brush*[palette.Syntax.Length]; for (var i = 0; i < palette.Syntax.Length; i++) @@ -40,8 +39,6 @@ public Brushes(ID2D1DeviceContext* context, Palette palette) public ID2D1Brush* SelectionText { get; } - public ID2D1Brush* Caret { get; } - public ID2D1Brush* FindMatch { get; } // Kinds past the syntax table are the editor's own: SelectedText marks high-contrast selected text. diff --git a/windows/src/TablePro.Editor/SqlEditor.Caret.cs b/windows/src/TablePro.Editor/SqlEditor.Caret.cs index 28bad833fe..4052848c6f 100644 --- a/windows/src/TablePro.Editor/SqlEditor.Caret.cs +++ b/windows/src/TablePro.Editor/SqlEditor.Caret.cs @@ -1,5 +1,8 @@ +using System.Numerics; +using Microsoft.UI.Composition; using Microsoft.UI.Dispatching; using Microsoft.UI.Input; +using Microsoft.UI.Xaml.Hosting; using TablePro.Editor.Model; using Windows.UI.ViewManagement; using static TerraFX.Interop.Windows.SPI; @@ -10,8 +13,15 @@ namespace TablePro.Editor; public sealed partial class SqlEditor { private readonly CaretBlink _blink = new(); + private readonly List _caretSpots = []; + private readonly List _caretSprites = []; private DispatcherQueueTimer? _blinkTimer; private InputActivationListener? _activation; + private ContainerVisual? _caretLayer; + private InsetClip? _caretClip; + private CompositionColorBrush? _caretBrush; + private int _caretsPlaced; + private uint _caretPixels; private bool _hooked; internal bool IsCaretBlinking => _blink.IsBlinking; @@ -20,6 +30,11 @@ public sealed partial class SqlEditor internal bool IsInActiveWindow => _activation?.State == InputActivationState.Activated; + internal bool IsCaretShown => _caretLayer is { IsVisible: true } && _caretsPlaced > 0; + + // Each time a blink, focus or the window showed or hid the carets. + internal int CaretToggles { get; private set; } + // Only while loaded: UISettings, the window's listener and the timer would hold the editor through its handlers. private void Hook() { @@ -42,6 +57,7 @@ private void Hook() _blinkTimer.Tick += OnBlinkTick; ReadCaretSettings(); _blink.SetActive(_activation?.State != InputActivationState.Deactivated); + ShowCaretState(); SyncBlinkTimer(); } @@ -68,10 +84,8 @@ private void Unhook() // Input shows the caret and starts its timeout again. private void RestartBlink() { - if (_blink.Restart()) - { - Invalidate(); - } + _blink.Restart(); + ShowCaretState(); SyncBlinkTimer(); } @@ -92,10 +106,8 @@ private void SyncBlinkTimer() private void OnBlinkTick(DispatcherQueueTimer sender, object args) { - if (_blink.Tick()) - { - Invalidate(); - } + _blink.Tick(); + ShowCaretState(); if (!_blink.IsBlinking) { sender.Stop(); @@ -105,10 +117,8 @@ private void OnBlinkTick(DispatcherQueueTimer sender, object args) private void OnInputActivationChanged(InputActivationListener sender, InputActivationListenerActivationChangedEventArgs args) { - if (_blink.SetActive(sender.State != InputActivationState.Deactivated)) - { - Invalidate(); - } + _blink.SetActive(sender.State != InputActivationState.Deactivated); + ShowCaretState(); SyncBlinkTimer(); } @@ -126,4 +136,111 @@ private unsafe void ReadCaretSettings() ? TimeSpan.FromMilliseconds(timeout) : CaretBlink.DefaultTimeout; } + + // A visual of its own over the swap chain, as WinUI's TextBox has a caret element, so a blink draws no frame. + private void EnsureCaretLayer() + { + if (_caretLayer is not null) + { + return; + } + var compositor = ElementCompositionPreview.GetElementVisual(_panel).Compositor; + _caretBrush = compositor.CreateColorBrush(_brushes?.Palette.Caret ?? default); + _caretClip = compositor.CreateInsetClip(); + _caretLayer = compositor.CreateContainerVisual(); + _caretLayer.Clip = _caretClip; + _caretLayer.IsVisible = _blink.CaretVisible; + // SwapChainPanel puts its swap chain first in render order, so a child visual draws above it. + ElementCompositionPreview.SetElementChildVisual(_panel, _caretLayer); + } + + private void ShowCaretState() + { + if (_caretLayer is null || _caretLayer.IsVisible == _blink.CaretVisible) + { + return; + } + _caretLayer.IsVisible = _blink.CaretVisible; + CaretToggles++; + } + + // With the frame just presented, so the carets move with the text; snapped to pixels, as a Win32 caret is. + private void PlaceCarets(float gutter, float width, float height, float lineHeight) + { + EnsureCaretLayer(); + var layer = _caretLayer!; + var scaleX = Math.Max(_panel.CompositionScaleX, 0.01f); + var scaleY = Math.Max(_panel.CompositionScaleY, 0.01f); + var caretWidth = CaretPixels() / scaleX; + layer.Size = new Vector2(width, height); + _caretClip!.LeftInset = gutter; + for (var i = 0; i < _caretSpots.Count; i++) + { + var spot = _caretSpots[i]; + if (i == _caretSprites.Count) + { + var created = layer.Compositor.CreateSpriteVisual(); + created.Brush = _caretBrush; + _caretSprites.Add(created); + } + var sprite = _caretSprites[i]; + var top = MathF.Round(spot.Y * scaleY) / scaleY; + var bottom = MathF.Round((spot.Y + lineHeight) * scaleY) / scaleY; + sprite.Offset = new Vector3(MathF.Round(spot.X * scaleX) / scaleX, top, 0); + sprite.Size = new Vector2(caretWidth, bottom - top); + if (i >= _caretsPlaced) + { + layer.Children.InsertAtTop(sprite); + } + } + for (var i = _caretSpots.Count; i < _caretsPlaced; i++) + { + layer.Children.Remove(_caretSprites[i]); + } + _caretsPlaced = _caretSpots.Count; + ShowCaretState(); + } + + // A tab shown again draws on a new swap chain, so its carets wait for that first frame. + private void ClearCarets() + { + if (_caretLayer is null) + { + return; + } + _caretLayer.Children.RemoveAll(); + _caretsPlaced = 0; + } + + private unsafe uint CaretPixels() + { + if (_caretPixels == 0) + { + uint pixels = 1; + SystemParametersInfoW(SPI_GETCARETWIDTH, 0, &pixels, 0); + _caretPixels = Math.Max(1, pixels); + } + return _caretPixels; + } + + private void ReleaseCaretLayer() + { + if (_caretLayer is null) + { + return; + } + ElementCompositionPreview.SetElementChildVisual(_panel, null); + foreach (var sprite in _caretSprites) + { + sprite.Dispose(); + } + _caretSprites.Clear(); + _caretsPlaced = 0; + _caretLayer.Dispose(); + _caretLayer = null; + _caretClip?.Dispose(); + _caretClip = null; + _caretBrush?.Dispose(); + _caretBrush = null; + } } diff --git a/windows/src/TablePro.Editor/SqlEditor.Render.cs b/windows/src/TablePro.Editor/SqlEditor.Render.cs index 2062ddcd4c..25d724e17e 100644 --- a/windows/src/TablePro.Editor/SqlEditor.Render.cs +++ b/windows/src/TablePro.Editor/SqlEditor.Render.cs @@ -5,8 +5,6 @@ using TerraFX.Interop.DirectX; using static TerraFX.Interop.DirectX.D2D1_ANTIALIAS_MODE; using static TerraFX.Interop.DirectX.D2D1_DRAW_TEXT_OPTIONS; -using static TerraFX.Interop.Windows.SPI; -using static TerraFX.Interop.Windows.Windows; namespace TablePro.Editor; @@ -15,7 +13,6 @@ public sealed partial class SqlEditor private readonly Dictionary _frameLayouts = []; private readonly List _runs = []; private long _frameVersion = -1; - private float _caretWidth = -1; private bool _idleLexingQueued; private bool _waitingForTick; @@ -113,8 +110,7 @@ private unsafe void Render() var matches = FindMatchesIn(first, last); var spanIndex = 0; var primaryLine = Document.GetLineFromOffset(_model.Primary.Active); - var caretOn = _blink.CaretVisible; - var caretWidth = CaretWidth(); + _caretSpots.Clear(); for (var line = first; line <= last; line++) { var lineStart = Document.GetLineStart(line); @@ -189,23 +185,18 @@ private unsafe void Render() DrawCompositionMarks(context, layout, compositionColumn, originX, y, lineHeight); } - if (caretOn) + foreach (var selection in selections) { - foreach (var selection in selections) + if (selection.Active < lineStart || selection.Active > lineEnd) { - if (selection.Active < lineStart || selection.Active > lineEnd) - { - continue; - } - var column = selection.Active - lineStart; - if (composing && selection.Active == _model.Primary.Active) - { - column += _compositionCaret; - } - var x = originX + layout.XAt(column); - var caret = Rect(x, y, caretWidth, lineHeight); - context->FillRectangle(&caret, brushes.Caret); + continue; } + var column = selection.Active - lineStart; + if (composing && selection.Active == _model.Primary.Active) + { + column += _compositionCaret; + } + _caretSpots.Add(new System.Numerics.Vector2(originX + layout.XAt(column), y)); } } context->PopAxisAlignedClip(); @@ -217,6 +208,7 @@ private unsafe void Render() return; } _layouts.EndFrame(); + PlaceCarets(gutter, width, height, lineHeight); var presented = Now(); FramePresented?.Invoke(this, new EditorFrame(presented, Milliseconds(started, presented), lexMilliseconds, Document.Version, first, last, created, _device.IsSoftware)); @@ -360,20 +352,6 @@ private unsafe void DrawCompositionMarks(ID2D1DeviceContext* context, LineLayout return TextSearch.InRange(Document, _findBar.Query, Document.GetLineStart(first), Document.GetLineEnd(last)); } - private float CaretWidth() - { - if (_caretWidth < 0) - { - uint pixels = 1; - unsafe - { - SystemParametersInfoW(SPI_GETCARETWIDTH, 0, &pixels, 0); - } - _caretWidth = Math.Max(1, pixels); - } - return _caretWidth / Math.Max(1, _panel.CompositionScaleX); - } - private static ulong StyleKey(List runs) { var hash = 14695981039346656037UL; diff --git a/windows/src/TablePro.Editor/SqlEditor.cs b/windows/src/TablePro.Editor/SqlEditor.cs index 8aae4ad7c7..3e3cbc44f6 100644 --- a/windows/src/TablePro.Editor/SqlEditor.cs +++ b/windows/src/TablePro.Editor/SqlEditor.cs @@ -183,6 +183,7 @@ public void Dispose() _disposed = true; Unhook(); _highlighter?.Dispose(); + ReleaseCaretLayer(); ReleaseDevice(); _tsf?.Dispose(); _tsf = null; @@ -255,6 +256,7 @@ private void OnUnloaded(object sender, RoutedEventArgs e) } _loaded = false; Unhook(); + ClearCarets(); _device?.Detach(); } @@ -353,6 +355,10 @@ private unsafe void RebuildBrushes() } _brushes?.Dispose(); _brushes = new Brushes(_device.Context, Palette.Resolve(ActualTheme)); + if (_caretBrush is not null) + { + _caretBrush.Color = _brushes.Palette.Caret; + } ForgetLayouts(); Invalidate(); } @@ -360,6 +366,7 @@ private unsafe void RebuildBrushes() private void OnFocusChanged(bool focused) { _blink.SetFocused(focused); + ShowCaretState(); SyncBlinkTimer(); if (focused) { @@ -370,7 +377,6 @@ private void OnFocusChanged(bool focused) _tsf?.Unfocus(); _model.Document.Undo.BreakJoin(); } - Invalidate(); } private int PixelWidth() => (int)Math.Ceiling(_panel.ActualWidth * _panel.CompositionScaleX); diff --git a/windows/src/TablePro.Interop/Generated/tablepro_ffi.cs b/windows/src/TablePro.Interop/Generated/tablepro_ffi.cs index 7d7351609b..7953220314 100644 --- a/windows/src/TablePro.Interop/Generated/tablepro_ffi.cs +++ b/windows/src/TablePro.Interop/Generated/tablepro_ffi.cs @@ -1082,6 +1082,8 @@ public struct UniffiVTableCallbackInterfaceRunListener + + @@ -1942,6 +1944,17 @@ public static extern ulong uniffi_tablepro_ffi_fn_method_queryrun_outcome(ulong @ptr ); + #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 + void uniffi_tablepro_ffi_fn_method_queryrun_release_set(ulong @ptr,uint @index,ref UniffiRustCallStatus _uniffi_out_err + ); + #if NET8_0_OR_GREATER [LibraryImport("tablepro_ffi")] [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] @@ -3559,6 +3572,17 @@ public static extern ushort uniffi_tablepro_ffi_checksum_method_queryrun_outcome( ); + #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_queryrun_release_set( + ); + #if NET8_0_OR_GREATER [LibraryImport("tablepro_ffi")] [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] @@ -4394,6 +4418,12 @@ static void uniffiCheckApiChecksums() { throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_queryrun_outcome` checksum `54313`, library returned `{checksum}`"); } } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_queryrun_release_set(); + if (checksum != 49856) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_queryrun_release_set` checksum `49856`, library returned `{checksum}`"); + } + } { var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_queryrun_result_set(); if (checksum != 63812) { @@ -6822,6 +6852,10 @@ internal interface IQueryRun { /// /// Task Outcome(); + /// + /// The app shows this set no more, so the run lets go of its rows; they go once no `ResultSet` holds them. + /// + void ReleaseSet(uint @index); ResultSet? ResultSet(uint @index); } /// @@ -6961,6 +6995,18 @@ public async Task Outcome() { ); } + /// + /// The app shows this set no more, so the run lets go of its rows; they go once no `ResultSet` holds them. + /// + public void ReleaseSet(uint @index) { + CallWithPointer(thisPtr => + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_queryrun_release_set(thisPtr, FfiConverterUInt32.INSTANCE.Lower(@index), ref _status) +)); + } + + + public ResultSet? ResultSet(uint @index) { return CallWithPointer(thisPtr => FfiConverterOptionalTypeResultSet.INSTANCE.Lift( _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => diff --git a/windows/src/TablePro.Interop/QueryRun.cs b/windows/src/TablePro.Interop/QueryRun.cs index c6c1415615..69192e7e10 100644 --- a/windows/src/TablePro.Interop/QueryRun.cs +++ b/windows/src/TablePro.Interop/QueryRun.cs @@ -68,6 +68,19 @@ public async IAsyncEnumerable ReadEventsAsync( } } + // The run lets go of the set's rows, which go once no ResultSet holds them; GetResultSet gives null for it after. + public void ReleaseSet(int index) + { + ArgumentOutOfRangeException.ThrowIfNegative(index); + lock (_gate) + { + if (!_disposed) + { + _run.ReleaseSet(checked((uint)index)); + } + } + } + public void Cancel() { lock (_gate) diff --git a/windows/tests/TablePro.App.Model.Tests/QueryTabTests.cs b/windows/tests/TablePro.App.Model.Tests/QueryTabTests.cs index f49eba94cb..1d2d74329e 100644 --- a/windows/tests/TablePro.App.Model.Tests/QueryTabTests.cs +++ b/windows/tests/TablePro.App.Model.Tests/QueryTabTests.cs @@ -107,6 +107,21 @@ public async Task ATabClosedAfterItsRunWhileItLetsGoOfALostEditorSaysNothingMore Assert.Equal("clear", _results.Shown[^1]); } + // Read as each run starts, so a change in Settings applies from the next run on. + [Fact] + public async Task EachRunKeepsTheResultsSettingsHeldWhenItStarted() + { + var settings = new AppSettings(); + var tab = new QueryTab("Query 2", _session, _view, _results, DataModel.Relational, () => settings); + + await tab.RunAsync(); + Assert.Equal(0, _results.KeptSets); + + settings = settings with { ResultSetsKeptPerRun = 50 }; + await tab.RunAsync(); + Assert.Equal(50, _results.KeptSets); + } + [Fact] public async Task ATabClosedAfterItsRunLetsGoOfEachPieceOnce() { diff --git a/windows/tests/TablePro.App.Model.Tests/RunResultsTests.cs b/windows/tests/TablePro.App.Model.Tests/RunResultsTests.cs index de9484875f..8cfe53e610 100644 --- a/windows/tests/TablePro.App.Model.Tests/RunResultsTests.cs +++ b/windows/tests/TablePro.App.Model.Tests/RunResultsTests.cs @@ -10,8 +10,8 @@ public sealed class RunResultsTests public void EverySetOfARunIsListedInTheOrderItStarted() { var results = New(); - var first = results.Add(0, Columns); - var second = results.Add(1, Columns); + var first = results.Add(0, Columns, out _); + var second = results.Add(1, Columns, out _); results.Apply(new QueryEvent.ResultSetFinished(0, 3, null, Truncation.Complete)); results.Apply(new QueryEvent.RowsAppended(1, 40)); @@ -27,8 +27,8 @@ public void EverySetOfARunIsListedInTheOrderItStarted() public void RowsOfOneSetNeverCountTowardAnother() { var results = New(); - var first = results.Add(0, Columns); - results.Add(1, Columns); + var first = results.Add(0, Columns, out _); + results.Add(1, Columns, out _); var changed = results.Apply(new QueryEvent.RowsAppended(1, 7)); @@ -41,8 +41,8 @@ public void RowsOfOneSetNeverCountTowardAnother() public void ASetTheLimitCutShortShowsTheCountedTotalOrAPlus() { var results = New(); - var counted = results.Add(0, Columns); - var uncounted = results.Add(1, Columns); + var counted = results.Add(0, Columns, out _); + var uncounted = results.Add(1, Columns, out _); results.Apply(new QueryEvent.ResultSetFinished(0, 10_000, 25_000, Truncation.ReadPastLimit)); results.Apply(new QueryEvent.RowLimitReached(1, 10_000)); @@ -60,9 +60,9 @@ public void ASetTheLimitCutShortShowsTheCountedTotalOrAPlus() public void ASetCutForSizeKeepsTheRunsLimitAndShowsAPlusWhenNobodyCounted() { var results = New(); - var uncounted = results.Add(0, Columns); - var counted = results.Add(1, Columns); - var rowLimited = results.Add(2, Columns); + var uncounted = results.Add(0, Columns, out _); + var counted = results.Add(1, Columns, out _); + var rowLimited = results.Add(2, Columns, out _); results.Apply(new QueryEvent.RowsAppended(0, 16)); results.Apply(new QueryEvent.ByteLimitReached(0, 16, 256_000_000)); @@ -84,7 +84,7 @@ public void ASetCutForSizeKeepsTheRunsLimitAndShowsAPlusWhenNobodyCounted() public void EventsAboutNoListedSetChangeNothing() { var results = New(); - var only = results.Add(0, Columns); + var only = results.Add(0, Columns, out _); Assert.Null(results.Apply(new QueryEvent.RowsAppended(4, 9))); Assert.Null(results.Apply(new QueryEvent.CommandCompleted(2))); @@ -96,7 +96,7 @@ public void EventsAboutNoListedSetChangeNothing() public void TenThousandSetsEachTakeTheirOwnRowsAndPlace() { var results = New(); - var sets = Enumerable.Range(0, 10_000).Select(index => results.Add(index * 2, Columns)).ToList(); + var sets = Enumerable.Range(0, 10_000).Select(index => results.Add(index * 2, Columns, out _)).ToList(); foreach (var index in Enumerable.Range(0, sets.Count).Reverse()) { @@ -114,14 +114,71 @@ public void TenThousandSetsEachTakeTheirOwnRowsAndPlace() public void TwoSetsWithOneIndexLeaveTheEventsToTheFirst() { var results = New(); - var first = results.Add(3, Columns); - var second = results.Add(3, Columns); + var first = results.Add(3, Columns, out _); + var second = results.Add(3, Columns, out _); Assert.Same(first, results.Apply(new QueryEvent.RowsAppended(3, 8))); Assert.Equal(0, second.Rows); Assert.Equal("Result 2 (0)", results.Label(second)); } + [Fact] + public void PastTheLimitTheNewestSetsStayWithTheirRunPlaceAndTheOldestGoInOrder() + { + var results = New(kept: 3); + var dropped = new List(); + var sets = new List(); + for (var index = 0; index < 10; index++) + { + sets.Add(results.Add(index, Columns, out var gone)); + if (gone is not null) + { + dropped.Add(gone); + } + } + + Assert.Equal(sets[7..], results.Results); + Assert.Equal(sets[..7], dropped); + Assert.Equal(7, results.Dropped); + Assert.Null(results.Apply(new QueryEvent.ResultSetFinished(0, 5, null, Truncation.Complete))); + Assert.Same(sets[9], results.Apply(new QueryEvent.ResultSetFinished(9, 5, null, Truncation.Complete))); + Assert.Equal(["Result 8 (0)", "Result 9 (0)", "Result 10 (5)"], results.Results.Select(results.Label)); + } + + [Fact] + public void ExactlyTheLimitDropsNothing() + { + var results = New(kept: 3); + + for (var index = 0; index < 3; index++) + { + results.Add(index, Columns, out var gone); + Assert.Null(gone); + } + + Assert.Equal(3, results.Results.Count); + Assert.Equal(0, results.Dropped); + } + + // The sets a 10,000-set script leaves held, with the limit at 100. + [Fact] + public void TenThousandSetsWithAHundredKeptHoldAHundred() + { + var results = New(kept: 100); + var dropped = 0; + + for (var index = 0; index < 10_000; index++) + { + results.Add(index, Columns, out var gone); + dropped += gone is null ? 0 : 1; + } + + Assert.Equal(100, results.Results.Count); + Assert.Equal(9_900, dropped); + Assert.Equal(9_900, results.Dropped); + Assert.Equal("Result 9901 (0)", results.Label(results.Results[0])); + } + // No number format, so the labels read the same under every culture. - private static RunResults New() => new("Result {0} ({1})", "Result {0} ({1}+)"); + private static RunResults New(int kept = 0) => new("Result {0} ({1})", "Result {0} ({1}+)", kept); } diff --git a/windows/tests/TablePro.App.Model.Tests/StoreTests.cs b/windows/tests/TablePro.App.Model.Tests/StoreTests.cs index 9b9210fdf4..e675960fd7 100644 --- a/windows/tests/TablePro.App.Model.Tests/StoreTests.cs +++ b/windows/tests/TablePro.App.Model.Tests/StoreTests.cs @@ -19,6 +19,37 @@ public void SettingsComeBackAsSaved() Assert.Equal(saved, store.Load()); } + [Fact] + public void TheCountThresholdComesBackAsSavedAndAFileWithoutOneCountsBelowAHundredThousand() + { + var path = File("settings.json"); + System.IO.File.WriteAllText(path, """{ "theme": "Dark", "pageSize": 500 }"""); + Assert.Equal(100_000, new SettingsStore(path).Load().CountRowsIfEstimateLessThan); + + var store = new SettingsStore(path); + store.Save(new AppSettings { CountRowsIfEstimateLessThan = AppSettings.AlwaysCount }); + Assert.Equal(AppSettings.AlwaysCount, store.Load().CountRowsIfEstimateLessThan); + + System.IO.File.WriteAllText(path, """{ "countRowsIfEstimateLessThan": -5 }"""); + Assert.Equal(0, new SettingsStore(path).Load().CountRowsIfEstimateLessThan); + } + + [Fact] + public void ResultsKeptPerRunComeBackAsSavedAndAFileWithoutThemKeepsEveryResult() + { + var path = File("settings.json"); + System.IO.File.WriteAllText(path, """{ "theme": "Dark" }"""); + Assert.Equal(0, new SettingsStore(path).Load().ResultSetsKeptPerRun); + + var store = new SettingsStore(path); + store.Save(new AppSettings { ResultSetsKeptPerRun = 200 }); + Assert.Equal(200, store.Load().ResultSetsKeptPerRun); + Assert.Contains("\"resultSetsKeptPerRun\": 200", System.IO.File.ReadAllText(path), StringComparison.Ordinal); + + System.IO.File.WriteAllText(path, """{ "resultSetsKeptPerRun": -3 }"""); + Assert.Equal(0, new SettingsStore(path).Load().ResultSetsKeptPerRun); + } + [Fact] public void AMissingOrBrokenSettingsFileGivesTheDefaults() { diff --git a/windows/tests/TablePro.App.Model.Tests/TabFakes.cs b/windows/tests/TablePro.App.Model.Tests/TabFakes.cs index 84fc9d2bc0..6d98a854fc 100644 --- a/windows/tests/TablePro.App.Model.Tests/TabFakes.cs +++ b/windows/tests/TablePro.App.Model.Tests/TabFakes.cs @@ -389,9 +389,13 @@ public async IAsyncEnumerable ReadEventsAsync( } } + public List Released { get; } = []; + // A fake run's sets live in no core. public ResultSet? GetResultSet(int index) => null; + public void ReleaseSet(int index) => Released.Add(index); + public void Cancel() => Cancels++; public void Dispose() => Disposals++; @@ -426,10 +430,14 @@ internal sealed class FakeResults : IResultsView public event EventHandler? ShownSetChanged; - public async Task ShowRunAsync(ITabRun run, GridSort sort, int visibleColumns, CancellationToken cancellationToken) + public int KeptSets { get; private set; } + + public async Task ShowRunAsync(ITabRun run, GridSort sort, int visibleColumns, int keptSets, + CancellationToken cancellationToken) { Shown.Add("run"); RunSort = sort; + KeptSets = keptSets; ResultSetCount = 0; Outcome = null; RowsAffected = null; diff --git a/windows/tests/TablePro.App.Model.Tests/TableTabCountTests.cs b/windows/tests/TablePro.App.Model.Tests/TableTabCountTests.cs index 24e3a939bd..a31cb5a8f9 100644 --- a/windows/tests/TablePro.App.Model.Tests/TableTabCountTests.cs +++ b/windows/tests/TablePro.App.Model.Tests/TableTabCountTests.cs @@ -60,6 +60,41 @@ public async Task TheServerCountsByItselfOnlyATableEstimatedUnderAHundredThousan Assert.Equal(estimate, tab.Page.Estimate); } + // The choices Settings offers, as macOS offers them; Always count counts whatever the estimate. + [Theory] + [InlineData(1_000L, 5_000L, 0)] + [InlineData(10_000L, 9_999L, 1)] + [InlineData(1_000_000L, 500_000L, 1)] + [InlineData(1_000_000L, 1_000_000L, 0)] + [InlineData(AppSettings.AlwaysCount, 2_000_000L, 1)] + public async Task TheThresholdInSettingsDecidesWhetherTheServerCounts(long threshold, long estimate, int counts) + { + _settings = new AppSettings { CountRowsIfEstimateLessThan = threshold }; + _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); + } + + [Fact] + public async Task ARefreshCountsWithTheThresholdSettingsHoldNow() + { + _session.Estimate = new RowEstimate(2_000_000, IsExact: false); + var tab = New(); + await tab.RunAsync(); + Assert.Equal(0, _session.Counts); + + _settings = _settings with { CountRowsIfEstimateLessThan = AppSettings.AlwaysCount }; + await tab.RefreshAsync(); + + Assert.Equal(1, _session.Counts); + Assert.Equal(2_000_123, tab.Page.Total); + } + [Fact] public async Task AnExactEstimateOfTheWholeTableIsItsTotalWithNoCount() { diff --git a/windows/tests/TablePro.App.UITests/RunStatementTests.cs b/windows/tests/TablePro.App.UITests/RunStatementTests.cs index c79149e58a..8ad6807026 100644 --- a/windows/tests/TablePro.App.UITests/RunStatementTests.cs +++ b/windows/tests/TablePro.App.UITests/RunStatementTests.cs @@ -50,4 +50,32 @@ public void EveryResultSetOfARunCanBePicked(string theme) Assert.Equal("2", app.WaitForCell(app.Find("ResultsGrid"), 0, 0, value => value == "2")); app.Screenshot("42-result-picker"); } + + // Settings keeps two results per run, so the first two go and the status line says so. + [Theory] + [MemberData(nameof(Themes))] + public void ARunPastTheResultLimitKeepsTheNewestAndSaysHowManyWent(string theme) + { + var folder = AppSession.NewDataFolder(theme); + File.WriteAllText( + Path.Combine(folder, "settings.json"), + $$"""{ "theme": "{{theme}}", "resultSetsKeptPerRun": 2 }"""); + using var app = AppSession.Relaunch(folder, theme); + + app.Click(app.Find("SampleCard"), () => app.TryFind("Rail_Chinook (Sample)") is not null); + app.FindByName("Track", app.Find("ObjectTree")); + app.TypeInto("Query 1", "SELECT 1 AS a; SELECT 2 AS b; SELECT 3 AS c; SELECT 4 AS d"); + app.Chord( + () => app.Find("QueryStatus").Name.EndsWith("2 earlier results were dropped.", StringComparison.Ordinal), + VirtualKeyShort.CONTROL, + VirtualKeyShort.ENTER); + + Assert.Equal("3", app.WaitForCell(app.Find("ResultsGrid"), 0, 0, value => value == "3")); + var picker = app.Find("ResultPicker").AsComboBox(); + picker.Expand(); + var listed = picker.Items.Select(item => item.Name).ToArray(); + picker.Collapse(); + Assert.Equal(["Result 3 (1)", "Result 4 (1)"], listed); + app.Screenshot("43-result-limit"); + } } diff --git a/windows/tests/TablePro.Editor.Tests/CaretTests.cs b/windows/tests/TablePro.Editor.Tests/CaretTests.cs index 8c80af7ce7..8bb07c8ef5 100644 --- a/windows/tests/TablePro.Editor.Tests/CaretTests.cs +++ b/windows/tests/TablePro.Editor.Tests/CaretTests.cs @@ -1,4 +1,5 @@ using System.Diagnostics; +using System.Globalization; using Microsoft.UI.Xaml; using TablePro.Testing; using TerraFX.Interop.Windows; @@ -10,9 +11,9 @@ 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. + // A Win32 edit control stops blinking after the caret timeout; each blink of the editor's caret drew a whole frame. [Fact] - public Task TheCaretStopsBlinkingAfterTheCaretTimeoutAndNoFrameFollows() + public Task TheCaretBlinksWithNoFrameAndStopsAfterTheCaretTimeout() { var blink = GetCaretBlinkTime(); Assert.SkipWhen(blink is 0 or uint.MaxValue, "Caret blinking is off on this machine."); @@ -26,6 +27,9 @@ public Task TheCaretStopsBlinkingAfterTheCaretTimeoutAndNoFrameFollows() { Assert.True(await EditorHost.ShowAsync(editor), "the editor drew no frame"); WinUiApp.Window.Activate(); + // Past any frame the show still had queued, so what is counted is the blink's. + await WinUiApp.NextFrameAsync(); + await WinUiApp.NextFrameAsync(); 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."); @@ -36,6 +40,8 @@ public Task TheCaretStopsBlinkingAfterTheCaretTimeoutAndNoFrameFollows() Assert.True(editor.Focus(FocusState.Programmatic)); await WinUiApp.NextFrameAsync(); Assert.True(editor.IsCaretBlinking); + Assert.True(editor.IsCaretShown, "no caret shown after focus"); + var toggles = editor.CaretToggles; var undisturbed = true; while (editor.IsCaretBlinking && focused.Elapsed < timeout + TimeSpan.FromSeconds(3)) { @@ -49,10 +55,10 @@ public Task TheCaretStopsBlinkingAfterTheCaretTimeoutAndNoFrameFollows() $"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"); - await WinUiApp.NextFrameAsync(); - await WinUiApp.NextFrameAsync(); - frames = 0; + var toggled = editor.CaretToggles - toggles; + Assert.True(toggled >= 2, $"the caret toggled {toggled} times"); + Assert.True(editor.IsCaretShown, "the caret is hidden after the timeout"); + Assert.Equal(0, frames); await Task.Delay(1000, cancel); Assert.Equal(0, frames); } @@ -64,6 +70,108 @@ public Task TheCaretStopsBlinkingAfterTheCaretTimeoutAndNoFrameFollows() }); } + // Read from the screen: the caret's visual draws over the swap chain and the blink hides it. + [Fact] + public Task TheCaretShowsOverTheTextAndTheBlinkHidesIt() + { + var blink = GetCaretBlinkTime(); + Assert.SkipWhen(blink is 0 or uint.MaxValue, "Caret blinking is off on this machine."); + Assert.SkipWhen( + CaretTimeout() < TimeSpan.FromMilliseconds(blink * 3), "The caret timeout here ends the blink too soon."); + return WinUiApp.RunAsync(async () => + { + // Empty, so only the current line band lies under the caret. + var editor = new SqlEditor(); + try + { + Assert.True(await EditorHost.ShowAsync(editor), "the editor drew no frame"); + WinUiApp.Window.Activate(); + await WinUiApp.NextFrameAsync(); + Assert.SkipUnless(editor.IsInActiveWindow, "The test window is not the active window."); + Assert.True(editor.Focus(FocusState.Programmatic)); + await WinUiApp.NextFrameAsync(); + var caret = editor.CaretScreenRectangle(); + var x = caret.X; + var y = caret.Y + caret.Height / 2; + Assert.SkipUnless(ShowsWindow(editor, x, y), "Another window covers the caret."); + + var shown = await ReadScreenAsync(editor, shown: true, x, y); + var hidden = await ReadScreenAsync(editor, shown: false, x, y); + + Assert.SkipUnless( + shown is not null && hidden is not null && editor.IsInActiveWindow && ShowsWindow(editor, x, y), + "The blink or the window's activation changed while the screen was read."); + // The caret is one pixel wide, and the pixel either side covers a rounding of its place. + var differs = shown!.Zip(hidden!, Distance).Max(); + Assert.True(differs > 90, + $"around ({x}, {y}) the screen holds {Hex(shown!)} with the caret shown, {Hex(hidden!)} hidden"); + } + finally + { + EditorHost.Clear(); + editor.Dispose(); + } + }); + } + + // Once the compositor has had time to show the caret's state; null when a blink changed it meanwhile. + private static async Task ReadScreenAsync(SqlEditor editor, bool shown, int x, int y) + { + var cancel = TestContext.Current.CancellationToken; + var waited = Stopwatch.StartNew(); + while (editor.IsCaretBlinking && waited.Elapsed < TimeSpan.FromSeconds(4)) + { + if (editor.IsCaretShown == shown) + { + var toggles = editor.CaretToggles; + await WinUiApp.NextFrameAsync(); + await WinUiApp.NextFrameAsync(); + await Task.Delay(50, cancel); + var pixels = ScreenPixels(x, y); + if (pixels is not null && editor.CaretToggles == toggles && editor.IsCaretShown == shown) + { + return pixels; + } + } + await Task.Delay(10, cancel); + } + return null; + } + + private static bool ShowsWindow(SqlEditor editor, int x, int y) => + GetAncestor(WindowFromPoint(new POINT { x = x, y = y }), GA.GA_ROOT) == editor.WindowHandle; + + private static uint[]? ScreenPixels(int x, int y) + { + var screen = GetDC(HWND.NULL); + try + { + var pixels = new uint[3]; + for (var i = 0; i < pixels.Length; i++) + { + pixels[i] = (uint)GetPixel(screen, x - 1 + i, y); + // CLR_INVALID: the point is off the screen. + if (pixels[i] == uint.MaxValue) + { + return null; + } + } + return pixels; + } + finally + { + _ = ReleaseDC(HWND.NULL, screen); + } + } + + private static string Hex(uint[] pixels) => + string.Join(' ', pixels.Select(pixel => pixel.ToString("X6", CultureInfo.InvariantCulture))); + + private static int Distance(uint a, uint b) => + Math.Abs((int)(a & 0xFF) - (int)(b & 0xFF)) + + Math.Abs((int)((a >> 8) & 0xFF) - (int)((b >> 8) & 0xFF)) + + Math.Abs((int)((a >> 16) & 0xFF) - (int)((b >> 16) & 0xFF)); + private static unsafe TimeSpan CaretTimeout() { uint milliseconds; diff --git a/windows/tests/TablePro.Interop.Tests/RunDisposalTests.cs b/windows/tests/TablePro.Interop.Tests/RunDisposalTests.cs index bbbe008a38..012d5c3c4a 100644 --- a/windows/tests/TablePro.Interop.Tests/RunDisposalTests.cs +++ b/windows/tests/TablePro.Interop.Tests/RunDisposalTests.cs @@ -52,6 +52,28 @@ public async Task ADisposedRunAnswersEveryCallWithoutThrowing() } } + // The results pane lets go of a set its limit dropped, while the grid may still read the one it shows. + [Fact] + public async Task AReleasedSetIsGoneFromTheRunAndAHandleStillHeldReadsOn() + { + await using var database = await SqliteDatabase.CreateAsync(); + using var run = database.Editor.Run( + "SELECT 1 AS a; SELECT 2 AS b; SELECT 3 AS c", + cancellationToken: TestContext.Current.CancellationToken); + Assert.IsType(await run.Completion); + using var shown = run.GetResultSet(0); + + run.ReleaseSet(0); + run.ReleaseSet(1); + run.ReleaseSet(7); + + Assert.Null(run.GetResultSet(0)); + Assert.Null(run.GetResultSet(1)); + using var kept = run.GetResultSet(2); + Assert.Equal("3", kept?.GetCellText(0, 0)); + Assert.Equal("1", shown?.GetCellText(0, 0)); + } + [Fact] public async Task ARunDisposedAtOnceStillCompletes() { From dbb1e1bfba397db43d000888c0870cd3d9352e6f Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Fri, 13 Nov 2026 02:08:00 +0700 Subject: [PATCH 2/3] chore(windows): say when the results pane lets go of a dropped set --- windows/src/TablePro.App/Views/ResultsPane.xaml.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/windows/src/TablePro.App/Views/ResultsPane.xaml.cs b/windows/src/TablePro.App/Views/ResultsPane.xaml.cs index 6aba8874f8..e250aa7b19 100644 --- a/windows/src/TablePro.App/Views/ResultsPane.xaml.cs +++ b/windows/src/TablePro.App/Views/ResultsPane.xaml.cs @@ -336,7 +336,7 @@ private void ShowFirstKept() ShowPickedLabel(); } - // Called from the run's events, never from the picker's own, so its list never changes while it takes a pick. + // Never inside the picker's own SelectionChanged, so its list never changes while it takes a pick. private void LetGoOfLeaving() { if (_leaving is not { } leaving || ReferenceEquals(leaving, _picked)) From 606d02f864dd0d19c34a7e8435feb47173dd0c08 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Fri, 13 Nov 2026 02:49:17 +0700 Subject: [PATCH 3/3] fix(windows): name the results pane's drop so it does not hide UIElement.Drop --- windows/src/TablePro.App/Views/ResultsPane.xaml.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/windows/src/TablePro.App/Views/ResultsPane.xaml.cs b/windows/src/TablePro.App/Views/ResultsPane.xaml.cs index e250aa7b19..a8757523a1 100644 --- a/windows/src/TablePro.App/Views/ResultsPane.xaml.cs +++ b/windows/src/TablePro.App/Views/ResultsPane.xaml.cs @@ -189,7 +189,7 @@ void Adopt() if (dropped is not null && heldBy.Remove(dropped, out var gone)) { run.ReleaseSet(gone.Result.SetIndex); - Drop(incoming, gone); + DropSet(incoming, gone); } } @@ -305,7 +305,7 @@ private void Pick(HeldSet held) } // Once the run is shown the grid reads the set it shows, so that one stays until the run lets it go. - private void Drop(List incoming, HeldSet gone) + private void DropSet(List incoming, HeldSet gone) { if (ReferenceEquals(gone, _picked)) {