From 14178410312ad4d06109d90134aa60a2704aba39 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sat, 14 Nov 2026 20:24:27 +0700 Subject: [PATCH 01/13] feat(windows): value viewer, cut-cell tips, foreign key navigation, results grid menu and grid header peers --- core/crates/ffi/src/filter.rs | 22 + core/crates/ffi/src/lib.rs | 2 + core/crates/ffi/src/references.rs | 197 ++++++ core/crates/ffi/src/results/result_set.rs | 8 + core/crates/ffi/src/results/store.rs | 7 + core/crates/ffi/tests/browse.rs | 181 +++++- .../0022-browsing-through-the-ffi.md | 2 + .../docs/decisions/0003-data-grid-control.md | 7 +- .../decisions/0007-browsing-a-connection.md | 9 + windows/src/TablePro.App.Model/CellValue.cs | 181 ++++++ windows/src/TablePro.App.Model/TabSession.cs | 20 + .../src/TablePro.App.Model/TableFilters.cs | 29 + windows/src/TablePro.App.Model/TableTab.cs | 133 ++++ .../TablePro.App/Strings/en-US/Resources.resw | 60 ++ .../src/TablePro.App/Views/CellValueViewer.cs | 210 +++++++ windows/src/TablePro.App/Views/GridMenus.cs | 46 ++ .../src/TablePro.App/Views/IExportSource.cs | 7 + .../TablePro.App/Views/QueryTabView.xaml.cs | 42 +- .../TablePro.App/Views/ResultsPane.xaml.cs | 40 ++ .../TablePro.App/Views/TableTabView.xaml.cs | 107 +++- .../TablePro.App/Views/WorkspaceView.xaml.cs | 56 ++ .../Automation/DataGridAutomationPeer.cs | 89 ++- .../Automation/HeaderItemAutomationPeers.cs | 160 +++++ .../DataGridView.Accessibility.cs | 121 ++++ .../TablePro.DataGrid/DataGridView.Editing.cs | 2 + .../DataGridView.Interaction.cs | 49 +- .../TablePro.DataGrid/DataGridView.Tips.cs | 130 ++++ windows/src/TablePro.DataGrid/DataGridView.cs | 11 + .../src/TablePro.Interop/DatabaseSession.cs | 9 + .../Generated/tablepro_ffi.cs | 580 ++++++++++++++++++ .../TablePro.Interop/Mapping.References.cs | 38 ++ windows/src/TablePro.Interop/ResultSet.cs | 8 + windows/src/TablePro.Interop/RowReference.cs | 29 + windows/src/TablePro.Interop/TableKeys.cs | 27 + .../CellValueTests.cs | 101 +++ .../DefinitionTabTests.cs | 3 + .../TablePro.App.Model.Tests/TabFakes.cs | 34 + .../TableTabReferenceTests.cs | 162 +++++ .../GridAccessibilityTests.cs | 32 + .../GridReferenceTests.cs | 45 ++ .../TablePro.App.UITests/GridValueTests.cs | 55 ++ .../TablePro.DataGrid.Tests/CellTipTests.cs | 55 ++ .../HeaderAutomationTests.cs | 122 ++++ .../RowReferenceTests.cs | 116 ++++ 44 files changed, 3225 insertions(+), 119 deletions(-) create mode 100644 core/crates/ffi/src/references.rs create mode 100644 windows/src/TablePro.App.Model/CellValue.cs create mode 100644 windows/src/TablePro.App.Model/TableFilters.cs create mode 100644 windows/src/TablePro.App/Views/CellValueViewer.cs create mode 100644 windows/src/TablePro.App/Views/GridMenus.cs create mode 100644 windows/src/TablePro.App/Views/IExportSource.cs create mode 100644 windows/src/TablePro.DataGrid/Automation/HeaderItemAutomationPeers.cs create mode 100644 windows/src/TablePro.DataGrid/DataGridView.Accessibility.cs create mode 100644 windows/src/TablePro.DataGrid/DataGridView.Tips.cs create mode 100644 windows/src/TablePro.Interop/Mapping.References.cs create mode 100644 windows/src/TablePro.Interop/RowReference.cs create mode 100644 windows/src/TablePro.Interop/TableKeys.cs create mode 100644 windows/tests/TablePro.App.Model.Tests/CellValueTests.cs create mode 100644 windows/tests/TablePro.App.Model.Tests/TableTabReferenceTests.cs create mode 100644 windows/tests/TablePro.App.UITests/GridAccessibilityTests.cs create mode 100644 windows/tests/TablePro.App.UITests/GridReferenceTests.cs create mode 100644 windows/tests/TablePro.App.UITests/GridValueTests.cs create mode 100644 windows/tests/TablePro.DataGrid.Tests/CellTipTests.cs create mode 100644 windows/tests/TablePro.DataGrid.Tests/HeaderAutomationTests.cs create mode 100644 windows/tests/TablePro.Interop.Tests/RowReferenceTests.cs diff --git a/core/crates/ffi/src/filter.rs b/core/crates/ffi/src/filter.rs index 075c2d00db..7acf6ea2a7 100644 --- a/core/crates/ffi/src/filter.rs +++ b/core/crates/ffi/src/filter.rs @@ -116,6 +116,28 @@ fn takes_raw_sql(dialect: &dyn SqlDialect) -> bool { SqlGrammar::SQL.contains(&dialect.grammar()) } +impl From for TableFilterArg { + fn from(filter: FilterSet) -> Self { + Self { + combinator: filter.combinator.into(), + rules: filter + .rules + .into_iter() + .map(|rule| FilterRuleArg { + column: rule.column, + op: rule.op.into(), + value: rule.value.map(|value| match value { + FilterValue::Single(value) => FilterValueArg::Single { value }, + FilterValue::Pair(low, high) => FilterValueArg::Pair { low, high }, + FilterValue::List(values) => FilterValueArg::List { values }, + }), + }) + .collect(), + raw_sql: filter.extra_sql, + } + } +} + impl From for FilterSet { fn from(filter: TableFilterArg) -> Self { Self { diff --git a/core/crates/ffi/src/lib.rs b/core/crates/ffi/src/lib.rs index f1a22133b6..08724f0062 100644 --- a/core/crates/ffi/src/lib.rs +++ b/core/crates/ffi/src/lib.rs @@ -22,6 +22,7 @@ mod host_key; mod library; mod masking; mod prompter; +mod references; mod results; mod row_edits; mod run; @@ -66,6 +67,7 @@ pub use masking::{ ShareColumnMasking, ShareRefusal, ShareSummary, }; pub use prompter::{HostPrompter, PromptAnswer, PromptFieldInfo, PromptPurposeTag, PromptReasonTag, PromptRequest}; +pub use references::{ReferenceRefusal, RowReferenceChoice, RowReferences, TableKeys}; pub use results::{ResultColumnInfo, ResultSet, ValueKind}; pub use row_edits::{ CellChange, CellEdit, EditColumnInfo, EditLock, EditStart, PlannedStatement, RowEdit, RowSave, RowSaveOutcome, diff --git a/core/crates/ffi/src/references.rs b/core/crates/ffi/src/references.rs new file mode 100644 index 0000000000..4cfbf7645c --- /dev/null +++ b/core/crates/ffi/src/references.rs @@ -0,0 +1,197 @@ +use std::sync::Arc; + +use tablepro_core::Value; +use tablepro_core::browse::{ReferenceError, RowReference}; +use tablepro_core::column::ResultColumn; +use tablepro_core::ddl::{InboundForeignKey, OutboundForeignKey}; +use tablepro_core::meta::TableRef; +use tablepro_session::OperationKind; + +use crate::cancel_token::{CancelToken, token}; +use crate::catalog::TableName; +use crate::error::CoreError; +use crate::filter::TableFilterArg; +use crate::results::ResultSet; +use crate::runtime::on_runtime; +use crate::session::DatabaseSession; + +// A table's foreign keys both ways, read once; what a row leads to is worked out from them without the server. +#[derive(Debug, uniffi::Object)] +pub struct TableKeys { + table: TableRef, + outbound: Vec, + inbound: Vec, +} + +// Why a key a row holds cannot be followed with a filter; the app words it. +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Enum)] +pub enum ReferenceRefusal { + UnevenKey { key: String }, + UnknownSchema { table: String }, + NoFilterText { column: String }, + ComparedOtherwise { table: String }, +} + +// `columns` are the key's columns in the table that holds it, which tell two keys into one table apart. +// Exactly one of `filter` and `refusal` is set. +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct RowReferenceChoice { + pub key_name: String, + pub table: TableName, + pub columns: Vec, + pub filter: Option, + pub refusal: Option, +} + +// A key with a NULL in the row, or one the rows do not hold every column of, leads nowhere and is left out. +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct RowReferences { + pub referenced: Vec, + pub referencing: Vec, +} + +#[uniffi::export] +impl DatabaseSession { + // Both ways in one operation, so a reconnect between the reads cannot pair keys of two connections. + pub async fn table_keys( + &self, + table: TableName, + cancel: Option>, + ) -> Result, CoreError> { + let session = self.session().clone(); + let cancel = token(cancel); + on_runtime(self.tasks(), async move { + let table: TableRef = table.into(); + let (outbound, inbound) = session + .run_cancellable(OperationKind::Metadata, &cancel, |lease, options| { + let table = table.clone(); + async move { + let outbound = lease.fetch_outbound_foreign_keys(&table, options.clone()).await?; + let inbound = lease.fetch_inbound_foreign_keys(&table, options).await?; + Ok((outbound, inbound)) + } + }) + .await?; + Ok(Arc::new(TableKeys { + table, + outbound, + inbound, + })) + }) + .await + } +} + +#[uniffi::export] +impl TableKeys { + // The table's keys that hold `column` (any column when None) and the other tables' keys, from `row` of `rows` + // as the server holds it. `rows` is a page of this table, sorted or not. + pub fn row_references( + &self, + rows: Arc, + row: u64, + column: Option, + ) -> Result { + if row >= rows.row_count() { + return Err(CoreError::failed( + "ffi.out_of_range", + format!("no row {row} in the result"), + )); + } + let read = rows.result_columns(); + let referenced = self + .outbound + .iter() + .filter(|key| column.as_ref().is_none_or(|column| key.key.columns.contains(column))) + .filter_map(|key| { + let cells = key_cells(&rows, row, &read, &key.key.columns, &key.key.ref_columns, &key.key.name); + choice( + &key.key.name, + TableRef::new(key.key.ref_schema.clone(), key.key.ref_table.clone()), + &key.key.columns, + cells.and_then(|(columns, values)| RowReference::referenced(&self.table, key, &columns, &values)), + ) + }) + .collect(); + let referencing = self + .inbound + .iter() + .filter_map(|key| { + let cells = key_cells(&rows, row, &read, &key.referenced_columns, &key.columns, &key.name); + choice( + &key.name, + key.table.clone(), + &key.columns, + cells.and_then(|(columns, values)| RowReference::referencing(&self.table, key, &columns, &values)), + ) + }) + .collect(); + Ok(RowReferences { + referenced, + referencing, + }) + } +} + +// Only the key's cells are copied, so a row of large values stays in the store. A value the store cannot name +// exactly, such as a float, has no text a filter would match. +fn key_cells( + rows: &ResultSet, + row: u64, + read: &[ResultColumn], + names: &[String], + targets: &[String], + key: &str, +) -> Result<(Vec, Vec), ReferenceError> { + let mut columns = Vec::with_capacity(names.len()); + let mut values = Vec::with_capacity(names.len()); + let mut unnamed = None; + for (position, name) in names.iter().enumerate() { + let Some(index) = read.iter().position(|column| column.name == *name) else { + return Err(ReferenceError::MissingColumn { column: name.clone() }); + }; + match rows.stored_value(row, index) { + Some(Value::Null) => return Err(ReferenceError::NullKey), + Some(value) => { + columns.push(read[index].clone()); + values.push(value); + } + None => { + unnamed.get_or_insert(position); + } + } + } + match unnamed { + None => Ok((columns, values)), + Some(position) => Err(match targets.get(position) { + Some(column) => ReferenceError::NoFilterText { column: column.clone() }, + None => ReferenceError::UnevenKey { key: key.to_owned() }, + }), + } +} + +fn choice( + key_name: &str, + table: TableRef, + columns: &[String], + reference: Result, +) -> Option { + let (filter, refusal) = match reference { + Ok(reference) => (Some(reference.filter.into()), None), + Err(ReferenceError::NullKey | ReferenceError::MissingColumn { .. }) => return None, + Err(ReferenceError::UnevenKey { key }) => (None, Some(ReferenceRefusal::UnevenKey { key })), + Err(ReferenceError::UnknownSchema { table }) => (None, Some(ReferenceRefusal::UnknownSchema { table })), + Err(ReferenceError::NoFilterText { column }) => (None, Some(ReferenceRefusal::NoFilterText { column })), + Err(ReferenceError::ComparedOtherwise { table }) => (None, Some(ReferenceRefusal::ComparedOtherwise { table })), + }; + Some(RowReferenceChoice { + key_name: key_name.to_owned(), + table: TableName { + schema: table.schema, + name: table.name, + }, + columns: columns.to_vec(), + filter, + refusal, + }) +} diff --git a/core/crates/ffi/src/results/result_set.rs b/core/crates/ffi/src/results/result_set.rs index 203a24f0da..48608682c0 100644 --- a/core/crates/ffi/src/results/result_set.rs +++ b/core/crates/ffi/src/results/result_set.rs @@ -84,6 +84,14 @@ impl ResultSet { .ok_or_else(|| CoreError::failed("ffi.out_of_range", format!("no cell at row {row}, column {column}"))) } + // The bytes of a binary value, for an image or a hex view; `None` for null or a value that is not binary. + pub fn cell_bytes(&self, row: u64, column: u32) -> Result>, CoreError> { + usize::try_from(column) + .ok() + .and_then(|column| self.store.binary(self.stored_row(row), column)) + .ok_or_else(|| CoreError::failed("ffi.out_of_range", format!("no cell at row {row}, column {column}"))) + } + // An address the caller frees with `tablepro_cursor_free`. pub fn open_cursor(&self) -> u64 { let cursor = Box::into_raw(Box::new(TpCursor::new(Cursor::new( diff --git a/core/crates/ffi/src/results/store.rs b/core/crates/ffi/src/results/store.rs index cc89924481..a1b2e7f09d 100644 --- a/core/crates/ffi/src/results/store.rs +++ b/core/crates/ffi/src/results/store.rs @@ -167,6 +167,13 @@ impl ResultStore { let cell = state.cell(row, column)?; Some(cell.kind.map(|kind| cell_text::full(kind, cell.bytes))) } + + // `Some(None)` for null or a value that is not binary. + pub(crate) fn binary(&self, row: u64, column: usize) -> Option>> { + let state = self.read(); + let cell = state.cell(row, column)?; + Some((cell.kind == Some(ValueKind::Bytes)).then(|| cell.bytes.to_vec())) + } } impl ResultStore { diff --git a/core/crates/ffi/tests/browse.rs b/core/crates/ffi/tests/browse.rs index 1e60a1f88a..409b814b8e 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, RowEstimate, - RunEvent, RunListener, RunOutcome, RunSettings, SecretItemTag, SecretKindTag, TableFilterArg, TableName, - TablePageRead, TransactionStateTag, TruncationTag, + FilterValueArg, HostConfig, HostSecretError, HostSecrets, ObjectEntry, ObjectKindTag, ObjectScopeArg, + ReferenceRefusal, RowEstimate, RunEvent, RunListener, RunOutcome, RunSettings, SecretItemTag, SecretKindTag, + TableFilterArg, TableName, TablePageRead, TransactionStateTag, TruncationTag, }; struct NoSecrets; @@ -548,3 +548,178 @@ async fn an_editor_moves_to_a_database_only_where_the_engine_switches_one() { assert_eq!(refused.code(), "driver.unsupported"); } + +const REFERENCES: &str = "CREATE TABLE parent (code TEXT NOT NULL, region INTEGER NOT NULL, \ + PRIMARY KEY (code, region)); \ + CREATE TABLE child (id INTEGER PRIMARY KEY, parent_code TEXT, parent_region INTEGER, \ + FOREIGN KEY (parent_code, parent_region) REFERENCES parent(code, region)); \ + INSERT INTO parent VALUES ('x'' OR 1=1 --', 7), ('x'' OR 1=1 --', 8), ('', 9); \ + INSERT INTO child VALUES (1, 'x'' OR 1=1 --', 7), (2, 'x'' OR 1=1 --', 8), (3, NULL, 7), (4, '', 9)"; + +async fn page_rows( + session: &DatabaseSession, + name: &str, + filter: Option, +) -> Arc { + let page = session + .read_table_page(table(name), None, filter, 100, 0, Box::new(Quiet), None) + .await + .unwrap(); + let outcome = page.run().outcome().await.unwrap(); + assert!(matches!(outcome, RunOutcome::Completed { .. }), "{outcome:?}"); + page.run().result_set(0).unwrap() +} + +#[tokio::test] +async fn a_composite_key_leads_to_its_row_and_back_with_every_value_bound() { + let dir = tempfile::tempdir().unwrap(); + let (_core, session) = fixture(dir.path(), REFERENCES).await; + let children = page_rows(&session, "child", None).await; + let keys = session.table_keys(table("child"), None).await.unwrap(); + + let from_child = keys + .row_references(children.clone(), 0, Some("parent_region".to_owned())) + .unwrap(); + let [choice] = from_child.referenced.as_slice() else { + panic!("one composite key: {from_child:?}") + }; + assert_eq!(choice.table, table("parent")); + assert_eq!(choice.columns, ["parent_code", "parent_region"]); + assert_eq!(choice.refusal, None); + let filter = choice.filter.clone().unwrap(); + assert_eq!(filter.combinator, CombinatorTag::And); + assert_eq!(filter.raw_sql, None); + assert_eq!( + filter.rules, + [ + rule("code", FilterOpTag::Eq, Some("x' OR 1=1 --")), + rule("region", FilterOpTag::Eq, Some("7")), + ] + ); + assert!(from_child.referencing.is_empty()); + assert!( + keys.row_references(children, 0, Some("id".to_owned())) + .unwrap() + .referenced + .is_empty(), + "a column outside the key offers it not" + ); + + let parents = page_rows(&session, "parent", Some(filter)).await; + assert_eq!(parents.row_count(), 1); + let back = session + .table_keys(table("parent"), None) + .await + .unwrap() + .row_references(parents, 0, None) + .unwrap(); + assert!(back.referenced.is_empty()); + let [incoming] = back.referencing.as_slice() else { + panic!("one key points at parent: {back:?}") + }; + assert_eq!(incoming.table, table("child")); + assert_eq!(incoming.columns, ["parent_code", "parent_region"]); + let child = session + .read_table_page( + table("child"), + None, + incoming.filter.clone(), + 100, + 0, + Box::new(Quiet), + None, + ) + .await + .unwrap(); + assert_eq!(column(&child, 0).await, texts(&["1"])); + session.close().await.unwrap(); +} + +#[tokio::test] +async fn a_null_part_leads_nowhere_an_empty_text_is_a_value_and_a_sorted_set_reads_its_own_row() { + let dir = tempfile::tempdir().unwrap(); + let (_core, session) = fixture(dir.path(), REFERENCES).await; + let children = page_rows(&session, "child", None).await; + let keys = session.table_keys(table("child"), None).await.unwrap(); + + assert!( + keys.row_references(children.clone(), 2, None) + .unwrap() + .referenced + .is_empty() + ); + // Descending by id, so the sorted set's first row is the last one read. + let sorted = children.sorted(0, false).unwrap(); + let first = keys.row_references(sorted, 0, None).unwrap(); + assert_eq!( + first.referenced[0].filter.as_ref().unwrap().rules[0], + rule("code", FilterOpTag::Eq, Some("")) + ); + let failure = keys.row_references(children, 99, None).unwrap_err(); + assert_eq!(failure.code(), "ffi.out_of_range"); + session.close().await.unwrap(); +} + +#[tokio::test] +async fn keys_that_compare_otherwise_or_hold_an_inexact_value_stay_as_refusals() { + let dir = tempfile::tempdir().unwrap(); + let (_core, session) = fixture( + dir.path(), + "CREATE TABLE parent (code TEXT COLLATE NOCASE PRIMARY KEY); \ + CREATE TABLE child (code TEXT REFERENCES parent(code)); \ + CREATE TABLE scale (weight REAL PRIMARY KEY); \ + CREATE TABLE measured (id INTEGER PRIMARY KEY, weight REAL REFERENCES scale(weight)); \ + INSERT INTO parent VALUES ('ABC'); INSERT INTO child VALUES ('abc'); \ + INSERT INTO scale VALUES (0.5); INSERT INTO measured VALUES (1, 0.5)", + ) + .await; + let parents = page_rows(&session, "parent", None).await; + let collated = session + .table_keys(table("parent"), None) + .await + .unwrap() + .row_references(parents, 0, None) + .unwrap(); + assert_eq!(collated.referencing.len(), 1); + assert_eq!( + collated.referencing[0].refusal, + Some(ReferenceRefusal::ComparedOtherwise { + table: "child".to_owned() + }) + ); + assert_eq!(collated.referencing[0].filter, None); + + let measured = page_rows(&session, "measured", None).await; + let inexact = session + .table_keys(table("measured"), None) + .await + .unwrap() + .row_references(measured, 0, Some("weight".to_owned())) + .unwrap(); + assert_eq!( + inexact.referenced[0].refusal, + Some(ReferenceRefusal::NoFilterText { + column: "weight".to_owned() + }) + ); + session.close().await.unwrap(); +} + +#[tokio::test] +async fn a_binary_cell_gives_its_bytes_and_other_cells_none() { + let dir = tempfile::tempdir().unwrap(); + let (_core, session) = fixture( + dir.path(), + "CREATE TABLE files (id INTEGER PRIMARY KEY, body BLOB, note TEXT); \ + INSERT INTO files VALUES (1, X'89504E47', 'png'), (2, NULL, NULL)", + ) + .await; + let rows = page_rows(&session, "files", None).await; + + assert_eq!(rows.cell_bytes(0, 1).unwrap(), Some(vec![0x89, 0x50, 0x4e, 0x47])); + assert_eq!(rows.cell_text(0, 1).unwrap().as_deref(), Some("0x89504e47")); + assert_eq!(rows.cell_bytes(0, 2).unwrap(), None); + assert_eq!(rows.cell_bytes(1, 1).unwrap(), None); + assert_eq!(rows.cell_bytes(5, 1).unwrap_err().code(), "ffi.out_of_range"); + session.close().await.unwrap(); +} diff --git a/core/docs/decisions/0022-browsing-through-the-ffi.md b/core/docs/decisions/0022-browsing-through-the-ffi.md index a7a76a24d7..1348152dff 100644 --- a/core/docs/decisions/0022-browsing-through-the-ffi.md +++ b/core/docs/decisions/0022-browsing-through-the-ffi.md @@ -18,6 +18,8 @@ The FFI exposes what the Linux app calls, and does the work the Linux app does, - `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. - `object_definition` reads `fetch_object_definition` for a function, procedure, trigger or sequence, with whether running the text in an editor would make the object as it is. - `export_rows` writes the rows a finished `ResultSet` holds, its visible columns only; `export_table` streams every row the filter and sort select through `build_export` and `stream_read`, as the Linux app exports a table. Both use the core's encoders (CSV with its default options, JSON, Excel, Markdown, HTML, XML, and SQL INSERT from a table), write beside the target and rename once complete, so a failed or cancelled export leaves no file. +- `DatabaseSession::table_keys` reads a table's outbound and inbound foreign keys in one Metadata operation, as the Linux browse tab reads them. Its `TableKeys::row_references` builds, without the server, what a row of a page of that table leads to through `browse::RowReference`, from the row's stored values: the table's keys holding a column, and the other tables' keys pointing at the row. A key with a NULL or a column the page lacks is left out; one whose value the store cannot name exactly, or that `RowReference` refuses, comes back with its refusal for the app to word. +- `ResultSet::cell_bytes` gives a binary cell's bytes, for an app's image or hex view, where `cell_text` gives their hex. - `Core::history` opens the query history at `/state/history.db` once. `record` takes the session, so the engine's `history_recording` withholds a statement that holds a secret, as on Linux; `search` pages by the store's keyset; `delete` and `clear` change it. ## Rationale diff --git a/windows/docs/decisions/0003-data-grid-control.md b/windows/docs/decisions/0003-data-grid-control.md index bb1bd48e99..9a246c92b6 100644 --- a/windows/docs/decisions/0003-data-grid-control.md +++ b/windows/docs/decisions/0003-data-grid-control.md @@ -103,6 +103,9 @@ - `ISelectionProvider.GetSelection` reads the model, so cells off the screen are in it, up to 10,000 cells. - A point query reaches a drawn cell through the pane's peer, which maps the point to the cell. - A header is a HeaderItem with Invoke, which sorts and raises the Invoked event, Transform, which resizes in physical pixels, and its sort order as `ItemStatus`, the property the [HeaderItem control type](https://learn.microsoft.com/en-us/windows/win32/winauto/uiauto-supportheaderitemcontroltype) gives sort orders. A change raises ItemStatus's property-changed event. The host words it through `SortedAscendingStatus` and `SortedDescendingStatus`. +- A column's header is a peer of its own, one per column like a cell's, not the header element: ItemsRepeater hands an element to another column as it scrolls, so a client holding the element's peer would read another column. The element's peer leaves the control view and sends a point query to its column's peer. `GetColumnHeaders` lists every column, a cell's TableItem names its column header on screen or not, and the tree lists the headers in view. +- A row number is a HeaderItem too, named as drawn, with Invoke, which selects the row as a click on the number does, and ScrollItem. `GetRowHeaders` lists the rows in view, a cell's TableItem names its row's, and the tree lists each row in view as its header then its cells. +- With `ShowsCellTips`, a cell the core cut or its column cuts shows its text, up to 1,000 characters, in a ToolTip after the pointer rests on it: twice `SPI_GETMOUSEHOVERTIME`, one and a half within 200 ms of the last tip closing, as ToolTipService times one. ToolTipService arms a tooltip only on its owner's `PointerEntered` (`ToolTipService_Partial.cpp`), so a ToolTip owned by a pane would open for the first cell alone; each cell's is opened by the grid instead, docked above the cell through `PlacementRect`, since a tooltip opened from code has no pointer to follow. Moving to another cell, pressing, scrolling, resizing a column, an edit and new data close it. - A cell's `ItemStatus` is its pending change: `EditedStatus`, `NewRowStatus` or `DeletedStatus`, the macOS grid's VoiceOver words. A change raises ItemStatus's property-changed event. Its Name stays the value, `DefaultText` for a DEFAULT cell. - An open editor is its pane's one automation child. @@ -115,11 +118,11 @@ ## Consequences - Text, hit testing, high contrast, text scale, DPI, device loss, right to left and color fonts are ours to keep right; a TextBlock would do them. Each has a test or a gate check. -- `TablePattern.ColumnHeaders` reads empty for clients on Windows App SDK 2.6.4: `CUIATableProviderWrapper::GetColumnHeaders` releases its SAFEARRAY before filling it. microsoft/microsoft-ui-xaml#11820 fixed it after 2.6.4. The grid returns the header peers on screen, and a cell's TableItem names its column header while that header is realized. +- `TablePattern.ColumnHeaders` reads empty for clients on Windows App SDK 2.6.4: `CUIATableProviderWrapper::GetColumnHeaders` releases its SAFEARRAY before filling it. microsoft/microsoft-ui-xaml#11820 fixed it after 2.6.4. Until the SDK has it, a client reads a cell's headers from its TableItem (`ColumnHeaderItems`, `RowHeaderItems`), which reaches every column and row, and the headers in view from the tree. - The grid raises `SortRequested` and the host sorts: on the server, or with the core's sort of the rows held. - A UI in a right-to-left language would need the grid mirrored; only values read right to left today. - The gate runs WARP on hosted runners; no machine with a GPU is measured yet. -- Not yet: column reorder, row header peers, find, tooltips for cut cells. +- Not yet: column reorder and find. ## Alternatives considered diff --git a/windows/docs/decisions/0007-browsing-a-connection.md b/windows/docs/decisions/0007-browsing-a-connection.md index 42043674a5..e50e15dbdd 100644 --- a/windows/docs/decisions/0007-browsing-a-connection.md +++ b/windows/docs/decisions/0007-browsing-a-connection.md @@ -24,6 +24,13 @@ Each one works as the macOS app's does, with its words in Windows sentence case, - The tree's context menu offers Open, Show structure and Copy name for objects with rows, and Show DDL and Copy name for the others. - Definition tabs are not kept in session.json: an older build reads an unknown tab kind as a damaged file and starts empty, and the tree brings one back in a click. +### Grid menus, values and foreign keys + +- A results grid's menu, in a query tab and a table tab, holds Copy, View value..., Export results... and Share; a table tab's adds its row and cell edits and the foreign keys below. Export and Share wait for the rows to finish. +- View value... shows the focused cell whole in a dialog, read only, with Copy: an image where a system codec decodes the bytes (`ResultSet.GetCellBytes`, `BitmapDecoder`), at its own size up to the dialog's and decoded at 2,048 pixels on its longer side at most, a picture past 64 megapixels as hex instead, JSON laid out one member per line where the text is one object or array, otherwise the text, and a binary value as its 0x hex. The JSON layout keeps each string's escapes and each number's digits as stored, which a serializer would not. The text and the JSON layout show their first 1,000,000 characters and the hex its first 256 KiB, saying so; Copy takes the whole value. A pending edit shows as typed; NULL and DEFAULT show as the grid words them. +- A table tab reads its table's foreign keys both ways once its first page shows, and again on Refresh (`ReadTableKeysAsync`, in one operation, as the Linux app reads them). The menu on a cell offers Open referenced row for the keys its column is in, a submenu when there are several, and Show referencing rows for the other tables' keys pointing at the row, each named by the other table and the key's columns, with the constraint where two read alike. The core builds each filter from the row as the server holds it (`TableKeys.GetRowReferences`, `browse::RowReference`), so a key whose cells hold a pending edit, a new row and a row marked for delete offer none. A key with a NULL leads nowhere and is left out; one the core refuses, such as columns that compare under another collation, is offered and says why when chosen. +- A chosen key opens the other table in a new tab beside this one, its filter the key's columns equal to the row's values, kept with the tab as a filter the user set; a tab whose rows were read under exactly that filter, and is not reading others, comes forward instead. + ### Export - File > Export results (Ctrl+Shift+E) asks for a format, CSV, JSON, Excel, Markdown, HTML, XML, or SQL INSERT from a table, and on a table tab for Current page or Entire table, then for a file with the system save picker. The core writes the file (`ExportRowsAsync`, `ExportTableAsync`): the rows held, or every row the tab's filter and sort select, streamed. A file appears only once complete. @@ -48,3 +55,5 @@ Each one works as the macOS app's does, with its words in Windows sentence case, - A page is read whole before it shows, under the core's page deadline of 60 seconds, as the Linux app reads one; the editor path streamed it with no deadline. Show all rows on a large table shows nothing until the last row is in. - A restored filter runs on the first read, Raw SQL included, as the rules do: one expression, read on a pooled connection. Text an engine that is not SQL would read as its own query language is refused by the core. - An export the app is killed in leaves its `.part` file beside the target. +- A query result offers no foreign key: which table its rows come from is not known (roadmap C-21). +- A binary value's hex has no offset or character columns until the core has the Linux app's hex dump (roadmap C-11). diff --git a/windows/src/TablePro.App.Model/CellValue.cs b/windows/src/TablePro.App.Model/CellValue.cs new file mode 100644 index 0000000000..ccddc44b0c --- /dev/null +++ b/windows/src/TablePro.App.Model/CellValue.cs @@ -0,0 +1,181 @@ +using System.Text; +using System.Text.Json; +using TablePro.DataGrid.Model; +using TablePro.Interop; + +namespace TablePro.App.Model; + +// One cell as the value viewer shows it: the text, or the bytes of a binary value. Neither is set for NULL. +public sealed record CellValue(string Column, string? Text, byte[]? Bytes, bool IsDefault) +{ + // A TextBox lays out all it holds, so the viewer shows a long value's start; Copy takes the whole. + public const int MaximumShownCharacters = 1_000_000; + + public const int MaximumHexBytes = 256 * 1024; + + public bool IsNull => Text is null && Bytes is null && !IsDefault; + + // The grid's text with its pending edit, and a binary value's bytes as the server holds them. A deleted row + // still shows what it holds; a new row and a changed cell have no bytes, only the text typed. + public static CellValue? Read(IGridData data, ResultSet? rows, int row, int column) + { + ArgumentNullException.ThrowIfNull(data); + if (row < 0 || row >= data.RowCount || column < 0 || column >= data.ColumnCount) + { + return null; + } + + using var reader = data.OpenReader(); + var block = new CellBlock(); + reader.Read(row, 1, column, 1, 1, block); + var state = block.Get(row, column).State; + if ((state & CellState.Missing) != 0) + { + return null; + } + + var name = data.GetColumnName(column); + if ((state & CellState.Default) != 0) + { + return new CellValue(name, null, null, IsDefault: true); + } + + var pending = (state & (CellState.Modified | CellState.Inserted)) != 0; + if (!pending && rows is not null && row < rows.RowCount && rows.GetCellBytes(row, column) is { } bytes) + { + return new CellValue(name, null, bytes, IsDefault: false); + } + + return new CellValue(name, reader.ReadWhole(row, column), null, IsDefault: false); + } + + // What Copy puts on the clipboard: the text, or a binary value in the 0x form the grid shows. Built only when + // asked, since a large value's hex is twice its size. + public string? CopyText() => Bytes is { } bytes ? "0x" + Convert.ToHexStringLower(bytes) : Text; + + public (string Text, bool Cut) ShownText() + { + if (Text is not { Length: > MaximumShownCharacters } text) + { + return (Text ?? string.Empty, false); + } + + var end = char.IsHighSurrogate(text[MaximumShownCharacters - 1]) ? MaximumShownCharacters - 1 : MaximumShownCharacters; + return (text[..end], true); + } + + // The 0x form of the first MaximumHexBytes, the way the grid shows a binary value. + public (string Text, bool Cut) Hex() + { + if (Bytes is not { } bytes) + { + return (string.Empty, false); + } + + var shown = bytes.AsSpan(0, Math.Min(bytes.Length, MaximumHexBytes)); + return ("0x" + Convert.ToHexStringLower(shown), shown.Length < bytes.Length); + } + + public (string Text, bool Cut)? Json() => Text is { } text ? JsonText.Indent(text, MaximumShownCharacters) : null; + + public bool CanCopy => Text is not null || Bytes is not null; +} + +// JSON laid out one member per line, token by token from the reader's raw spans, so each string keeps the escapes +// it was stored with and each number its digits; a serializer would escape non-ASCII text and could reformat numbers. +public static class JsonText +{ + public const int MaximumCharacters = 4_000_000; + + private const int IndentWidth = 2; + + // Only an object or an array, read whole as one JSON value; anything else is null. Nesting can make the layout + // many times the text, so past maxCharacters the rest is only checked, not laid out. + public static (string Text, bool Cut)? Indent(string text, int maxCharacters = int.MaxValue) + { + ArgumentNullException.ThrowIfNull(text); + var trimmed = text.AsSpan().TrimStart(); + if (text.Length > MaximumCharacters || trimmed.IsEmpty || (trimmed[0] != '{' && trimmed[0] != '[')) + { + return null; + } + + var utf8 = Encoding.UTF8.GetBytes(text); + var reader = new Utf8JsonReader(utf8, new JsonReaderOptions { MaxDepth = 512 }); + var output = new StringBuilder(Math.Min(maxCharacters, text.Length + (text.Length / 2))); + var open = new Stack(); + var afterName = false; + var cut = false; + try + { + while (reader.Read()) + { + if (cut || output.Length > maxCharacters) + { + cut = true; + continue; + } + + switch (reader.TokenType) + { + case JsonTokenType.StartObject or JsonTokenType.StartArray: + BeginItem(output, open, ref afterName); + output.Append(reader.TokenType == JsonTokenType.StartObject ? '{' : '['); + open.Push(false); + break; + case JsonTokenType.EndObject or JsonTokenType.EndArray: + if (open.Pop()) + { + NewLine(output, open.Count); + } + + output.Append(reader.TokenType == JsonTokenType.EndObject ? '}' : ']'); + break; + case JsonTokenType.PropertyName: + BeginItem(output, open, ref afterName); + output.Append('"').Append(Encoding.UTF8.GetString(reader.ValueSpan)).Append("\": "); + afterName = true; + break; + case JsonTokenType.String: + BeginItem(output, open, ref afterName); + output.Append('"').Append(Encoding.UTF8.GetString(reader.ValueSpan)).Append('"'); + break; + default: + BeginItem(output, open, ref afterName); + output.Append(Encoding.UTF8.GetString(reader.ValueSpan)); + break; + } + } + } + catch (JsonException) + { + return null; + } + + return cut ? (output.ToString(0, Math.Min(output.Length, maxCharacters)), true) : (output.ToString(), false); + } + + private static void BeginItem(StringBuilder output, Stack open, ref bool afterName) + { + if (afterName) + { + afterName = false; + return; + } + + if (open.Count == 0) + { + return; + } + + if (open.Pop()) + { + output.Append(','); + } + + open.Push(true); + NewLine(output, open.Count); + } + + private static void NewLine(StringBuilder output, int depth) => output.Append('\n').Append(' ', depth * IndentWidth); +} diff --git a/windows/src/TablePro.App.Model/TabSession.cs b/windows/src/TablePro.App.Model/TabSession.cs index 3cad780acc..3ae877f112 100644 --- a/windows/src/TablePro.App.Model/TabSession.cs +++ b/windows/src/TablePro.App.Model/TabSession.cs @@ -43,6 +43,8 @@ Task ReadTablePageAsync( // Refresh reads the table's columns from the server again, as a Refresh of the tab asks. Task OpenTableEditorAsync(TableName table, bool refresh, CancellationToken cancellationToken); + Task ReadTableKeysAsync(TableName table, CancellationToken cancellationToken); + ValueTask ReleaseAsync(); } @@ -67,6 +69,13 @@ public interface ITableEditor : IDisposable IRowSave Plan(ResultSet? rows, IReadOnlyList edits); } +// A table's foreign keys both ways, read once; what a row of a page leads to is worked out from them. +public interface ITableKeys : IDisposable +{ + // `rows` is the page the row is in, null when no set is shown. + RowReferences ReferencesAt(ResultSet? rows, long row, string? column); +} + // One save, which runs only the statements it was planned with. public interface IRowSave : IDisposable { @@ -168,9 +177,20 @@ public async Task OpenTableEditorAsync( new CoreTableEditor( await _share.Session.OpenTableEditorAsync(table, refresh, cancellationToken).ConfigureAwait(true)); + public async Task ReadTableKeysAsync(TableName table, CancellationToken cancellationToken) => + new CoreTableKeys(await _share.Session.ReadTableKeysAsync(table, cancellationToken).ConfigureAwait(true)); + public ValueTask ReleaseAsync() => _share.ReleaseAsync(); } +internal sealed class CoreTableKeys(TableKeys keys) : ITableKeys +{ + public RowReferences ReferencesAt(ResultSet? rows, long row, string? column) => + rows is null ? RowReferences.None : keys.GetRowReferences(rows, row, column); + + public void Dispose() => keys.Dispose(); +} + internal sealed class CoreTableEditor(TableEditor editor) : ITableEditor { // The rows the edits name are gone, as when the page went before its save was planned. diff --git a/windows/src/TablePro.App.Model/TableFilters.cs b/windows/src/TablePro.App.Model/TableFilters.cs new file mode 100644 index 0000000000..838e77fdb6 --- /dev/null +++ b/windows/src/TablePro.App.Model/TableFilters.cs @@ -0,0 +1,29 @@ +using TablePro.Interop; + +namespace TablePro.App.Model; + +// A record compares a list by reference, so two filters with the same rules compare here part by part. +public static class TableFilters +{ + public static bool Same(TableFilter? first, TableFilter? second) + { + if (first is null || second is null) + { + return first is null && second is null; + } + + return first.Combinator == second.Combinator + && string.Equals(first.RawSql, second.RawSql, StringComparison.Ordinal) + && first.Rules.Count == second.Rules.Count + && first.Rules.Zip(second.Rules).All(pair => + string.Equals(pair.First.Column, pair.Second.Column, StringComparison.Ordinal) + && pair.First.Operator == pair.Second.Operator + && SameValue(pair.First.Value, pair.Second.Value)); + } + + private static bool SameValue(FilterValue? first, FilterValue? second) => (first, second) switch + { + (FilterValue.List one, FilterValue.List other) => one.Values.SequenceEqual(other.Values, StringComparer.Ordinal), + _ => first == second, + }; +} diff --git a/windows/src/TablePro.App.Model/TableTab.cs b/windows/src/TablePro.App.Model/TableTab.cs index 2587a0c034..ddd13c0859 100644 --- a/windows/src/TablePro.App.Model/TableTab.cs +++ b/windows/src/TablePro.App.Model/TableTab.cs @@ -162,6 +162,12 @@ public sealed class TableTab : IWorkspaceTab // The set the edits name rows of, which the core reads each key and stored value from. private ResultSet? _editsRows; + + // Read once a page shows and again after a refresh; a read that fails leaves the grid's menu without references. + private ITableKeys? _keys; + private bool _keysStale = true; + private bool _readingKeys; + private int _keysVersion; private EditLock? _pageLock; private bool _saveBlocked; private Task _save = Task.FromResult(true); @@ -298,6 +304,64 @@ public bool Shows(string? schema, string table) => string.Equals(Table.Name, table, StringComparison.Ordinal) && string.Equals(Table.Schema, schema, StringComparison.Ordinal); + // A tab on the table a reference leads to whose rows were read with exactly its filter. One still reading may end + // on the rows it showed before, so it does not count. + public bool ShowsReference(RowReferenceChoice reference) + { + ArgumentNullException.ThrowIfNull(reference); + return reference.Filter is { } filter && !IsRunning && Table == reference.Table + && TableFilters.Same(_shownFilter, filter); + } + + // A new table tab on the rows a reference leads to, its filter kept with the tab as one the user set. + public static SessionTab? TabFor(RowReferenceChoice reference) + { + ArgumentNullException.ThrowIfNull(reference); + return reference.Filter is { } filter + ? new SessionTab + { + Kind = TabKind.Table, + Title = reference.Table.Name, + Schema = reference.Table.Schema, + Table = reference.Table.Name, + ObjectKind = nameof(Interop.ObjectKind.Table), + Filter = SavedFilter.From(filter), + } + : null; + } + + // What a cell's row leads to as the server holds the row: nothing while the page is read or saved, or on a new + // or deleted row; and of the row's own keys, none whose cells hold a pending change, which the server has not. + public RowReferences ReferencesAt(int row, int column) + { + if (_keys is not { } keys || IsRunning || IsSaving || _work.IsClosed + || column < 0 || column >= _results.Columns.Count || row < 0 || row >= _results.ShownRowCount + || (Edits is { } shown && (shown.IsAdded(row) || shown.IsDeleted(row)))) + { + return RowReferences.None; + } + + RowReferences references; + try + { + references = keys.ReferencesAt(_results.ShownSet, row, _results.Columns[column].Name); + } + catch (TableProException) + { + return RowReferences.None; + } + + if (Edits is not { } edits) + { + return references; + } + + return references with + { + Referenced = [.. references.Referenced.Where(reference => !reference.Columns.Any(name => IsChanged(edits, row, name)))], + }; + } + public SessionTab Snapshot() => new() { Kind = TabKind.Table, @@ -362,6 +426,11 @@ public async Task RefreshAsync() { _page = _page with { Total = null, Estimate = null }; _reopenTableEditor = true; + // A key another client dropped or changed would lead to the wrong rows, so none is offered until read again. + _keysVersion++; + _keysStale = true; + _keys?.Dispose(); + _keys = null; _structure.MarkStale(); _choices.MarkStale(); await LoadAsync(_page.Offset, recount: true).ConfigureAwait(true); @@ -696,6 +765,8 @@ private async Task CloseOnceAsync() SetEdits(null, null); _tableEditor?.Dispose(); _tableEditor = null; + _keys?.Dispose(); + _keys = null; await _session.ReleaseAsync().ConfigureAwait(true); } @@ -822,6 +893,7 @@ await _results.ShowRunAsync(_run, _sort, read.VisibleColumns, keptSets: 0, cance _saveBlocked = false; BindEdits(); CountIfNeeded(); + ReadKeysIfNeeded(); } catch (TableProException exception) { @@ -1174,6 +1246,67 @@ private void SetSaving(bool saving) StateChanged?.Invoke(this, EventArgs.Empty); } + private bool IsChanged(TableEdits edits, int row, string name) + { + for (var column = 0; column < _results.Columns.Count && column < edits.Columns.Count; column++) + { + if (string.Equals(_results.Columns[column].Name, name, StringComparison.Ordinal)) + { + return edits.GetCell(row, column) is not null; + } + } + + return false; + } + + private async void ReadKeysIfNeeded() + { + if (!_keysStale || _readingKeys || _work.IsClosed) + { + return; + } + + _keysStale = false; + _readingKeys = true; + var version = _keysVersion; + try + { + await _work.RunAsync(async token => + { + ITableKeys keys; + try + { + keys = await _session.ReadTableKeysAsync(Table, token).ConfigureAwait(true); + } + catch (TableProException) + { + // An engine without foreign keys, or a read that failed; a refresh reads them again. + return; + } + + // Read before a refresh or as the tab closed, the keys may no longer be the table's. + if (_work.IsClosed || version != _keysVersion) + { + keys.Dispose(); + return; + } + + _keys?.Dispose(); + _keys = keys; + }).ConfigureAwait(true); + } + finally + { + _readingKeys = false; + } + + // A refresh while this read ran wants its own, which its page could not start while this one ran. + if (version != _keysVersion && !IsRunning) + { + ReadKeysIfNeeded(); + } + } + private async void CountIfNeeded() => await _work.RunAsync(token => CountAsync(asked: false, token)).ConfigureAwait(true); diff --git a/windows/src/TablePro.App/Strings/en-US/Resources.resw b/windows/src/TablePro.App/Strings/en-US/Resources.resw index 0c723caba4..dd5d0d85b0 100644 --- a/windows/src/TablePro.App/Strings/en-US/Resources.resw +++ b/windows/src/TablePro.App/Strings/en-US/Resources.resw @@ -1773,6 +1773,66 @@ New fingerprint: {2} Copy + + View value... + + + Export results... + + + Open referenced row + + + Show referencing rows + + + {0} ({1}) + + + {0} through {1} + + + Can't read the columns of the key {0}. + + + Can't tell which schema {0} is in. + + + Can't filter {0} on this value. + + + Can't filter {0} on this key: its columns differ in type or collation. + + + Value of {0} + + + View as + + + Text + + + JSON + + + Hex + + + Image + + + Copy + + + Close + + + Only the start of this value shows here. Copy takes all of it. + + + The value could not be put on the clipboard. + DEFAULT diff --git a/windows/src/TablePro.App/Views/CellValueViewer.cs b/windows/src/TablePro.App/Views/CellValueViewer.cs new file mode 100644 index 0000000000..a5fc6c30d9 --- /dev/null +++ b/windows/src/TablePro.App/Views/CellValueViewer.cs @@ -0,0 +1,210 @@ +using System.Runtime.InteropServices; +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Automation; +using Microsoft.UI.Xaml.Controls; +using Microsoft.UI.Xaml.Media; +using Microsoft.UI.Xaml.Media.Imaging; +using TablePro.App.Model; +using TablePro.App.Services; +using Windows.ApplicationModel.DataTransfer; +using Windows.Graphics.Imaging; +using Windows.Storage.Streams; + +namespace TablePro.App.Views; + +// One cell's whole value, read only: a picture where the system decodes the bytes, JSON laid out, the text, or a +// binary value's hex. The offset and character columns of a hex dump wait for the core's (roadmap C-11). +internal static class CellValueViewer +{ + private const double ViewerHeight = 400; + + // Wide enough for 64 bytes of hex on a line at the default size. + private const double ViewerWidth = 720; + + private const int DecodedSide = 2048; + + // A larger picture shows as its hex: the decode size bounds the pixels kept, not the work the codec does to make them. + private const long MaximumPixels = 64L * 1024 * 1024; + + private enum Mode + { + Image, + Json, + Text, + Hex, + } + + public static async Task ShowAsync(FrameworkElement owner, CellValue value) + { + ArgumentNullException.ThrowIfNull(owner); + ArgumentNullException.ThrowIfNull(value); + var picture = value.Bytes is { Length: > 0 } bytes ? await DecodeAsync(bytes).ConfigureAwait(true) : null; + var json = value.Json(); + var modes = new List(); + if (picture is not null) + { + modes.Add(Mode.Image); + } + + if (json is not null) + { + modes.Add(Mode.Json); + } + + modes.Add(value.Bytes is null ? Mode.Text : Mode.Hex); + + var bar = new SelectorBar { Visibility = modes.Count > 1 ? Visibility.Visible : Visibility.Collapsed }; + AutomationProperties.SetName(bar, Strings.Get("ValueViewerModes")); + AutomationProperties.SetAutomationId(bar, "ValueViewerModes"); + foreach (var mode in modes) + { + var item = new SelectorBarItem { Text = Strings.Get("ValueViewer" + mode), Tag = mode }; + AutomationProperties.SetAutomationId(item, "ValueViewer" + mode + "Item"); + bar.Items.Add(item); + } + + var notice = new InfoBar { IsClosable = false, Severity = InfoBarSeverity.Informational, Message = Strings.Get("ValueViewerCut") }; + AutomationProperties.SetAutomationId(notice, "ValueViewerNotice"); + var text = new TextBox + { + IsReadOnly = true, + AcceptsReturn = true, + IsSpellCheckEnabled = false, + TextWrapping = TextWrapping.Wrap, + FontFamily = new FontFamily("Cascadia Mono, Consolas, Courier New"), + Height = ViewerHeight, + // NULL and DEFAULT are no text, so they show as the grid words them, apart from a value that reads so. + PlaceholderText = value.IsDefault ? Strings.Get("GridDefaultText") : value.IsNull ? Strings.Get("GridMenuNull") : string.Empty, + }; + ScrollViewer.SetVerticalScrollBarVisibility(text, ScrollBarVisibility.Auto); + AutomationProperties.SetName(text, value.Column); + AutomationProperties.SetAutomationId(text, "ValueViewerText"); + // A picture smaller than the viewer shows at its own size, a larger one fits. + var image = new Image + { + Source = picture, + Stretch = Stretch.Uniform, + HorizontalAlignment = HorizontalAlignment.Left, + MaxWidth = picture?.PixelWidth ?? 0, + MaxHeight = Math.Min(ViewerHeight, picture?.PixelHeight ?? 0), + }; + AutomationProperties.SetName(image, value.Column); + AutomationProperties.SetAutomationId(image, "ValueViewerImage"); + var copy = new Button { Content = Strings.Get("ValueViewerCopy"), IsEnabled = value.CanCopy }; + AutomationProperties.SetAutomationId(copy, "ValueViewerCopy"); + copy.Click += (_, _) => Copy(value, notice); + + void Show(Mode mode) + { + var (shown, cut) = mode switch + { + Mode.Json => json!.Value, + Mode.Hex => value.Hex(), + Mode.Text => value.ShownText(), + _ => (string.Empty, false), + }; + image.Visibility = mode == Mode.Image ? Visibility.Visible : Visibility.Collapsed; + text.Visibility = mode == Mode.Image ? Visibility.Collapsed : Visibility.Visible; + text.Text = shown; + notice.Severity = InfoBarSeverity.Informational; + notice.Message = Strings.Get("ValueViewerCut"); + notice.IsOpen = cut; + } + + bar.SelectionChanged += (sender, _) => + { + if (sender.SelectedItem?.Tag is Mode mode) + { + Show(mode); + } + }; + bar.SelectedItem = bar.Items[0]; + Show(modes[0]); + + var top = new Grid { ColumnSpacing = 12 }; + top.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }); + top.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto }); + top.Children.Add(bar); + Grid.SetColumn(copy, 1); + copy.VerticalAlignment = VerticalAlignment.Center; + top.Children.Add(copy); + var content = new StackPanel { Spacing = 8, Width = ViewerWidth }; + content.Children.Add(top); + content.Children.Add(notice); + content.Children.Add(image); + content.Children.Add(text); + + var dialog = new ContentDialog + { + RequestedTheme = owner.ActualTheme, + Title = Strings.Format("ValueViewerTitle", value.Column), + Content = content, + CloseButtonText = Strings.Get("ValueViewerClose"), + DefaultButton = ContentDialogButton.Close, + }; + // ContentDialog caps its width at 548 by default, too narrow for a value. + dialog.Resources["ContentDialogMaxWidth"] = ViewerWidth + 48; + AutomationProperties.SetAutomationId(dialog, "ValueViewer"); + await WindowDialogs.ShowAsync(dialog, owner).ConfigureAwait(true); + } + + private static void Copy(CellValue value, InfoBar notice) + { + var package = new DataPackage(); + package.SetText(value.CopyText() ?? string.Empty); + try + { + Clipboard.SetContent(package); + Clipboard.Flush(); + } + catch (COMException) + { + notice.Severity = InfoBarSeverity.Warning; + notice.Message = Strings.Get("ValueViewerCopyFailed"); + notice.IsOpen = true; + } + } + + // Null where no codec on the system reads the bytes as an image, or the image is too large to decode here. + private static async Task DecodeAsync(byte[] bytes) + { + using var stream = new InMemoryRandomAccessStream(); + using (var writer = new DataWriter(stream)) + { + writer.WriteBytes(bytes); + await writer.StoreAsync(); + writer.DetachStream(); + } + + try + { + stream.Seek(0); + var decoder = await BitmapDecoder.CreateAsync(stream); + var (width, height) = (decoder.PixelWidth, decoder.PixelHeight); + if (width == 0 || height == 0 || (long)width * height > MaximumPixels) + { + return null; + } + + // A picture larger than the viewer decodes at a size it can show, its longer side bounded, not at every + // pixel it holds; the other side follows the aspect ratio. + var bitmap = new BitmapImage(); + if (width >= height && width > DecodedSide) + { + bitmap.DecodePixelWidth = DecodedSide; + } + else if (height > width && height > DecodedSide) + { + bitmap.DecodePixelHeight = DecodedSide; + } + + stream.Seek(0); + await bitmap.SetSourceAsync(stream); + return bitmap; + } + catch (Exception error) when (error is COMException or ArgumentException or OutOfMemoryException) + { + return null; + } + } +} diff --git a/windows/src/TablePro.App/Views/GridMenus.cs b/windows/src/TablePro.App/Views/GridMenus.cs new file mode 100644 index 0000000000..e9ff3e09b6 --- /dev/null +++ b/windows/src/TablePro.App/Views/GridMenus.cs @@ -0,0 +1,46 @@ +using Microsoft.UI.Xaml.Controls; +using Microsoft.UI.Xaml.Controls.Primitives; +using Microsoft.UI.Xaml.Input; +using TablePro.App.Services; +using TablePro.DataGrid; + +namespace TablePro.App.Views; + +// What a results grid's menu holds in every tab, and where it opens. +internal static class GridMenus +{ + public static MenuFlyoutItem Item(string text, bool enabled, Action invoke, Symbol? icon = null) + { + var item = new MenuFlyoutItem { Text = Strings.Get(text), IsEnabled = enabled }; + if (icon is { } symbol) + { + item.Icon = new SymbolIcon(symbol); + } + + item.Click += (_, _) => invoke(); + return item; + } + + public static MenuFlyoutItem Copy(DataGridView grid) => + Item("GridMenuCopy", grid.RowCount > 0, async () => await grid.CopySelectionAsync().ConfigureAwait(true), Symbol.Copy); + + public static MenuFlyoutItem ViewValue(ResultsPane results) => + Item("GridMenuViewValue", results.CanViewValue, async () => await results.ViewValueAsync().ConfigureAwait(true)); + + // From the keyboard the menu opens at the cell it acts on, not over the editor; a pointer's opens where it was. + public static void Show(MenuFlyout menu, DataGridView grid, ContextRequestedEventArgs args) + { + if (args.TryGetPosition(grid, out var point)) + { + menu.ShowAt(grid, new FlyoutShowOptions { Position = point }); + } + else if (grid.FocusedCellMenuPoint() is { } cell) + { + menu.ShowAt(grid, new FlyoutShowOptions { Position = cell }); + } + else + { + menu.ShowAt(grid); + } + } +} diff --git a/windows/src/TablePro.App/Views/IExportSource.cs b/windows/src/TablePro.App/Views/IExportSource.cs new file mode 100644 index 0000000000..dfb64f30f7 --- /dev/null +++ b/windows/src/TablePro.App/Views/IExportSource.cs @@ -0,0 +1,7 @@ +namespace TablePro.App.Views; + +// A tab whose grid menu offers Export results; the workspace that holds it asks for the format and the file. +internal interface IExportSource +{ + event EventHandler? ExportRequested; +} diff --git a/windows/src/TablePro.App/Views/QueryTabView.xaml.cs b/windows/src/TablePro.App/Views/QueryTabView.xaml.cs index 0a07f3cc24..64b7cbd81b 100644 --- a/windows/src/TablePro.App/Views/QueryTabView.xaml.cs +++ b/windows/src/TablePro.App/Views/QueryTabView.xaml.cs @@ -1,7 +1,6 @@ using Microsoft.UI.Xaml; using Microsoft.UI.Xaml.Automation; using Microsoft.UI.Xaml.Controls; -using Microsoft.UI.Xaml.Controls.Primitives; using Microsoft.UI.Xaml.Input; using Microsoft.UI.Xaml.Media; using TablePro.App.Model; @@ -13,7 +12,7 @@ namespace TablePro.App.Views; // The editor over the run's results; the run, the close and the transaction are QueryTab's. -public sealed partial class QueryTabView : UserControl, ITabContent, IQueryTabView, IShareSource +public sealed partial class QueryTabView : UserControl, ITabContent, IQueryTabView, IShareSource, IExportSource { private readonly QueryTab _model; private EditTarget _target; @@ -60,6 +59,8 @@ internal QueryTabView( // Share result... on the grid's menu and Share query... on the editor's; the workspace opens the sheet. public event EventHandler? ShareRequested; + public event EventHandler? ExportRequested; + // The history kept a run of this tab, so a history pane reads it again. public event EventHandler? HistoryRecorded; @@ -214,37 +215,16 @@ private void OnGridContextRequested(UIElement sender, ContextRequestedEventArgs { args.Handled = true; var grid = Results.GridView; + // Rows still arriving would be exported or shared as if they were all of them. + var finished = !IsRunning && Results.ShownSet is { IsFinished: true }; var menu = new MenuFlyout(); - var copy = new MenuFlyoutItem - { - Text = Strings.Get("GridMenuCopy"), - Icon = new SymbolIcon(Symbol.Copy), - IsEnabled = grid.RowCount > 0, - }; - copy.Click += async (_, _) => await grid.CopySelectionAsync().ConfigureAwait(true); - menu.Items.Add(copy); + menu.Items.Add(GridMenus.Copy(grid)); + menu.Items.Add(GridMenus.ViewValue(Results)); menu.Items.Add(new MenuFlyoutSeparator()); - var share = new MenuFlyoutItem - { - Text = Strings.Get("ShareResultCommand"), - Icon = new SymbolIcon(Symbol.Share), - IsEnabled = !IsRunning && Results.ShownSet is { IsFinished: true }, - }; - share.Click += (_, _) => ShareRequested?.Invoke(this, ShareKind.Result); - menu.Items.Add(share); - if (args.TryGetPosition(grid, out var point)) - { - menu.ShowAt(grid, new FlyoutShowOptions { Position = point }); - } - else if (grid.FocusedCellMenuPoint() is { } cell) - { - // From the keyboard, the menu opens at the cell it acts on, not over the editor. - menu.ShowAt(grid, new FlyoutShowOptions { Position = cell }); - } - else - { - menu.ShowAt(grid); - } + menu.Items.Add(GridMenus.Item("GridMenuExport", finished, () => ExportRequested?.Invoke(this, EventArgs.Empty))); + menu.Items.Add(GridMenus.Item( + "ShareResultCommand", finished, () => ShareRequested?.Invoke(this, ShareKind.Result), Symbol.Share)); + GridMenus.Show(menu, grid, args); } private void OnEditorMenuOpening(object? sender, IList items) diff --git a/windows/src/TablePro.App/Views/ResultsPane.xaml.cs b/windows/src/TablePro.App/Views/ResultsPane.xaml.cs index 0b3ef3ebbf..dd1f4532ae 100644 --- a/windows/src/TablePro.App/Views/ResultsPane.xaml.cs +++ b/windows/src/TablePro.App/Views/ResultsPane.xaml.cs @@ -31,6 +31,7 @@ public ResultsPane() InitializeComponent(); Placeholder.Text = Strings.Get("ResultsEmpty"); ResultGrid.SizeColumnsToContent = true; + ResultGrid.ShowsCellTips = true; ResultGrid.SortedAscendingStatus = Strings.Get("GridSortedAscending"); ResultGrid.SortedDescendingStatus = Strings.Get("GridSortedDescending"); ResultGrid.SortRequested += (_, sort) => SortRequested?.Invoke(this, sort); @@ -80,6 +81,44 @@ public GridSort Sort public long ShownRowCount => ShownSet?.RowCount ?? 0; + internal bool CanViewValue => + ResultGrid.Data is { RowCount: > 0, ColumnCount: > 0 } data + && ResultGrid.FocusedRow < data.RowCount && ResultGrid.FocusedColumn < data.ColumnCount; + + // The focused cell's whole value, with its pending edit where a table tab holds one. + internal async Task ViewValueAsync() + { + if (!CanViewValue || ResultGrid.Data is not { } data) + { + return; + } + + CellValue? value; + try + { + value = CellValue.Read(data, ShownSet, ResultGrid.FocusedRow, ResultGrid.FocusedColumn); + } + catch (TableProException exception) + { + ShowError(exception.Error); + return; + } + + if (value is not null) + { + await CellValueViewer.ShowAsync(this, value).ConfigureAwait(true); + } + } + + // About the rows, not a failure of the run, so the status keeps what the run said. + internal void ShowNotice(string message) + { + ErrorBar.Severity = InfoBarSeverity.Informational; + ErrorBar.Message = message; + ErrorBar.IsOpen = false; + ErrorBar.IsOpen = true; + } + public async Task SortHeldRowsAsync(GridSort sort) { var picked = _picked; @@ -109,6 +148,7 @@ public async Task SortHeldRowsAsync(GridSort sort) public void ShowError(string message) { + ErrorBar.Severity = InfoBarSeverity.Error; ErrorBar.Message = message; ErrorBar.IsOpen = false; ErrorBar.IsOpen = true; diff --git a/windows/src/TablePro.App/Views/TableTabView.xaml.cs b/windows/src/TablePro.App/Views/TableTabView.xaml.cs index f5e48b2018..80411ea65a 100644 --- a/windows/src/TablePro.App/Views/TableTabView.xaml.cs +++ b/windows/src/TablePro.App/Views/TableTabView.xaml.cs @@ -1,4 +1,5 @@ using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Automation; using Microsoft.UI.Xaml.Controls; using Microsoft.UI.Xaml.Controls.Primitives; using Microsoft.UI.Xaml.Input; @@ -12,7 +13,7 @@ namespace TablePro.App.Views; // Data and Structure over one table; the page, its count and filter, every reload and every save are TableTab's. -public sealed partial class TableTabView : UserControl, ITabContent, ITableTabView, IShareSource +public sealed partial class TableTabView : UserControl, ITabContent, ITableTabView, IShareSource, IExportSource { private readonly TableTab _model; private bool _messagesIsTarget; @@ -74,6 +75,11 @@ internal TableTabView( // Share... on the grid's menu shares the page shown; the workspace opens the sheet. public event EventHandler? ShareRequested; + public event EventHandler? ExportRequested; + + // A foreign key's rows to open, in a tab of the workspace that holds this one. + public event EventHandler? ReferenceRequested; + public string Title => _model.Title; public TabKind Kind => _model.Kind; @@ -584,31 +590,96 @@ private void OnGridContextRequested(UIElement sender, ContextRequestedEventArgs } menu.Items.Add(new MenuFlyoutSeparator()); - var copy = new MenuFlyoutItem { Text = Strings.Get("GridMenuCopy"), IsEnabled = grid.RowCount > 0 }; - copy.Click += async (_, _) => await grid.CopySelectionAsync().ConfigureAwait(true); - menu.Items.Add(copy); + menu.Items.Add(GridMenus.Copy(grid)); + menu.Items.Add(GridMenus.ViewValue(Results)); + AddReferences(menu, _model.ReferencesAt(row, column)); menu.Items.Add(new MenuFlyoutSeparator()); - var share = new MenuFlyoutItem + var finished = !IsRunning && Results.ShownSet is { IsFinished: true }; + menu.Items.Add(GridMenus.Item("GridMenuExport", finished, () => ExportRequested?.Invoke(this, EventArgs.Empty))); + menu.Items.Add(GridMenus.Item( + "ShareCommand", + finished && !_model.HasUnsavedChanges, + () => ShareRequested?.Invoke(this, ShareKind.Result), + Symbol.Share)); + GridMenus.Show(menu, grid, args); + } + + // One key the cell's column is in opens from the menu itself; several, and every key pointing at the row, are + // listed by the other table and the key's columns, which tell two keys into one table apart. + private void AddReferences(MenuFlyout menu, RowReferences references) + { + if (references.IsEmpty) { - Text = Strings.Get("ShareCommand"), - Icon = new SymbolIcon(Symbol.Share), - IsEnabled = !IsRunning && !_model.HasUnsavedChanges && Results.ShownSet is { IsFinished: true }, - }; - share.Click += (_, _) => ShareRequested?.Invoke(this, ShareKind.Result); - menu.Items.Add(share); - if (args.TryGetPosition(grid, out var point)) + return; + } + + menu.Items.Add(new MenuFlyoutSeparator()); + var open = Labels(references.Referenced); + if (open.Count == 1) { - menu.ShowAt(grid, new FlyoutShowOptions { Position = point }); + menu.Items.Add(ReferenceItem(Strings.Get("GridMenuOpenReferenced"), open[0].Reference, "OpenReferencedRow")); } - else if (grid.FocusedCellMenuPoint() is { } cell) + else if (open.Count > 1) { - // From the keyboard, the menu opens at the cell it acts on, not over the editor. - menu.ShowAt(grid, new FlyoutShowOptions { Position = cell }); + var choose = new MenuFlyoutSubItem { Text = Strings.Get("GridMenuOpenReferenced") }; + foreach (var (label, reference) in open) + { + choose.Items.Add(ReferenceItem(label, reference, null)); + } + + menu.Items.Add(choose); } - else + + var pointing = Labels(references.Referencing); + if (pointing.Count > 0) + { + var show = new MenuFlyoutSubItem { Text = Strings.Get("GridMenuShowReferencing") }; + foreach (var (label, reference) in pointing) + { + show.Items.Add(ReferenceItem(label, reference, null)); + } + + menu.Items.Add(show); + } + } + + private MenuFlyoutItem ReferenceItem(string label, RowReferenceChoice reference, string? automationId) + { + var item = new MenuFlyoutItem { Text = label }; + if (automationId is not null) + { + AutomationProperties.SetAutomationId(item, automationId); + } + + item.Click += (_, _) => FollowReference(reference); + return item; + } + + // A key that cannot be followed is still offered, so choosing it says why. + private void FollowReference(RowReferenceChoice reference) + { + if (reference.Refusal is { } refusal) { - menu.ShowAt(grid); + Results.ShowNotice(Strings.Format("Reference" + refusal, reference.RefusalSubject ?? string.Empty)); + return; } + + ReferenceRequested?.Invoke(this, reference); + } + + private List<(string Label, RowReferenceChoice Reference)> Labels(IReadOnlyList references) + { + var shorts = references.Select(reference => + { + var table = reference.Table.Schema is { } schema && !string.Equals(schema, _model.Table.Schema, StringComparison.Ordinal) + ? $"{schema}.{reference.Table.Name}" + : reference.Table.Name; + return Strings.Format("ReferenceKey", table, string.Join(", ", reference.Columns)); + }).ToList(); + return [.. references.Select((reference, index) => + (shorts.Count(label => label == shorts[index]) > 1 + ? Strings.Format("ReferenceKeyThrough", shorts[index], reference.KeyName) + : shorts[index], reference))]; } private MenuFlyoutItem ValueItem(string text, int row, int column, CellValueKind kind) => diff --git a/windows/src/TablePro.App/Views/WorkspaceView.xaml.cs b/windows/src/TablePro.App/Views/WorkspaceView.xaml.cs index 00e6ac43e8..8245fecdce 100644 --- a/windows/src/TablePro.App/Views/WorkspaceView.xaml.cs +++ b/windows/src/TablePro.App/Views/WorkspaceView.xaml.cs @@ -622,6 +622,42 @@ private async Task ShareAsync(ITabContent? tab, ShareKind kind) await ShareSheet.ShowAsync(this, _workbench, subject).ConfigureAwait(true); } + // The menu opened on the tab shown, which is the one ExportAsync reads. + private async void OnExportRequested(object? sender, EventArgs e) + { + if (ReferenceEquals(sender, ActiveTab)) + { + await ExportAsync().ConfigureAwait(true); + } + } + + // A tab already showing the reference's rows comes forward; otherwise a new one opens beside the tab it came from. + private void OnReferenceRequested(object? sender, RowReferenceChoice reference) + { + if (_share is null || TableTab.TabFor(reference) is not { } spec) + { + return; + } + + int? index = null; + var items = Tabs.TabItems.OfType().ToList(); + foreach (var item in items) + { + if (item.Content is TableTabView view && view.Model.ShowsReference(reference)) + { + Tabs.SelectedItem = item; + return; + } + + if (ReferenceEquals(item.Content, sender)) + { + index = Tabs.TabItems.IndexOf(item) + 1; + } + } + + AddTable(reference.Table.Schema, reference.Table.Name, ObjectKind.Table, index, spec); + } + private async void OnShareRequested(object? sender, ShareKind kind) => await ShareAsync(sender as ITabContent, kind).ConfigureAwait(true); @@ -747,6 +783,16 @@ internal void Take(TabViewItem item, int? index = null) source.ShareRequested += OnShareRequested; } + if (item.Content is IExportSource exports) + { + exports.ExportRequested += OnExportRequested; + } + + if (item.Content is TableTabView referencing) + { + referencing.ReferenceRequested += OnReferenceRequested; + } + if (item.Content is QueryTabView query) { query.HistoryRecorded += OnHistoryRecorded; @@ -791,6 +837,16 @@ internal void Release(TabViewItem item) source.ShareRequested -= OnShareRequested; } + if (item.Content is IExportSource exports) + { + exports.ExportRequested -= OnExportRequested; + } + + if (item.Content is TableTabView referencing) + { + referencing.ReferenceRequested -= OnReferenceRequested; + } + if (item.Content is QueryTabView query) { query.HistoryRecorded -= OnHistoryRecorded; diff --git a/windows/src/TablePro.DataGrid/Automation/DataGridAutomationPeer.cs b/windows/src/TablePro.DataGrid/Automation/DataGridAutomationPeer.cs index bfade0cd28..e633491861 100644 --- a/windows/src/TablePro.DataGrid/Automation/DataGridAutomationPeer.cs +++ b/windows/src/TablePro.DataGrid/Automation/DataGridAutomationPeer.cs @@ -13,6 +13,8 @@ internal sealed partial class DataGridAutomationPeer(DataGridView owner) : Frame public const int MaxSelectionPeers = 10_000; private readonly Dictionary _cells = []; + private readonly Dictionary _rowHeaders = []; + private readonly Dictionary _columnHeaders = []; public int RowCount => owner.RowCount; @@ -42,8 +44,38 @@ public CellAutomationPeer Cell(int row, int column) return peer; } + // One per row in use, as for cells, so the tree and a cell's TableItem hand a client the same provider. + public RowHeaderAutomationPeer RowHeader(int row) + { + if (!_rowHeaders.TryGetValue(row, out var peer)) + { + if (_rowHeaders.Count >= 8192) + { + Prune(); + } + peer = new RowHeaderAutomationPeer(owner, row); + peer.SetParent(this); + _rowHeaders[row] = peer; + } + return peer; + } + + // One per column, not the header element: ItemsRepeater hands an element to another column as it scrolls. + public ColumnHeaderAutomationPeer ColumnHeader(int column) + { + if (!_columnHeaders.TryGetValue(column, out var peer)) + { + peer = new ColumnHeaderAutomationPeer(owner, column); + peer.SetParent(this); + _columnHeaders[column] = peer; + } + return peer; + } + public IRawElementProviderSimple Provider(AutomationPeer peer) => ProviderFromPeer(peer); + public AutomationPeer? Peer(IRawElementProviderSimple provider) => PeerFromProvider(provider); + // After the edits or the data changed; each held cell whose ItemStatus moved raises the change. public void RefreshStatuses(bool raise) { @@ -57,21 +89,21 @@ public void RefreshStatuses(bool raise) public IRawElementProviderSimple? GetItem(int row, int column) => row < 0 || row >= RowCount || column < 0 || column >= ColumnCount ? null : ProviderFromPeer(Cell(row, column)); - // Clients read none back on Windows App SDK 2.6.4, a WinUI bug fixed after it (microsoft-ui-xaml#11820). + // Clients read none back on Windows App SDK 2.6.4, a WinUI bug fixed after it (microsoft-ui-xaml#11820); each + // cell's TableItem gives its column header, on screen or not. public IRawElementProviderSimple[] GetColumnHeaders() { - var headers = new List(); - foreach (var header in owner.HeaderCells()) + var headers = new IRawElementProviderSimple[ColumnCount]; + for (var column = 0; column < headers.Length; column++) { - if (header.Column >= 0 && CreatePeerForElement(header) is { } peer) - { - headers.Add(ProviderFromPeer(peer)); - } + headers[column] = ProviderFromPeer(ColumnHeader(column)); } - return [.. headers]; + return headers; } - public IRawElementProviderSimple[] GetRowHeaders() => []; + // The rows in view: a million row headers would not fit one call. A cell's TableItem reaches any row's. + public IRawElementProviderSimple[] GetRowHeaders() => + [.. owner.VisibleRowNumbers().Select(row => ProviderFromPeer(RowHeader(row)))]; public IRawElementProviderSimple[] GetSelection() { @@ -109,13 +141,23 @@ public IRawElementProviderSimple[] GetSelection() _ => base.GetPatternCore(patternInterface), }; - // The headers come from the elements; the drawn cells on screen join as peers of their own, row by row. + // The column headers in view, then each row in view as its row header and its cells. protected override IList GetChildrenCore() { var children = new List(base.GetChildrenCore() ?? []); - foreach (var (row, column) in owner.VisibleCells()) + foreach (var column in owner.VisibleColumns()) { - children.Add(Cell(row, column)); + children.Add(ColumnHeader(column)); + } + var row = -1; + foreach (var (cellRow, column) in owner.VisibleCells()) + { + if (cellRow != row) + { + row = cellRow; + children.Add(RowHeader(row)); + } + children.Add(Cell(cellRow, column)); } return children; } @@ -134,6 +176,10 @@ private void Prune() { _cells.Remove(key); } + foreach (var row in _rowHeaders.Keys.Where(row => !owner.IsRowNumberVisible(row)).ToList()) + { + _rowHeaders.Remove(row); + } } } @@ -157,13 +203,10 @@ internal sealed partial class CellAutomationPeer(DataGridView grid, DataGridAuto public IRawElementProviderSimple SelectionContainer => ContainingGrid; public IRawElementProviderSimple[] GetColumnHeaderItems() => - grid.Contains(row, column) - && grid.HeaderCell(column) is { } header - && FrameworkElementAutomationPeer.CreatePeerForElement(header) is { } peer - ? [gridPeer.Provider(peer)] - : []; + grid.Contains(row, column) ? [gridPeer.Provider(gridPeer.ColumnHeader(column))] : []; - public IRawElementProviderSimple[] GetRowHeaderItems() => []; + public IRawElementProviderSimple[] GetRowHeaderItems() => + grid.Contains(row, column) ? [gridPeer.Provider(gridPeer.RowHeader(row))] : []; // A cell the data no longer holds takes no selection, which the grid would clamp onto another cell. public void Select() @@ -299,6 +342,14 @@ public void Resize(double width, double height) protected override string GetItemStatusCore() => grid.SortStatus(owner.SortDirection); + // A column's header is its column peer in the control view; the element serves whichever column is in view. + protected override bool IsControlElementCore() => owner.Column < 0; + + protected override bool IsContentElementCore() => false; + + protected override object? GetElementFromPointCore(Windows.Foundation.Point pointInWindowCoordinates) => + owner.Column >= 0 && CreatePeerForElement(grid) is DataGridAutomationPeer peer ? peer.ColumnHeader(owner.Column) : this; + protected override object? GetPatternCore(PatternInterface patternInterface) => patternInterface switch { PatternInterface.Invoke or PatternInterface.Transform => this, @@ -325,5 +376,5 @@ internal sealed partial class PaneAutomationPeer(PaneContent owner, DataGridView // XAML passes physical pixels from the window's client area here (ElementProviderFromPointImpl, UIAWindow.cpp). protected override object? GetElementFromPointCore(Windows.Foundation.Point pointInWindowCoordinates) => - grid.CellPeerAt(pointInWindowCoordinates) ?? base.GetElementFromPointCore(pointInWindowCoordinates); + grid.ItemPeerAt(pointInWindowCoordinates) ?? base.GetElementFromPointCore(pointInWindowCoordinates); } diff --git a/windows/src/TablePro.DataGrid/Automation/HeaderItemAutomationPeers.cs b/windows/src/TablePro.DataGrid/Automation/HeaderItemAutomationPeers.cs new file mode 100644 index 0000000000..86715f491d --- /dev/null +++ b/windows/src/TablePro.DataGrid/Automation/HeaderItemAutomationPeers.cs @@ -0,0 +1,160 @@ +using Microsoft.UI.Xaml.Automation; +using Microsoft.UI.Xaml.Automation.Peers; +using Microsoft.UI.Xaml.Automation.Provider; +using TablePro.DataGrid.Model; +using Windows.Foundation; + +namespace TablePro.DataGrid.Automation; + +// A column's HeaderItem: Invoke sorts, Transform resizes, ItemStatus names the sort order, as the header element's +// peer does. A column the data no longer has reads as empty and off screen, as a cell does. +internal sealed partial class ColumnHeaderAutomationPeer(DataGridView grid, int column) + : AutomationPeer, IInvokeProvider, ITransformProvider, IScrollItemProvider +{ + public int Column => column; + + public bool CanMove => false; + + public bool CanResize => Exists; + + public bool CanRotate => false; + + private bool Exists => column >= 0 && column < grid.ColumnCount; + + public void Invoke() + { + if (Exists) + { + grid.SortBy(column); + RaiseAutomationEvent(AutomationEvents.InvokePatternOnInvoked); + } + } + + public void Move(double x, double y) => throw new InvalidOperationException("A column header does not move."); + + // UIA sizes in physical pixels, as the bounding rectangle reports them. + public void Resize(double width, double height) + { + if (Exists) + { + grid.ResizeColumn(column, width / (grid.XamlRoot?.RasterizationScale ?? 1)); + } + } + + public void Rotate(double degrees) => throw new InvalidOperationException("A column header does not rotate."); + + public void ScrollIntoView() + { + if (Exists && grid.RowCount > 0) + { + grid.ScrollIntoView(grid.FocusedRow, column); + } + } + + protected override string GetClassNameCore() => "DataGridColumnHeader"; + + protected override AutomationControlType GetAutomationControlTypeCore() => AutomationControlType.HeaderItem; + + protected override string GetNameCore() => grid.ColumnName(column); + + protected override string GetItemStatusCore() => + grid.SortStatus(Exists && grid.Sort.Column == column ? grid.Sort.Direction : SortDirection.None); + + protected override string GetHelpTextCore() => (Exists ? grid.MaskNote(column) : null) ?? string.Empty; + + protected override bool IsContentElementCore() => false; + + protected override bool IsControlElementCore() => true; + + protected override bool IsEnabledCore() => Exists; + + protected override bool IsKeyboardFocusableCore() => false; + + protected override bool HasKeyboardFocusCore() => false; + + protected override int GetPositionInSetCore() => Exists ? column + 1 : 0; + + protected override int GetSizeOfSetCore() => grid.ColumnCount; + + protected override bool IsOffscreenCore() => GetBoundingRectangleCore().Width <= 0; + + protected override Rect GetBoundingRectangleCore() => grid.ColumnHeaderBoundsPhysical(column); + + protected override Point GetClickablePointCore() + { + var bounds = GetBoundingRectangleCore(); + return new Point(bounds.X + (bounds.Width / 2), bounds.Y + (bounds.Height / 2)); + } + + protected override IList? GetChildrenCore() => null; + + protected override object? GetPatternCore(PatternInterface patternInterface) => patternInterface switch + { + PatternInterface.Invoke or PatternInterface.Transform or PatternInterface.ScrollItem => this, + _ => base.GetPatternCore(patternInterface), + }; +} + +// A row number's HeaderItem. Invoke selects the row, as a click on its number does. +internal sealed partial class RowHeaderAutomationPeer(DataGridView grid, int row) + : AutomationPeer, IInvokeProvider, IScrollItemProvider +{ + public int Row => row; + + private bool Exists => row >= 0 && row < grid.RowCount && grid.ColumnCount > 0; + + public void Invoke() + { + if (Exists) + { + grid.SelectRows(row, extend: false); + RaiseAutomationEvent(AutomationEvents.InvokePatternOnInvoked); + } + } + + public void ScrollIntoView() + { + if (Exists) + { + grid.ScrollIntoView(row, grid.FocusedColumn); + } + } + + protected override string GetClassNameCore() => "DataGridRowHeader"; + + protected override AutomationControlType GetAutomationControlTypeCore() => AutomationControlType.HeaderItem; + + protected override string GetNameCore() => grid.RowNumberName(row); + + protected override bool IsContentElementCore() => false; + + protected override bool IsControlElementCore() => true; + + protected override bool IsEnabledCore() => Exists; + + protected override bool IsKeyboardFocusableCore() => false; + + protected override bool HasKeyboardFocusCore() => false; + + protected override int GetPositionInSetCore() => Exists ? row + 1 : 0; + + protected override int GetSizeOfSetCore() => grid.RowCount; + + protected override bool IsOffscreenCore() => !grid.IsRowNumberVisible(row); + + protected override Rect GetBoundingRectangleCore() => grid.RowNumberBoundsPhysical(row); + + protected override Point GetClickablePointCore() + { + var bounds = GetBoundingRectangleCore(); + return new Point(bounds.X + (bounds.Width / 2), bounds.Y + (bounds.Height / 2)); + } + + protected override IList? GetChildrenCore() => null; + + protected override object? GetPatternCore(PatternInterface patternInterface) => patternInterface switch + { + PatternInterface.Invoke or PatternInterface.ScrollItem => this, + _ => base.GetPatternCore(patternInterface), + }; +} diff --git a/windows/src/TablePro.DataGrid/DataGridView.Accessibility.cs b/windows/src/TablePro.DataGrid/DataGridView.Accessibility.cs new file mode 100644 index 0000000000..33d0831f35 --- /dev/null +++ b/windows/src/TablePro.DataGrid/DataGridView.Accessibility.cs @@ -0,0 +1,121 @@ +using System.Globalization; +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Automation; +using Microsoft.UI.Xaml.Automation.Peers; +using TablePro.DataGrid.Automation; +using TablePro.DataGrid.Model; +using Windows.Foundation; + +namespace TablePro.DataGrid; + +public sealed partial class DataGridView +{ + // The rows in view, top to bottom: what the automation tree lists a row header and cells for. + internal IEnumerable VisibleRowNumbers() + { + var (first, last) = VisibleRows(); + for (var row = first; row <= last; row++) + { + yield return row; + } + } + + // The frozen columns, then the scrolling ones in view. + internal IEnumerable VisibleColumns() + { + for (var column = 0; column < _columns.FrozenCount && column < ColumnCount; column++) + { + yield return column; + } + var (first, last) = _columnWindow; + for (var column = Math.Max(first, _columns.FrozenCount); column <= last && column < ColumnCount; column++) + { + yield return column; + } + } + + internal string ColumnName(int column) => column >= 0 && column < ColumnCount ? _names[column] : string.Empty; + + // As the row number is drawn. + internal string RowNumberName(int row) => + row >= 0 && row < RowCount ? ((long)row + 1).ToString(CultureInfo.CurrentCulture) : string.Empty; + + internal bool IsRowNumberVisible(int row) + { + var (first, last) = VisibleRows(); + return row >= 0 && row < RowCount && row >= first && row <= last; + } + + internal Rect RowNumberBoundsPhysical(int row) + { + if (!IsRowNumberVisible(row) || XamlRoot is null) + { + return default; + } + var bounds = _frozenContent.TransformToVisual(null).TransformBounds( + new Rect(0, row * _rowHeight, _columns.RowHeaderWidth, _rowHeight)); + return PhysicalBounds(bounds); + } + + // The header element bound to the column, while it is realized. + internal Rect ColumnHeaderBoundsPhysical(int column) + { + if (column < 0 || column >= ColumnCount || HeaderCell(column) is not { Column: var bound } header + || bound != column || XamlRoot is null) + { + return default; + } + return PhysicalBounds(header.TransformToVisual(null).TransformBounds( + new Rect(0, 0, header.ActualWidth, header.ActualHeight))); + } + + // A cell, or a row number in the frozen pane, under a point in physical pixels from the window's client area. + internal AutomationPeer? ItemPeerAt(Point physical) + { + if (XamlRoot is null || FrameworkElementAutomationPeer.CreatePeerForElement(this) is not DataGridAutomationPeer peer) + { + return null; + } + var scale = XamlRoot.RasterizationScale; + var point = new Point(physical.X / scale, physical.Y / scale); + foreach (var frozen in new[] { true, false }) + { + var pane = frozen ? (UIElement)_frozenContent : _content; + var local = pane.TransformToVisual(null).Inverse.TransformPoint(point); + switch (HitTest(frozen, local)) + { + case { Column: >= 0 } hit when IsCellVisible(hit.Row, hit.Column): + return peer.Cell(hit.Row, hit.Column); + case { Column: < 0 } hit when frozen && IsRowNumberVisible(hit.Row): + return peer.RowHeader(hit.Row); + } + } + return null; + } + + // Each column whose sort order changed says so on its header peer, which a client may hold off screen too. + private void RaiseSortStatus(GridSort previous, GridSort current) + { + if (!AutomationPeer.ListenerExists(AutomationEvents.PropertyChanged) + || FrameworkElementAutomationPeer.FromElement(this) is not DataGridAutomationPeer peer) + { + return; + } + foreach (var column in new[] { previous.Column, current.Column }.Distinct()) + { + var before = previous.Column == column ? previous.Direction : SortDirection.None; + var after = current.Column == column ? current.Direction : SortDirection.None; + if (column >= 0 && column < ColumnCount && before != after) + { + peer.ColumnHeader(column).RaisePropertyChangedEvent( + AutomationElementIdentifiers.ItemStatusProperty, SortStatus(before), SortStatus(after)); + } + } + } + + private Rect PhysicalBounds(Rect bounds) + { + var scale = XamlRoot.RasterizationScale; + return new Rect(bounds.X * scale, bounds.Y * scale, bounds.Width * scale, bounds.Height * scale); + } +} diff --git a/windows/src/TablePro.DataGrid/DataGridView.Editing.cs b/windows/src/TablePro.DataGrid/DataGridView.Editing.cs index bf78b600d0..a1b041eb9c 100644 --- a/windows/src/TablePro.DataGrid/DataGridView.Editing.cs +++ b/windows/src/TablePro.DataGrid/DataGridView.Editing.cs @@ -106,6 +106,7 @@ public void BeginEdit() public void EditsChanged() { + ClearCellTip(); if (_data is null) { return; @@ -315,6 +316,7 @@ private void CommitOrCancel(bool refocus) private void OpenEditor(int row, int column, string text) { + ClearCellTip(); var editor = _editor ??= CreateEditor(); var window = column < _columns.FrozenCount ? _frozenWindow : _window; if (!ReferenceEquals(editor.Parent, window)) diff --git a/windows/src/TablePro.DataGrid/DataGridView.Interaction.cs b/windows/src/TablePro.DataGrid/DataGridView.Interaction.cs index 4041f7de23..53b8390b6b 100644 --- a/windows/src/TablePro.DataGrid/DataGridView.Interaction.cs +++ b/windows/src/TablePro.DataGrid/DataGridView.Interaction.cs @@ -338,26 +338,6 @@ internal Rect CellBoundsPhysical(int row, int column) return new Rect(bounds.X * scale, bounds.Y * scale, bounds.Width * scale, bounds.Height * scale); } - internal AutomationPeer? CellPeerAt(Point physical) - { - if (XamlRoot is null || FrameworkElementAutomationPeer.CreatePeerForElement(this) is not DataGridAutomationPeer peer) - { - return null; - } - var scale = XamlRoot.RasterizationScale; - var point = new Point(physical.X / scale, physical.Y / scale); - foreach (var frozen in new[] { true, false }) - { - var pane = frozen ? (UIElement)_frozenContent : _content; - var local = pane.TransformToVisual(null).Inverse.TransformPoint(point); - if (HitTest(frozen, local) is { Column: >= 0 } hit && IsCellVisible(hit.Row, hit.Column)) - { - return peer.Cell(hit.Row, hit.Column); - } - } - return null; - } - protected override void OnKeyDown(KeyRoutedEventArgs e) { ArgumentNullException.ThrowIfNull(e); @@ -444,6 +424,7 @@ private void OnPaneDoubleTapped(DoubleTappedRoutedEventArgs e, bool frozen) // A press picks a cell, or a row on the row numbers; Shift extends from the anchor. Dragging extends too. private void OnPanePressed(PointerRoutedEventArgs e, bool frozen) { + ClearCellTip(); var pane = frozen ? (UIElement)_frozenContent : _content; var point = e.GetCurrentPoint(pane); if (!point.Properties.IsLeftButtonPressed) @@ -462,9 +443,9 @@ private void OnPanePressed(PointerRoutedEventArgs e, bool frozen) private void OnPaneMoved(PointerRoutedEventArgs e, bool frozen) { var pane = frozen ? (UIElement)_frozenContent : _content; - if (!_dragging && ShowsCellTips) + if (!_dragging) { - ShowCellTip(pane, HitTest(frozen, e.GetCurrentPoint(pane).Position)); + TrackCellTip(frozen, HitTest(frozen, e.GetCurrentPoint(pane).Position)); } if (!_dragging || frozen != _dragFrozen) { @@ -487,30 +468,6 @@ private void OnPaneMoved(PointerRoutedEventArgs e, bool frozen) } } - // One tooltip per pane, its text following the cell under the pointer; none over a NULL or the row numbers. - private void ShowCellTip(UIElement pane, (int Row, int Column)? hit) - { - string? text = null; - if (hit is { Column: >= 0 } at) - { - var cell = Cell(at.Row, at.Column); - text = cell.IsNull || cell.IsDefault ? null - : cell.IsTruncated ? _cache?.ReadWhole(at.Row, at.Column) - : cell.Text.ToString(); - } - if (string.IsNullOrEmpty(text)) - { - ToolTipService.SetToolTip(pane, null); - return; - } - var tip = ToolTipService.GetToolTip(pane) as ToolTip ?? new ToolTip(); - if (!string.Equals(tip.Content as string, text, StringComparison.Ordinal)) - { - tip.Content = text; - } - ToolTipService.SetToolTip(pane, tip); - } - // A press at a point in a pane, in that pane's coordinates. Also how the tests click. internal void HandlePress(bool frozen, Point point, bool shift) { diff --git a/windows/src/TablePro.DataGrid/DataGridView.Tips.cs b/windows/src/TablePro.DataGrid/DataGridView.Tips.cs new file mode 100644 index 0000000000..82e346825e --- /dev/null +++ b/windows/src/TablePro.DataGrid/DataGridView.Tips.cs @@ -0,0 +1,130 @@ +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Controls; +using Microsoft.UI.Xaml.Controls.Primitives; +using TablePro.DataGrid.Model; +using TerraFX.Interop.Windows; +using Windows.Foundation; +using static TerraFX.Interop.Windows.Windows; + +namespace TablePro.DataGrid; + +// ToolTipService arms a tooltip only on its owner's PointerEntered, so one owned by a pane would open for the first +// cell alone. Each cut cell gets its own, timed as ToolTipService times a pointer's (ToolTipService_Partial.cpp). +public sealed partial class DataGridView +{ + private const int TipCharacters = 1_000; + private const long ReshowWindowMilliseconds = 200; + private const uint DefaultHoverMilliseconds = 400; + + private readonly DispatcherTimer _tipTimer = new(); + private ToolTip? _tip; + private (bool Frozen, int Row, int Column)? _tipCell; + private long _tipClosedAt = long.MinValue / 2; + + internal ToolTip? OpenTip => _tip; + + private void InitializeCellTips() + { + _tipTimer.Tick += (_, _) => OpenCellTip(); + _content.PointerExited += (_, _) => ClearCellTip(); + _frozenContent.PointerExited += (_, _) => ClearCellTip(); + } + + // The pointer rests over a cell of a pane, or over none. + internal void TrackCellTip(bool frozen, (int Row, int Column)? hit) + { + (bool, int, int)? cell = hit is { Column: >= 0 } at ? (frozen, at.Row, at.Column) : null; + if (cell == _tipCell) + { + return; + } + ClearCellTip(); + if (cell is not { } over || !ShowsCellTips || IsEditing || !IsCut(over.Item2, over.Item3)) + { + return; + } + _tipCell = over; + _tipTimer.Interval = TipDelay(); + _tipTimer.Start(); + } + + internal void ClearCellTip() + { + _tipTimer.Stop(); + _tipCell = null; + if (_tip is { } tip) + { + _tip = null; + if (tip.IsOpen) + { + tip.IsOpen = false; + _tipClosedAt = Environment.TickCount64; + } + } + } + + // Opened now rather than after the hover time, as the tests do. + internal void OpenCellTip() + { + _tipTimer.Stop(); + if (_tipCell is not { } at || IsEditing || XamlRoot is null || CellTipText(at.Row, at.Column) is not { } text) + { + return; + } + var pane = at.Frozen ? (UIElement)_frozenContent : _content; + // A tooltip opened by code has no pointer to follow, so it docks to the cell's rectangle. + _tip = new ToolTip + { + Content = text, + XamlRoot = XamlRoot, + RequestedTheme = ActualTheme, + PlacementTarget = pane, + PlacementRect = new Rect(_columns.PaneX(at.Column), at.Row * _rowHeight, _columns.Width(at.Column), _rowHeight), + Placement = PlacementMode.Top, + }; + _tip.IsOpen = true; + } + + // Null where nothing is cut: a NULL, a DEFAULT and text the column shows whole have no tip. + internal string? CellTipText(int row, int column) + { + if (!IsCut(row, column)) + { + return null; + } + var cell = Cell(row, column); + if (!cell.IsTruncated) + { + return cell.Text.ToString(); + } + using var reader = _data!.OpenReader(); + var block = new CellBlock(); + reader.Read(row, 1, column, 1, TipCharacters, block); + var read = block.Get(row, column); + return read.IsTruncated ? string.Concat(read.Text, "…") : read.Text.ToString(); + } + + private bool IsCut(int row, int column) + { + if (_data is null || !Contains(row, column)) + { + return false; + } + var cell = Cell(row, column); + return !cell.IsNull && !cell.IsDefault && !cell.Text.IsEmpty + && (cell.IsTruncated || Painter.Measure(cell.Text) > _columns.Width(column) - (CellPainter.Padding * 2)); + } + + // Twice the hover time, or one and a half within the reshow window after a tip closed. + private unsafe TimeSpan TipDelay() + { + uint hover = 0; + bool read = SystemParametersInfoW(SPI.SPI_GETMOUSEHOVERTIME, 0, &hover, 0); + if (!read || hover == 0) + { + hover = DefaultHoverMilliseconds; + } + var reshow = Environment.TickCount64 - _tipClosedAt < ReshowWindowMilliseconds; + return TimeSpan.FromMilliseconds(hover * (reshow ? 1.5 : 2)); + } +} diff --git a/windows/src/TablePro.DataGrid/DataGridView.cs b/windows/src/TablePro.DataGrid/DataGridView.cs index d83cd003af..e991ef1c0b 100644 --- a/windows/src/TablePro.DataGrid/DataGridView.cs +++ b/windows/src/TablePro.DataGrid/DataGridView.cs @@ -174,6 +174,7 @@ public DataGridView() _header.SizeChanged += (_, _) => MeasureInsets(); _frozenContent.SizeChanged += (_, _) => MeasureInsets(); Content = _scroller; + InitializeCellTips(); IsTabStop = true; UseSystemFocusVisuals = false; @@ -240,8 +241,10 @@ public GridSort Sort get => _sort; set { + var previous = _sort; _sort = value; RebindHeaders(); + RaiseSortStatus(previous, value); } } @@ -357,6 +360,7 @@ void IGridWindow.PrepareHeader(UIElement header, int column) // Shows data, or nothing for null. The grid opens its own reader on this thread and disposes it with the data. public void SetData(IGridData? data) { + ClearCellTip(); Cancel(EditorFocused); // A copy still reading the old data would read it after the host lets it go, then put it on the clipboard. _copy?.Cancel(); @@ -563,6 +567,7 @@ private void OnLoaded(object sender, RoutedEventArgs e) private void OnUnloaded(object sender, RoutedEventArgs e) { + ClearCellTip(); // As when the editor loses focus, so text typed into a grid that leaves the window still reaches the host. CommitOrCancel(refocus: false); foreach (var rows in new[] { _rowsLayout.Realized.Values, _frozenRowsLayout.Realized.Values, _rowPool.Pooled, _frozenRowPool.Pooled }) @@ -604,6 +609,8 @@ internal void RefreshTheme() private void ColumnsChanged() { + // A wider column may show the value whole now. + ClearCellTip(); _layoutVersion++; _content.Width = _columns.ScrollWidth; _frozenContent.Width = _columns.FrozenWidth; @@ -725,6 +732,10 @@ internal void ScrollTo(double x, double y) private void Follow(double x, double y) { + if (x != _viewX || y != _viewY) + { + ClearCellTip(); + } _viewX = x; _viewY = y; var origin = Math.Floor(y / OriginStep) * OriginStep; diff --git a/windows/src/TablePro.Interop/DatabaseSession.cs b/windows/src/TablePro.Interop/DatabaseSession.cs index 4c64a6ca9c..e49e7bf577 100644 --- a/windows/src/TablePro.Interop/DatabaseSession.cs +++ b/windows/src/TablePro.Interop/DatabaseSession.cs @@ -227,6 +227,15 @@ public async Task OpenTableEditorAsync( return new TableEditor(editor); } + // The table's foreign keys and the other tables' keys that point at it, read in one operation. + public async Task ReadTableKeysAsync(TableName table, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(table); + var keys = await CoreCall.RunAsync(token => _session.TableKeys(Mapping.Table(table), token), cancellationToken) + .ConfigureAwait(false); + return new TableKeys(keys); + } + // An editor tab's own connection, which keeps its transaction from one run to the next. public async Task OpenEditorAsync(CancellationToken cancellationToken = default) { diff --git a/windows/src/TablePro.Interop/Generated/tablepro_ffi.cs b/windows/src/TablePro.Interop/Generated/tablepro_ffi.cs index 597ac4d08b..02dcccacd3 100644 --- a/windows/src/TablePro.Interop/Generated/tablepro_ffi.cs +++ b/windows/src/TablePro.Interop/Generated/tablepro_ffi.cs @@ -1154,6 +1154,14 @@ public struct UniffiVTableCallbackInterfaceRunListener + + + + + + + + @@ -1912,6 +1920,39 @@ public static extern ulong uniffi_tablepro_ffi_fn_method_connectionlibrary_update_tag(ulong @ptr,RustBuffer @id,RustBuffer @name,RustBuffer @color ); + #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_clone_tablekeys(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err + ); + + #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_free_tablekeys(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err + ); + + #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 + RustBuffer uniffi_tablepro_ffi_fn_method_tablekeys_row_references(ulong @ptr,ulong @rows,ulong @row,RustBuffer @column,ref UniffiRustCallStatus _uniffi_out_err + ); + #if NET8_0_OR_GREATER [LibraryImport("tablepro_ffi")] [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] @@ -1967,6 +2008,17 @@ public static extern ulong uniffi_tablepro_ffi_fn_method_resultset_share_summary(ulong @ptr,uint @visibleColumns,uint @maxRows,RustBuffer @columns ); + #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 + RustBuffer uniffi_tablepro_ffi_fn_method_resultset_cell_bytes(ulong @ptr,ulong @row,uint @column,ref UniffiRustCallStatus _uniffi_out_err + ); + #if NET8_0_OR_GREATER [LibraryImport("tablepro_ffi")] [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] @@ -2319,6 +2371,17 @@ public static extern ulong uniffi_tablepro_ffi_fn_method_databasesession_export_table(ulong @ptr,RustBuffer @table,RustBuffer @sort,RustBuffer @filter,RustBuffer @format,RustBuffer @path,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_keys(ulong @ptr,RustBuffer @table,RustBuffer @cancel + ); + #if NET8_0_OR_GREATER [LibraryImport("tablepro_ffi")] [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] @@ -3958,6 +4021,17 @@ public static extern ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_update_tag( ); + #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_tablekeys_row_references( + ); + #if NET8_0_OR_GREATER [LibraryImport("tablepro_ffi")] [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] @@ -3991,6 +4065,17 @@ public static extern ushort uniffi_tablepro_ffi_checksum_method_resultset_share_summary( ); + #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_resultset_cell_bytes( + ); + #if NET8_0_OR_GREATER [LibraryImport("tablepro_ffi")] [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] @@ -4255,6 +4340,17 @@ public static extern ushort uniffi_tablepro_ffi_checksum_method_databasesession_export_table( ); + #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_keys( + ); + #if NET8_0_OR_GREATER [LibraryImport("tablepro_ffi")] [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] @@ -5090,6 +5186,12 @@ static void uniffiCheckApiChecksums() { throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_connectionlibrary_update_tag` checksum `62856`, library returned `{checksum}`"); } } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_tablekeys_row_references(); + if (checksum != 17848) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_tablekeys_row_references` checksum `17848`, library returned `{checksum}`"); + } + } { var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_resultset_share_masking(); if (checksum != 22678) { @@ -5108,6 +5210,12 @@ static void uniffiCheckApiChecksums() { throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_resultset_share_summary` checksum `53471`, library returned `{checksum}`"); } } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_resultset_cell_bytes(); + if (checksum != 39609) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_resultset_cell_bytes` checksum `39609`, library returned `{checksum}`"); + } + } { var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_resultset_cell_text(); if (checksum != 54600) { @@ -5252,6 +5360,12 @@ static void uniffiCheckApiChecksums() { throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_databasesession_export_table` checksum `50830`, library returned `{checksum}`"); } } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_databasesession_table_keys(); + if (checksum != 62706) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_databasesession_table_keys` checksum `62706`, library returned `{checksum}`"); + } + } { var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_databasesession_close(); if (checksum != 35830) { @@ -5705,6 +5819,27 @@ public override void Write(string value, BigEndianStream stream) { + +class FfiConverterByteArray: FfiConverterRustBuffer { + public static FfiConverterByteArray INSTANCE = new FfiConverterByteArray(); + + public override byte[] Read(BigEndianStream stream) { + var length = stream.ReadInt(); + return stream.ReadBytes(length); + } + + public override int AllocationSize(byte[] value) { + return 4 + value.Length; + } + + public override void Write(byte[] value, BigEndianStream stream) { + stream.WriteInt(value.Length); + stream.WriteBytes(value); + } +} + + + internal interface IAccountService { /// Task Devices(); @@ -7113,6 +7248,8 @@ internal interface IDatabaseSession { /// Task ExportTable(TableName @table, ColumnSort? @sort, TableFilterArg? @filter, ExportFormatTag @format, string @path, CancelToken? @cancel); /// + Task TableKeys(TableName @table, CancelToken? @cancel); + /// Task Close(); /// Task Columns(TableName @table, CancelToken? @cancel); @@ -7285,6 +7422,28 @@ public async Task ExportTable(TableName @table, ColumnSort? @sort, TableF ); } + /// + public async Task TableKeys(TableName @table, CancelToken? @cancel) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_table_keys(thisPtr, FfiConverterTypeTableName.INSTANCE.Lower(@table), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_u64(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_u64(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_u64(future), + // Lift + (result) => FfiConverterTypeTableKeys.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + /// public async Task Close() {await _UniFFIAsync.UniffiRustCallAsync( // Get rust future @@ -8336,6 +8495,8 @@ internal interface IResultSet { /// Task ShareSummary(uint @visibleColumns, uint @maxRows, ShareColumnChoice[] @columns); /// + byte[]? CellBytes(ulong @row, uint @column); + /// string? CellText(ulong @row, uint @column); ResultColumnInfo[] Columns(); /// @@ -8506,6 +8667,15 @@ public async Task ShareSummary(uint @visibleColumns, uint @maxRows ); } + /// + public byte[]? CellBytes(ulong @row, uint @column) { + return CallWithPointer(thisPtr => FfiConverterOptionalByteArray.INSTANCE.Lift( + _UniffiHelpers.RustCallWithError(FfiConverterTypeCoreError.INSTANCE, (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_resultset_cell_bytes(thisPtr, FfiConverterUInt64.INSTANCE.Lower(@row), FfiConverterUInt32.INSTANCE.Lower(@column), ref _status) +))); + } + + /// public string? CellText(ulong @row, uint @column) { return CallWithPointer(thisPtr => FfiConverterOptionalString.INSTANCE.Lift( @@ -8954,6 +9124,138 @@ public override void Write(TableEditor value, BigEndianStream stream) { +internal interface ITableKeys { + /// + RowReferences RowReferences(ResultSet @rows, ulong @row, string? @column); +} +internal class TableKeys : ITableKeys, IDisposable { + protected ulong pointer; + private int _wasDestroyed = 0; + private long _callCounter = 1; + + public TableKeys(ulong pointer) { + this.pointer = pointer; + } + + ~TableKeys() { + Destroy(); + } + + protected void FreeRustArcPtr() { + _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { + _UniFFILib.uniffi_tablepro_ffi_fn_free_tablekeys(this.pointer, ref status); + }); + } + + protected ulong CloneRustArcPtr() { + return _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { + return _UniFFILib.uniffi_tablepro_ffi_fn_clone_tablekeys(this.pointer, ref status); + }); + } + + public void Destroy() + { + // Only allow a single call to this method. + if (Interlocked.CompareExchange(ref _wasDestroyed, 1, 0) == 0) + { + // This decrement always matches the initial count of 1 given at creation time. + if (Interlocked.Decrement(ref _callCounter) == 0) + { + FreeRustArcPtr(); + } + } + } + + public void Dispose() + { + Destroy(); + GC.SuppressFinalize(this); // Suppress finalization to avoid unnecessary GC overhead. + } + + private void IncrementCallCounter() + { + // Check and increment the call counter, to keep the object alive. + // This needs a compare-and-set retry loop in case of concurrent updates. + long count; + do + { + count = Interlocked.Read(ref _callCounter); + if (count == 0L) throw new System.ObjectDisposedException(String.Format("'{0}' object has already been destroyed", this.GetType().Name)); + if (count == long.MaxValue) throw new System.OverflowException(String.Format("'{0}' call counter would overflow", this.GetType().Name)); + + } while (Interlocked.CompareExchange(ref _callCounter, count + 1, count) != count); + } + + private void DecrementCallCounter() + { + // This decrement always matches the increment we performed above. + if (Interlocked.Decrement(ref _callCounter) == 0) { + FreeRustArcPtr(); + } + } + + internal void CallWithPointer(Action action) + { + IncrementCallCounter(); + try { + action(CloneRustArcPtr()); + } + finally { + DecrementCallCounter(); + } + } + + internal T CallWithPointer(Func func) + { + IncrementCallCounter(); + try { + return func(CloneRustArcPtr()); + } + finally { + DecrementCallCounter(); + } + } + + + /// + public RowReferences RowReferences(ResultSet @rows, ulong @row, string? @column) { + return CallWithPointer(thisPtr => FfiConverterTypeRowReferences.INSTANCE.Lift( + _UniffiHelpers.RustCallWithError(FfiConverterTypeCoreError.INSTANCE, (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_tablekeys_row_references(thisPtr, FfiConverterTypeResultSet.INSTANCE.Lower(@rows), FfiConverterUInt64.INSTANCE.Lower(@row), FfiConverterOptionalString.INSTANCE.Lower(@column), ref _status) +))); + } + + + + +} +class FfiConverterTypeTableKeys: FfiConverter { + public static FfiConverterTypeTableKeys INSTANCE = new FfiConverterTypeTableKeys(); + + + public override ulong Lower(TableKeys value) { + return value.CallWithPointer(thisPtr => thisPtr); + } + + public override TableKeys Lift(ulong value) { + return new TableKeys(value); + } + + public override TableKeys Read(BigEndianStream stream) { + return Lift(stream.ReadULong()); + } + + public override int AllocationSize(TableKeys value) { + return 8; + } + + public override void Write(TableKeys value, BigEndianStream stream) { + stream.WriteULong(Lower(value)); + } +} + + + internal interface ITablePageRead { bool CanSeek(); QueryRun Run(); @@ -10902,6 +11204,78 @@ public override void Write(ResultColumnInfo value, BigEndianStream stream) { +internal record RowReferenceChoice ( + string KeyName, + TableName Table, + string[] Columns, + TableFilterArg? Filter, + ReferenceRefusal? Refusal +) { +} + +class FfiConverterTypeRowReferenceChoice: FfiConverterRustBuffer { + public static FfiConverterTypeRowReferenceChoice INSTANCE = new FfiConverterTypeRowReferenceChoice(); + + public override RowReferenceChoice Read(BigEndianStream stream) { + return new RowReferenceChoice( + KeyName: FfiConverterString.INSTANCE.Read(stream), + Table: FfiConverterTypeTableName.INSTANCE.Read(stream), + Columns: FfiConverterSequenceString.INSTANCE.Read(stream), + Filter: FfiConverterOptionalTypeTableFilterArg.INSTANCE.Read(stream), + Refusal: FfiConverterOptionalTypeReferenceRefusal.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(RowReferenceChoice value) { + return 0 + + FfiConverterString.INSTANCE.AllocationSize(value.KeyName) + + FfiConverterTypeTableName.INSTANCE.AllocationSize(value.Table) + + FfiConverterSequenceString.INSTANCE.AllocationSize(value.Columns) + + FfiConverterOptionalTypeTableFilterArg.INSTANCE.AllocationSize(value.Filter) + + FfiConverterOptionalTypeReferenceRefusal.INSTANCE.AllocationSize(value.Refusal); + } + + public override void Write(RowReferenceChoice value, BigEndianStream stream) { + FfiConverterString.INSTANCE.Write(value.KeyName, stream); + FfiConverterTypeTableName.INSTANCE.Write(value.Table, stream); + FfiConverterSequenceString.INSTANCE.Write(value.Columns, stream); + FfiConverterOptionalTypeTableFilterArg.INSTANCE.Write(value.Filter, stream); + FfiConverterOptionalTypeReferenceRefusal.INSTANCE.Write(value.Refusal, stream); + } +} + + + +internal record RowReferences ( + RowReferenceChoice[] Referenced, + RowReferenceChoice[] Referencing +) { +} + +class FfiConverterTypeRowReferences: FfiConverterRustBuffer { + public static FfiConverterTypeRowReferences INSTANCE = new FfiConverterTypeRowReferences(); + + public override RowReferences Read(BigEndianStream stream) { + return new RowReferences( + Referenced: FfiConverterSequenceTypeRowReferenceChoice.INSTANCE.Read(stream), + Referencing: FfiConverterSequenceTypeRowReferenceChoice.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(RowReferences value) { + return 0 + + FfiConverterSequenceTypeRowReferenceChoice.INSTANCE.AllocationSize(value.Referenced) + + FfiConverterSequenceTypeRowReferenceChoice.INSTANCE.AllocationSize(value.Referencing); + } + + public override void Write(RowReferences value, BigEndianStream stream) { + FfiConverterSequenceTypeRowReferenceChoice.INSTANCE.Write(value.Referenced, stream); + FfiConverterSequenceTypeRowReferenceChoice.INSTANCE.Write(value.Referencing, stream); + } +} + + + internal record RunGate ( bool Refused, string[] Confirm, @@ -13725,6 +14099,104 @@ public override void Write(PromptReasonTag value, BigEndianStream stream) { +internal record ReferenceRefusal { + + public record UnevenKey ( + string Key + ) : ReferenceRefusal {} + + public record UnknownSchema ( + string Table + ) : ReferenceRefusal {} + + public record NoFilterText ( + string Column + ) : ReferenceRefusal {} + + public record ComparedOtherwise ( + string Table + ) : ReferenceRefusal {} + + + +} + +class FfiConverterTypeReferenceRefusal : FfiConverterRustBuffer{ + public static FfiConverterRustBuffer INSTANCE = new FfiConverterTypeReferenceRefusal(); + + public override ReferenceRefusal Read(BigEndianStream stream) { + var value = stream.ReadInt(); + switch (value) { + case 1: + return new ReferenceRefusal.UnevenKey( + FfiConverterString.INSTANCE.Read(stream) + ); + case 2: + return new ReferenceRefusal.UnknownSchema( + FfiConverterString.INSTANCE.Read(stream) + ); + case 3: + return new ReferenceRefusal.NoFilterText( + FfiConverterString.INSTANCE.Read(stream) + ); + case 4: + return new ReferenceRefusal.ComparedOtherwise( + FfiConverterString.INSTANCE.Read(stream) + ); + default: + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeReferenceRefusal.Read()", value)); + } + } + + public override int AllocationSize(ReferenceRefusal value) { + switch (value) { + case ReferenceRefusal.UnevenKey variant_value: + return 4 + + FfiConverterString.INSTANCE.AllocationSize(variant_value.Key); + case ReferenceRefusal.UnknownSchema variant_value: + return 4 + + FfiConverterString.INSTANCE.AllocationSize(variant_value.Table); + case ReferenceRefusal.NoFilterText variant_value: + return 4 + + FfiConverterString.INSTANCE.AllocationSize(variant_value.Column); + case ReferenceRefusal.ComparedOtherwise variant_value: + return 4 + + FfiConverterString.INSTANCE.AllocationSize(variant_value.Table); + default: + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeReferenceRefusal.AllocationSize()", value)); + } + } + + public override void Write(ReferenceRefusal value, BigEndianStream stream) { + switch (value) { + case ReferenceRefusal.UnevenKey variant_value: + stream.WriteInt(1); + FfiConverterString.INSTANCE.Write(variant_value.Key, stream); + break; + case ReferenceRefusal.UnknownSchema variant_value: + stream.WriteInt(2); + FfiConverterString.INSTANCE.Write(variant_value.Table, stream); + break; + case ReferenceRefusal.NoFilterText variant_value: + stream.WriteInt(3); + FfiConverterString.INSTANCE.Write(variant_value.Column, stream); + break; + case ReferenceRefusal.ComparedOtherwise variant_value: + stream.WriteInt(4); + FfiConverterString.INSTANCE.Write(variant_value.Table, stream); + break; + default: + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeReferenceRefusal.Write()", value)); + } + } +} + + + + + + + internal record RowEdit { public record Update ( @@ -16413,6 +16885,37 @@ public override void Write(string? value, BigEndianStream stream) { +class FfiConverterOptionalByteArray: FfiConverterRustBuffer { + public static FfiConverterOptionalByteArray INSTANCE = new FfiConverterOptionalByteArray(); + + public override byte[]? Read(BigEndianStream stream) { + if (stream.ReadByte() == 0) { + return null; + } + return FfiConverterByteArray.INSTANCE.Read(stream); + } + + public override int AllocationSize(byte[]? value) { + if (value == null) { + return 1; + } else { + return 1 + FfiConverterByteArray.INSTANCE.AllocationSize((byte[])value); + } + } + + public override void Write(byte[]? value, BigEndianStream stream) { + if (value == null) { + stream.WriteByte(0); + } else { + stream.WriteByte(1); + FfiConverterByteArray.INSTANCE.Write((byte[])value, stream); + } + } +} + + + + class FfiConverterOptionalTypeCancelToken: FfiConverterRustBuffer { public static FfiConverterOptionalTypeCancelToken INSTANCE = new FfiConverterOptionalTypeCancelToken(); @@ -16909,6 +17412,37 @@ public override void Write(FilterValueArg? value, BigEndianStream stream) { +class FfiConverterOptionalTypeReferenceRefusal: FfiConverterRustBuffer { + public static FfiConverterOptionalTypeReferenceRefusal INSTANCE = new FfiConverterOptionalTypeReferenceRefusal(); + + public override ReferenceRefusal? Read(BigEndianStream stream) { + if (stream.ReadByte() == 0) { + return null; + } + return FfiConverterTypeReferenceRefusal.INSTANCE.Read(stream); + } + + public override int AllocationSize(ReferenceRefusal? value) { + if (value == null) { + return 1; + } else { + return 1 + FfiConverterTypeReferenceRefusal.INSTANCE.AllocationSize((ReferenceRefusal)value); + } + } + + public override void Write(ReferenceRefusal? value, BigEndianStream stream) { + if (value == null) { + stream.WriteByte(0); + } else { + stream.WriteByte(1); + FfiConverterTypeReferenceRefusal.INSTANCE.Write((ReferenceRefusal)value, stream); + } + } +} + + + + class FfiConverterOptionalTypeSecretKindTag: FfiConverterRustBuffer { public static FfiConverterOptionalTypeSecretKindTag INSTANCE = new FfiConverterOptionalTypeSecretKindTag(); @@ -18200,6 +18734,52 @@ public override void Write(ResultColumnInfo[] value, BigEndianStream stream) { +class FfiConverterSequenceTypeRowReferenceChoice: FfiConverterRustBuffer { + public static FfiConverterSequenceTypeRowReferenceChoice INSTANCE = new FfiConverterSequenceTypeRowReferenceChoice(); + + public override RowReferenceChoice[] Read(BigEndianStream stream) { + var length = stream.ReadInt(); + if (length == 0) { + return []; + } + + var result = new RowReferenceChoice[length]; + var readFn = FfiConverterTypeRowReferenceChoice.INSTANCE.Read; + for (int i = 0; i < length; i++) { + result[i] = readFn(stream); + } + return result; + } + + public override int AllocationSize(RowReferenceChoice[] value) { + var sizeForLength = 4; + + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + return sizeForLength; + } + + var allocationSizeFn = FfiConverterTypeRowReferenceChoice.INSTANCE.AllocationSize; + var sizeForItems = value.Sum(item => allocationSizeFn(item)); + return sizeForLength + sizeForItems; + } + + public override void Write(RowReferenceChoice[] value, BigEndianStream stream) { + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + stream.WriteInt(0); + return; + } + + stream.WriteInt(value.Length); + var writerFn = FfiConverterTypeRowReferenceChoice.INSTANCE.Write; + value.ForEach(item => writerFn(item, stream)); + } +} + + + + class FfiConverterSequenceTypeSchemaEntry: FfiConverterRustBuffer { public static FfiConverterSequenceTypeSchemaEntry INSTANCE = new FfiConverterSequenceTypeSchemaEntry(); diff --git a/windows/src/TablePro.Interop/Mapping.References.cs b/windows/src/TablePro.Interop/Mapping.References.cs new file mode 100644 index 0000000000..6e249918f7 --- /dev/null +++ b/windows/src/TablePro.Interop/Mapping.References.cs @@ -0,0 +1,38 @@ +using Native = TablePro.Interop.Native; + +namespace TablePro.Interop; + +internal static partial class Mapping +{ + public static RowReferenceChoice Reference(Native.RowReferenceChoice choice) + { + var (refusal, subject) = choice.Refusal switch + { + Native.ReferenceRefusal.UnevenKey uneven => (ReferenceRefusal.UnevenKey, uneven.Key), + Native.ReferenceRefusal.UnknownSchema unknown => (ReferenceRefusal.UnknownSchema, unknown.Table), + Native.ReferenceRefusal.NoFilterText text => (ReferenceRefusal.NoFilterText, text.Column), + Native.ReferenceRefusal.ComparedOtherwise otherwise => (ReferenceRefusal.ComparedOtherwise, otherwise.Table), + _ => ((ReferenceRefusal?)null, (string?)null), + }; + return new RowReferenceChoice( + choice.KeyName, + new TableName(choice.Table.Schema, choice.Table.Name), + choice.Columns, + choice.Filter is { } filter ? Filter(filter) : null, + refusal, + subject); + } + + private static TableFilter Filter(Native.TableFilterArg filter) => new( + filter.Combinator == Native.CombinatorTag.Or ? FilterCombinator.Or : FilterCombinator.And, + [.. filter.Rules.Select(rule => new FilterRule(rule.Column, Operator(rule.Op), Value(rule.Value)))], + filter.RawSql); + + private static FilterValue? Value(Native.FilterValueArg? value) => value switch + { + Native.FilterValueArg.Single single => new FilterValue.One(single.Value), + Native.FilterValueArg.Pair pair => new FilterValue.Pair(pair.Low, pair.High), + Native.FilterValueArg.List list => new FilterValue.List(list.Values), + _ => null, + }; +} diff --git a/windows/src/TablePro.Interop/ResultSet.cs b/windows/src/TablePro.Interop/ResultSet.cs index 3b69181a72..5b2fb828fc 100644 --- a/windows/src/TablePro.Interop/ResultSet.cs +++ b/windows/src/TablePro.Interop/ResultSet.cs @@ -31,6 +31,14 @@ internal ResultSet(Native.ResultSet set, int index) return CoreCall.Run(() => _set.CellText(checked((ulong)row), checked((uint)column))); } + // Every byte of a binary value, for an image or a hex view. Null for SQL NULL or a value that is not binary. + public byte[]? GetCellBytes(long row, int column) + { + ArgumentOutOfRangeException.ThrowIfNegative(row); + ArgumentOutOfRangeException.ThrowIfNegative(column); + return CoreCall.Run(() => _set.CellBytes(checked((ulong)row), checked((uint)column))); + } + // Each thread that reads windows opens its own. public ResultCursor OpenCursor() => new(_set.OpenCursor()); diff --git a/windows/src/TablePro.Interop/RowReference.cs b/windows/src/TablePro.Interop/RowReference.cs new file mode 100644 index 0000000000..63821c6f17 --- /dev/null +++ b/windows/src/TablePro.Interop/RowReference.cs @@ -0,0 +1,29 @@ +namespace TablePro.Interop; + +// Why a key the row holds cannot be followed with a filter; Subject names the key, table or column it is about. +public enum ReferenceRefusal +{ + UnevenKey, + UnknownSchema, + NoFilterText, + ComparedOtherwise, +} + +// Columns are the key's columns in the table that holds it. Exactly one of Filter and Refusal is set. +public sealed record RowReferenceChoice( + string KeyName, + TableName Table, + IReadOnlyList Columns, + TableFilter? Filter, + ReferenceRefusal? Refusal, + string? RefusalSubject); + +// Referenced: the rows the row's keys point at. Referencing: other tables' keys that point at the row. +public sealed record RowReferences( + IReadOnlyList Referenced, + IReadOnlyList Referencing) +{ + public static RowReferences None { get; } = new([], []); + + public bool IsEmpty => Referenced.Count == 0 && Referencing.Count == 0; +} diff --git a/windows/src/TablePro.Interop/TableKeys.cs b/windows/src/TablePro.Interop/TableKeys.cs new file mode 100644 index 0000000000..171032a30c --- /dev/null +++ b/windows/src/TablePro.Interop/TableKeys.cs @@ -0,0 +1,27 @@ +using Native = TablePro.Interop.Native; + +namespace TablePro.Interop; + +// A table's foreign keys both ways, read once; what a row leads to is worked out from them without the server. +public sealed class TableKeys : IDisposable +{ + private readonly Native.TableKeys _keys; + + internal TableKeys(Native.TableKeys keys) + { + _keys = keys; + } + + // From a row of a page of this table as the server holds it; column narrows the row's keys to those holding it. + public RowReferences GetRowReferences(ResultSet rows, long row, string? column) + { + ArgumentNullException.ThrowIfNull(rows); + ArgumentOutOfRangeException.ThrowIfNegative(row); + var references = CoreCall.Run(() => _keys.RowReferences(rows.Handle, checked((ulong)row), column)); + return new RowReferences( + [.. references.Referenced.Select(Mapping.Reference)], + [.. references.Referencing.Select(Mapping.Reference)]); + } + + public void Dispose() => _keys.Dispose(); +} diff --git a/windows/tests/TablePro.App.Model.Tests/CellValueTests.cs b/windows/tests/TablePro.App.Model.Tests/CellValueTests.cs new file mode 100644 index 0000000000..c565a61020 --- /dev/null +++ b/windows/tests/TablePro.App.Model.Tests/CellValueTests.cs @@ -0,0 +1,101 @@ +using TablePro.DataGrid.Model; + +namespace TablePro.App.Model.Tests; + +public sealed class CellValueTests +{ + [Fact] + public void JsonIsLaidOutOneMemberPerLineKeepingEscapesAndNumbersAsStored() + { + const string stored = """{"name":"Zoë","n":1.50,"e":1E+2,"list":[1,{"a":null}],"empty":{},"arr":[],"t":true}"""; + + Assert.Equal( + """ + { + "name": "Zoë", + "n": 1.50, + "e": 1E+2, + "list": [ + 1, + { + "a": null + } + ], + "empty": {}, + "arr": [], + "t": true + } + """.ReplaceLineEndings("\n"), + JsonText.Indent(stored)?.Text); + Assert.Equal(("[\n \"Zoë 👋\"\n]", false), JsonText.Indent(" [\"Zoë 👋\"]")); + } + + [Fact] + public void ALayoutPastItsLimitStopsThereButStillChecksTheRest() + { + var nested = string.Concat(Enumerable.Repeat("[", 40)) + string.Join(',', Enumerable.Repeat("1", 2_000)) + + string.Concat(Enumerable.Repeat("]", 40)); + + var (laid, cut) = JsonText.Indent(nested, 10_000)!.Value; + + Assert.True(cut); + Assert.Equal(10_000, laid.Length); + Assert.Null(JsonText.Indent(nested + ",", 10_000)); + Assert.False(JsonText.Indent(nested)!.Value.Cut); + } + + [Theory] + [InlineData("{\"a\":")] + [InlineData("42")] + [InlineData("\"text\"")] + [InlineData("{} x")] + [InlineData("// note\n{}")] + [InlineData("plain text")] + public void TextThatIsNotOneObjectOrArrayHasNoJsonView(string text) => Assert.Null(JsonText.Indent(text)); + + [Fact] + public void BinaryShowsAsHexUpToItsLimitAndCopiesWhole() + { + var small = new CellValue("body", null, [0xde, 0xad], IsDefault: false); + var large = new CellValue("body", null, new byte[CellValue.MaximumHexBytes + 1], IsDefault: false); + + Assert.Equal(("0xdead", false), small.Hex()); + Assert.Equal("0xdead", small.CopyText()); + var (hex, cut) = large.Hex(); + Assert.True(cut); + Assert.Equal(2 + (CellValue.MaximumHexBytes * 2), hex.Length); + Assert.Equal(2 + ((CellValue.MaximumHexBytes + 1) * 2), large.CopyText()!.Length); + Assert.False(small.IsNull); + Assert.Null(small.Json()); + } + + [Fact] + public void LongTextShowsItsStartWithoutSplittingACharacterAndCopiesWhole() + { + var text = new string('a', CellValue.MaximumShownCharacters - 1) + "👋" + "tail"; + var value = new CellValue("note", text, null, IsDefault: false); + + var (shown, cut) = value.ShownText(); + + Assert.True(cut); + Assert.Equal(CellValue.MaximumShownCharacters - 1, shown.Length); + Assert.Equal(text, value.CopyText()); + Assert.Equal((string.Empty, false), new CellValue("note", null, null, IsDefault: false).ShownText()); + Assert.True(new CellValue("note", null, null, IsDefault: false).IsNull); + Assert.False(new CellValue("note", null, null, IsDefault: true).IsNull); + } + + [Fact] + public void ACellReadsWholeThroughTheGridsData() + { + var data = new TextGridData(["doc", "note"], [["{\"a\":1}", null]]); + + var doc = CellValue.Read(data, null, 0, 0)!; + + Assert.Equal(new CellValue("doc", "{\"a\":1}", null, IsDefault: false), doc); + Assert.Equal(("{\n \"a\": 1\n}", false), doc.Json()); + Assert.True(CellValue.Read(data, null, 0, 1)!.IsNull); + Assert.Null(CellValue.Read(data, null, 1, 0)); + Assert.Null(CellValue.Read(data, null, 0, 2)); + } +} diff --git a/windows/tests/TablePro.App.Model.Tests/DefinitionTabTests.cs b/windows/tests/TablePro.App.Model.Tests/DefinitionTabTests.cs index 42d8785e79..574d4548c0 100644 --- a/windows/tests/TablePro.App.Model.Tests/DefinitionTabTests.cs +++ b/windows/tests/TablePro.App.Model.Tests/DefinitionTabTests.cs @@ -260,6 +260,9 @@ public Task GetStructureAsync( CancellationToken cancellationToken) => throw new NotSupportedException(); + public Task ReadTableKeysAsync(TableName table, CancellationToken cancellationToken) => + throw new NotSupportedException(); + public RunGate GateRun(string sql) => throw new NotSupportedException(); public Range? StatementAt(string sql, int caret) => throw new NotSupportedException(); diff --git a/windows/tests/TablePro.App.Model.Tests/TabFakes.cs b/windows/tests/TablePro.App.Model.Tests/TabFakes.cs index e8d575449e..032f766012 100644 --- a/windows/tests/TablePro.App.Model.Tests/TabFakes.cs +++ b/windows/tests/TablePro.App.Model.Tests/TabFakes.cs @@ -128,6 +128,13 @@ internal sealed class FakeSession : ITabSession public ObjectSource? Definition { get; set; } + // What every key read gives; each read makes a new one, so a test tells a kept read from a new one. + public RowReferences References { get; set; } = RowReferences.None; + + public CoreError? KeysFailure { get; set; } + + public List KeyReads { get; } = []; + // Every open gives this one, so a test sets it up before the page loads. public FakeTableEditor TableEditor { get; } = new(); @@ -292,6 +299,18 @@ public async Task OpenTableEditorAsync( return TableEditorFailure is { } failure ? throw new TableProException(failure) : TableEditor; } + public Task ReadTableKeysAsync(TableName table, CancellationToken cancellationToken) + { + if (KeysFailure is { } failure) + { + return Task.FromException(new TableProException(failure)); + } + + var keys = new FakeKeys(this); + KeyReads.Add(keys); + return Task.FromResult(keys); + } + public ValueTask ReleaseAsync() { Releases++; @@ -301,6 +320,21 @@ public ValueTask ReleaseAsync() private long RowsPicked(TableFilter? filter) => filter is null ? TableRows : FilteredRows; } +internal sealed class FakeKeys(FakeSession session) : ITableKeys +{ + public List<(long Row, string? Column)> Asked { get; } = []; + + public bool IsDisposed { get; private set; } + + public RowReferences ReferencesAt(ResultSet? rows, long row, string? column) + { + Asked.Add((row, column)); + return session.References; + } + + public void Dispose() => IsDisposed = true; +} + internal sealed class FakeEditor(FakeSession session) : ITabEditor { public List Runs { get; } = []; diff --git a/windows/tests/TablePro.App.Model.Tests/TableTabReferenceTests.cs b/windows/tests/TablePro.App.Model.Tests/TableTabReferenceTests.cs new file mode 100644 index 0000000000..7e7dc7fe72 --- /dev/null +++ b/windows/tests/TablePro.App.Model.Tests/TableTabReferenceTests.cs @@ -0,0 +1,162 @@ +using TablePro.Interop; + +namespace TablePro.App.Model.Tests; + +public sealed class TableTabReferenceTests +{ + private static readonly TableName Artist = new(null, "Artist"); + + private static readonly TableFilter ToArtist = new( + FilterCombinator.And, [new FilterRule("ArtistId", FilterOperator.Equal, new FilterValue.One("1"))], null); + + private static readonly RowReferenceChoice Referenced = new("fk_artist", Artist, ["name"], ToArtist, null, null); + + private static readonly RowReferenceChoice Referencing = + new("fk_album", new TableName(null, "Album"), ["ArtistId"], ToArtist, null, null); + + private readonly FakeSession _session = new() { TableRows = 3, References = new([Referenced], [Referencing]) }; + private readonly FakeTableView _view = new(); + private readonly FakeResults _results = new(); + private readonly TableTab _tab; + + public TableTabReferenceTests() + { + _tab = new TableTab(_session, _view, _results, new TableName(null, "Album"), ObjectKind.Table, () => new AppSettings()); + _view.Tab = _tab; + } + + [Fact] + public async Task TheKeysAreReadOnceThePageShowsAndAgainAfterARefreshAndGoWithTheTab() + { + Assert.True(_tab.ReferencesAt(0, 1).IsEmpty); + + await _tab.RunAsync(); + var references = _tab.ReferencesAt(0, 1); + await _tab.RunAsync(); + + Assert.Same(Referenced, Assert.Single(references.Referenced)); + Assert.Same(Referencing, Assert.Single(references.Referencing)); + var first = Assert.Single(_session.KeyReads); + Assert.Equal((0L, "name"), Assert.Single(first.Asked)); + + await _tab.RefreshAsync(); + Assert.Equal(2, _session.KeyReads.Count); + Assert.True(first.IsDisposed); + + await _tab.CloseAsync(); + Assert.True(_session.KeyReads[1].IsDisposed); + Assert.True(_tab.ReferencesAt(0, 1).IsEmpty); + } + + [Fact] + public async Task APendingChangeInAKeysColumnHidesThatKeyButNotTheRowsPointingAtTheRow() + { + await _tab.RunAsync(); + + Assert.Null(_tab.CommitEdit(0, 1, "renamed")); + var changed = _tab.ReferencesAt(0, 1); + Assert.Null(_tab.AddRow(out var added)); + Assert.Null(_tab.DeleteRows([2])); + + Assert.Empty(changed.Referenced); + Assert.Single(changed.Referencing); + Assert.False(_tab.ReferencesAt(1, 1).IsEmpty); + Assert.True(_tab.ReferencesAt(added, 1).IsEmpty); + Assert.True(_tab.ReferencesAt(2, 1).IsEmpty); + Assert.True(_tab.ReferencesAt(0, 5).IsEmpty); + } + + [Fact] + public async Task ARefreshWhoseKeyReadFailsOffersNoneOfTheKeysReadBefore() + { + await _tab.RunAsync(); + Assert.False(_tab.ReferencesAt(0, 1).IsEmpty); + + _session.KeysFailure = Errors.Of("driver.connection_lost"); + await _tab.RefreshAsync(); + + Assert.True(Assert.Single(_session.KeyReads).IsDisposed); + Assert.True(_tab.ReferencesAt(0, 1).IsEmpty); + } + + [Fact] + public async Task AKeyReadThatFailsLeavesTheRowsWithoutReferences() + { + _session.KeysFailure = Errors.Of("driver.unsupported"); + + await _tab.RunAsync(); + + Assert.Equal(3, _results.RowCount); + Assert.True(_tab.ReferencesAt(0, 1).IsEmpty); + Assert.DoesNotContain("error driver.unsupported", _results.Shown); + } + + [Fact] + public void AReferenceOpensAsATableTabOnItsFilterWhichATabReadWithTheSameFilterShows() + { + var spec = TableTab.TabFor(Referenced)!; + var refused = Referenced with { Filter = null, Refusal = ReferenceRefusal.ComparedOtherwise, RefusalSubject = "Artist" }; + var shown = new TableTab(_session, _view, _results, Artist, ObjectKind.Table, () => new AppSettings(), spec); + var other = new TableTab( + _session, + _view, + _results, + Artist, + ObjectKind.Table, + () => new AppSettings(), + TableTab.TabFor(Referenced with + { + Filter = ToArtist with { Rules = [new FilterRule("ArtistId", FilterOperator.Equal, new FilterValue.One("2"))] }, + })); + + Assert.Equal((TabKind.Table, "Artist", (string?)null, "Artist"), (spec.Kind, spec.Table, spec.Schema, spec.Title)); + Assert.True(TableFilters.Same(ToArtist, spec.Filter!.ToFilter())); + Assert.True(shown.ShowsReference(Referenced)); + Assert.False(other.ShowsReference(Referenced)); + Assert.False(shown.ShowsReference(refused)); + Assert.Null(TableTab.TabFor(refused)); + Assert.False(_tab.ShowsReference(Referenced)); + } + + [Fact] + public async Task ATabReadingAnotherFilterDoesNotShowAReferenceUntilItsRowsAreRead() + { + var view = new FakeTableView(); + var results = new FakeResults(); + var target = new TableTab( + _session, view, results, Artist, ObjectKind.Table, () => new AppSettings(), TableTab.TabFor(Referenced)); + view.Tab = target; + await target.RunAsync(); + var second = Referenced with + { + Filter = ToArtist with { Rules = [new FilterRule("ArtistId", FilterOperator.Equal, new FilterValue.One("2"))] }, + }; + var querying = new Gate(); + _session.Querying = querying; + _session.RefusesFilter = true; + + var applying = target.ApplyFilterAsync(second.Filter); + await querying.Reached; + var whileReading = (target.ShowsReference(second), target.ShowsReference(Referenced)); + querying.Open(); + await applying; + + Assert.Equal((false, false), whileReading); + Assert.False(target.ShowsReference(second)); + Assert.True(target.ShowsReference(Referenced)); + } + + [Fact] + public void FiltersCompareByTheirRulesNotTheListsHoldingThem() + { + var copy = new TableFilter(FilterCombinator.And, [.. ToArtist.Rules], null); + var list = new TableFilter(FilterCombinator.And, [new FilterRule("id", FilterOperator.In, new FilterValue.List(["1", "2"]))], null); + + Assert.True(TableFilters.Same(ToArtist, copy)); + Assert.True(TableFilters.Same(list, list with { Rules = [new FilterRule("id", FilterOperator.In, new FilterValue.List(["1", "2"]))] })); + Assert.False(TableFilters.Same(ToArtist, copy with { Combinator = FilterCombinator.Or })); + Assert.False(TableFilters.Same(ToArtist, copy with { RawSql = "1 = 1" })); + Assert.False(TableFilters.Same(ToArtist, null)); + Assert.True(TableFilters.Same(null, null)); + } +} diff --git a/windows/tests/TablePro.App.UITests/GridAccessibilityTests.cs b/windows/tests/TablePro.App.UITests/GridAccessibilityTests.cs new file mode 100644 index 0000000000..2d4584dc6f --- /dev/null +++ b/windows/tests/TablePro.App.UITests/GridAccessibilityTests.cs @@ -0,0 +1,32 @@ +using FlaUI.Core.WindowsAPI; + +namespace TablePro.App.UITests; + +public sealed partial class ShellTests +{ + [Theory] + [MemberData(nameof(Themes))] + public void AGridCellNamesItsRowAndColumnHeadersAndARowHeaderSelectsItsRow(string theme) + { + using var app = AppSession.Launch(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 TrackId, Name FROM Track ORDER BY TrackId"); + app.Chord( + () => app.Find("QueryStatus").Name.StartsWith("Rows: ", StringComparison.Ordinal), + VirtualKeyShort.CONTROL, + VirtualKeyShort.ENTER); + var grid = app.Find("ResultsGrid"); + Assert.Equal("1", app.WaitForCell(grid, 0, 0, value => value == "1")); + var cell = CellOf(grid, 0, 1); + var column = Assert.Single(cell.Patterns.TableItem.Pattern.ColumnHeaderItems.Value); + var row = Assert.Single(cell.Patterns.TableItem.Pattern.RowHeaderItems.Value); + Assert.Equal("Name", column.Name); + Assert.Equal("1", row.Name); + Assert.Equal("DataGridColumnHeader", column.Properties.ClassName.Value); + Assert.Equal("DataGridRowHeader", row.Properties.ClassName.Value); + row.Patterns.Invoke.Pattern.Invoke(); + Assert.Equal(2, grid.Patterns.Selection.Pattern.Selection.Value.Length); + app.Screenshot("87-grid-row-headers"); + } +} diff --git a/windows/tests/TablePro.App.UITests/GridReferenceTests.cs b/windows/tests/TablePro.App.UITests/GridReferenceTests.cs new file mode 100644 index 0000000000..af1aaeddab --- /dev/null +++ b/windows/tests/TablePro.App.UITests/GridReferenceTests.cs @@ -0,0 +1,45 @@ +using FlaUI.Core.Tools; + +namespace TablePro.App.UITests; + +public sealed partial class ShellTests +{ + [Theory] + [MemberData(nameof(Themes))] + public void AForeignKeyOpensTheRowItPointsAtAndTheRowsPointingBack(string theme) + { + using var app = AppSession.Launch(theme); + app.Click(app.Find("SampleCard"), () => app.TryFind("Rail_Chinook (Sample)") is not null); + app.Click(app.FindByName("Track", app.Find("ObjectTree")), () => app.TryFind("TableStatus") is not null); + var tracks = app.Find("ResultsGrid"); + Assert.Equal("1", app.WaitForCell(tracks, 0, 2, value => value == "1")); + + // The tab reads its keys once its first page shows, so the menu offers them a moment later. + Assert.True(Retry.WhileFalse( + () => + { + app.RightClick(CellOf(tracks, 0, 2), () => app.TryFindMenuItem("View value...") is not null); + if (app.TryFindMenuItem("Open referenced row") is not null) + { + return true; + } + + app.Chord(() => app.TryFindMenuItem("View value...") is null, FlaUI.Core.WindowsAPI.VirtualKeyShort.ESCAPE); + return false; + }, + AppSession.Wait, + throwOnTimeout: false).Success); + app.Screenshot("84-grid-foreign-key-menu"); + app.Click(app.FindMenuItem("Open referenced row"), () => app.TryFind("TableStatus") is { } status + && status.Name.StartsWith("Rows: 1 ", StringComparison.Ordinal)); + var albums = app.Find("ResultsGrid"); + Assert.Equal("For Those About To Rock We Salute You", app.WaitForCell(albums, 0, 1, value => value.Length > 0)); + app.Screenshot("85-referenced-row"); + + app.RightClick(CellOf(albums, 0, 0), () => app.TryFindMenuItem("Show referencing rows") is not null); + app.Click(app.OpenSubmenu("Show referencing rows", "Track (AlbumId)"), () => app.TryFind("TableStatus") is { } status + && status.Name.StartsWith("Rows: 10 ", StringComparison.Ordinal)); + Assert.Equal("1", app.WaitForCell(app.Find("ResultsGrid"), 0, 2, value => value == "1")); + app.Screenshot("86-referencing-rows"); + } +} diff --git a/windows/tests/TablePro.App.UITests/GridValueTests.cs b/windows/tests/TablePro.App.UITests/GridValueTests.cs new file mode 100644 index 0000000000..1af2665575 --- /dev/null +++ b/windows/tests/TablePro.App.UITests/GridValueTests.cs @@ -0,0 +1,55 @@ +using FlaUI.Core.AutomationElements; +using FlaUI.Core.Tools; +using FlaUI.Core.WindowsAPI; + +namespace TablePro.App.UITests; + +public sealed partial class ShellTests +{ + // A 160 by 80 PNG of four colored bands. + private const string Picture = + "89504E470D0A1A0A0000000D49484452000000A0000000500802000000113FE963000000D54944415478DAEDD1310D00200C00B049181A30" + + "C981317C2002176082644F933A68C4D825726689D37A89BBA24408162C58B060C182050B162C58B060C182050B162C58B060C182050B162C" + + "58B060C182050B162C58B060C182050B162C58B060C182050B162C58B060C182050B162C58B060C182050B162C58B060C182050B162C58B0" + + "60C182050B162C58B060C182050B162C58B060C182050B162C58B060C182050B162C58B060C182050B162C58B060C182050B162C58B060C1" + + "82050B162C58B060C182050B162C58B060C182050B162CF89707A4833176794B97350000000049454E44AE426082"; + + [Theory] + [MemberData(nameof(Themes))] + public void AQueryResultsMenuOpensAValueAsJsonAnImageOrItsHex(string theme) + { + using var app = AppSession.Launch(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 '{{\"album\":\"Let There Be Rock\",\"tracks\":[15,16]}}' AS doc, X'{Picture}' AS cover"); + app.Chord( + () => app.Find("QueryStatus").Name.StartsWith("Rows: ", StringComparison.Ordinal), + VirtualKeyShort.CONTROL, + VirtualKeyShort.ENTER); + var grid = app.Find("ResultsGrid"); + app.WaitForCell(grid, 0, 0, value => value.StartsWith("{\"album\"", StringComparison.Ordinal)); + + app.RightClick(CellOf(grid, 0, 0), () => app.TryFindMenuItem("View value...") is not null); + Assert.NotNull(app.TryFindMenuItem("Export results...")); + Assert.NotNull(app.TryFindMenuItem("Share result...")); + app.Screenshot("80-results-grid-menu"); + app.Click(app.FindMenuItem("View value..."), () => app.TryFind("ValueViewer") is not null); + var text = AppSession.WaitForText( + app.Find("ValueViewerText"), value => value.Contains("\"tracks\": [", StringComparison.Ordinal)); + Assert.Contains("\"album\": \"Let There Be Rock\"", text, StringComparison.Ordinal); + app.Screenshot("81-value-viewer-json"); + app.CloseDialog(); + Assert.True(Retry.WhileTrue(() => app.TryFind("ValueViewer") is not null, AppSession.Wait, throwOnTimeout: false).Success); + + app.RightClick(CellOf(grid, 0, 1), () => app.TryFindMenuItem("View value...") is not null); + app.Click(app.FindMenuItem("View value..."), () => app.TryFind("ValueViewerImage") is { IsOffscreen: false }); + app.Screenshot("82-value-viewer-image"); + app.Click(app.Find("ValueViewerHexItem"), () => app.TryFind("ValueViewerText") is { IsOffscreen: false }); + Assert.StartsWith( + "0x89504e47", + AppSession.WaitForText(app.Find("ValueViewerText"), value => value.StartsWith("0x", StringComparison.Ordinal)), + StringComparison.Ordinal); + app.Screenshot("83-value-viewer-hex"); + app.CloseDialog(); + } +} diff --git a/windows/tests/TablePro.DataGrid.Tests/CellTipTests.cs b/windows/tests/TablePro.DataGrid.Tests/CellTipTests.cs new file mode 100644 index 0000000000..c865f95775 --- /dev/null +++ b/windows/tests/TablePro.DataGrid.Tests/CellTipTests.cs @@ -0,0 +1,55 @@ +using Microsoft.UI.Xaml.Controls.Primitives; +using TablePro.DataGrid.Model; + +namespace TablePro.DataGrid.Tests; + +// A tip shows what a cell cuts: the core's cap, or text wider than its column. Each cell opens its own. +public sealed class CellTipTests +{ + [Fact] + public Task OnlyACutCellHasATipAndItReadsPastTheGridsCap() => WinUiHost.RunAsync(async () => + { + var grid = await WinUiHost.ShowAsync(new SyntheticData()); + grid.ShowsCellTips = true; + + Assert.Null(grid.CellTipText(1, 0)); + Assert.Null(grid.CellTipText(0, 3)); + Assert.Equal(SyntheticData.Value(1, 5), grid.CellTipText(1, 5)); + + grid.ResizeColumn(0, GridColumns.MinimumWidth); + await WinUiHost.NextFrameAsync(); + Assert.Equal("r1c0", grid.CellTipText(1, 0)); + }); + + [Fact] + public Task EachCutCellOpensItsOwnTipAndLeavingItCloses() => WinUiHost.RunAsync(async () => + { + var grid = await WinUiHost.ShowAsync(new SyntheticData()); + grid.ShowsCellTips = true; + grid.ResizeColumn(0, GridColumns.MinimumWidth); + await WinUiHost.NextFrameAsync(); + + grid.TrackCellTip(frozen: false, (1, 5)); + Assert.Null(grid.OpenTip); + grid.OpenCellTip(); + var first = grid.OpenTip!; + Assert.True(first.IsOpen); + Assert.Equal(SyntheticData.Value(1, 5), first.Content); + Assert.Equal(PlacementMode.Top, first.Placement); + + grid.TrackCellTip(frozen: false, (2, 0)); + Assert.False(first.IsOpen); + grid.OpenCellTip(); + Assert.Equal("r2c0", grid.OpenTip!.Content); + + grid.TrackCellTip(frozen: false, (2, 1)); + Assert.Null(grid.OpenTip); + grid.OpenCellTip(); + Assert.Null(grid.OpenTip); + + grid.ShowsCellTips = false; + grid.TrackCellTip(frozen: false, (1, 5)); + grid.OpenCellTip(); + Assert.Null(grid.OpenTip); + }); +} diff --git a/windows/tests/TablePro.DataGrid.Tests/HeaderAutomationTests.cs b/windows/tests/TablePro.DataGrid.Tests/HeaderAutomationTests.cs new file mode 100644 index 0000000000..7edaa6e9d2 --- /dev/null +++ b/windows/tests/TablePro.DataGrid.Tests/HeaderAutomationTests.cs @@ -0,0 +1,122 @@ +using Microsoft.UI.Xaml.Automation.Peers; +using Microsoft.UI.Xaml.Automation.Provider; +using TablePro.DataGrid.Automation; + +namespace TablePro.DataGrid.Tests; + +// Windows App SDK 2.6.4 hands clients an empty TablePattern.ColumnHeaders (microsoft-ui-xaml#11820), so each cell's +// TableItem is how a client reads its headers, on screen or not. +public sealed class HeaderAutomationTests +{ + [Fact] + public Task AnOffscreenCellNamesItsHeadersAndKeepsThemAsColumnsScroll() => WinUiHost.RunAsync(async () => + { + var grid = await WinUiHost.ShowAsync(new SyntheticData()); + var peer = (DataGridAutomationPeer)FrameworkElementAutomationPeer.CreatePeerForElement(grid); + var cell = peer.Cell(999_999, 199); + var column = peer.ColumnHeader(199); + var row = peer.RowHeader(999_999); + + Assert.Same(column, peer.Peer(Assert.Single(cell.GetColumnHeaderItems()))); + Assert.Same(row, peer.Peer(Assert.Single(cell.GetRowHeaderItems()))); + Assert.Equal("column_199", column.GetName()); + Assert.Equal(1_000_000.ToString(System.Globalization.CultureInfo.CurrentCulture), row.GetName()); + Assert.Equal(AutomationControlType.HeaderItem, column.GetAutomationControlType()); + Assert.Equal(AutomationControlType.HeaderItem, row.GetAutomationControlType()); + Assert.True(column.IsOffscreen()); + Assert.True(row.IsOffscreen()); + Assert.Equal(200, peer.GetColumnHeaders().Length); + + cell.ScrollIntoView(); + grid.UpdateLayout(); + await WinUiHost.NextFrameAsync(); + Assert.Same(column, peer.ColumnHeader(199)); + Assert.Same(row, peer.RowHeader(999_999)); + Assert.False(column.IsOffscreen()); + Assert.False(row.IsOffscreen()); + var children = peer.GetChildren(); + Assert.Contains(column, children); + Assert.Contains(row, children); + Assert.True(children.IndexOf(row) < children.IndexOf(cell)); + + grid.ScrollTo(0, 0); + grid.UpdateLayout(); + await WinUiHost.NextFrameAsync(); + Assert.Equal("column_199", column.GetName()); + Assert.True(column.IsOffscreen()); + Assert.Same(column, peer.Peer(Assert.Single(cell.GetColumnHeaderItems()))); + }); + + [Fact] + public Task ARowHeaderSelectsItsRowAndAPointOnTheNumberFindsIt() => WinUiHost.RunAsync(async () => + { + var grid = await WinUiHost.ShowAsync(new SyntheticData(), frozen: 2); + var peer = (DataGridAutomationPeer)FrameworkElementAutomationPeer.CreatePeerForElement(grid); + var rows = peer.GetChildren().OfType().ToList(); + Assert.InRange(rows.Count, 1, 100); + Assert.Equal(rows.Count, peer.GetRowHeaders().Length); + + var row = peer.RowHeader(2); + Assert.Equal(3, row.GetPositionInSet()); + Assert.Equal(1_000_000, row.GetSizeOfSet()); + ((IInvokeProvider)row.GetPattern(PatternInterface.Invoke)).Invoke(); + Assert.Equal((2, 2), (grid.SelectionRange.FirstRow, grid.SelectionRange.LastRow)); + Assert.Equal((0, 199), (grid.SelectionRange.FirstColumn, grid.SelectionRange.LastColumn)); + + var bounds = row.GetBoundingRectangle(); + Assert.True(bounds.Width > 0 && bounds.Height > 0); + Assert.Same(row, grid.ItemPeerAt(new Windows.Foundation.Point( + bounds.X + (bounds.Width / 2), bounds.Y + (bounds.Height / 2)))); + }); + + [Fact] + public Task AColumnHeaderSortsResizesAndSaysWhenItsSortChanges() => WinUiHost.RunAsync(async () => + { + var grid = await WinUiHost.ShowAsync(new SyntheticData()); + var peer = (DataGridAutomationPeer)FrameworkElementAutomationPeer.CreatePeerForElement(grid); + var column = peer.ColumnHeader(2); + var scale = grid.XamlRoot.RasterizationScale; + + ((IInvokeProvider)column.GetPattern(PatternInterface.Invoke)).Invoke(); + Assert.Equal(new Model.GridSort(2, Model.SortDirection.Ascending), grid.Sort); + Assert.Equal("Sorted ascending", column.GetItemStatus()); + ((ITransformProvider)column.GetPattern(PatternInterface.Transform)).Resize(250 * scale, grid.HeaderHeight * scale); + Assert.Equal(250, grid.Columns.Width(2), 3); + grid.Sort = new Model.GridSort(3, Model.SortDirection.Descending); + Assert.Equal(string.Empty, column.GetItemStatus()); + Assert.Equal("Sorted descending", peer.ColumnHeader(3).GetItemStatus()); + + // The header element in view stays out of the control view and sends a point query to its column's peer. + var element = FrameworkElementAutomationPeer.CreatePeerForElement(grid.HeaderCell(2)!); + Assert.False(element.IsControlElement()); + var bounds = column.GetBoundingRectangle(); + Assert.True(bounds.Width > 0); + Assert.Same(column, element.GetElementFromPoint(new Windows.Foundation.Point( + bounds.X + (bounds.Width / 2), bounds.Y + (bounds.Height / 2)))); + }); + + [Fact] + public Task HeadersPastAReplacementResultReadAsEmptyAndDoNothing() => WinUiHost.RunAsync(async () => + { + var grid = await WinUiHost.ShowAsync(new SyntheticData()); + var peer = (DataGridAutomationPeer)FrameworkElementAutomationPeer.CreatePeerForElement(grid); + var cell = peer.Cell(50, 199); + var row = peer.RowHeader(50); + var column = peer.ColumnHeader(199); + + grid.SetData(new SyntheticData(rows: 2, columns: 2)); + grid.UpdateLayout(); + + Assert.Equal(string.Empty, row.GetName()); + Assert.Equal(string.Empty, column.GetName()); + Assert.True(row.IsOffscreen()); + Assert.True(column.IsOffscreen()); + Assert.Empty(cell.GetRowHeaderItems()); + Assert.Empty(cell.GetColumnHeaderItems()); + ((IInvokeProvider)row.GetPattern(PatternInterface.Invoke)).Invoke(); + ((IInvokeProvider)column.GetPattern(PatternInterface.Invoke)).Invoke(); + Assert.Equal((0, 0), (grid.FocusedRow, grid.FocusedColumn)); + Assert.Equal(Model.GridSort.None, grid.Sort); + Assert.Equal(2, peer.GetColumnHeaders().Length); + }); +} diff --git a/windows/tests/TablePro.Interop.Tests/RowReferenceTests.cs b/windows/tests/TablePro.Interop.Tests/RowReferenceTests.cs new file mode 100644 index 0000000000..c27cdcab58 --- /dev/null +++ b/windows/tests/TablePro.Interop.Tests/RowReferenceTests.cs @@ -0,0 +1,116 @@ +namespace TablePro.Interop.Tests; + +public sealed class RowReferenceTests +{ + private const string Schema = """ + CREATE TABLE parent (code TEXT NOT NULL, region INTEGER NOT NULL, PRIMARY KEY (code, region)); + CREATE TABLE child (id INTEGER PRIMARY KEY, parent_code TEXT, parent_region INTEGER, + FOREIGN KEY (parent_code, parent_region) REFERENCES parent(code, region)); + INSERT INTO parent VALUES ('x'' OR 1=1 --', 7), ('x'' OR 1=1 --', 8), ('', 9); + INSERT INTO child VALUES (1, 'x'' OR 1=1 --', 7), (2, 'x'' OR 1=1 --', 8), (3, NULL, 7), (4, '', 9); + """; + + private static readonly TableName Child = new(null, "child"); + + [Fact] + public async Task ACompositeKeyLeadsToItsRowAndBackWithEveryValueBound() + { + var cancel = TestContext.Current.CancellationToken; + await using var database = await SqliteDatabase.CreateAsync(); + await database.ExecuteAsync(Schema); + using var children = await ReadAsync(database.Session, Child, null, cancel); + using var keys = await database.Session.ReadTableKeysAsync(Child, cancel); + + var references = keys.GetRowReferences(children, 0, "parent_code"); + var choice = Assert.Single(references.Referenced); + Assert.Empty(references.Referencing); + Assert.Equal(new TableName(null, "parent"), choice.Table); + Assert.Equal(["parent_code", "parent_region"], choice.Columns); + Assert.Null(choice.Refusal); + Assert.NotNull(choice.Filter); + Assert.Null(choice.Filter.RawSql); + Assert.Equal(FilterCombinator.And, choice.Filter.Combinator); + Assert.Equal([ + new FilterRule("code", FilterOperator.Equal, new FilterValue.One("x' OR 1=1 --")), + new FilterRule("region", FilterOperator.Equal, new FilterValue.One("7")), + ], choice.Filter.Rules); + Assert.True(keys.GetRowReferences(children, 0, "id").IsEmpty); + + using var parent = await ReadAsync(database.Session, choice.Table, choice.Filter, cancel); + Assert.Equal(1, parent.RowCount); + Assert.Equal("7", parent.GetCellText(0, 1)); + using var parentKeys = await database.Session.ReadTableKeysAsync(choice.Table, cancel); + var incoming = Assert.Single(parentKeys.GetRowReferences(parent, 0, null).Referencing); + Assert.Equal(Child, incoming.Table); + using var child = await ReadAsync(database.Session, incoming.Table, incoming.Filter, cancel); + Assert.Equal(1, child.RowCount); + Assert.Equal("1", child.GetCellText(0, 0)); + } + + [Fact] + public async Task ANullPartLeadsNowhereWhileAnEmptyTextAndASortedRowKeepTheirValues() + { + var cancel = TestContext.Current.CancellationToken; + await using var database = await SqliteDatabase.CreateAsync(); + await database.ExecuteAsync(Schema); + using var children = await ReadAsync(database.Session, Child, null, cancel); + using var keys = await database.Session.ReadTableKeysAsync(Child, cancel); + + Assert.True(keys.GetRowReferences(children, 2, null).IsEmpty); + using var sorted = await children.SortedAsync(0, ascending: false); + var choice = Assert.Single(keys.GetRowReferences(sorted, 0, null).Referenced); + Assert.NotNull(choice.Filter); + Assert.Equal(new FilterValue.One(string.Empty), choice.Filter.Rules[0].Value); + using var parent = await ReadAsync(database.Session, choice.Table, choice.Filter, cancel); + Assert.Equal("9", parent.GetCellText(0, 1)); + var failure = Assert.Throws(() => keys.GetRowReferences(children, 99, null)); + Assert.Equal("ffi.out_of_range", failure.Code); + } + + [Fact] + public async Task KeysThatCompareOtherwiseStayAsRefusalsNamingTheTable() + { + var cancel = TestContext.Current.CancellationToken; + await using var database = await SqliteDatabase.CreateAsync(); + await database.ExecuteAsync(""" + CREATE TABLE parent (code TEXT COLLATE NOCASE PRIMARY KEY); + CREATE TABLE child (code TEXT REFERENCES parent(code)); + INSERT INTO parent VALUES ('ABC'); + INSERT INTO child VALUES ('abc'); + """); + var table = new TableName(null, "parent"); + using var parents = await ReadAsync(database.Session, table, null, cancel); + using var keys = await database.Session.ReadTableKeysAsync(table, cancel); + + var choice = Assert.Single(keys.GetRowReferences(parents, 0, null).Referencing); + Assert.Equal(ReferenceRefusal.ComparedOtherwise, choice.Refusal); + Assert.Equal("child", choice.RefusalSubject); + Assert.Null(choice.Filter); + } + + [Fact] + public async Task ABinaryCellGivesItsBytesAndOtherCellsNone() + { + var cancel = TestContext.Current.CancellationToken; + await using var database = await SqliteDatabase.CreateAsync(); + await database.ExecuteAsync(""" + CREATE TABLE files (id INTEGER PRIMARY KEY, body BLOB, note TEXT); + INSERT INTO files VALUES (1, X'89504E47', 'png'), (2, NULL, NULL); + """); + using var files = await ReadAsync(database.Session, new TableName(null, "files"), null, cancel); + + Assert.Equal([0x89, 0x50, 0x4e, 0x47], files.GetCellBytes(0, 1)); + Assert.Null(files.GetCellBytes(0, 2)); + Assert.Null(files.GetCellBytes(1, 1)); + Assert.Equal("ffi.out_of_range", Assert.Throws(() => files.GetCellBytes(5, 1)).Code); + } + + private static async Task ReadAsync( + DatabaseSession session, TableName table, TableFilter? filter, CancellationToken cancel) + { + var page = await session.ReadTablePageAsync(table, null, filter, 100, cancellationToken: cancel); + using var run = page.Run; + Assert.IsType(await run.Completion); + return Assert.IsType(run.GetResultSet(0)); + } +} From 7c321b64470517c2ff710b9c54e083b7bb49e5a3 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sat, 14 Nov 2026 20:35:22 +0700 Subject: [PATCH 02/13] fix(windows): read only as much of a cell as the value viewer shows --- core/crates/ffi/src/lib.rs | 2 +- core/crates/ffi/src/results/cell_text.rs | 28 +++ core/crates/ffi/src/results/mod.rs | 2 +- core/crates/ffi/src/results/result_set.rs | 32 ++- core/crates/ffi/src/results/store.rs | 16 +- core/crates/ffi/tests/browse.rs | 24 ++- .../0022-browsing-through-the-ffi.md | 2 +- .../decisions/0007-browsing-a-connection.md | 2 +- windows/src/TablePro.App.Model/CellValue.cs | 61 ++++-- .../TablePro.App/Strings/en-US/Resources.resw | 2 +- .../src/TablePro.App/Views/CellValueViewer.cs | 6 +- .../Generated/tablepro_ffi.cs | 194 +++++++++++++++--- windows/src/TablePro.Interop/ResultSet.cs | 24 ++- .../CellValueTests.cs | 35 ++-- .../RowReferenceTests.cs | 17 +- 15 files changed, 349 insertions(+), 98 deletions(-) diff --git a/core/crates/ffi/src/lib.rs b/core/crates/ffi/src/lib.rs index 08724f0062..db068c903e 100644 --- a/core/crates/ffi/src/lib.rs +++ b/core/crates/ffi/src/lib.rs @@ -68,7 +68,7 @@ pub use masking::{ }; pub use prompter::{HostPrompter, PromptAnswer, PromptFieldInfo, PromptPurposeTag, PromptReasonTag, PromptRequest}; pub use references::{ReferenceRefusal, RowReferenceChoice, RowReferences, TableKeys}; -pub use results::{ResultColumnInfo, ResultSet, ValueKind}; +pub use results::{CellBytes, CellTextHead, ResultColumnInfo, ResultSet, ValueKind}; pub use row_edits::{ CellChange, CellEdit, EditColumnInfo, EditLock, EditStart, PlannedStatement, RowEdit, RowSave, RowSaveOutcome, SaveGate, TableEditor, diff --git a/core/crates/ffi/src/results/cell_text.rs b/core/crates/ffi/src/results/cell_text.rs index 9bfa4f403b..4659f51ab6 100644 --- a/core/crates/ffi/src/results/cell_text.rs +++ b/core/crates/ffi/src/results/cell_text.rs @@ -13,6 +13,21 @@ pub(super) fn full(kind: ValueKind, bytes: &[u8]) -> String { } } +// The value's start as `full` gives it, control characters kept, and whether anything was cut. +pub(super) fn head(kind: ValueKind, bytes: &[u8], max_chars: usize) -> (String, bool) { + match kind { + ValueKind::Bytes => { + let mut out = Vec::new(); + let cut = push_hex(bytes, max_chars.saturating_sub(2) / 2, &mut out); + (String::from_utf8_lossy(&out).into_owned(), cut) + } + _ => { + let end = char_boundary_after(bytes, max_chars); + (String::from_utf8_lossy(&bytes[..end]).into_owned(), end < bytes.len()) + } + } +} + // Returns whether anything was cut. pub(super) fn display(kind: ValueKind, bytes: &[u8], max_chars: usize, out: &mut Vec) -> bool { match kind { @@ -88,6 +103,19 @@ mod tests { assert_eq!(shown(ValueKind::Text, "👋👋".as_bytes(), 1), ("👋".to_owned(), true)); } + #[test] + fn a_head_keeps_line_breaks_and_cuts_at_a_character() { + assert_eq!( + head(ValueKind::Text, "a\nb👋c".as_bytes(), 3), + ("a\nb".to_owned(), true) + ); + assert_eq!(head(ValueKind::Json, b"{}", 10), ("{}".to_owned(), false)); + assert_eq!( + head(ValueKind::Bytes, &[0xde, 0xad, 0xbe], 6), + ("0xdead".to_owned(), true) + ); + } + #[test] fn binary_shows_its_leading_bytes_in_hex() { assert_eq!( diff --git a/core/crates/ffi/src/results/mod.rs b/core/crates/ffi/src/results/mod.rs index dfe678983c..ce71655d19 100644 --- a/core/crates/ffi/src/results/mod.rs +++ b/core/crates/ffi/src/results/mod.rs @@ -8,6 +8,6 @@ mod store; mod value_kind; pub(crate) use cursor::Cursor; -pub use result_set::{ResultColumnInfo, ResultSet}; +pub use result_set::{CellBytes, CellTextHead, ResultColumnInfo, ResultSet}; pub(crate) use store::ResultStore; pub use value_kind::ValueKind; diff --git a/core/crates/ffi/src/results/result_set.rs b/core/crates/ffi/src/results/result_set.rs index 48608682c0..3c01ed3817 100644 --- a/core/crates/ffi/src/results/result_set.rs +++ b/core/crates/ffi/src/results/result_set.rs @@ -12,6 +12,18 @@ pub struct ResultSet { order: Option>, } +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct CellTextHead { + pub text: String, + pub cut: bool, +} + +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct CellBytes { + pub bytes: Vec, + pub length: u64, +} + #[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] pub struct ResultColumnInfo { pub name: String, @@ -84,11 +96,25 @@ impl ResultSet { .ok_or_else(|| CoreError::failed("ffi.out_of_range", format!("no cell at row {row}, column {column}"))) } - // The bytes of a binary value, for an image or a hex view; `None` for null or a value that is not binary. - pub fn cell_bytes(&self, row: u64, column: u32) -> Result>, CoreError> { + // A value's start for a viewer, read without copying the rest: its text with line breaks kept, or a binary + // value's hex. `None` for null. + pub fn cell_text_head(&self, row: u64, column: u32, max_chars: u32) -> Result, CoreError> { + let max_chars = usize::try_from(max_chars).unwrap_or(usize::MAX); + usize::try_from(column) + .ok() + .and_then(|column| self.store.text_head(self.stored_row(row), column, max_chars)) + .map(|head| head.map(|(text, cut)| CellTextHead { text, cut })) + .ok_or_else(|| CoreError::failed("ffi.out_of_range", format!("no cell at row {row}, column {column}"))) + } + + // A binary value's first `max_bytes` and its whole length, for an image or a hex view; `None` for null or a + // value that is not binary. + pub fn cell_bytes(&self, row: u64, column: u32, max_bytes: u64) -> Result, CoreError> { + let max_bytes = usize::try_from(max_bytes).unwrap_or(usize::MAX); usize::try_from(column) .ok() - .and_then(|column| self.store.binary(self.stored_row(row), column)) + .and_then(|column| self.store.binary(self.stored_row(row), column, max_bytes)) + .map(|binary| binary.map(|(bytes, length)| CellBytes { bytes, length })) .ok_or_else(|| CoreError::failed("ffi.out_of_range", format!("no cell at row {row}, column {column}"))) } diff --git a/core/crates/ffi/src/results/store.rs b/core/crates/ffi/src/results/store.rs index a1b2e7f09d..1658421c4e 100644 --- a/core/crates/ffi/src/results/store.rs +++ b/core/crates/ffi/src/results/store.rs @@ -168,11 +168,21 @@ impl ResultStore { Some(cell.kind.map(|kind| cell_text::full(kind, cell.bytes))) } - // `Some(None)` for null or a value that is not binary. - pub(crate) fn binary(&self, row: u64, column: usize) -> Option>> { + // `Some(None)` for null; otherwise the start of what `full_text` gives, and whether it was cut. + pub(crate) fn text_head(&self, row: u64, column: usize, max_chars: usize) -> Option> { let state = self.read(); let cell = state.cell(row, column)?; - Some((cell.kind == Some(ValueKind::Bytes)).then(|| cell.bytes.to_vec())) + Some(cell.kind.map(|kind| cell_text::head(kind, cell.bytes, max_chars))) + } + + // `Some(None)` for null or a value that is not binary; otherwise its first `max_bytes` and its whole length. + pub(crate) fn binary(&self, row: u64, column: usize, max_bytes: usize) -> Option, u64)>> { + let state = self.read(); + let cell = state.cell(row, column)?; + Some((cell.kind == Some(ValueKind::Bytes)).then(|| { + let kept = &cell.bytes[..cell.bytes.len().min(max_bytes)]; + (kept.to_vec(), cell.bytes.len() as u64) + })) } } diff --git a/core/crates/ffi/tests/browse.rs b/core/crates/ffi/tests/browse.rs index 409b814b8e..d181db1367 100644 --- a/core/crates/ffi/tests/browse.rs +++ b/core/crates/ffi/tests/browse.rs @@ -706,20 +706,30 @@ async fn keys_that_compare_otherwise_or_hold_an_inexact_value_stay_as_refusals() } #[tokio::test] -async fn a_binary_cell_gives_its_bytes_and_other_cells_none() { +async fn a_cell_reads_its_start_and_a_binary_cell_its_first_bytes_with_its_length() { let dir = tempfile::tempdir().unwrap(); let (_core, session) = fixture( dir.path(), "CREATE TABLE files (id INTEGER PRIMARY KEY, body BLOB, note TEXT); \ - INSERT INTO files VALUES (1, X'89504E47', 'png'), (2, NULL, NULL)", + INSERT INTO files VALUES (1, X'89504E47', 'line one' || char(10) || 'line two'), (2, NULL, NULL)", ) .await; let rows = page_rows(&session, "files", None).await; - assert_eq!(rows.cell_bytes(0, 1).unwrap(), Some(vec![0x89, 0x50, 0x4e, 0x47])); - assert_eq!(rows.cell_text(0, 1).unwrap().as_deref(), Some("0x89504e47")); - assert_eq!(rows.cell_bytes(0, 2).unwrap(), None); - assert_eq!(rows.cell_bytes(1, 1).unwrap(), None); - assert_eq!(rows.cell_bytes(5, 1).unwrap_err().code(), "ffi.out_of_range"); + let whole = rows.cell_bytes(0, 1, 100).unwrap().unwrap(); + assert_eq!((whole.bytes, whole.length), (vec![0x89, 0x50, 0x4e, 0x47], 4)); + let first = rows.cell_bytes(0, 1, 2).unwrap().unwrap(); + assert_eq!((first.bytes, first.length), (vec![0x89, 0x50], 4)); + assert_eq!(rows.cell_bytes(0, 2, 100).unwrap(), None); + assert_eq!(rows.cell_bytes(1, 1, 100).unwrap(), None); + assert_eq!(rows.cell_bytes(5, 1, 100).unwrap_err().code(), "ffi.out_of_range"); + + let note = rows.cell_text_head(0, 2, 100).unwrap().unwrap(); + assert_eq!((note.text.as_str(), note.cut), ("line one\nline two", false)); + let cut = rows.cell_text_head(0, 2, 4).unwrap().unwrap(); + assert_eq!((cut.text.as_str(), cut.cut), ("line", true)); + let hex = rows.cell_text_head(0, 1, 6).unwrap().unwrap(); + assert_eq!((hex.text.as_str(), hex.cut), ("0x8950", true)); + assert_eq!(rows.cell_text_head(1, 2, 100).unwrap(), None); session.close().await.unwrap(); } diff --git a/core/docs/decisions/0022-browsing-through-the-ffi.md b/core/docs/decisions/0022-browsing-through-the-ffi.md index 1348152dff..f2d9e5ba18 100644 --- a/core/docs/decisions/0022-browsing-through-the-ffi.md +++ b/core/docs/decisions/0022-browsing-through-the-ffi.md @@ -19,7 +19,7 @@ The FFI exposes what the Linux app calls, and does the work the Linux app does, - `object_definition` reads `fetch_object_definition` for a function, procedure, trigger or sequence, with whether running the text in an editor would make the object as it is. - `export_rows` writes the rows a finished `ResultSet` holds, its visible columns only; `export_table` streams every row the filter and sort select through `build_export` and `stream_read`, as the Linux app exports a table. Both use the core's encoders (CSV with its default options, JSON, Excel, Markdown, HTML, XML, and SQL INSERT from a table), write beside the target and rename once complete, so a failed or cancelled export leaves no file. - `DatabaseSession::table_keys` reads a table's outbound and inbound foreign keys in one Metadata operation, as the Linux browse tab reads them. Its `TableKeys::row_references` builds, without the server, what a row of a page of that table leads to through `browse::RowReference`, from the row's stored values: the table's keys holding a column, and the other tables' keys pointing at the row. A key with a NULL or a column the page lacks is left out; one whose value the store cannot name exactly, or that `RowReference` refuses, comes back with its refusal for the app to word. -- `ResultSet::cell_bytes` gives a binary cell's bytes, for an app's image or hex view, where `cell_text` gives their hex. +- `ResultSet::cell_text_head` gives a value's start, line breaks kept, and `cell_bytes` a binary value's first bytes and its length, so an app's viewer copies no more of a large cell than it shows, where `cell_text` copies all of it. - `Core::history` opens the query history at `/state/history.db` once. `record` takes the session, so the engine's `history_recording` withholds a statement that holds a secret, as on Linux; `search` pages by the store's keyset; `delete` and `clear` change it. ## Rationale diff --git a/windows/docs/decisions/0007-browsing-a-connection.md b/windows/docs/decisions/0007-browsing-a-connection.md index e50e15dbdd..70873e9c5d 100644 --- a/windows/docs/decisions/0007-browsing-a-connection.md +++ b/windows/docs/decisions/0007-browsing-a-connection.md @@ -27,7 +27,7 @@ Each one works as the macOS app's does, with its words in Windows sentence case, ### Grid menus, values and foreign keys - A results grid's menu, in a query tab and a table tab, holds Copy, View value..., Export results... and Share; a table tab's adds its row and cell edits and the foreign keys below. Export and Share wait for the rows to finish. -- View value... shows the focused cell whole in a dialog, read only, with Copy: an image where a system codec decodes the bytes (`ResultSet.GetCellBytes`, `BitmapDecoder`), at its own size up to the dialog's and decoded at 2,048 pixels on its longer side at most, a picture past 64 megapixels as hex instead, JSON laid out one member per line where the text is one object or array, otherwise the text, and a binary value as its 0x hex. The JSON layout keeps each string's escapes and each number's digits as stored, which a serializer would not. The text and the JSON layout show their first 1,000,000 characters and the hex its first 256 KiB, saying so; Copy takes the whole value. A pending edit shows as typed; NULL and DEFAULT show as the grid words them. +- View value... shows the focused cell in a dialog, read only, with Copy: an image where a system codec decodes the bytes (`BitmapDecoder`), at its own size up to the dialog's and decoded at 2,048 pixels on its longer side at most, a picture past 64 megapixels as hex instead, JSON laid out one member per line where the text is one object or array, otherwise the text, and a binary value as its 0x hex. The JSON layout keeps each string's escapes and each number's digits as stored, which a serializer would not. A cell is read only as far as the dialog goes (`ResultSet.GetCellTextHead`, `GetCellBytes`), since a cell can hold more than the app should copy: the text and the JSON layout show their first 1,000,000 characters, the hex its first 256 KiB, and a picture is decoded only from a value of 16 MiB at most read whole. A cut value says so, and Copy takes what shows. A pending edit shows as typed; NULL and DEFAULT show as the grid words them. - A table tab reads its table's foreign keys both ways once its first page shows, and again on Refresh (`ReadTableKeysAsync`, in one operation, as the Linux app reads them). The menu on a cell offers Open referenced row for the keys its column is in, a submenu when there are several, and Show referencing rows for the other tables' keys pointing at the row, each named by the other table and the key's columns, with the constraint where two read alike. The core builds each filter from the row as the server holds it (`TableKeys.GetRowReferences`, `browse::RowReference`), so a key whose cells hold a pending edit, a new row and a row marked for delete offer none. A key with a NULL leads nowhere and is left out; one the core refuses, such as columns that compare under another collation, is offered and says why when chosen. - A chosen key opens the other table in a new tab beside this one, its filter the key's columns equal to the row's values, kept with the tab as a filter the user set; a tab whose rows were read under exactly that filter, and is not reading others, comes forward instead. diff --git a/windows/src/TablePro.App.Model/CellValue.cs b/windows/src/TablePro.App.Model/CellValue.cs index ccddc44b0c..2d0e7b391d 100644 --- a/windows/src/TablePro.App.Model/CellValue.cs +++ b/windows/src/TablePro.App.Model/CellValue.cs @@ -5,18 +5,26 @@ namespace TablePro.App.Model; -// One cell as the value viewer shows it: the text, or the bytes of a binary value. Neither is set for NULL. -public sealed record CellValue(string Column, string? Text, byte[]? Bytes, bool IsDefault) +// One cell as the value viewer shows it, read only as far as the viewer goes, since a cell can hold far more than +// the app should copy: the text's start, or a binary value's first bytes and its length. Neither is set for NULL. +public sealed record CellValue(string Column, string? Text, bool TextCut, ReadOnlyMemory? Bytes, long ByteLength, + bool IsDefault) { - // A TextBox lays out all it holds, so the viewer shows a long value's start; Copy takes the whole. + // A TextBox lays out all it holds, so the viewer shows a long value's start. public const int MaximumShownCharacters = 1_000_000; public const int MaximumHexBytes = 256 * 1024; + // A picture is decoded only when read whole, so this bounds what a binary cell copies into the app. + public const int MaximumPictureBytes = 16 * 1024 * 1024; + public bool IsNull => Text is null && Bytes is null && !IsDefault; - // The grid's text with its pending edit, and a binary value's bytes as the server holds them. A deleted row - // still shows what it holds; a new row and a changed cell have no bytes, only the text typed. + // A binary value read whole, which a picture needs. + public bool IsWholeBinary => Bytes is { } bytes && bytes.Length == ByteLength; + + // The grid's text with its pending edit, and the server's value otherwise. A deleted row still shows what it + // holds; a new row and a changed cell show the text typed. public static CellValue? Read(IGridData data, ResultSet? rows, int row, int column) { ArgumentNullException.ThrowIfNull(data); @@ -37,33 +45,43 @@ public sealed record CellValue(string Column, string? Text, byte[]? Bytes, bool var name = data.GetColumnName(column); if ((state & CellState.Default) != 0) { - return new CellValue(name, null, null, IsDefault: true); + return new CellValue(name, null, false, null, 0, IsDefault: true); } var pending = (state & (CellState.Modified | CellState.Inserted)) != 0; - if (!pending && rows is not null && row < rows.RowCount && rows.GetCellBytes(row, column) is { } bytes) + if (pending || rows is null || row >= rows.RowCount) { - return new CellValue(name, null, bytes, IsDefault: false); + // Text the user typed, or text the app holds itself, is in memory already. + return Of(name, reader.ReadWhole(row, column)); } - return new CellValue(name, reader.ReadWhole(row, column), null, IsDefault: false); - } + if (rows.GetCellBytes(row, column, MaximumPictureBytes) is { } binary) + { + return new CellValue(name, null, false, binary.Bytes, binary.Length, IsDefault: false); + } - // What Copy puts on the clipboard: the text, or a binary value in the 0x form the grid shows. Built only when - // asked, since a large value's hex is twice its size. - public string? CopyText() => Bytes is { } bytes ? "0x" + Convert.ToHexStringLower(bytes) : Text; + return rows.GetCellTextHead(row, column, MaximumShownCharacters) is { } head + ? new CellValue(name, head.Text, head.Cut, null, 0, IsDefault: false) + : new CellValue(name, null, false, null, 0, IsDefault: false); + } - public (string Text, bool Cut) ShownText() + public static CellValue Of(string column, string? text) { - if (Text is not { Length: > MaximumShownCharacters } text) + ArgumentNullException.ThrowIfNull(column); + if (text is not { Length: > MaximumShownCharacters }) { - return (Text ?? string.Empty, false); + return new CellValue(column, text, false, null, 0, IsDefault: false); } var end = char.IsHighSurrogate(text[MaximumShownCharacters - 1]) ? MaximumShownCharacters - 1 : MaximumShownCharacters; - return (text[..end], true); + return new CellValue(column, text[..end], true, null, 0, IsDefault: false); } + public bool CanCopy => Text is not null || Bytes is not null; + + // The viewer shows only a start of a long value, so that start is what Copy takes, never more than was read. + public string? CopyText() => Bytes is not null ? Hex().Text : Text; + // The 0x form of the first MaximumHexBytes, the way the grid shows a binary value. public (string Text, bool Cut) Hex() { @@ -72,13 +90,12 @@ public sealed record CellValue(string Column, string? Text, byte[]? Bytes, bool return (string.Empty, false); } - var shown = bytes.AsSpan(0, Math.Min(bytes.Length, MaximumHexBytes)); - return ("0x" + Convert.ToHexStringLower(shown), shown.Length < bytes.Length); + var shown = bytes.Span[..Math.Min(bytes.Length, MaximumHexBytes)]; + return ("0x" + Convert.ToHexStringLower(shown), shown.Length < ByteLength); } - public (string Text, bool Cut)? Json() => Text is { } text ? JsonText.Indent(text, MaximumShownCharacters) : null; - - public bool CanCopy => Text is not null || Bytes is not null; + // A text cut short is not one JSON value, so only a whole text has a JSON layout. + public (string Text, bool Cut)? Json() => Text is { } text && !TextCut ? JsonText.Indent(text, MaximumShownCharacters) : null; } // JSON laid out one member per line, token by token from the reader's raw spans, so each string keeps the escapes diff --git a/windows/src/TablePro.App/Strings/en-US/Resources.resw b/windows/src/TablePro.App/Strings/en-US/Resources.resw index dd5d0d85b0..95ec3da1f2 100644 --- a/windows/src/TablePro.App/Strings/en-US/Resources.resw +++ b/windows/src/TablePro.App/Strings/en-US/Resources.resw @@ -1828,7 +1828,7 @@ New fingerprint: {2} Close - Only the start of this value shows here. Copy takes all of it. + Only the start of this value shows here, and Copy takes that part. The value could not be put on the clipboard. diff --git a/windows/src/TablePro.App/Views/CellValueViewer.cs b/windows/src/TablePro.App/Views/CellValueViewer.cs index a5fc6c30d9..5a4abf245a 100644 --- a/windows/src/TablePro.App/Views/CellValueViewer.cs +++ b/windows/src/TablePro.App/Views/CellValueViewer.cs @@ -38,7 +38,9 @@ public static async Task ShowAsync(FrameworkElement owner, CellValue value) { ArgumentNullException.ThrowIfNull(owner); ArgumentNullException.ThrowIfNull(value); - var picture = value.Bytes is { Length: > 0 } bytes ? await DecodeAsync(bytes).ConfigureAwait(true) : null; + var picture = value.IsWholeBinary && value.Bytes is { Length: > 0 } bytes + ? await DecodeAsync(bytes.ToArray()).ConfigureAwait(true) + : null; var json = value.Json(); var modes = new List(); if (picture is not null) @@ -100,7 +102,7 @@ void Show(Mode mode) { Mode.Json => json!.Value, Mode.Hex => value.Hex(), - Mode.Text => value.ShownText(), + Mode.Text => (value.Text ?? string.Empty, value.TextCut), _ => (string.Empty, false), }; image.Visibility = mode == Mode.Image ? Visibility.Visible : Visibility.Collapsed; diff --git a/windows/src/TablePro.Interop/Generated/tablepro_ffi.cs b/windows/src/TablePro.Interop/Generated/tablepro_ffi.cs index 02dcccacd3..82fac9b89b 100644 --- a/windows/src/TablePro.Interop/Generated/tablepro_ffi.cs +++ b/windows/src/TablePro.Interop/Generated/tablepro_ffi.cs @@ -1168,6 +1168,8 @@ public struct UniffiVTableCallbackInterfaceRunListener + + @@ -2016,7 +2018,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - RustBuffer uniffi_tablepro_ffi_fn_method_resultset_cell_bytes(ulong @ptr,ulong @row,uint @column,ref UniffiRustCallStatus _uniffi_out_err + RustBuffer uniffi_tablepro_ffi_fn_method_resultset_cell_bytes(ulong @ptr,ulong @row,uint @column,ulong @maxBytes,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2030,6 +2032,17 @@ public static extern RustBuffer uniffi_tablepro_ffi_fn_method_resultset_cell_text(ulong @ptr,ulong @row,uint @column,ref UniffiRustCallStatus _uniffi_out_err ); + #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 + RustBuffer uniffi_tablepro_ffi_fn_method_resultset_cell_text_head(ulong @ptr,ulong @row,uint @column,uint @maxChars,ref UniffiRustCallStatus _uniffi_out_err + ); + #if NET8_0_OR_GREATER [LibraryImport("tablepro_ffi")] [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] @@ -4087,6 +4100,17 @@ public static extern ushort uniffi_tablepro_ffi_checksum_method_resultset_cell_text( ); + #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_resultset_cell_text_head( + ); + #if NET8_0_OR_GREATER [LibraryImport("tablepro_ffi")] [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] @@ -5212,8 +5236,8 @@ static void uniffiCheckApiChecksums() { } { var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_resultset_cell_bytes(); - if (checksum != 39609) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_resultset_cell_bytes` checksum `39609`, library returned `{checksum}`"); + if (checksum != 40157) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_resultset_cell_bytes` checksum `40157`, library returned `{checksum}`"); } } { @@ -5222,6 +5246,12 @@ static void uniffiCheckApiChecksums() { throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_resultset_cell_text` checksum `54600`, library returned `{checksum}`"); } } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_resultset_cell_text_head(); + if (checksum != 5341) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_resultset_cell_text_head` checksum `5341`, library returned `{checksum}`"); + } + } { var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_resultset_columns(); if (checksum != 43715) { @@ -8495,9 +8525,11 @@ internal interface IResultSet { /// Task ShareSummary(uint @visibleColumns, uint @maxRows, ShareColumnChoice[] @columns); /// - byte[]? CellBytes(ulong @row, uint @column); + CellBytes? CellBytes(ulong @row, uint @column, ulong @maxBytes); /// string? CellText(ulong @row, uint @column); + /// + CellTextHead? CellTextHead(ulong @row, uint @column, uint @maxChars); ResultColumnInfo[] Columns(); /// /// Its place among the run's result sets, from 0. @@ -8668,10 +8700,10 @@ public async Task ShareSummary(uint @visibleColumns, uint @maxRows } /// - public byte[]? CellBytes(ulong @row, uint @column) { - return CallWithPointer(thisPtr => FfiConverterOptionalByteArray.INSTANCE.Lift( + public CellBytes? CellBytes(ulong @row, uint @column, ulong @maxBytes) { + return CallWithPointer(thisPtr => FfiConverterOptionalTypeCellBytes.INSTANCE.Lift( _UniffiHelpers.RustCallWithError(FfiConverterTypeCoreError.INSTANCE, (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_resultset_cell_bytes(thisPtr, FfiConverterUInt64.INSTANCE.Lower(@row), FfiConverterUInt32.INSTANCE.Lower(@column), ref _status) + _UniFFILib.uniffi_tablepro_ffi_fn_method_resultset_cell_bytes(thisPtr, FfiConverterUInt64.INSTANCE.Lower(@row), FfiConverterUInt32.INSTANCE.Lower(@column), FfiConverterUInt64.INSTANCE.Lower(@maxBytes), ref _status) ))); } @@ -8685,6 +8717,15 @@ public async Task ShareSummary(uint @visibleColumns, uint @maxRows } + /// + public CellTextHead? CellTextHead(ulong @row, uint @column, uint @maxChars) { + return CallWithPointer(thisPtr => FfiConverterOptionalTypeCellTextHead.INSTANCE.Lift( + _UniffiHelpers.RustCallWithError(FfiConverterTypeCoreError.INSTANCE, (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_resultset_cell_text_head(thisPtr, FfiConverterUInt64.INSTANCE.Lower(@row), FfiConverterUInt32.INSTANCE.Lower(@column), FfiConverterUInt32.INSTANCE.Lower(@maxChars), ref _status) +))); + } + + public ResultColumnInfo[] Columns() { return CallWithPointer(thisPtr => FfiConverterSequenceTypeResultColumnInfo.INSTANCE.Lift( _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => @@ -9533,6 +9574,36 @@ public override void Write(AccountStatusInfo value, BigEndianStream stream) { +internal record CellBytes ( + byte[] Bytes, + ulong Length +) { +} + +class FfiConverterTypeCellBytes: FfiConverterRustBuffer { + public static FfiConverterTypeCellBytes INSTANCE = new FfiConverterTypeCellBytes(); + + public override CellBytes Read(BigEndianStream stream) { + return new CellBytes( + Bytes: FfiConverterByteArray.INSTANCE.Read(stream), + Length: FfiConverterUInt64.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(CellBytes value) { + return 0 + + FfiConverterByteArray.INSTANCE.AllocationSize(value.Bytes) + + FfiConverterUInt64.INSTANCE.AllocationSize(value.Length); + } + + public override void Write(CellBytes value, BigEndianStream stream) { + FfiConverterByteArray.INSTANCE.Write(value.Bytes, stream); + FfiConverterUInt64.INSTANCE.Write(value.Length, stream); + } +} + + + internal record CellChange ( uint Column, CellEdit Edit @@ -9563,6 +9634,36 @@ public override void Write(CellChange value, BigEndianStream stream) { +internal record CellTextHead ( + string Text, + bool Cut +) { +} + +class FfiConverterTypeCellTextHead: FfiConverterRustBuffer { + public static FfiConverterTypeCellTextHead INSTANCE = new FfiConverterTypeCellTextHead(); + + public override CellTextHead Read(BigEndianStream stream) { + return new CellTextHead( + Text: FfiConverterString.INSTANCE.Read(stream), + Cut: FfiConverterBoolean.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(CellTextHead value) { + return 0 + + FfiConverterString.INSTANCE.AllocationSize(value.Text) + + FfiConverterBoolean.INSTANCE.AllocationSize(value.Cut); + } + + public override void Write(CellTextHead value, BigEndianStream stream) { + FfiConverterString.INSTANCE.Write(value.Text, stream); + FfiConverterBoolean.INSTANCE.Write(value.Cut, stream); + } +} + + + internal record CloudConnectionFields ( string ConnectionId, string? Name, @@ -16885,30 +16986,30 @@ public override void Write(string? value, BigEndianStream stream) { -class FfiConverterOptionalByteArray: FfiConverterRustBuffer { - public static FfiConverterOptionalByteArray INSTANCE = new FfiConverterOptionalByteArray(); +class FfiConverterOptionalTypeCancelToken: FfiConverterRustBuffer { + public static FfiConverterOptionalTypeCancelToken INSTANCE = new FfiConverterOptionalTypeCancelToken(); - public override byte[]? Read(BigEndianStream stream) { + public override CancelToken? Read(BigEndianStream stream) { if (stream.ReadByte() == 0) { return null; } - return FfiConverterByteArray.INSTANCE.Read(stream); + return FfiConverterTypeCancelToken.INSTANCE.Read(stream); } - public override int AllocationSize(byte[]? value) { + public override int AllocationSize(CancelToken? value) { if (value == null) { return 1; } else { - return 1 + FfiConverterByteArray.INSTANCE.AllocationSize((byte[])value); + return 1 + FfiConverterTypeCancelToken.INSTANCE.AllocationSize((CancelToken)value); } } - public override void Write(byte[]? value, BigEndianStream stream) { + public override void Write(CancelToken? value, BigEndianStream stream) { if (value == null) { stream.WriteByte(0); } else { stream.WriteByte(1); - FfiConverterByteArray.INSTANCE.Write((byte[])value, stream); + FfiConverterTypeCancelToken.INSTANCE.Write((CancelToken)value, stream); } } } @@ -16916,30 +17017,30 @@ public override void Write(byte[]? value, BigEndianStream stream) { -class FfiConverterOptionalTypeCancelToken: FfiConverterRustBuffer { - public static FfiConverterOptionalTypeCancelToken INSTANCE = new FfiConverterOptionalTypeCancelToken(); +class FfiConverterOptionalTypeResultSet: FfiConverterRustBuffer { + public static FfiConverterOptionalTypeResultSet INSTANCE = new FfiConverterOptionalTypeResultSet(); - public override CancelToken? Read(BigEndianStream stream) { + public override ResultSet? Read(BigEndianStream stream) { if (stream.ReadByte() == 0) { return null; } - return FfiConverterTypeCancelToken.INSTANCE.Read(stream); + return FfiConverterTypeResultSet.INSTANCE.Read(stream); } - public override int AllocationSize(CancelToken? value) { + public override int AllocationSize(ResultSet? value) { if (value == null) { return 1; } else { - return 1 + FfiConverterTypeCancelToken.INSTANCE.AllocationSize((CancelToken)value); + return 1 + FfiConverterTypeResultSet.INSTANCE.AllocationSize((ResultSet)value); } } - public override void Write(CancelToken? value, BigEndianStream stream) { + public override void Write(ResultSet? value, BigEndianStream stream) { if (value == null) { stream.WriteByte(0); } else { stream.WriteByte(1); - FfiConverterTypeCancelToken.INSTANCE.Write((CancelToken)value, stream); + FfiConverterTypeResultSet.INSTANCE.Write((ResultSet)value, stream); } } } @@ -16947,30 +17048,61 @@ public override void Write(CancelToken? value, BigEndianStream stream) { -class FfiConverterOptionalTypeResultSet: FfiConverterRustBuffer { - public static FfiConverterOptionalTypeResultSet INSTANCE = new FfiConverterOptionalTypeResultSet(); +class FfiConverterOptionalTypeCellBytes: FfiConverterRustBuffer { + public static FfiConverterOptionalTypeCellBytes INSTANCE = new FfiConverterOptionalTypeCellBytes(); - public override ResultSet? Read(BigEndianStream stream) { + public override CellBytes? Read(BigEndianStream stream) { if (stream.ReadByte() == 0) { return null; } - return FfiConverterTypeResultSet.INSTANCE.Read(stream); + return FfiConverterTypeCellBytes.INSTANCE.Read(stream); } - public override int AllocationSize(ResultSet? value) { + public override int AllocationSize(CellBytes? value) { if (value == null) { return 1; } else { - return 1 + FfiConverterTypeResultSet.INSTANCE.AllocationSize((ResultSet)value); + return 1 + FfiConverterTypeCellBytes.INSTANCE.AllocationSize((CellBytes)value); } } - public override void Write(ResultSet? value, BigEndianStream stream) { + public override void Write(CellBytes? value, BigEndianStream stream) { if (value == null) { stream.WriteByte(0); } else { stream.WriteByte(1); - FfiConverterTypeResultSet.INSTANCE.Write((ResultSet)value, stream); + FfiConverterTypeCellBytes.INSTANCE.Write((CellBytes)value, stream); + } + } +} + + + + +class FfiConverterOptionalTypeCellTextHead: FfiConverterRustBuffer { + public static FfiConverterOptionalTypeCellTextHead INSTANCE = new FfiConverterOptionalTypeCellTextHead(); + + public override CellTextHead? Read(BigEndianStream stream) { + if (stream.ReadByte() == 0) { + return null; + } + return FfiConverterTypeCellTextHead.INSTANCE.Read(stream); + } + + public override int AllocationSize(CellTextHead? value) { + if (value == null) { + return 1; + } else { + return 1 + FfiConverterTypeCellTextHead.INSTANCE.AllocationSize((CellTextHead)value); + } + } + + public override void Write(CellTextHead? value, BigEndianStream stream) { + if (value == null) { + stream.WriteByte(0); + } else { + stream.WriteByte(1); + FfiConverterTypeCellTextHead.INSTANCE.Write((CellTextHead)value, stream); } } } diff --git a/windows/src/TablePro.Interop/ResultSet.cs b/windows/src/TablePro.Interop/ResultSet.cs index 5b2fb828fc..5c13d69c4d 100644 --- a/windows/src/TablePro.Interop/ResultSet.cs +++ b/windows/src/TablePro.Interop/ResultSet.cs @@ -2,6 +2,11 @@ namespace TablePro.Interop; +public sealed record CellTextHead(string Text, bool Cut); + +// Bytes is the value's start, Length the whole value's. +public sealed record CellBytes(ReadOnlyMemory Bytes, long Length); + // Held by the core and readable while its rows still arrive. public sealed class ResultSet : IDisposable { @@ -31,12 +36,25 @@ internal ResultSet(Native.ResultSet set, int index) return CoreCall.Run(() => _set.CellText(checked((ulong)row), checked((uint)column))); } - // Every byte of a binary value, for an image or a hex view. Null for SQL NULL or a value that is not binary. - public byte[]? GetCellBytes(long row, int column) + // A value's start for a viewer, read without copying the rest: its text with line breaks kept, or a binary + // value's hex. Null for SQL NULL. + public CellTextHead? GetCellTextHead(long row, int column, int maxCharacters) + { + ArgumentOutOfRangeException.ThrowIfNegative(row); + ArgumentOutOfRangeException.ThrowIfNegative(column); + ArgumentOutOfRangeException.ThrowIfNegative(maxCharacters); + return CoreCall.Run(() => _set.CellTextHead(checked((ulong)row), checked((uint)column), (uint)maxCharacters)) + is { } head ? new CellTextHead(head.Text, head.Cut) : null; + } + + // A binary value's first maxBytes and its whole length. Null for SQL NULL or a value that is not binary. + public CellBytes? GetCellBytes(long row, int column, long maxBytes) { ArgumentOutOfRangeException.ThrowIfNegative(row); ArgumentOutOfRangeException.ThrowIfNegative(column); - return CoreCall.Run(() => _set.CellBytes(checked((ulong)row), checked((uint)column))); + ArgumentOutOfRangeException.ThrowIfNegative(maxBytes); + return CoreCall.Run(() => _set.CellBytes(checked((ulong)row), checked((uint)column), (ulong)maxBytes)) + is { } binary ? new CellBytes(binary.Bytes, Mapping.Count(binary.Length)) : null; } // Each thread that reads windows opens its own. diff --git a/windows/tests/TablePro.App.Model.Tests/CellValueTests.cs b/windows/tests/TablePro.App.Model.Tests/CellValueTests.cs index c565a61020..d0f958f71c 100644 --- a/windows/tests/TablePro.App.Model.Tests/CellValueTests.cs +++ b/windows/tests/TablePro.App.Model.Tests/CellValueTests.cs @@ -54,45 +54,48 @@ public void ALayoutPastItsLimitStopsThereButStillChecksTheRest() public void TextThatIsNotOneObjectOrArrayHasNoJsonView(string text) => Assert.Null(JsonText.Indent(text)); [Fact] - public void BinaryShowsAsHexUpToItsLimitAndCopiesWhole() + public void BinaryShowsAndCopiesItsHexUpToItsLimitAndOnlyAWholeValueIsAPicture() { - var small = new CellValue("body", null, [0xde, 0xad], IsDefault: false); - var large = new CellValue("body", null, new byte[CellValue.MaximumHexBytes + 1], IsDefault: false); + var small = new CellValue("body", null, false, new byte[] { 0xde, 0xad }, 2, IsDefault: false); + var large = new CellValue("body", null, false, new byte[CellValue.MaximumHexBytes + 1], 40_000_000, IsDefault: false); Assert.Equal(("0xdead", false), small.Hex()); Assert.Equal("0xdead", small.CopyText()); + Assert.True(small.IsWholeBinary); var (hex, cut) = large.Hex(); Assert.True(cut); Assert.Equal(2 + (CellValue.MaximumHexBytes * 2), hex.Length); - Assert.Equal(2 + ((CellValue.MaximumHexBytes + 1) * 2), large.CopyText()!.Length); + Assert.Equal(hex, large.CopyText()); + Assert.False(large.IsWholeBinary); Assert.False(small.IsNull); Assert.Null(small.Json()); } [Fact] - public void LongTextShowsItsStartWithoutSplittingACharacterAndCopiesWhole() + public void LongTextKeepsItsStartWithoutSplittingACharacterAndHasNoJsonLayout() { - var text = new string('a', CellValue.MaximumShownCharacters - 1) + "👋" + "tail"; - var value = new CellValue("note", text, null, IsDefault: false); + var text = "[" + new string('1', CellValue.MaximumShownCharacters - 2) + "👋" + "]"; - var (shown, cut) = value.ShownText(); + var value = CellValue.Of("note", text); - Assert.True(cut); - Assert.Equal(CellValue.MaximumShownCharacters - 1, shown.Length); - Assert.Equal(text, value.CopyText()); - Assert.Equal((string.Empty, false), new CellValue("note", null, null, IsDefault: false).ShownText()); - Assert.True(new CellValue("note", null, null, IsDefault: false).IsNull); - Assert.False(new CellValue("note", null, null, IsDefault: true).IsNull); + Assert.True(value.TextCut); + Assert.Equal(CellValue.MaximumShownCharacters - 1, value.Text!.Length); + Assert.Equal(value.Text, value.CopyText()); + Assert.Null(value.Json()); + Assert.False(CellValue.Of("note", "[1]").TextCut); + Assert.True(CellValue.Of("note", null).IsNull); + Assert.False(new CellValue("note", null, false, null, 0, IsDefault: true).IsNull); + Assert.False(new CellValue("note", null, false, null, 0, IsDefault: true).CanCopy); } [Fact] - public void ACellReadsWholeThroughTheGridsData() + public void ACellTheAppHoldsReadsThroughTheGridsData() { var data = new TextGridData(["doc", "note"], [["{\"a\":1}", null]]); var doc = CellValue.Read(data, null, 0, 0)!; - Assert.Equal(new CellValue("doc", "{\"a\":1}", null, IsDefault: false), doc); + Assert.Equal(CellValue.Of("doc", "{\"a\":1}"), doc); Assert.Equal(("{\n \"a\": 1\n}", false), doc.Json()); Assert.True(CellValue.Read(data, null, 0, 1)!.IsNull); Assert.Null(CellValue.Read(data, null, 1, 0)); diff --git a/windows/tests/TablePro.Interop.Tests/RowReferenceTests.cs b/windows/tests/TablePro.Interop.Tests/RowReferenceTests.cs index c27cdcab58..5d314dc63d 100644 --- a/windows/tests/TablePro.Interop.Tests/RowReferenceTests.cs +++ b/windows/tests/TablePro.Interop.Tests/RowReferenceTests.cs @@ -89,20 +89,25 @@ await database.ExecuteAsync(""" } [Fact] - public async Task ABinaryCellGivesItsBytesAndOtherCellsNone() + public async Task ACellReadsOnlyItsStartAndABinaryCellItsFirstBytesWithItsLength() { var cancel = TestContext.Current.CancellationToken; await using var database = await SqliteDatabase.CreateAsync(); await database.ExecuteAsync(""" CREATE TABLE files (id INTEGER PRIMARY KEY, body BLOB, note TEXT); - INSERT INTO files VALUES (1, X'89504E47', 'png'), (2, NULL, NULL); + INSERT INTO files VALUES (1, X'89504E47', 'line one' || char(10) || 'line two'), (2, NULL, NULL); """); using var files = await ReadAsync(database.Session, new TableName(null, "files"), null, cancel); - Assert.Equal([0x89, 0x50, 0x4e, 0x47], files.GetCellBytes(0, 1)); - Assert.Null(files.GetCellBytes(0, 2)); - Assert.Null(files.GetCellBytes(1, 1)); - Assert.Equal("ffi.out_of_range", Assert.Throws(() => files.GetCellBytes(5, 1)).Code); + var first = files.GetCellBytes(0, 1, 2)!; + Assert.Equal([0x89, 0x50], first.Bytes.ToArray()); + Assert.Equal(4, first.Length); + Assert.Null(files.GetCellBytes(0, 2, 100)); + Assert.Null(files.GetCellBytes(1, 1, 100)); + Assert.Equal(new CellTextHead("line one\nline two", false), files.GetCellTextHead(0, 2, 100)); + Assert.Equal(new CellTextHead("line", true), files.GetCellTextHead(0, 2, 4)); + Assert.Null(files.GetCellTextHead(1, 2, 100)); + Assert.Equal("ffi.out_of_range", Assert.Throws(() => files.GetCellBytes(5, 1, 100)).Code); } private static async Task ReadAsync( From 29d1a6ac2e1420fcb9860b24d344292d45358856 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sat, 14 Nov 2026 20:39:23 +0700 Subject: [PATCH 03/13] fix(core): refuse a foreign key value past 8 KiB before copying it for a menu --- core/crates/ffi/src/references.rs | 8 +++++++ core/crates/ffi/src/results/result_set.rs | 5 +++++ core/crates/ffi/src/results/store.rs | 4 ++++ core/crates/ffi/tests/browse.rs | 21 +++++++++++++++++++ .../0022-browsing-through-the-ffi.md | 2 +- 5 files changed, 39 insertions(+), 1 deletion(-) diff --git a/core/crates/ffi/src/references.rs b/core/crates/ffi/src/references.rs index 4cfbf7645c..484be846e6 100644 --- a/core/crates/ffi/src/references.rs +++ b/core/crates/ffi/src/references.rs @@ -133,6 +133,10 @@ impl TableKeys { } } +// A key value past this has no filter: every key of a row is built as a menu opens, and a row could hold many +// keys of megabytes each. +const MAX_KEY_BYTES: usize = 8 * 1024; + // Only the key's cells are copied, so a row of large values stays in the store. A value the store cannot name // exactly, such as a float, has no text a filter would match. fn key_cells( @@ -150,6 +154,10 @@ fn key_cells( let Some(index) = read.iter().position(|column| column.name == *name) else { return Err(ReferenceError::MissingColumn { column: name.clone() }); }; + if rows.cell_len(row, index).is_some_and(|length| length > MAX_KEY_BYTES) { + unnamed.get_or_insert(position); + continue; + } match rows.stored_value(row, index) { Some(Value::Null) => return Err(ReferenceError::NullKey), Some(value) => { diff --git a/core/crates/ffi/src/results/result_set.rs b/core/crates/ffi/src/results/result_set.rs index 3c01ed3817..e731b0862c 100644 --- a/core/crates/ffi/src/results/result_set.rs +++ b/core/crates/ffi/src/results/result_set.rs @@ -52,6 +52,11 @@ impl ResultSet { self.store.stored_value(self.stored_row(row), column) } + // The bytes the store keeps for a cell, so a caller can refuse a large value before copying it. + pub(crate) fn cell_len(&self, row: u64, column: usize) -> Option { + self.store.cell_len(self.stored_row(row), column) + } + pub(crate) fn cell_kind(&self, row: u64, column: usize) -> Option> { self.store.cell_kind(self.stored_row(row), column) } diff --git a/core/crates/ffi/src/results/store.rs b/core/crates/ffi/src/results/store.rs index 1658421c4e..a495b626ef 100644 --- a/core/crates/ffi/src/results/store.rs +++ b/core/crates/ffi/src/results/store.rs @@ -194,6 +194,10 @@ impl ResultStore { stored_value(state.cell(row, column)?, read) } + pub(crate) fn cell_len(&self, row: u64, column: usize) -> Option { + Some(self.read().cell(row, column)?.bytes.len()) + } + // The kind of the value in a cell, `None` for null; a dynamically typed column can hold any. pub(crate) fn cell_kind(&self, row: u64, column: usize) -> Option> { Some(self.read().cell(row, column)?.kind) diff --git a/core/crates/ffi/tests/browse.rs b/core/crates/ffi/tests/browse.rs index d181db1367..bde0e21f32 100644 --- a/core/crates/ffi/tests/browse.rs +++ b/core/crates/ffi/tests/browse.rs @@ -689,6 +689,27 @@ async fn keys_that_compare_otherwise_or_hold_an_inexact_value_stay_as_refusals() ); assert_eq!(collated.referencing[0].filter, None); + execute( + &session, + "CREATE TABLE big (code TEXT PRIMARY KEY); CREATE TABLE small (code TEXT REFERENCES big(code)); \ + INSERT INTO big VALUES (printf('%.9000c', 'x')); INSERT INTO small SELECT code FROM big", + ) + .await; + let big = page_rows(&session, "big", None).await; + let large = session + .table_keys(table("big"), None) + .await + .unwrap() + .row_references(big, 0, None) + .unwrap(); + assert_eq!( + large.referencing[0].refusal, + Some(ReferenceRefusal::NoFilterText { + column: "code".to_owned() + }), + "a key too long to filter on is refused before it is copied" + ); + let measured = page_rows(&session, "measured", None).await; let inexact = session .table_keys(table("measured"), None) diff --git a/core/docs/decisions/0022-browsing-through-the-ffi.md b/core/docs/decisions/0022-browsing-through-the-ffi.md index f2d9e5ba18..14d79af70b 100644 --- a/core/docs/decisions/0022-browsing-through-the-ffi.md +++ b/core/docs/decisions/0022-browsing-through-the-ffi.md @@ -18,7 +18,7 @@ The FFI exposes what the Linux app calls, and does the work the Linux app does, - `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. - `object_definition` reads `fetch_object_definition` for a function, procedure, trigger or sequence, with whether running the text in an editor would make the object as it is. - `export_rows` writes the rows a finished `ResultSet` holds, its visible columns only; `export_table` streams every row the filter and sort select through `build_export` and `stream_read`, as the Linux app exports a table. Both use the core's encoders (CSV with its default options, JSON, Excel, Markdown, HTML, XML, and SQL INSERT from a table), write beside the target and rename once complete, so a failed or cancelled export leaves no file. -- `DatabaseSession::table_keys` reads a table's outbound and inbound foreign keys in one Metadata operation, as the Linux browse tab reads them. Its `TableKeys::row_references` builds, without the server, what a row of a page of that table leads to through `browse::RowReference`, from the row's stored values: the table's keys holding a column, and the other tables' keys pointing at the row. A key with a NULL or a column the page lacks is left out; one whose value the store cannot name exactly, or that `RowReference` refuses, comes back with its refusal for the app to word. +- `DatabaseSession::table_keys` reads a table's outbound and inbound foreign keys in one Metadata operation, as the Linux browse tab reads them. Its `TableKeys::row_references` builds, without the server, what a row of a page of that table leads to through `browse::RowReference`, from the row's stored values: the table's keys holding a column, and the other tables' keys pointing at the row. A key with a NULL or a column the page lacks is left out; one whose value the store cannot name exactly or holds more than 8 KiB, or that `RowReference` refuses, comes back with its refusal for the app to word. The size bound holds because every key of a row is built as a menu opens. - `ResultSet::cell_text_head` gives a value's start, line breaks kept, and `cell_bytes` a binary value's first bytes and its length, so an app's viewer copies no more of a large cell than it shows, where `cell_text` copies all of it. - `Core::history` opens the query history at `/state/history.db` once. `record` takes the session, so the engine's `history_recording` withholds a statement that holds a secret, as on Linux; `search` pages by the store's keyset; `delete` and `clear` change it. From 20754fc53815348d295dc2d9a831bcc4dd7ea41a Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sat, 14 Nov 2026 20:44:01 +0700 Subject: [PATCH 04/13] fix(windows): decode only a picture's first frame at a bounded size in the value viewer --- .../decisions/0007-browsing-a-connection.md | 2 +- .../src/TablePro.App/Views/CellValueViewer.cs | 50 +++++++++++++------ 2 files changed, 35 insertions(+), 17 deletions(-) diff --git a/windows/docs/decisions/0007-browsing-a-connection.md b/windows/docs/decisions/0007-browsing-a-connection.md index 70873e9c5d..bd4034f822 100644 --- a/windows/docs/decisions/0007-browsing-a-connection.md +++ b/windows/docs/decisions/0007-browsing-a-connection.md @@ -27,7 +27,7 @@ Each one works as the macOS app's does, with its words in Windows sentence case, ### Grid menus, values and foreign keys - A results grid's menu, in a query tab and a table tab, holds Copy, View value..., Export results... and Share; a table tab's adds its row and cell edits and the foreign keys below. Export and Share wait for the rows to finish. -- View value... shows the focused cell in a dialog, read only, with Copy: an image where a system codec decodes the bytes (`BitmapDecoder`), at its own size up to the dialog's and decoded at 2,048 pixels on its longer side at most, a picture past 64 megapixels as hex instead, JSON laid out one member per line where the text is one object or array, otherwise the text, and a binary value as its 0x hex. The JSON layout keeps each string's escapes and each number's digits as stored, which a serializer would not. A cell is read only as far as the dialog goes (`ResultSet.GetCellTextHead`, `GetCellBytes`), since a cell can hold more than the app should copy: the text and the JSON layout show their first 1,000,000 characters, the hex its first 256 KiB, and a picture is decoded only from a value of 16 MiB at most read whole. A cut value says so, and Copy takes what shows. A pending edit shows as typed; NULL and DEFAULT show as the grid words them. +- View value... shows the focused cell in a dialog, read only, with Copy: an image where a system codec decodes the bytes, its first frame only (`BitmapDecoder.GetSoftwareBitmapAsync`, since an animated GIF's canvas can be far larger than its frames and BitmapImage would allocate the canvas), at its own size up to the dialog's and decoded at 2,048 pixels on its longer side at most, a picture past 64 megapixels as hex instead, JSON laid out one member per line where the text is one object or array, otherwise the text, and a binary value as its 0x hex. The JSON layout keeps each string's escapes and each number's digits as stored, which a serializer would not. A cell is read only as far as the dialog goes (`ResultSet.GetCellTextHead`, `GetCellBytes`), since a cell can hold more than the app should copy: the text and the JSON layout show their first 1,000,000 characters, the hex its first 256 KiB, and a picture is decoded only from a value of 16 MiB at most read whole. A cut value says so, and Copy takes what shows. A pending edit shows as typed; NULL and DEFAULT show as the grid words them. - A table tab reads its table's foreign keys both ways once its first page shows, and again on Refresh (`ReadTableKeysAsync`, in one operation, as the Linux app reads them). The menu on a cell offers Open referenced row for the keys its column is in, a submenu when there are several, and Show referencing rows for the other tables' keys pointing at the row, each named by the other table and the key's columns, with the constraint where two read alike. The core builds each filter from the row as the server holds it (`TableKeys.GetRowReferences`, `browse::RowReference`), so a key whose cells hold a pending edit, a new row and a row marked for delete offer none. A key with a NULL leads nowhere and is left out; one the core refuses, such as columns that compare under another collation, is offered and says why when chosen. - A chosen key opens the other table in a new tab beside this one, its filter the key's columns equal to the row's values, kept with the tab as a filter the user set; a tab whose rows were read under exactly that filter, and is not reading others, comes forward instead. diff --git a/windows/src/TablePro.App/Views/CellValueViewer.cs b/windows/src/TablePro.App/Views/CellValueViewer.cs index 5a4abf245a..312614c2d7 100644 --- a/windows/src/TablePro.App/Views/CellValueViewer.cs +++ b/windows/src/TablePro.App/Views/CellValueViewer.cs @@ -38,7 +38,7 @@ public static async Task ShowAsync(FrameworkElement owner, CellValue value) { ArgumentNullException.ThrowIfNull(owner); ArgumentNullException.ThrowIfNull(value); - var picture = value.IsWholeBinary && value.Bytes is { Length: > 0 } bytes + using var picture = value.IsWholeBinary && value.Bytes is { Length: > 0 } bytes ? await DecodeAsync(bytes.ToArray()).ConfigureAwait(true) : null; var json = value.Json(); @@ -84,11 +84,11 @@ public static async Task ShowAsync(FrameworkElement owner, CellValue value) // A picture smaller than the viewer shows at its own size, a larger one fits. var image = new Image { - Source = picture, + Source = picture?.Source, Stretch = Stretch.Uniform, HorizontalAlignment = HorizontalAlignment.Left, - MaxWidth = picture?.PixelWidth ?? 0, - MaxHeight = Math.Min(ViewerHeight, picture?.PixelHeight ?? 0), + MaxWidth = picture?.Width ?? 0, + MaxHeight = Math.Min(ViewerHeight, picture?.Height ?? 0), }; AutomationProperties.SetName(image, value.Column); AutomationProperties.SetAutomationId(image, "ValueViewerImage"); @@ -167,8 +167,10 @@ private static void Copy(CellValue value, InfoBar notice) } } - // Null where no codec on the system reads the bytes as an image, or the image is too large to decode here. - private static async Task DecodeAsync(byte[] bytes) + // Null where no codec on the system reads the bytes as an image, or the image is too large to decode here. Only + // the first frame is decoded, through the frame's own size: an animated GIF's canvas can be far larger than its + // frames, and BitmapImage would allocate the canvas. + private static async Task DecodeAsync(byte[] bytes) { using var stream = new InMemoryRandomAccessStream(); using (var writer = new DataWriter(stream)) @@ -188,25 +190,41 @@ private static void Copy(CellValue value, InfoBar notice) return null; } - // A picture larger than the viewer decodes at a size it can show, its longer side bounded, not at every - // pixel it holds; the other side follows the aspect ratio. - var bitmap = new BitmapImage(); - if (width >= height && width > DecodedSide) + // A picture larger than the viewer is decoded at a size it can show, its longer side bounded. + var scale = Math.Min(1.0, (double)DecodedSide / Math.Max(width, height)); + var transform = new BitmapTransform { - bitmap.DecodePixelWidth = DecodedSide; + ScaledWidth = Math.Max(1u, (uint)Math.Round(width * scale)), + ScaledHeight = Math.Max(1u, (uint)Math.Round(height * scale)), + InterpolationMode = BitmapInterpolationMode.Fant, + }; + using var bitmap = await decoder.GetSoftwareBitmapAsync( + BitmapPixelFormat.Bgra8, + BitmapAlphaMode.Premultiplied, + transform, + ExifOrientationMode.RespectExifOrientation, + ColorManagementMode.ColorManageToSRgb); + var source = new SoftwareBitmapSource(); + try + { + await source.SetBitmapAsync(bitmap); } - else if (height > width && height > DecodedSide) + catch { - bitmap.DecodePixelHeight = DecodedSide; + source.Dispose(); + throw; } - stream.Seek(0); - await bitmap.SetSourceAsync(stream); - return bitmap; + return new Picture(source, bitmap.PixelWidth, bitmap.PixelHeight); } catch (Exception error) when (error is COMException or ArgumentException or OutOfMemoryException) { return null; } } + + private sealed record Picture(SoftwareBitmapSource Source, int Width, int Height) : IDisposable + { + public void Dispose() => Source.Dispose(); + } } From 4e2ae4876adc74b0e7d70ea33b3e8f2b43e233d0 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sat, 14 Nov 2026 20:55:49 +0700 Subject: [PATCH 05/13] refactor(windows): list a row's foreign keys without their values and build the chosen one's filter on click --- core/crates/ffi/src/lib.rs | 2 +- core/crates/ffi/src/references.rs | 166 ++++++++++------ core/crates/ffi/tests/browse.rs | 179 ++++++++++-------- .../0022-browsing-through-the-ffi.md | 2 +- .../decisions/0007-browsing-a-connection.md | 2 +- windows/src/TablePro.App.Model/TabSession.cs | 8 + windows/src/TablePro.App.Model/TableTab.cs | 75 +++++--- .../TablePro.App/Views/TableTabView.xaml.cs | 59 +++--- .../TablePro.App/Views/WorkspaceView.xaml.cs | 9 +- .../Generated/tablepro_ffi.cs | 166 ++++++++++++---- .../TablePro.Interop/Mapping.References.cs | 37 ++-- windows/src/TablePro.Interop/RowReference.cs | 24 ++- windows/src/TablePro.Interop/TableKeys.cs | 13 +- .../TablePro.App.Model.Tests/TabFakes.cs | 10 + .../TableTabReferenceTests.cs | 87 +++++---- .../RowReferenceTests.cs | 38 ++-- 16 files changed, 569 insertions(+), 308 deletions(-) diff --git a/core/crates/ffi/src/lib.rs b/core/crates/ffi/src/lib.rs index db068c903e..1f58c984e6 100644 --- a/core/crates/ffi/src/lib.rs +++ b/core/crates/ffi/src/lib.rs @@ -67,7 +67,7 @@ pub use masking::{ ShareColumnMasking, ShareRefusal, ShareSummary, }; pub use prompter::{HostPrompter, PromptAnswer, PromptFieldInfo, PromptPurposeTag, PromptReasonTag, PromptRequest}; -pub use references::{ReferenceRefusal, RowReferenceChoice, RowReferences, TableKeys}; +pub use references::{FollowedReference, ReferenceRefusal, RowReferenceChoice, RowReferences, TableKeys}; pub use results::{CellBytes, CellTextHead, ResultColumnInfo, ResultSet, ValueKind}; pub use row_edits::{ CellChange, CellEdit, EditColumnInfo, EditLock, EditStart, PlannedStatement, RowEdit, RowSave, RowSaveOutcome, diff --git a/core/crates/ffi/src/references.rs b/core/crates/ffi/src/references.rs index 484be846e6..963c24c841 100644 --- a/core/crates/ffi/src/references.rs +++ b/core/crates/ffi/src/references.rs @@ -15,6 +15,9 @@ use crate::results::ResultSet; use crate::runtime::on_runtime; use crate::session::DatabaseSession; +// A menu lists no more than this each way; a table can declare thousands of keys over one column. +const MAX_CHOICES: usize = 64; + // A table's foreign keys both ways, read once; what a row leads to is worked out from them without the server. #[derive(Debug, uniffi::Object)] pub struct TableKeys { @@ -32,15 +35,15 @@ pub enum ReferenceRefusal { ComparedOtherwise { table: String }, } +// A key a row leads somewhere by, named for a menu. `key` and `referencing` are what `follow_reference` takes back; // `columns` are the key's columns in the table that holds it, which tell two keys into one table apart. -// Exactly one of `filter` and `refusal` is set. #[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] pub struct RowReferenceChoice { + pub key: u32, + pub referencing: bool, pub key_name: String, pub table: TableName, pub columns: Vec, - pub filter: Option, - pub refusal: Option, } // A key with a NULL in the row, or one the rows do not hold every column of, leads nowhere and is left out. @@ -50,6 +53,13 @@ pub struct RowReferences { pub referencing: Vec, } +// The rows a chosen key leads to, or why a filter cannot reach them. +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Enum)] +pub enum FollowedReference { + Rows { table: TableName, filter: TableFilterArg }, + Refused { refusal: ReferenceRefusal }, +} + #[uniffi::export] impl DatabaseSession { // Both ways in one operation, so a reconnect between the reads cannot pair keys of two connections. @@ -84,46 +94,50 @@ impl DatabaseSession { #[uniffi::export] impl TableKeys { - // The table's keys that hold `column` (any column when None) and the other tables' keys, from `row` of `rows` - // as the server holds it. `rows` is a page of this table, sorted or not. + // The table's keys that hold `column` (any column when None) and the other tables' keys, from `row` of `rows`. + // Only whether each key's cells hold a value is read, so a menu copies no value; `follow_reference` builds the + // filter of the one chosen. pub fn row_references( &self, rows: Arc, row: u64, column: Option, ) -> Result { - if row >= rows.row_count() { - return Err(CoreError::failed( - "ffi.out_of_range", - format!("no row {row} in the result"), - )); - } + in_range(&rows, row)?; let read = rows.result_columns(); let referenced = self .outbound .iter() - .filter(|key| column.as_ref().is_none_or(|column| key.key.columns.contains(column))) - .filter_map(|key| { - let cells = key_cells(&rows, row, &read, &key.key.columns, &key.key.ref_columns, &key.key.name); - choice( - &key.key.name, - TableRef::new(key.key.ref_schema.clone(), key.key.ref_table.clone()), - &key.key.columns, - cells.and_then(|(columns, values)| RowReference::referenced(&self.table, key, &columns, &values)), - ) + .enumerate() + .filter(|(_, key)| column.as_ref().is_none_or(|column| key.key.columns.contains(column))) + .filter(|(_, key)| holds_values(&rows, row, &read, &key.key.columns)) + .take(MAX_CHOICES) + .map(|(index, key)| RowReferenceChoice { + key: u32::try_from(index).unwrap_or(u32::MAX), + referencing: false, + key_name: key.key.name.clone(), + table: TableName { + schema: key.key.ref_schema.clone(), + name: key.key.ref_table.clone(), + }, + columns: key.key.columns.clone(), }) .collect(); let referencing = self .inbound .iter() - .filter_map(|key| { - let cells = key_cells(&rows, row, &read, &key.referenced_columns, &key.columns, &key.name); - choice( - &key.name, - key.table.clone(), - &key.columns, - cells.and_then(|(columns, values)| RowReference::referencing(&self.table, key, &columns, &values)), - ) + .enumerate() + .filter(|(_, key)| holds_values(&rows, row, &read, &key.referenced_columns)) + .take(MAX_CHOICES) + .map(|(index, key)| RowReferenceChoice { + key: u32::try_from(index).unwrap_or(u32::MAX), + referencing: true, + key_name: key.name.clone(), + table: TableName { + schema: key.table.schema.clone(), + name: key.table.name.clone(), + }, + columns: key.columns.clone(), }) .collect(); Ok(RowReferences { @@ -131,10 +145,76 @@ impl TableKeys { referencing, }) } + + // The filter of one key `row_references` offered, built from the row's stored values. + pub fn follow_reference( + &self, + rows: Arc, + row: u64, + referencing: bool, + key: u32, + ) -> Result { + in_range(&rows, row)?; + let read = rows.result_columns(); + let index = usize::try_from(key).unwrap_or(usize::MAX); + let reference = match referencing { + false => { + let key = self.outbound.get(index).ok_or_else(no_key)?; + key_cells(&rows, row, &read, &key.key.columns, &key.key.ref_columns, &key.key.name) + .and_then(|(columns, values)| RowReference::referenced(&self.table, key, &columns, &values)) + } + true => { + let key = self.inbound.get(index).ok_or_else(no_key)?; + key_cells(&rows, row, &read, &key.referenced_columns, &key.columns, &key.name) + .and_then(|(columns, values)| RowReference::referencing(&self.table, key, &columns, &values)) + } + }; + let refusal = match reference { + Ok(reference) => { + return Ok(FollowedReference::Rows { + table: TableName { + schema: reference.table.schema, + name: reference.table.name, + }, + filter: reference.filter.into(), + }); + } + Err(ReferenceError::NullKey | ReferenceError::MissingColumn { .. }) => { + return Err(CoreError::failed("ffi.out_of_range", "the row no longer holds the key")); + } + Err(ReferenceError::UnevenKey { key }) => ReferenceRefusal::UnevenKey { key }, + Err(ReferenceError::UnknownSchema { table }) => ReferenceRefusal::UnknownSchema { table }, + Err(ReferenceError::NoFilterText { column }) => ReferenceRefusal::NoFilterText { column }, + Err(ReferenceError::ComparedOtherwise { table }) => ReferenceRefusal::ComparedOtherwise { table }, + }; + Ok(FollowedReference::Refused { refusal }) + } +} + +fn in_range(rows: &ResultSet, row: u64) -> Result<(), CoreError> { + match row < rows.row_count() { + true => Ok(()), + false => Err(CoreError::failed( + "ffi.out_of_range", + format!("no row {row} in the result"), + )), + } +} + +fn no_key() -> CoreError { + CoreError::failed("ffi.out_of_range", "no such key") } -// A key value past this has no filter: every key of a row is built as a menu opens, and a row could hold many -// keys of megabytes each. +// Every column of the key is in the rows and holds a value in the row, read from the cells' kinds alone. +fn holds_values(rows: &ResultSet, row: u64, read: &[ResultColumn], names: &[String]) -> bool { + names.iter().all(|name| { + read.iter() + .position(|column| column.name == *name) + .is_some_and(|index| matches!(rows.cell_kind(row, index), Some(Some(_)))) + }) +} + +// A key value past this has no filter: the filter would carry it, twice its size as hex for a binary key. const MAX_KEY_BYTES: usize = 8 * 1024; // Only the key's cells are copied, so a row of large values stays in the store. A value the store cannot name @@ -177,29 +257,3 @@ fn key_cells( }), } } - -fn choice( - key_name: &str, - table: TableRef, - columns: &[String], - reference: Result, -) -> Option { - let (filter, refusal) = match reference { - Ok(reference) => (Some(reference.filter.into()), None), - Err(ReferenceError::NullKey | ReferenceError::MissingColumn { .. }) => return None, - Err(ReferenceError::UnevenKey { key }) => (None, Some(ReferenceRefusal::UnevenKey { key })), - Err(ReferenceError::UnknownSchema { table }) => (None, Some(ReferenceRefusal::UnknownSchema { table })), - Err(ReferenceError::NoFilterText { column }) => (None, Some(ReferenceRefusal::NoFilterText { column })), - Err(ReferenceError::ComparedOtherwise { table }) => (None, Some(ReferenceRefusal::ComparedOtherwise { table })), - }; - Some(RowReferenceChoice { - key_name: key_name.to_owned(), - table: TableName { - schema: table.schema, - name: table.name, - }, - columns: columns.to_vec(), - filter, - refusal, - }) -} diff --git a/core/crates/ffi/tests/browse.rs b/core/crates/ffi/tests/browse.rs index bde0e21f32..07ecdd9c72 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, - ReferenceRefusal, RowEstimate, RunEvent, RunListener, RunOutcome, RunSettings, SecretItemTag, SecretKindTag, - TableFilterArg, TableName, TablePageRead, TransactionStateTag, TruncationTag, + FilterValueArg, FollowedReference, HostConfig, HostSecretError, HostSecrets, ObjectEntry, ObjectKindTag, + ObjectScopeArg, ReferenceRefusal, RowEstimate, RowReferenceChoice, RunEvent, RunListener, RunOutcome, RunSettings, + SecretItemTag, SecretKindTag, TableFilterArg, TableName, TablePageRead, TransactionStateTag, TruncationTag, }; struct NoSecrets; @@ -570,6 +570,24 @@ async fn page_rows( page.run().result_set(0).unwrap() } +fn followed( + keys: &tablepro_ffi::TableKeys, + rows: Arc, + row: u64, + choice: &RowReferenceChoice, +) -> FollowedReference { + keys.follow_reference(rows, row, choice.referencing, choice.key) + .unwrap() +} + +// None for a refusal, which the test unwraps. +fn filter_of(followed: FollowedReference) -> Option<(TableName, TableFilterArg)> { + match followed { + FollowedReference::Rows { table, filter } => Some((table, filter)), + FollowedReference::Refused { .. } => None, + } +} + #[tokio::test] async fn a_composite_key_leads_to_its_row_and_back_with_every_value_bound() { let dir = tempfile::tempdir().unwrap(); @@ -585,8 +603,17 @@ async fn a_composite_key_leads_to_its_row_and_back_with_every_value_bound() { }; assert_eq!(choice.table, table("parent")); assert_eq!(choice.columns, ["parent_code", "parent_region"]); - assert_eq!(choice.refusal, None); - let filter = choice.filter.clone().unwrap(); + assert!(!choice.referencing); + assert!(from_child.referencing.is_empty()); + assert!( + keys.row_references(children.clone(), 0, Some("id".to_owned())) + .unwrap() + .referenced + .is_empty(), + "a column outside the key offers it not" + ); + let (target, filter) = filter_of(followed(&keys, children, 0, choice)).unwrap(); + assert_eq!(target, table("parent")); assert_eq!(filter.combinator, CombinatorTag::And); assert_eq!(filter.raw_sql, None); assert_eq!( @@ -596,39 +623,20 @@ async fn a_composite_key_leads_to_its_row_and_back_with_every_value_bound() { rule("region", FilterOpTag::Eq, Some("7")), ] ); - assert!(from_child.referencing.is_empty()); - assert!( - keys.row_references(children, 0, Some("id".to_owned())) - .unwrap() - .referenced - .is_empty(), - "a column outside the key offers it not" - ); let parents = page_rows(&session, "parent", Some(filter)).await; assert_eq!(parents.row_count(), 1); - let back = session - .table_keys(table("parent"), None) - .await - .unwrap() - .row_references(parents, 0, None) - .unwrap(); + let parent_keys = session.table_keys(table("parent"), None).await.unwrap(); + let back = parent_keys.row_references(parents.clone(), 0, None).unwrap(); assert!(back.referenced.is_empty()); let [incoming] = back.referencing.as_slice() else { panic!("one key points at parent: {back:?}") }; assert_eq!(incoming.table, table("child")); assert_eq!(incoming.columns, ["parent_code", "parent_region"]); + let (_, filter) = filter_of(followed(&parent_keys, parents, 0, incoming)).unwrap(); let child = session - .read_table_page( - table("child"), - None, - incoming.filter.clone(), - 100, - 0, - Box::new(Quiet), - None, - ) + .read_table_page(table("child"), None, Some(filter), 100, 0, Box::new(Quiet), None) .await .unwrap(); assert_eq!(column(&child, 0).await, texts(&["1"])); @@ -650,18 +658,27 @@ async fn a_null_part_leads_nowhere_an_empty_text_is_a_value_and_a_sorted_set_rea ); // Descending by id, so the sorted set's first row is the last one read. let sorted = children.sorted(0, false).unwrap(); - let first = keys.row_references(sorted, 0, None).unwrap(); + let first = keys.row_references(sorted.clone(), 0, None).unwrap(); + let (_, filter) = filter_of(followed(&keys, sorted, 0, &first.referenced[0])).unwrap(); + assert_eq!(filter.rules[0], rule("code", FilterOpTag::Eq, Some(""))); assert_eq!( - first.referenced[0].filter.as_ref().unwrap().rules[0], - rule("code", FilterOpTag::Eq, Some("")) + keys.row_references(children.clone(), 99, None).unwrap_err().code(), + "ffi.out_of_range" + ); + assert_eq!( + keys.follow_reference(children.clone(), 2, false, 0).unwrap_err().code(), + "ffi.out_of_range", + "a key the row holds NULL in was never offered" + ); + assert_eq!( + keys.follow_reference(children, 0, true, 5).unwrap_err().code(), + "ffi.out_of_range" ); - let failure = keys.row_references(children, 99, None).unwrap_err(); - assert_eq!(failure.code(), "ffi.out_of_range"); session.close().await.unwrap(); } #[tokio::test] -async fn keys_that_compare_otherwise_or_hold_an_inexact_value_stay_as_refusals() { +async fn keys_that_compare_otherwise_or_hold_an_inexact_or_long_value_are_offered_and_refused() { let dir = tempfile::tempdir().unwrap(); let (_core, session) = fixture( dir.path(), @@ -669,60 +686,74 @@ async fn keys_that_compare_otherwise_or_hold_an_inexact_value_stay_as_refusals() CREATE TABLE child (code TEXT REFERENCES parent(code)); \ CREATE TABLE scale (weight REAL PRIMARY KEY); \ CREATE TABLE measured (id INTEGER PRIMARY KEY, weight REAL REFERENCES scale(weight)); \ + CREATE TABLE big (code TEXT PRIMARY KEY); CREATE TABLE small (code TEXT REFERENCES big(code)); \ INSERT INTO parent VALUES ('ABC'); INSERT INTO child VALUES ('abc'); \ - INSERT INTO scale VALUES (0.5); INSERT INTO measured VALUES (1, 0.5)", + INSERT INTO scale VALUES (0.5); INSERT INTO measured VALUES (1, 0.5); \ + INSERT INTO big VALUES (printf('%.9000c', 'x')); INSERT INTO small SELECT code FROM big", ) .await; - let parents = page_rows(&session, "parent", None).await; - let collated = session - .table_keys(table("parent"), None) - .await - .unwrap() - .row_references(parents, 0, None) - .unwrap(); - assert_eq!(collated.referencing.len(), 1); + let refusal = |table_name: &'static str, column: Option<&'static str>| { + let session = session.clone(); + async move { + let rows = page_rows(&session, table_name, None).await; + let keys = session.table_keys(table(table_name), None).await.unwrap(); + let references = keys.row_references(rows.clone(), 0, column.map(str::to_owned)).unwrap(); + let choice = references + .referenced + .first() + .or(references.referencing.first()) + .unwrap() + .clone(); + match followed(&keys, rows, 0, &choice) { + FollowedReference::Refused { refusal } => refusal, + rows => panic!("followed: {rows:?}"), + } + } + }; + assert_eq!( - collated.referencing[0].refusal, - Some(ReferenceRefusal::ComparedOtherwise { + refusal("parent", None).await, + ReferenceRefusal::ComparedOtherwise { table: "child".to_owned() - }) + } + ); + assert_eq!( + refusal("measured", Some("weight")).await, + ReferenceRefusal::NoFilterText { + column: "weight".to_owned() + } ); - assert_eq!(collated.referencing[0].filter, None); - - execute( - &session, - "CREATE TABLE big (code TEXT PRIMARY KEY); CREATE TABLE small (code TEXT REFERENCES big(code)); \ - INSERT INTO big VALUES (printf('%.9000c', 'x')); INSERT INTO small SELECT code FROM big", - ) - .await; - let big = page_rows(&session, "big", None).await; - let large = session - .table_keys(table("big"), None) - .await - .unwrap() - .row_references(big, 0, None) - .unwrap(); assert_eq!( - large.referencing[0].refusal, - Some(ReferenceRefusal::NoFilterText { + refusal("big", None).await, + ReferenceRefusal::NoFilterText { column: "code".to_owned() - }), + }, "a key too long to filter on is refused before it is copied" ); + session.close().await.unwrap(); +} + +#[tokio::test] +async fn a_menu_lists_at_most_64_keys_each_way() { + let dir = tempfile::tempdir().unwrap(); + let children: String = (0..70) + .map(|index| format!("CREATE TABLE child_{index} (code TEXT REFERENCES parent(code)); ")) + .collect(); + let (_core, session) = fixture( + dir.path(), + &format!("CREATE TABLE parent (code TEXT PRIMARY KEY); {children} INSERT INTO parent VALUES ('a')"), + ) + .await; + let parents = page_rows(&session, "parent", None).await; - let measured = page_rows(&session, "measured", None).await; - let inexact = session - .table_keys(table("measured"), None) + let references = session + .table_keys(table("parent"), None) .await .unwrap() - .row_references(measured, 0, Some("weight".to_owned())) + .row_references(parents, 0, None) .unwrap(); - assert_eq!( - inexact.referenced[0].refusal, - Some(ReferenceRefusal::NoFilterText { - column: "weight".to_owned() - }) - ); + + assert_eq!(references.referencing.len(), 64); session.close().await.unwrap(); } diff --git a/core/docs/decisions/0022-browsing-through-the-ffi.md b/core/docs/decisions/0022-browsing-through-the-ffi.md index 14d79af70b..f505ea83fb 100644 --- a/core/docs/decisions/0022-browsing-through-the-ffi.md +++ b/core/docs/decisions/0022-browsing-through-the-ffi.md @@ -18,7 +18,7 @@ The FFI exposes what the Linux app calls, and does the work the Linux app does, - `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. - `object_definition` reads `fetch_object_definition` for a function, procedure, trigger or sequence, with whether running the text in an editor would make the object as it is. - `export_rows` writes the rows a finished `ResultSet` holds, its visible columns only; `export_table` streams every row the filter and sort select through `build_export` and `stream_read`, as the Linux app exports a table. Both use the core's encoders (CSV with its default options, JSON, Excel, Markdown, HTML, XML, and SQL INSERT from a table), write beside the target and rename once complete, so a failed or cancelled export leaves no file. -- `DatabaseSession::table_keys` reads a table's outbound and inbound foreign keys in one Metadata operation, as the Linux browse tab reads them. Its `TableKeys::row_references` builds, without the server, what a row of a page of that table leads to through `browse::RowReference`, from the row's stored values: the table's keys holding a column, and the other tables' keys pointing at the row. A key with a NULL or a column the page lacks is left out; one whose value the store cannot name exactly or holds more than 8 KiB, or that `RowReference` refuses, comes back with its refusal for the app to word. The size bound holds because every key of a row is built as a menu opens. +- `DatabaseSession::table_keys` reads a table's outbound and inbound foreign keys in one Metadata operation, as the Linux browse tab reads them. `TableKeys::row_references` lists, without the server, the keys a row of a page of that table leads somewhere by: the table's keys holding a column, and the other tables' keys pointing at the row, at most 64 each way. It reads only whether each key's cells hold a value, so a menu copies no value however many keys a table declares; a key with a NULL or a column the page lacks is left out. `follow_reference` then builds the chosen key's filter through `browse::RowReference` from the row's stored values, or its refusal for the app to word, as for a value the store cannot name exactly or one past 8 KiB. - `ResultSet::cell_text_head` gives a value's start, line breaks kept, and `cell_bytes` a binary value's first bytes and its length, so an app's viewer copies no more of a large cell than it shows, where `cell_text` copies all of it. - `Core::history` opens the query history at `/state/history.db` once. `record` takes the session, so the engine's `history_recording` withholds a statement that holds a secret, as on Linux; `search` pages by the store's keyset; `delete` and `clear` change it. diff --git a/windows/docs/decisions/0007-browsing-a-connection.md b/windows/docs/decisions/0007-browsing-a-connection.md index bd4034f822..5359096217 100644 --- a/windows/docs/decisions/0007-browsing-a-connection.md +++ b/windows/docs/decisions/0007-browsing-a-connection.md @@ -28,7 +28,7 @@ Each one works as the macOS app's does, with its words in Windows sentence case, - A results grid's menu, in a query tab and a table tab, holds Copy, View value..., Export results... and Share; a table tab's adds its row and cell edits and the foreign keys below. Export and Share wait for the rows to finish. - View value... shows the focused cell in a dialog, read only, with Copy: an image where a system codec decodes the bytes, its first frame only (`BitmapDecoder.GetSoftwareBitmapAsync`, since an animated GIF's canvas can be far larger than its frames and BitmapImage would allocate the canvas), at its own size up to the dialog's and decoded at 2,048 pixels on its longer side at most, a picture past 64 megapixels as hex instead, JSON laid out one member per line where the text is one object or array, otherwise the text, and a binary value as its 0x hex. The JSON layout keeps each string's escapes and each number's digits as stored, which a serializer would not. A cell is read only as far as the dialog goes (`ResultSet.GetCellTextHead`, `GetCellBytes`), since a cell can hold more than the app should copy: the text and the JSON layout show their first 1,000,000 characters, the hex its first 256 KiB, and a picture is decoded only from a value of 16 MiB at most read whole. A cut value says so, and Copy takes what shows. A pending edit shows as typed; NULL and DEFAULT show as the grid words them. -- A table tab reads its table's foreign keys both ways once its first page shows, and again on Refresh (`ReadTableKeysAsync`, in one operation, as the Linux app reads them). The menu on a cell offers Open referenced row for the keys its column is in, a submenu when there are several, and Show referencing rows for the other tables' keys pointing at the row, each named by the other table and the key's columns, with the constraint where two read alike. The core builds each filter from the row as the server holds it (`TableKeys.GetRowReferences`, `browse::RowReference`), so a key whose cells hold a pending edit, a new row and a row marked for delete offer none. A key with a NULL leads nowhere and is left out; one the core refuses, such as columns that compare under another collation, is offered and says why when chosen. +- A table tab reads its table's foreign keys both ways once its first page shows, and again on Refresh (`ReadTableKeysAsync`, in one operation, as the Linux app reads them). The menu on a cell offers Open referenced row for the keys its column is in, a submenu when there are several, and Show referencing rows for the other tables' keys pointing at the row, each named by the other table and the key's columns, with the constraint where two read alike. The menu lists the keys from the row as the server holds it (`TableKeys.GetRowReferences`, at most 64 each way), so a key whose cells hold a pending edit, a new row and a row marked for delete offer none, and the core builds the chosen key's filter only then (`TableKeys.Follow`, `browse::RowReference`), from the row the menu opened on; a reload in between follows nothing. A key with a NULL leads nowhere and is left out; one the core refuses, such as columns that compare under another collation, is offered and says why when chosen. - A chosen key opens the other table in a new tab beside this one, its filter the key's columns equal to the row's values, kept with the tab as a filter the user set; a tab whose rows were read under exactly that filter, and is not reading others, comes forward instead. ### Export diff --git a/windows/src/TablePro.App.Model/TabSession.cs b/windows/src/TablePro.App.Model/TabSession.cs index 3ae877f112..eaf6fd3c8a 100644 --- a/windows/src/TablePro.App.Model/TabSession.cs +++ b/windows/src/TablePro.App.Model/TabSession.cs @@ -74,6 +74,8 @@ public interface ITableKeys : IDisposable { // `rows` is the page the row is in, null when no set is shown. RowReferences ReferencesAt(ResultSet? rows, long row, string? column); + + FollowedReference Follow(ResultSet? rows, long row, RowReferenceChoice choice); } // One save, which runs only the statements it was planned with. @@ -188,6 +190,12 @@ internal sealed class CoreTableKeys(TableKeys keys) : ITableKeys public RowReferences ReferencesAt(ResultSet? rows, long row, string? column) => rows is null ? RowReferences.None : keys.GetRowReferences(rows, row, column); + public FollowedReference Follow(ResultSet? rows, long row, RowReferenceChoice choice) + { + ArgumentNullException.ThrowIfNull(rows); + return keys.Follow(rows, row, choice); + } + public void Dispose() => keys.Dispose(); } diff --git a/windows/src/TablePro.App.Model/TableTab.cs b/windows/src/TablePro.App.Model/TableTab.cs index ddd13c0859..a7c2f4381c 100644 --- a/windows/src/TablePro.App.Model/TableTab.cs +++ b/windows/src/TablePro.App.Model/TableTab.cs @@ -306,60 +306,80 @@ public bool Shows(string? schema, string table) => // A tab on the table a reference leads to whose rows were read with exactly its filter. One still reading may end // on the rows it showed before, so it does not count. - public bool ShowsReference(RowReferenceChoice reference) + public bool ShowsReference(FollowedReference.Rows reference) { ArgumentNullException.ThrowIfNull(reference); - return reference.Filter is { } filter && !IsRunning && Table == reference.Table - && TableFilters.Same(_shownFilter, filter); + return !IsRunning && Table == reference.Table && TableFilters.Same(_shownFilter, reference.Filter); } // A new table tab on the rows a reference leads to, its filter kept with the tab as one the user set. - public static SessionTab? TabFor(RowReferenceChoice reference) + public static SessionTab TabFor(FollowedReference.Rows reference) { ArgumentNullException.ThrowIfNull(reference); - return reference.Filter is { } filter - ? new SessionTab - { - Kind = TabKind.Table, - Title = reference.Table.Name, - Schema = reference.Table.Schema, - Table = reference.Table.Name, - ObjectKind = nameof(Interop.ObjectKind.Table), - Filter = SavedFilter.From(filter), - } - : null; + return new SessionTab + { + Kind = TabKind.Table, + Title = reference.Table.Name, + Schema = reference.Table.Schema, + Table = reference.Table.Name, + ObjectKind = nameof(Interop.ObjectKind.Table), + Filter = SavedFilter.From(reference.Filter), + }; } // What a cell's row leads to as the server holds the row: nothing while the page is read or saved, or on a new // or deleted row; and of the row's own keys, none whose cells hold a pending change, which the server has not. - public RowReferences ReferencesAt(int row, int column) + public ReferenceMenu ReferencesAt(int row, int column) { if (_keys is not { } keys || IsRunning || IsSaving || _work.IsClosed || column < 0 || column >= _results.Columns.Count || row < 0 || row >= _results.ShownRowCount || (Edits is { } shown && (shown.IsAdded(row) || shown.IsDeleted(row)))) { - return RowReferences.None; + return ReferenceMenu.None; } + var rows = _results.ShownSet; RowReferences references; try { - references = keys.ReferencesAt(_results.ShownSet, row, _results.Columns[column].Name); + references = keys.ReferencesAt(rows, row, _results.Columns[column].Name); } catch (TableProException) { - return RowReferences.None; + return ReferenceMenu.None; } - if (Edits is not { } edits) + if (Edits is { } edits) { - return references; + references = references with + { + Referenced = [.. references.Referenced.Where(reference => + !reference.Columns.Any(name => IsChanged(edits, row, name)))], + }; } - return references with + return new ReferenceMenu(references, keys, rows, row); + } + + // Built once a key is chosen. Null when the menu's page or keys are no longer the tab's, as after a reload. + public FollowedReference? Follow(ReferenceMenu menu, RowReferenceChoice choice) + { + ArgumentNullException.ThrowIfNull(menu); + ArgumentNullException.ThrowIfNull(choice); + if (menu.Keys is not { } keys || !ReferenceEquals(keys, _keys) || !ReferenceEquals(menu.Rows, _results.ShownSet) + || IsRunning || IsSaving || _work.IsClosed) { - Referenced = [.. references.Referenced.Where(reference => !reference.Columns.Any(name => IsChanged(edits, row, name)))], - }; + return null; + } + + try + { + return keys.Follow(menu.Rows, menu.Row, choice); + } + catch (TableProException) + { + return null; + } } public SessionTab Snapshot() => new() @@ -1493,3 +1513,10 @@ await work.RunAsync(async token => return work.IsClosed ? null : value; } } + +// What a grid menu offers from one row, and the page and keys it was worked out from, so a choice made later +// follows that row or nothing. +public sealed record ReferenceMenu(RowReferences References, ITableKeys? Keys, ResultSet? Rows, int Row) +{ + public static ReferenceMenu None { get; } = new(RowReferences.None, null, null, -1); +} diff --git a/windows/src/TablePro.App/Views/TableTabView.xaml.cs b/windows/src/TablePro.App/Views/TableTabView.xaml.cs index 80411ea65a..fa4269780a 100644 --- a/windows/src/TablePro.App/Views/TableTabView.xaml.cs +++ b/windows/src/TablePro.App/Views/TableTabView.xaml.cs @@ -78,7 +78,7 @@ internal TableTabView( public event EventHandler? ExportRequested; // A foreign key's rows to open, in a tab of the workspace that holds this one. - public event EventHandler? ReferenceRequested; + public event EventHandler? ReferenceRequested; public string Title => _model.Title; @@ -606,44 +606,44 @@ private void OnGridContextRequested(UIElement sender, ContextRequestedEventArgs // One key the cell's column is in opens from the menu itself; several, and every key pointing at the row, are // listed by the other table and the key's columns, which tell two keys into one table apart. - private void AddReferences(MenuFlyout menu, RowReferences references) + private void AddReferences(MenuFlyout menu, ReferenceMenu references) { - if (references.IsEmpty) + if (references.References.IsEmpty) { return; } menu.Items.Add(new MenuFlyoutSeparator()); - var open = Labels(references.Referenced); + var open = Labels(references.References.Referenced); if (open.Count == 1) { - menu.Items.Add(ReferenceItem(Strings.Get("GridMenuOpenReferenced"), open[0].Reference, "OpenReferencedRow")); + menu.Items.Add(ReferenceItem(Strings.Get("GridMenuOpenReferenced"), references, open[0].Choice, "OpenReferencedRow")); } else if (open.Count > 1) { var choose = new MenuFlyoutSubItem { Text = Strings.Get("GridMenuOpenReferenced") }; - foreach (var (label, reference) in open) + foreach (var (label, choice) in open) { - choose.Items.Add(ReferenceItem(label, reference, null)); + choose.Items.Add(ReferenceItem(label, references, choice, null)); } menu.Items.Add(choose); } - var pointing = Labels(references.Referencing); + var pointing = Labels(references.References.Referencing); if (pointing.Count > 0) { var show = new MenuFlyoutSubItem { Text = Strings.Get("GridMenuShowReferencing") }; - foreach (var (label, reference) in pointing) + foreach (var (label, choice) in pointing) { - show.Items.Add(ReferenceItem(label, reference, null)); + show.Items.Add(ReferenceItem(label, references, choice, null)); } menu.Items.Add(show); } } - private MenuFlyoutItem ReferenceItem(string label, RowReferenceChoice reference, string? automationId) + private MenuFlyoutItem ReferenceItem(string label, ReferenceMenu references, RowReferenceChoice choice, string? automationId) { var item = new MenuFlyoutItem { Text = label }; if (automationId is not null) @@ -651,35 +651,38 @@ private MenuFlyoutItem ReferenceItem(string label, RowReferenceChoice reference, AutomationProperties.SetAutomationId(item, automationId); } - item.Click += (_, _) => FollowReference(reference); + item.Click += (_, _) => FollowReference(references, choice); return item; } // A key that cannot be followed is still offered, so choosing it says why. - private void FollowReference(RowReferenceChoice reference) + private void FollowReference(ReferenceMenu references, RowReferenceChoice choice) { - if (reference.Refusal is { } refusal) + switch (_model.Follow(references, choice)) { - Results.ShowNotice(Strings.Format("Reference" + refusal, reference.RefusalSubject ?? string.Empty)); - return; + case FollowedReference.Refused refused: + Results.ShowNotice(Strings.Format("Reference" + refused.Refusal, refused.Subject)); + break; + case FollowedReference.Rows rows: + ReferenceRequested?.Invoke(this, rows); + break; + default: + break; } - - ReferenceRequested?.Invoke(this, reference); } - private List<(string Label, RowReferenceChoice Reference)> Labels(IReadOnlyList references) + private List<(string Label, RowReferenceChoice Choice)> Labels(IReadOnlyList choices) { - var shorts = references.Select(reference => + var shorts = choices.Select(choice => { - var table = reference.Table.Schema is { } schema && !string.Equals(schema, _model.Table.Schema, StringComparison.Ordinal) - ? $"{schema}.{reference.Table.Name}" - : reference.Table.Name; - return Strings.Format("ReferenceKey", table, string.Join(", ", reference.Columns)); + var table = choice.Table.Schema is { } schema && !string.Equals(schema, _model.Table.Schema, StringComparison.Ordinal) + ? $"{schema}.{choice.Table.Name}" + : choice.Table.Name; + return Strings.Format("ReferenceKey", table, string.Join(", ", choice.Columns)); }).ToList(); - return [.. references.Select((reference, index) => - (shorts.Count(label => label == shorts[index]) > 1 - ? Strings.Format("ReferenceKeyThrough", shorts[index], reference.KeyName) - : shorts[index], reference))]; + var counts = shorts.CountBy(label => label).ToDictionary(StringComparer.Ordinal); + return [.. choices.Select((choice, index) => + (counts[shorts[index]] > 1 ? Strings.Format("ReferenceKeyThrough", shorts[index], choice.KeyName) : shorts[index], choice))]; } private MenuFlyoutItem ValueItem(string text, int row, int column, CellValueKind kind) => diff --git a/windows/src/TablePro.App/Views/WorkspaceView.xaml.cs b/windows/src/TablePro.App/Views/WorkspaceView.xaml.cs index 8245fecdce..2bff98475c 100644 --- a/windows/src/TablePro.App/Views/WorkspaceView.xaml.cs +++ b/windows/src/TablePro.App/Views/WorkspaceView.xaml.cs @@ -632,16 +632,15 @@ private async void OnExportRequested(object? sender, EventArgs e) } // A tab already showing the reference's rows comes forward; otherwise a new one opens beside the tab it came from. - private void OnReferenceRequested(object? sender, RowReferenceChoice reference) + private void OnReferenceRequested(object? sender, FollowedReference.Rows reference) { - if (_share is null || TableTab.TabFor(reference) is not { } spec) + if (_share is null) { return; } int? index = null; - var items = Tabs.TabItems.OfType().ToList(); - foreach (var item in items) + foreach (var item in Tabs.TabItems.OfType().ToList()) { if (item.Content is TableTabView view && view.Model.ShowsReference(reference)) { @@ -655,7 +654,7 @@ private void OnReferenceRequested(object? sender, RowReferenceChoice reference) } } - AddTable(reference.Table.Schema, reference.Table.Name, ObjectKind.Table, index, spec); + AddTable(reference.Table.Schema, reference.Table.Name, ObjectKind.Table, index, TableTab.TabFor(reference)); } private async void OnShareRequested(object? sender, ShareKind kind) => diff --git a/windows/src/TablePro.Interop/Generated/tablepro_ffi.cs b/windows/src/TablePro.Interop/Generated/tablepro_ffi.cs index 82fac9b89b..3021feb577 100644 --- a/windows/src/TablePro.Interop/Generated/tablepro_ffi.cs +++ b/windows/src/TablePro.Interop/Generated/tablepro_ffi.cs @@ -1170,6 +1170,8 @@ public struct UniffiVTableCallbackInterfaceRunListener + + @@ -1944,6 +1946,17 @@ public static extern void uniffi_tablepro_ffi_fn_free_tablekeys(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); + #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 + RustBuffer uniffi_tablepro_ffi_fn_method_tablekeys_follow_reference(ulong @ptr,ulong @rows,ulong @row,sbyte @referencing,uint @key,ref UniffiRustCallStatus _uniffi_out_err + ); + #if NET8_0_OR_GREATER [LibraryImport("tablepro_ffi")] [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] @@ -4034,6 +4047,17 @@ public static extern ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_update_tag( ); + #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_tablekeys_follow_reference( + ); + #if NET8_0_OR_GREATER [LibraryImport("tablepro_ffi")] [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] @@ -5210,6 +5234,12 @@ static void uniffiCheckApiChecksums() { throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_connectionlibrary_update_tag` checksum `62856`, library returned `{checksum}`"); } } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_tablekeys_follow_reference(); + if (checksum != 56096) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_tablekeys_follow_reference` checksum `56096`, library returned `{checksum}`"); + } + } { var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_tablekeys_row_references(); if (checksum != 17848) { @@ -9166,6 +9196,8 @@ public override void Write(TableEditor value, BigEndianStream stream) { internal interface ITableKeys { + /// + FollowedReference FollowReference(ResultSet @rows, ulong @row, bool @referencing, uint @key); /// RowReferences RowReferences(ResultSet @rows, ulong @row, string? @column); } @@ -9258,6 +9290,15 @@ internal T CallWithPointer(Func func) } + /// + public FollowedReference FollowReference(ResultSet @rows, ulong @row, bool @referencing, uint @key) { + return CallWithPointer(thisPtr => FfiConverterTypeFollowedReference.INSTANCE.Lift( + _UniffiHelpers.RustCallWithError(FfiConverterTypeCoreError.INSTANCE, (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_tablekeys_follow_reference(thisPtr, FfiConverterTypeResultSet.INSTANCE.Lower(@rows), FfiConverterUInt64.INSTANCE.Lower(@row), FfiConverterBoolean.INSTANCE.Lower(@referencing), FfiConverterUInt32.INSTANCE.Lower(@key), ref _status) +))); + } + + /// public RowReferences RowReferences(ResultSet @rows, ulong @row, string? @column) { return CallWithPointer(thisPtr => FfiConverterTypeRowReferences.INSTANCE.Lift( @@ -11306,11 +11347,11 @@ public override void Write(ResultColumnInfo value, BigEndianStream stream) { internal record RowReferenceChoice ( + uint Key, + bool Referencing, string KeyName, TableName Table, - string[] Columns, - TableFilterArg? Filter, - ReferenceRefusal? Refusal + string[] Columns ) { } @@ -11319,29 +11360,29 @@ class FfiConverterTypeRowReferenceChoice: FfiConverterRustBuffer{ + public static FfiConverterRustBuffer INSTANCE = new FfiConverterTypeFollowedReference(); + + public override FollowedReference Read(BigEndianStream stream) { + var value = stream.ReadInt(); + switch (value) { + case 1: + return new FollowedReference.Rows( + FfiConverterTypeTableName.INSTANCE.Read(stream), + FfiConverterTypeTableFilterArg.INSTANCE.Read(stream) + ); + case 2: + return new FollowedReference.Refused( + FfiConverterTypeReferenceRefusal.INSTANCE.Read(stream) + ); + default: + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeFollowedReference.Read()", value)); + } + } + + public override int AllocationSize(FollowedReference value) { + switch (value) { + case FollowedReference.Rows variant_value: + return 4 + + FfiConverterTypeTableName.INSTANCE.AllocationSize(variant_value.Table) + + FfiConverterTypeTableFilterArg.INSTANCE.AllocationSize(variant_value.Filter); + case FollowedReference.Refused variant_value: + return 4 + + FfiConverterTypeReferenceRefusal.INSTANCE.AllocationSize(variant_value.Refusal); + default: + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeFollowedReference.AllocationSize()", value)); + } + } + + public override void Write(FollowedReference value, BigEndianStream stream) { + switch (value) { + case FollowedReference.Rows variant_value: + stream.WriteInt(1); + FfiConverterTypeTableName.INSTANCE.Write(variant_value.Table, stream); + FfiConverterTypeTableFilterArg.INSTANCE.Write(variant_value.Filter, stream); + break; + case FollowedReference.Refused variant_value: + stream.WriteInt(2); + FfiConverterTypeReferenceRefusal.INSTANCE.Write(variant_value.Refusal, stream); + break; + default: + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeFollowedReference.Write()", value)); + } + } +} + + + + + + + internal record HistoryOutcomeTag { public record Succeeded: HistoryOutcomeTag {} @@ -17544,37 +17657,6 @@ public override void Write(FilterValueArg? value, BigEndianStream stream) { -class FfiConverterOptionalTypeReferenceRefusal: FfiConverterRustBuffer { - public static FfiConverterOptionalTypeReferenceRefusal INSTANCE = new FfiConverterOptionalTypeReferenceRefusal(); - - public override ReferenceRefusal? Read(BigEndianStream stream) { - if (stream.ReadByte() == 0) { - return null; - } - return FfiConverterTypeReferenceRefusal.INSTANCE.Read(stream); - } - - public override int AllocationSize(ReferenceRefusal? value) { - if (value == null) { - return 1; - } else { - return 1 + FfiConverterTypeReferenceRefusal.INSTANCE.AllocationSize((ReferenceRefusal)value); - } - } - - public override void Write(ReferenceRefusal? value, BigEndianStream stream) { - if (value == null) { - stream.WriteByte(0); - } else { - stream.WriteByte(1); - FfiConverterTypeReferenceRefusal.INSTANCE.Write((ReferenceRefusal)value, stream); - } - } -} - - - - class FfiConverterOptionalTypeSecretKindTag: FfiConverterRustBuffer { public static FfiConverterOptionalTypeSecretKindTag INSTANCE = new FfiConverterOptionalTypeSecretKindTag(); diff --git a/windows/src/TablePro.Interop/Mapping.References.cs b/windows/src/TablePro.Interop/Mapping.References.cs index 6e249918f7..630741b351 100644 --- a/windows/src/TablePro.Interop/Mapping.References.cs +++ b/windows/src/TablePro.Interop/Mapping.References.cs @@ -4,24 +4,29 @@ namespace TablePro.Interop; internal static partial class Mapping { - public static RowReferenceChoice Reference(Native.RowReferenceChoice choice) + public static RowReferenceChoice Reference(Native.RowReferenceChoice choice) => new( + checked((int)choice.Key), + choice.Referencing, + choice.KeyName, + new TableName(choice.Table.Schema, choice.Table.Name), + choice.Columns); + + public static FollowedReference Followed(Native.FollowedReference followed) => followed switch { - var (refusal, subject) = choice.Refusal switch + Native.FollowedReference.Rows rows => + new FollowedReference.Rows(new TableName(rows.Table.Schema, rows.Table.Name), Filter(rows.Filter)), + Native.FollowedReference.Refused { Refusal: var refusal } => refusal switch { - Native.ReferenceRefusal.UnevenKey uneven => (ReferenceRefusal.UnevenKey, uneven.Key), - Native.ReferenceRefusal.UnknownSchema unknown => (ReferenceRefusal.UnknownSchema, unknown.Table), - Native.ReferenceRefusal.NoFilterText text => (ReferenceRefusal.NoFilterText, text.Column), - Native.ReferenceRefusal.ComparedOtherwise otherwise => (ReferenceRefusal.ComparedOtherwise, otherwise.Table), - _ => ((ReferenceRefusal?)null, (string?)null), - }; - return new RowReferenceChoice( - choice.KeyName, - new TableName(choice.Table.Schema, choice.Table.Name), - choice.Columns, - choice.Filter is { } filter ? Filter(filter) : null, - refusal, - subject); - } + Native.ReferenceRefusal.UnevenKey uneven => new FollowedReference.Refused(ReferenceRefusal.UnevenKey, uneven.Key), + Native.ReferenceRefusal.UnknownSchema unknown => + new FollowedReference.Refused(ReferenceRefusal.UnknownSchema, unknown.Table), + Native.ReferenceRefusal.NoFilterText text => new FollowedReference.Refused(ReferenceRefusal.NoFilterText, text.Column), + Native.ReferenceRefusal.ComparedOtherwise otherwise => + new FollowedReference.Refused(ReferenceRefusal.ComparedOtherwise, otherwise.Table), + _ => throw new InvalidOperationException("The core sent a refusal this build does not know."), + }, + _ => throw new InvalidOperationException("The core sent a reference this build does not know."), + }; private static TableFilter Filter(Native.TableFilterArg filter) => new( filter.Combinator == Native.CombinatorTag.Or ? FilterCombinator.Or : FilterCombinator.And, diff --git a/windows/src/TablePro.Interop/RowReference.cs b/windows/src/TablePro.Interop/RowReference.cs index 63821c6f17..6cfeb38515 100644 --- a/windows/src/TablePro.Interop/RowReference.cs +++ b/windows/src/TablePro.Interop/RowReference.cs @@ -9,16 +9,16 @@ public enum ReferenceRefusal ComparedOtherwise, } -// Columns are the key's columns in the table that holds it. Exactly one of Filter and Refusal is set. +// A key a row leads somewhere by, named for a menu; Key and Referencing are what TableKeys.Follow takes back. +// Columns are the key's columns in the table that holds it. public sealed record RowReferenceChoice( + int Key, + bool Referencing, string KeyName, TableName Table, - IReadOnlyList Columns, - TableFilter? Filter, - ReferenceRefusal? Refusal, - string? RefusalSubject); + IReadOnlyList Columns); -// Referenced: the rows the row's keys point at. Referencing: other tables' keys that point at the row. +// Referenced: the row's keys that hold a column. Referencing: other tables' keys that point at the row. public sealed record RowReferences( IReadOnlyList Referenced, IReadOnlyList Referencing) @@ -27,3 +27,15 @@ public sealed record RowReferences( public bool IsEmpty => Referenced.Count == 0 && Referencing.Count == 0; } + +// The rows a chosen key leads to, or why a filter cannot reach them. +public abstract record FollowedReference +{ + private FollowedReference() + { + } + + public sealed record Rows(TableName Table, TableFilter Filter) : FollowedReference; + + public sealed record Refused(ReferenceRefusal Refusal, string Subject) : FollowedReference; +} diff --git a/windows/src/TablePro.Interop/TableKeys.cs b/windows/src/TablePro.Interop/TableKeys.cs index 171032a30c..b7e3025412 100644 --- a/windows/src/TablePro.Interop/TableKeys.cs +++ b/windows/src/TablePro.Interop/TableKeys.cs @@ -12,7 +12,8 @@ internal TableKeys(Native.TableKeys keys) _keys = keys; } - // From a row of a page of this table as the server holds it; column narrows the row's keys to those holding it. + // From a row of a page of this table; column narrows the row's own keys to those holding it. Reads only + // whether each key's cells hold a value, so a menu copies none. public RowReferences GetRowReferences(ResultSet rows, long row, string? column) { ArgumentNullException.ThrowIfNull(rows); @@ -23,5 +24,15 @@ [.. references.Referenced.Select(Mapping.Reference)], [.. references.Referencing.Select(Mapping.Reference)]); } + // The filter of a key GetRowReferences offered for the same row, built from the row as the server holds it. + public FollowedReference Follow(ResultSet rows, long row, RowReferenceChoice choice) + { + ArgumentNullException.ThrowIfNull(rows); + ArgumentNullException.ThrowIfNull(choice); + ArgumentOutOfRangeException.ThrowIfNegative(row); + return Mapping.Followed(CoreCall.Run(() => + _keys.FollowReference(rows.Handle, checked((ulong)row), choice.Referencing, checked((uint)choice.Key)))); + } + public void Dispose() => _keys.Dispose(); } diff --git a/windows/tests/TablePro.App.Model.Tests/TabFakes.cs b/windows/tests/TablePro.App.Model.Tests/TabFakes.cs index 032f766012..e6946ac4b6 100644 --- a/windows/tests/TablePro.App.Model.Tests/TabFakes.cs +++ b/windows/tests/TablePro.App.Model.Tests/TabFakes.cs @@ -131,6 +131,8 @@ internal sealed class FakeSession : ITabSession // What every key read gives; each read makes a new one, so a test tells a kept read from a new one. public RowReferences References { get; set; } = RowReferences.None; + public FollowedReference Followed { get; set; } = new FollowedReference.Refused(ReferenceRefusal.UnevenKey, "fk"); + public CoreError? KeysFailure { get; set; } public List KeyReads { get; } = []; @@ -326,12 +328,20 @@ internal sealed class FakeKeys(FakeSession session) : ITableKeys public bool IsDisposed { get; private set; } + public List<(long Row, RowReferenceChoice Choice)> Follows { get; } = []; + public RowReferences ReferencesAt(ResultSet? rows, long row, string? column) { Asked.Add((row, column)); return session.References; } + public FollowedReference Follow(ResultSet? rows, long row, RowReferenceChoice choice) + { + Follows.Add((row, choice)); + return session.Followed; + } + public void Dispose() => IsDisposed = true; } diff --git a/windows/tests/TablePro.App.Model.Tests/TableTabReferenceTests.cs b/windows/tests/TablePro.App.Model.Tests/TableTabReferenceTests.cs index 7e7dc7fe72..fb785adda9 100644 --- a/windows/tests/TablePro.App.Model.Tests/TableTabReferenceTests.cs +++ b/windows/tests/TablePro.App.Model.Tests/TableTabReferenceTests.cs @@ -9,12 +9,19 @@ public sealed class TableTabReferenceTests private static readonly TableFilter ToArtist = new( FilterCombinator.And, [new FilterRule("ArtistId", FilterOperator.Equal, new FilterValue.One("1"))], null); - private static readonly RowReferenceChoice Referenced = new("fk_artist", Artist, ["name"], ToArtist, null, null); + private static readonly FollowedReference.Rows ArtistRows = new(Artist, ToArtist); - private static readonly RowReferenceChoice Referencing = - new("fk_album", new TableName(null, "Album"), ["ArtistId"], ToArtist, null, null); + private static readonly RowReferenceChoice Referenced = new(0, false, "fk_artist", Artist, ["name"]); + + private static readonly RowReferenceChoice Referencing = new(0, true, "fk_album", new TableName(null, "Album"), ["ArtistId"]); + + private readonly FakeSession _session = new() + { + TableRows = 3, + References = new([Referenced], [Referencing]), + Followed = ArtistRows, + }; - private readonly FakeSession _session = new() { TableRows = 3, References = new([Referenced], [Referencing]) }; private readonly FakeTableView _view = new(); private readonly FakeResults _results = new(); private readonly TableTab _tab; @@ -28,14 +35,14 @@ public TableTabReferenceTests() [Fact] public async Task TheKeysAreReadOnceThePageShowsAndAgainAfterARefreshAndGoWithTheTab() { - Assert.True(_tab.ReferencesAt(0, 1).IsEmpty); + Assert.True(_tab.ReferencesAt(0, 1).References.IsEmpty); await _tab.RunAsync(); - var references = _tab.ReferencesAt(0, 1); + var menu = _tab.ReferencesAt(0, 1); await _tab.RunAsync(); - Assert.Same(Referenced, Assert.Single(references.Referenced)); - Assert.Same(Referencing, Assert.Single(references.Referencing)); + Assert.Same(Referenced, Assert.Single(menu.References.Referenced)); + Assert.Same(Referencing, Assert.Single(menu.References.Referencing)); var first = Assert.Single(_session.KeyReads); Assert.Equal((0L, "name"), Assert.Single(first.Asked)); @@ -45,7 +52,23 @@ public async Task TheKeysAreReadOnceThePageShowsAndAgainAfterARefreshAndGoWithTh await _tab.CloseAsync(); Assert.True(_session.KeyReads[1].IsDisposed); - Assert.True(_tab.ReferencesAt(0, 1).IsEmpty); + Assert.True(_tab.ReferencesAt(0, 1).References.IsEmpty); + } + + [Fact] + public async Task AChosenKeyIsFollowedFromTheRowItsMenuOpenedOnUntilThePageChanges() + { + await _tab.RunAsync(); + var menu = _tab.ReferencesAt(2, 1); + + var followed = _tab.Follow(menu, Referencing); + await _tab.RefreshAsync(); + var stale = _tab.Follow(menu, Referencing); + + Assert.Same(ArtistRows, followed); + Assert.Equal((2L, Referencing), Assert.Single(_session.KeyReads[0].Follows)); + Assert.Null(stale); + Assert.Null(_tab.Follow(ReferenceMenu.None, Referencing)); } [Fact] @@ -54,29 +77,29 @@ public async Task APendingChangeInAKeysColumnHidesThatKeyButNotTheRowsPointingAt await _tab.RunAsync(); Assert.Null(_tab.CommitEdit(0, 1, "renamed")); - var changed = _tab.ReferencesAt(0, 1); + var changed = _tab.ReferencesAt(0, 1).References; Assert.Null(_tab.AddRow(out var added)); Assert.Null(_tab.DeleteRows([2])); Assert.Empty(changed.Referenced); Assert.Single(changed.Referencing); - Assert.False(_tab.ReferencesAt(1, 1).IsEmpty); - Assert.True(_tab.ReferencesAt(added, 1).IsEmpty); - Assert.True(_tab.ReferencesAt(2, 1).IsEmpty); - Assert.True(_tab.ReferencesAt(0, 5).IsEmpty); + Assert.False(_tab.ReferencesAt(1, 1).References.IsEmpty); + Assert.True(_tab.ReferencesAt(added, 1).References.IsEmpty); + Assert.True(_tab.ReferencesAt(2, 1).References.IsEmpty); + Assert.True(_tab.ReferencesAt(0, 5).References.IsEmpty); } [Fact] public async Task ARefreshWhoseKeyReadFailsOffersNoneOfTheKeysReadBefore() { await _tab.RunAsync(); - Assert.False(_tab.ReferencesAt(0, 1).IsEmpty); + Assert.False(_tab.ReferencesAt(0, 1).References.IsEmpty); _session.KeysFailure = Errors.Of("driver.connection_lost"); await _tab.RefreshAsync(); Assert.True(Assert.Single(_session.KeyReads).IsDisposed); - Assert.True(_tab.ReferencesAt(0, 1).IsEmpty); + Assert.True(_tab.ReferencesAt(0, 1).References.IsEmpty); } [Fact] @@ -87,15 +110,14 @@ public async Task AKeyReadThatFailsLeavesTheRowsWithoutReferences() await _tab.RunAsync(); Assert.Equal(3, _results.RowCount); - Assert.True(_tab.ReferencesAt(0, 1).IsEmpty); + Assert.True(_tab.ReferencesAt(0, 1).References.IsEmpty); Assert.DoesNotContain("error driver.unsupported", _results.Shown); } [Fact] public void AReferenceOpensAsATableTabOnItsFilterWhichATabReadWithTheSameFilterShows() { - var spec = TableTab.TabFor(Referenced)!; - var refused = Referenced with { Filter = null, Refusal = ReferenceRefusal.ComparedOtherwise, RefusalSubject = "Artist" }; + var spec = TableTab.TabFor(ArtistRows); var shown = new TableTab(_session, _view, _results, Artist, ObjectKind.Table, () => new AppSettings(), spec); var other = new TableTab( _session, @@ -104,18 +126,13 @@ public void AReferenceOpensAsATableTabOnItsFilterWhichATabReadWithTheSameFilterS Artist, ObjectKind.Table, () => new AppSettings(), - TableTab.TabFor(Referenced with - { - Filter = ToArtist with { Rules = [new FilterRule("ArtistId", FilterOperator.Equal, new FilterValue.One("2"))] }, - })); + TableTab.TabFor(ArtistRows with { Filter = SecondArtist })); Assert.Equal((TabKind.Table, "Artist", (string?)null, "Artist"), (spec.Kind, spec.Table, spec.Schema, spec.Title)); Assert.True(TableFilters.Same(ToArtist, spec.Filter!.ToFilter())); - Assert.True(shown.ShowsReference(Referenced)); - Assert.False(other.ShowsReference(Referenced)); - Assert.False(shown.ShowsReference(refused)); - Assert.Null(TableTab.TabFor(refused)); - Assert.False(_tab.ShowsReference(Referenced)); + Assert.True(shown.ShowsReference(ArtistRows)); + Assert.False(other.ShowsReference(ArtistRows)); + Assert.False(_tab.ShowsReference(ArtistRows)); } [Fact] @@ -124,26 +141,23 @@ public async Task ATabReadingAnotherFilterDoesNotShowAReferenceUntilItsRowsAreRe var view = new FakeTableView(); var results = new FakeResults(); var target = new TableTab( - _session, view, results, Artist, ObjectKind.Table, () => new AppSettings(), TableTab.TabFor(Referenced)); + _session, view, results, Artist, ObjectKind.Table, () => new AppSettings(), TableTab.TabFor(ArtistRows)); view.Tab = target; await target.RunAsync(); - var second = Referenced with - { - Filter = ToArtist with { Rules = [new FilterRule("ArtistId", FilterOperator.Equal, new FilterValue.One("2"))] }, - }; + var second = ArtistRows with { Filter = SecondArtist }; var querying = new Gate(); _session.Querying = querying; _session.RefusesFilter = true; var applying = target.ApplyFilterAsync(second.Filter); await querying.Reached; - var whileReading = (target.ShowsReference(second), target.ShowsReference(Referenced)); + var whileReading = (target.ShowsReference(second), target.ShowsReference(ArtistRows)); querying.Open(); await applying; Assert.Equal((false, false), whileReading); Assert.False(target.ShowsReference(second)); - Assert.True(target.ShowsReference(Referenced)); + Assert.True(target.ShowsReference(ArtistRows)); } [Fact] @@ -159,4 +173,7 @@ public void FiltersCompareByTheirRulesNotTheListsHoldingThem() Assert.False(TableFilters.Same(ToArtist, null)); Assert.True(TableFilters.Same(null, null)); } + + private static TableFilter SecondArtist => + ToArtist with { Rules = [new FilterRule("ArtistId", FilterOperator.Equal, new FilterValue.One("2"))] }; } diff --git a/windows/tests/TablePro.Interop.Tests/RowReferenceTests.cs b/windows/tests/TablePro.Interop.Tests/RowReferenceTests.cs index 5d314dc63d..16b7f96a5c 100644 --- a/windows/tests/TablePro.Interop.Tests/RowReferenceTests.cs +++ b/windows/tests/TablePro.Interop.Tests/RowReferenceTests.cs @@ -26,23 +26,24 @@ public async Task ACompositeKeyLeadsToItsRowAndBackWithEveryValueBound() Assert.Empty(references.Referencing); Assert.Equal(new TableName(null, "parent"), choice.Table); Assert.Equal(["parent_code", "parent_region"], choice.Columns); - Assert.Null(choice.Refusal); - Assert.NotNull(choice.Filter); - Assert.Null(choice.Filter.RawSql); - Assert.Equal(FilterCombinator.And, choice.Filter.Combinator); + Assert.True(keys.GetRowReferences(children, 0, "id").IsEmpty); + var rows = Assert.IsType(keys.Follow(children, 0, choice)); + Assert.Equal(new TableName(null, "parent"), rows.Table); + Assert.Null(rows.Filter.RawSql); + Assert.Equal(FilterCombinator.And, rows.Filter.Combinator); Assert.Equal([ new FilterRule("code", FilterOperator.Equal, new FilterValue.One("x' OR 1=1 --")), new FilterRule("region", FilterOperator.Equal, new FilterValue.One("7")), - ], choice.Filter.Rules); - Assert.True(keys.GetRowReferences(children, 0, "id").IsEmpty); + ], rows.Filter.Rules); - using var parent = await ReadAsync(database.Session, choice.Table, choice.Filter, cancel); + using var parent = await ReadAsync(database.Session, rows.Table, rows.Filter, cancel); Assert.Equal(1, parent.RowCount); Assert.Equal("7", parent.GetCellText(0, 1)); - using var parentKeys = await database.Session.ReadTableKeysAsync(choice.Table, cancel); + using var parentKeys = await database.Session.ReadTableKeysAsync(rows.Table, cancel); var incoming = Assert.Single(parentKeys.GetRowReferences(parent, 0, null).Referencing); Assert.Equal(Child, incoming.Table); - using var child = await ReadAsync(database.Session, incoming.Table, incoming.Filter, cancel); + var back = Assert.IsType(parentKeys.Follow(parent, 0, incoming)); + using var child = await ReadAsync(database.Session, back.Table, back.Filter, cancel); Assert.Equal(1, child.RowCount); Assert.Equal("1", child.GetCellText(0, 0)); } @@ -59,16 +60,16 @@ public async Task ANullPartLeadsNowhereWhileAnEmptyTextAndASortedRowKeepTheirVal Assert.True(keys.GetRowReferences(children, 2, null).IsEmpty); using var sorted = await children.SortedAsync(0, ascending: false); var choice = Assert.Single(keys.GetRowReferences(sorted, 0, null).Referenced); - Assert.NotNull(choice.Filter); - Assert.Equal(new FilterValue.One(string.Empty), choice.Filter.Rules[0].Value); - using var parent = await ReadAsync(database.Session, choice.Table, choice.Filter, cancel); + var rows = Assert.IsType(keys.Follow(sorted, 0, choice)); + Assert.Equal(new FilterValue.One(string.Empty), rows.Filter.Rules[0].Value); + using var parent = await ReadAsync(database.Session, rows.Table, rows.Filter, cancel); Assert.Equal("9", parent.GetCellText(0, 1)); - var failure = Assert.Throws(() => keys.GetRowReferences(children, 99, null)); - Assert.Equal("ffi.out_of_range", failure.Code); + Assert.Equal("ffi.out_of_range", Assert.Throws(() => keys.GetRowReferences(children, 99, null)).Code); + Assert.Equal("ffi.out_of_range", Assert.Throws(() => keys.Follow(children, 2, choice)).Code); } [Fact] - public async Task KeysThatCompareOtherwiseStayAsRefusalsNamingTheTable() + public async Task AKeyThatComparesOtherwiseIsOfferedAndRefusedNamingTheTable() { var cancel = TestContext.Current.CancellationToken; await using var database = await SqliteDatabase.CreateAsync(); @@ -83,9 +84,10 @@ await database.ExecuteAsync(""" using var keys = await database.Session.ReadTableKeysAsync(table, cancel); var choice = Assert.Single(keys.GetRowReferences(parents, 0, null).Referencing); - Assert.Equal(ReferenceRefusal.ComparedOtherwise, choice.Refusal); - Assert.Equal("child", choice.RefusalSubject); - Assert.Null(choice.Filter); + + Assert.Equal( + new FollowedReference.Refused(ReferenceRefusal.ComparedOtherwise, "child"), + keys.Follow(parents, 0, choice)); } [Fact] From e5c4288608ae4ab27e442b0a20e0b48fdca59fd5 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sat, 14 Nov 2026 21:01:51 +0700 Subject: [PATCH 06/13] fix(windows): leave references out when the key read is stopped, and copy the view shown --- windows/src/TablePro.App.Model/TableTab.cs | 5 +++-- windows/src/TablePro.App/Views/CellValueViewer.cs | 9 ++++++--- windows/tests/TablePro.App.Model.Tests/TabFakes.cs | 8 ++++++++ .../TablePro.App.Model.Tests/TableTabReferenceTests.cs | 9 ++++++--- 4 files changed, 23 insertions(+), 8 deletions(-) diff --git a/windows/src/TablePro.App.Model/TableTab.cs b/windows/src/TablePro.App.Model/TableTab.cs index a7c2f4381c..2e5ac39b4f 100644 --- a/windows/src/TablePro.App.Model/TableTab.cs +++ b/windows/src/TablePro.App.Model/TableTab.cs @@ -1298,9 +1298,10 @@ await _work.RunAsync(async token => { keys = await _session.ReadTableKeysAsync(Table, token).ConfigureAwait(true); } - catch (TableProException) + catch (Exception exception) when (exception is TableProException or OperationCanceledException) { - // An engine without foreign keys, or a read that failed; a refresh reads them again. + // An engine without foreign keys, a read that failed or one the server stopped; a refresh reads + // them again. return; } diff --git a/windows/src/TablePro.App/Views/CellValueViewer.cs b/windows/src/TablePro.App/Views/CellValueViewer.cs index 312614c2d7..d9c380a9e4 100644 --- a/windows/src/TablePro.App/Views/CellValueViewer.cs +++ b/windows/src/TablePro.App/Views/CellValueViewer.cs @@ -94,7 +94,9 @@ public static async Task ShowAsync(FrameworkElement owner, CellValue value) AutomationProperties.SetAutomationId(image, "ValueViewerImage"); var copy = new Button { Content = Strings.Get("ValueViewerCopy"), IsEnabled = value.CanCopy }; AutomationProperties.SetAutomationId(copy, "ValueViewerCopy"); - copy.Click += (_, _) => Copy(value, notice); + // Copy takes what the chosen view shows, so the clipboard matches its layout and what it says was cut. + string? copied = null; + copy.Click += (_, _) => Copy(copied ?? value.CopyText() ?? string.Empty, notice); void Show(Mode mode) { @@ -108,6 +110,7 @@ void Show(Mode mode) image.Visibility = mode == Mode.Image ? Visibility.Visible : Visibility.Collapsed; text.Visibility = mode == Mode.Image ? Visibility.Collapsed : Visibility.Visible; text.Text = shown; + copied = mode == Mode.Image ? null : shown; notice.Severity = InfoBarSeverity.Informational; notice.Message = Strings.Get("ValueViewerCut"); notice.IsOpen = cut; @@ -150,10 +153,10 @@ void Show(Mode mode) await WindowDialogs.ShowAsync(dialog, owner).ConfigureAwait(true); } - private static void Copy(CellValue value, InfoBar notice) + private static void Copy(string text, InfoBar notice) { var package = new DataPackage(); - package.SetText(value.CopyText() ?? string.Empty); + package.SetText(text); try { Clipboard.SetContent(package); diff --git a/windows/tests/TablePro.App.Model.Tests/TabFakes.cs b/windows/tests/TablePro.App.Model.Tests/TabFakes.cs index e6946ac4b6..ab4e907741 100644 --- a/windows/tests/TablePro.App.Model.Tests/TabFakes.cs +++ b/windows/tests/TablePro.App.Model.Tests/TabFakes.cs @@ -135,6 +135,9 @@ internal sealed class FakeSession : ITabSession public CoreError? KeysFailure { get; set; } + // The read ends as one the server stopped does. + public bool KeysStopped { get; set; } + public List KeyReads { get; } = []; // Every open gives this one, so a test sets it up before the page loads. @@ -308,6 +311,11 @@ public Task ReadTableKeysAsync(TableName table, CancellationToken ca return Task.FromException(new TableProException(failure)); } + if (KeysStopped) + { + return Task.FromException(new OperationCanceledException()); + } + var keys = new FakeKeys(this); KeyReads.Add(keys); return Task.FromResult(keys); diff --git a/windows/tests/TablePro.App.Model.Tests/TableTabReferenceTests.cs b/windows/tests/TablePro.App.Model.Tests/TableTabReferenceTests.cs index fb785adda9..08585f4032 100644 --- a/windows/tests/TablePro.App.Model.Tests/TableTabReferenceTests.cs +++ b/windows/tests/TablePro.App.Model.Tests/TableTabReferenceTests.cs @@ -102,10 +102,13 @@ public async Task ARefreshWhoseKeyReadFailsOffersNoneOfTheKeysReadBefore() Assert.True(_tab.ReferencesAt(0, 1).References.IsEmpty); } - [Fact] - public async Task AKeyReadThatFailsLeavesTheRowsWithoutReferences() + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task AKeyReadThatFailsOrIsStoppedLeavesTheRowsWithoutReferences(bool stopped) { - _session.KeysFailure = Errors.Of("driver.unsupported"); + _session.KeysFailure = stopped ? null : Errors.Of("driver.unsupported"); + _session.KeysStopped = stopped; await _tab.RunAsync(); From 9f834be7781542f3fb076c3f8f639e8ee3becb9d Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sat, 14 Nov 2026 21:07:30 +0700 Subject: [PATCH 07/13] fix(core): read each child's CREATE TABLE once when listing the SQLite keys that point at a table --- core/crates/drivers/sqlite/src/catalog/mod.rs | 2 +- .../sqlite/src/catalog/table_definition.rs | 25 ++++++++++--------- core/crates/drivers/sqlite/src/metadata.rs | 16 +++++++----- 3 files changed, 24 insertions(+), 19 deletions(-) diff --git a/core/crates/drivers/sqlite/src/catalog/mod.rs b/core/crates/drivers/sqlite/src/catalog/mod.rs index f2e278239f..a73e5cae48 100644 --- a/core/crates/drivers/sqlite/src/catalog/mod.rs +++ b/core/crates/drivers/sqlite/src/catalog/mod.rs @@ -86,7 +86,7 @@ pub(crate) fn dependents_sql(schema_sql: &str) -> String { /// the ids number them all. pub(crate) fn inbound_keys_sql(schema_sql: &str) -> String { format!( - "SELECT m.name AS child, m.sql AS child_sql, \ + "SELECT m.name AS child, \ (SELECT count(DISTINCT k.id) FROM pragma_foreign_key_list(m.name, ?2) k) AS child_keys, \ f.id AS id, f.\"from\" AS \"from\", f.\"to\" AS \"to\" \ FROM {schema_sql}.sqlite_schema m, pragma_foreign_key_list(m.name, ?2) f \ diff --git a/core/crates/drivers/sqlite/src/catalog/table_definition.rs b/core/crates/drivers/sqlite/src/catalog/table_definition.rs index c21ce7d190..4e9becbc67 100644 --- a/core/crates/drivers/sqlite/src/catalog/table_definition.rs +++ b/core/crates/drivers/sqlite/src/catalog/table_definition.rs @@ -14,8 +14,6 @@ use crate::ddl::declared_foreign_key_names; #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) struct InboundKeyRow { pub child: String, - /// The child's CREATE TABLE, where the key's declared name is. - pub child_sql: Option, /// How many foreign keys the child has, here or elsewhere. pub child_keys: usize, pub id: i64, @@ -26,11 +24,14 @@ pub(crate) struct InboundKeyRow { } /// Group key columns into keys, in the order the query returned them. -/// A key that names no parent columns points at `primary_key`. +/// A key that names no parent columns points at `primary_key`. A key's +/// declared name is in its child's CREATE TABLE, `child_sql`, read once +/// per child rather than once per key column. pub(crate) fn inbound_foreign_keys( schema: Option<&str>, rows: Vec, primary_key: &[String], + child_sql: &HashMap>, ) -> Vec { let mut keys: Vec = Vec::new(); let mut positions: HashMap<(String, i64), usize> = HashMap::new(); @@ -38,7 +39,10 @@ pub(crate) fn inbound_foreign_keys( let mut names: HashMap> = HashMap::new(); for row in rows { let child_names = names.entry(row.child.clone()).or_insert_with(|| { - let declared = row.child_sql.as_deref().and_then(declared_foreign_key_names); + let declared = child_sql + .get(&row.child) + .and_then(Option::as_deref) + .and_then(declared_foreign_key_names); foreign_key_names(&row.child, declared, row.child_keys) }); let name = usize::try_from(row.id) @@ -138,7 +142,6 @@ mod tests { fn key_row(child: &str, id: i64, from: &str, to: Option<&str>) -> InboundKeyRow { InboundKeyRow { child: child.to_owned(), - child_sql: None, child_keys: 3, id, from: from.to_owned(), @@ -154,7 +157,7 @@ mod tests { key_row("notes", 0, "order_b", Some("b")), ]; - let keys = inbound_foreign_keys(None, rows, &["id".to_owned()]); + let keys = inbound_foreign_keys(None, rows, &["id".to_owned()], &HashMap::new()); assert_eq!(keys.len(), 2); assert_eq!(keys[0].name, "fk_lines_0"); @@ -168,12 +171,10 @@ mod tests { fn a_declared_constraint_name_is_the_key_name() { let child_sql = "CREATE TABLE lines (a INTEGER CONSTRAINT to_orders REFERENCES orders, b INTEGER REFERENCES \ orders, CONSTRAINT to_orders FOREIGN KEY (a) REFERENCES orders)"; - let rows = [(0, "a"), (1, "b"), (2, "a")].map(|(id, from)| InboundKeyRow { - child_sql: Some(child_sql.to_owned()), - ..key_row("lines", id, from, None) - }); + let rows = [(0, "a"), (1, "b"), (2, "a")].map(|(id, from)| key_row("lines", id, from, None)); + let sql = HashMap::from([("lines".to_owned(), Some(child_sql.to_owned()))]); - let keys = inbound_foreign_keys(None, rows.to_vec(), &["id".to_owned()]); + let keys = inbound_foreign_keys(None, rows.to_vec(), &["id".to_owned()], &sql); let names: Vec<&str> = keys.iter().map(|key| key.name.as_str()).collect(); assert_eq!(names, ["to_orders", "fk_lines_1", "fk_lines_2"]); @@ -184,7 +185,7 @@ mod tests { ..row.clone() }) .collect(); - let unsure: Vec = inbound_foreign_keys(None, miscounted, &["id".to_owned()]) + let unsure: Vec = inbound_foreign_keys(None, miscounted, &["id".to_owned()], &sql) .into_iter() .map(|key| key.name) .collect(); diff --git a/core/crates/drivers/sqlite/src/metadata.rs b/core/crates/drivers/sqlite/src/metadata.rs index 8745ac145b..a51a46a5d0 100644 --- a/core/crates/drivers/sqlite/src/metadata.rs +++ b/core/crates/drivers/sqlite/src/metadata.rs @@ -348,7 +348,6 @@ async fn inbound_keys( .map(|row| { Ok(InboundKeyRow { child: text(row, "child")?, - child_sql: row.try_get("child_sql").map_err(map_error)?, child_keys: usize::try_from(row.try_get::("child_keys").map_err(map_error)?).unwrap_or(0), id: row.try_get("id").map_err(map_error)?, from: text(row, "from")?, @@ -356,15 +355,20 @@ async fn inbound_keys( }) }) .collect::, DriverError>>()?; - let child_sql: HashMap> = rows - .iter() - .map(|row| (row.child.clone(), row.child_sql.clone())) - .collect(); + // Read once per child, not on every key column's row: a child declaring thousands of keys would repeat its + // whole CREATE TABLE in each. + let mut child_sql: HashMap> = HashMap::new(); + for row in &rows { + if !child_sql.contains_key(&row.child) { + let child = TableRef::new(table.schema.clone(), row.child.clone()); + child_sql.insert(row.child.clone(), create_statement(connection, &child).await?); + } + } let parent_sql = match rows.is_empty() { true => None, false => create_statement(connection, table).await?, }; - let mut keys = inbound_foreign_keys(table.schema.as_deref(), rows, &shape.primary_key()); + let mut keys = inbound_foreign_keys(table.schema.as_deref(), rows, &shape.primary_key(), &child_sql); for key in &mut keys { for column in &mut key.referenced_columns { *column = declared_spelling(column, shape.columns.iter().map(|declared| declared.name.as_str())); From 44170e1c14a21868efeafb2902b4a946c59d9cbe Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sat, 14 Nov 2026 21:16:58 +0700 Subject: [PATCH 08/13] fix(windows): copy a picture as a bitmap from the value viewer --- .../decisions/0007-browsing-a-connection.md | 2 +- .../src/TablePro.App/Views/CellValueViewer.cs | 37 ++++++++++++++++++- 2 files changed, 36 insertions(+), 3 deletions(-) diff --git a/windows/docs/decisions/0007-browsing-a-connection.md b/windows/docs/decisions/0007-browsing-a-connection.md index 5359096217..909aef5b41 100644 --- a/windows/docs/decisions/0007-browsing-a-connection.md +++ b/windows/docs/decisions/0007-browsing-a-connection.md @@ -27,7 +27,7 @@ Each one works as the macOS app's does, with its words in Windows sentence case, ### Grid menus, values and foreign keys - A results grid's menu, in a query tab and a table tab, holds Copy, View value..., Export results... and Share; a table tab's adds its row and cell edits and the foreign keys below. Export and Share wait for the rows to finish. -- View value... shows the focused cell in a dialog, read only, with Copy: an image where a system codec decodes the bytes, its first frame only (`BitmapDecoder.GetSoftwareBitmapAsync`, since an animated GIF's canvas can be far larger than its frames and BitmapImage would allocate the canvas), at its own size up to the dialog's and decoded at 2,048 pixels on its longer side at most, a picture past 64 megapixels as hex instead, JSON laid out one member per line where the text is one object or array, otherwise the text, and a binary value as its 0x hex. The JSON layout keeps each string's escapes and each number's digits as stored, which a serializer would not. A cell is read only as far as the dialog goes (`ResultSet.GetCellTextHead`, `GetCellBytes`), since a cell can hold more than the app should copy: the text and the JSON layout show their first 1,000,000 characters, the hex its first 256 KiB, and a picture is decoded only from a value of 16 MiB at most read whole. A cut value says so, and Copy takes what shows. A pending edit shows as typed; NULL and DEFAULT show as the grid words them. +- View value... shows the focused cell in a dialog, read only, with Copy: an image where a system codec decodes the bytes, its first frame only (`BitmapDecoder.GetSoftwareBitmapAsync`, since an animated GIF's canvas can be far larger than its frames and BitmapImage would allocate the canvas), at its own size up to the dialog's and decoded at 2,048 pixels on its longer side at most, a picture past 64 megapixels as hex instead, JSON laid out one member per line where the text is one object or array, otherwise the text, and a binary value as its 0x hex. The JSON layout keeps each string's escapes and each number's digits as stored, which a serializer would not. A cell is read only as far as the dialog goes (`ResultSet.GetCellTextHead`, `GetCellBytes`), since a cell can hold more than the app should copy: the text and the JSON layout show their first 1,000,000 characters, the hex its first 256 KiB, and a picture is decoded only from a value of 16 MiB at most read whole. A cut value says so, and Copy takes what shows: the text or hex of the view chosen, and a picture as a bitmap. A pending edit shows as typed; NULL and DEFAULT show as the grid words them. - A table tab reads its table's foreign keys both ways once its first page shows, and again on Refresh (`ReadTableKeysAsync`, in one operation, as the Linux app reads them). The menu on a cell offers Open referenced row for the keys its column is in, a submenu when there are several, and Show referencing rows for the other tables' keys pointing at the row, each named by the other table and the key's columns, with the constraint where two read alike. The menu lists the keys from the row as the server holds it (`TableKeys.GetRowReferences`, at most 64 each way), so a key whose cells hold a pending edit, a new row and a row marked for delete offer none, and the core builds the chosen key's filter only then (`TableKeys.Follow`, `browse::RowReference`), from the row the menu opened on; a reload in between follows nothing. A key with a NULL leads nowhere and is left out; one the core refuses, such as columns that compare under another collation, is offered and says why when chosen. - A chosen key opens the other table in a new tab beside this one, its filter the key's columns equal to the row's values, kept with the tab as a filter the user set; a tab whose rows were read under exactly that filter, and is not reading others, comes forward instead. diff --git a/windows/src/TablePro.App/Views/CellValueViewer.cs b/windows/src/TablePro.App/Views/CellValueViewer.cs index d9c380a9e4..a4259a62e0 100644 --- a/windows/src/TablePro.App/Views/CellValueViewer.cs +++ b/windows/src/TablePro.App/Views/CellValueViewer.cs @@ -94,9 +94,20 @@ public static async Task ShowAsync(FrameworkElement owner, CellValue value) AutomationProperties.SetAutomationId(image, "ValueViewerImage"); var copy = new Button { Content = Strings.Get("ValueViewerCopy"), IsEnabled = value.CanCopy }; AutomationProperties.SetAutomationId(copy, "ValueViewerCopy"); - // Copy takes what the chosen view shows, so the clipboard matches its layout and what it says was cut. + // Copy takes what the chosen view shows, so the clipboard matches its layout and what it says was cut; a + // picture copies as one. string? copied = null; - copy.Click += (_, _) => Copy(copied ?? value.CopyText() ?? string.Empty, notice); + copy.Click += async (_, _) => + { + if (copied is null && value.IsWholeBinary && value.Bytes is { } picked) + { + await CopyPictureAsync(picked.ToArray(), notice).ConfigureAwait(true); + } + else + { + Copy(copied ?? value.CopyText() ?? string.Empty, notice); + } + }; void Show(Mode mode) { @@ -157,6 +168,28 @@ private static void Copy(string text, InfoBar notice) { var package = new DataPackage(); package.SetText(text); + Put(package, notice); + } + + private static async Task CopyPictureAsync(byte[] bytes, InfoBar notice) + { + using var stream = new InMemoryRandomAccessStream(); + using (var writer = new DataWriter(stream)) + { + writer.WriteBytes(bytes); + await writer.StoreAsync(); + writer.DetachStream(); + } + + stream.Seek(0); + var package = new DataPackage(); + package.SetBitmap(RandomAccessStreamReference.CreateFromStream(stream)); + // Flush hands the clipboard the bitmap now, while the stream is still open. + Put(package, notice); + } + + private static void Put(DataPackage package, InfoBar notice) + { try { Clipboard.SetContent(package); From f660e66391e2bdbbfc755db8f79ec4b0517d0b72 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sat, 14 Nov 2026 21:22:38 +0700 Subject: [PATCH 09/13] fix(windows): show the rows when a reference brings an open tab forward --- windows/src/TablePro.App/Views/WorkspaceView.xaml.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/windows/src/TablePro.App/Views/WorkspaceView.xaml.cs b/windows/src/TablePro.App/Views/WorkspaceView.xaml.cs index 2bff98475c..64ac9082a6 100644 --- a/windows/src/TablePro.App/Views/WorkspaceView.xaml.cs +++ b/windows/src/TablePro.App/Views/WorkspaceView.xaml.cs @@ -644,6 +644,7 @@ private void OnReferenceRequested(object? sender, FollowedReference.Rows referen { if (item.Content is TableTabView view && view.Model.ShowsReference(reference)) { + view.ShowData(); Tabs.SelectedItem = item; return; } From dbccb27378d8e2dcb7eb73bfca6837094c94d951 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sat, 14 Nov 2026 21:26:24 +0700 Subject: [PATCH 10/13] fix(windows): reuse a reference tab only when it shows rows read with that filter --- windows/src/TablePro.App.Model/TableTab.cs | 7 ++++--- .../TableTabReferenceTests.cs | 14 ++++++++++++++ 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/windows/src/TablePro.App.Model/TableTab.cs b/windows/src/TablePro.App.Model/TableTab.cs index 2e5ac39b4f..d3a9391e9a 100644 --- a/windows/src/TablePro.App.Model/TableTab.cs +++ b/windows/src/TablePro.App.Model/TableTab.cs @@ -304,12 +304,13 @@ public bool Shows(string? schema, string table) => string.Equals(Table.Name, table, StringComparison.Ordinal) && string.Equals(Table.Schema, schema, StringComparison.Ordinal); - // A tab on the table a reference leads to whose rows were read with exactly its filter. One still reading may end - // on the rows it showed before, so it does not count. + // A tab on the table a reference leads to that shows rows read with exactly its filter, or will on its first + // show. One still reading may end on the rows it showed before, and one whose read failed shows none. public bool ShowsReference(FollowedReference.Rows reference) { ArgumentNullException.ThrowIfNull(reference); - return !IsRunning && Table == reference.Table && TableFilters.Same(_shownFilter, reference.Filter); + return !IsRunning && Table == reference.Table && TableFilters.Same(_shownFilter, reference.Filter) + && (!_shown || _results.Outcome is QueryOutcome.Completed); } // A new table tab on the rows a reference leads to, its filter kept with the tab as one the user set. diff --git a/windows/tests/TablePro.App.Model.Tests/TableTabReferenceTests.cs b/windows/tests/TablePro.App.Model.Tests/TableTabReferenceTests.cs index 08585f4032..e7b2ec3164 100644 --- a/windows/tests/TablePro.App.Model.Tests/TableTabReferenceTests.cs +++ b/windows/tests/TablePro.App.Model.Tests/TableTabReferenceTests.cs @@ -163,6 +163,20 @@ public async Task ATabReadingAnotherFilterDoesNotShowAReferenceUntilItsRowsAreRe Assert.True(target.ShowsReference(ArtistRows)); } + [Fact] + public async Task ATabWhoseReadFailedShowsNoReference() + { + var view = new FakeTableView(); + var target = new TableTab( + _session, view, new FakeResults(), Artist, ObjectKind.Table, () => new AppSettings(), TableTab.TabFor(ArtistRows)); + view.Tab = target; + _session.FilteredReadEnds = new QueryOutcome.Failed(Errors.Of("driver.query_failed")); + + await target.RunAsync(); + + Assert.False(target.ShowsReference(ArtistRows)); + } + [Fact] public void FiltersCompareByTheirRulesNotTheListsHoldingThem() { From a4a9c9cb3707b4d2bda1e385fd2f894a57b5d381 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sat, 14 Nov 2026 21:36:59 +0700 Subject: [PATCH 11/13] fix(windows): open a cell's tip through the pane as its owner --- windows/docs/decisions/0003-data-grid-control.md | 2 +- windows/src/TablePro.DataGrid/DataGridView.Tips.cs | 14 ++++++++++++-- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/windows/docs/decisions/0003-data-grid-control.md b/windows/docs/decisions/0003-data-grid-control.md index 9a246c92b6..ed0ba50172 100644 --- a/windows/docs/decisions/0003-data-grid-control.md +++ b/windows/docs/decisions/0003-data-grid-control.md @@ -105,7 +105,7 @@ - A header is a HeaderItem with Invoke, which sorts and raises the Invoked event, Transform, which resizes in physical pixels, and its sort order as `ItemStatus`, the property the [HeaderItem control type](https://learn.microsoft.com/en-us/windows/win32/winauto/uiauto-supportheaderitemcontroltype) gives sort orders. A change raises ItemStatus's property-changed event. The host words it through `SortedAscendingStatus` and `SortedDescendingStatus`. - A column's header is a peer of its own, one per column like a cell's, not the header element: ItemsRepeater hands an element to another column as it scrolls, so a client holding the element's peer would read another column. The element's peer leaves the control view and sends a point query to its column's peer. `GetColumnHeaders` lists every column, a cell's TableItem names its column header on screen or not, and the tree lists the headers in view. - A row number is a HeaderItem too, named as drawn, with Invoke, which selects the row as a click on the number does, and ScrollItem. `GetRowHeaders` lists the rows in view, a cell's TableItem names its row's, and the tree lists each row in view as its header then its cells. -- With `ShowsCellTips`, a cell the core cut or its column cuts shows its text, up to 1,000 characters, in a ToolTip after the pointer rests on it: twice `SPI_GETMOUSEHOVERTIME`, one and a half within 200 ms of the last tip closing, as ToolTipService times one. ToolTipService arms a tooltip only on its owner's `PointerEntered` (`ToolTipService_Partial.cpp`), so a ToolTip owned by a pane would open for the first cell alone; each cell's is opened by the grid instead, docked above the cell through `PlacementRect`, since a tooltip opened from code has no pointer to follow. Moving to another cell, pressing, scrolling, resizing a column, an edit and new data close it. +- With `ShowsCellTips`, a cell the core cut or its column cuts shows its text, up to 1,000 characters, in a ToolTip after the pointer rests on it: twice `SPI_GETMOUSEHOVERTIME`, one and a half within 200 ms of the last tip closing, as ToolTipService times one. ToolTipService arms a tooltip only on its owner's `PointerEntered` (`ToolTipService_Partial.cpp`), so a ToolTip owned by a pane would open for the first cell alone; each cell's is opened by the grid instead, docked above the cell through `PlacementRect`, since a tooltip opened from code has no pointer to follow. A ToolTip opens from code only through an owner ToolTipService knows, which it takes as its container (`ToolTip::OnIsOpenChanged`; with none, `IsOpen` throws, run 43604877228), so the pane owns the tip only while it shows. Moving to another cell, pressing, scrolling, resizing a column, an edit and new data close it. - A cell's `ItemStatus` is its pending change: `EditedStatus`, `NewRowStatus` or `DeletedStatus`, the macOS grid's VoiceOver words. A change raises ItemStatus's property-changed event. Its Name stays the value, `DefaultText` for a DEFAULT cell. - An open editor is its pane's one automation child. diff --git a/windows/src/TablePro.DataGrid/DataGridView.Tips.cs b/windows/src/TablePro.DataGrid/DataGridView.Tips.cs index 82e346825e..cfd3ffc5d3 100644 --- a/windows/src/TablePro.DataGrid/DataGridView.Tips.cs +++ b/windows/src/TablePro.DataGrid/DataGridView.Tips.cs @@ -18,6 +18,7 @@ public sealed partial class DataGridView private readonly DispatcherTimer _tipTimer = new(); private ToolTip? _tip; + private UIElement? _tipOwner; private (bool Frozen, int Row, int Column)? _tipCell; private long _tipClosedAt = long.MinValue / 2; @@ -61,6 +62,11 @@ internal void ClearCellTip() _tipClosedAt = Environment.TickCount64; } } + if (_tipOwner is { } owner) + { + _tipOwner = null; + ToolTipService.SetToolTip(owner, null); + } } // Opened now rather than after the hover time, as the tests do. @@ -72,16 +78,20 @@ internal void OpenCellTip() return; } var pane = at.Frozen ? (UIElement)_frozenContent : _content; - // A tooltip opened by code has no pointer to follow, so it docks to the cell's rectangle. + // A tooltip opened by code has no pointer to follow, so it docks to the cell's rectangle. It opens only + // through an owner ToolTipService knows (ToolTip::OnIsOpenChanged takes the owner as its container), and the + // pane is that owner only while the tip shows, so ToolTipService opens nothing of its own on the pane. _tip = new ToolTip { Content = text, XamlRoot = XamlRoot, RequestedTheme = ActualTheme, - PlacementTarget = pane, PlacementRect = new Rect(_columns.PaneX(at.Column), at.Row * _rowHeight, _columns.Width(at.Column), _rowHeight), Placement = PlacementMode.Top, }; + ToolTipService.SetPlacement(pane, PlacementMode.Top); + ToolTipService.SetToolTip(pane, _tip); + _tipOwner = pane; _tip.IsOpen = true; } From e26449e00892936311a2b147e6cc2c561fa48f9f Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sat, 14 Nov 2026 21:59:42 +0700 Subject: [PATCH 12/13] test(windows): read the value viewer's text through its text box --- .../TablePro.App.UITests/GridValueTests.cs | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/windows/tests/TablePro.App.UITests/GridValueTests.cs b/windows/tests/TablePro.App.UITests/GridValueTests.cs index 1af2665575..6b7cfb8f07 100644 --- a/windows/tests/TablePro.App.UITests/GridValueTests.cs +++ b/windows/tests/TablePro.App.UITests/GridValueTests.cs @@ -34,8 +34,7 @@ public void AQueryResultsMenuOpensAValueAsJsonAnImageOrItsHex(string theme) Assert.NotNull(app.TryFindMenuItem("Share result...")); app.Screenshot("80-results-grid-menu"); app.Click(app.FindMenuItem("View value..."), () => app.TryFind("ValueViewer") is not null); - var text = AppSession.WaitForText( - app.Find("ValueViewerText"), value => value.Contains("\"tracks\": [", StringComparison.Ordinal)); + var text = ViewerText(app, value => value.Contains("\"tracks\": [", StringComparison.Ordinal)); Assert.Contains("\"album\": \"Let There Be Rock\"", text, StringComparison.Ordinal); app.Screenshot("81-value-viewer-json"); app.CloseDialog(); @@ -46,10 +45,19 @@ public void AQueryResultsMenuOpensAValueAsJsonAnImageOrItsHex(string theme) app.Screenshot("82-value-viewer-image"); app.Click(app.Find("ValueViewerHexItem"), () => app.TryFind("ValueViewerText") is { IsOffscreen: false }); Assert.StartsWith( - "0x89504e47", - AppSession.WaitForText(app.Find("ValueViewerText"), value => value.StartsWith("0x", StringComparison.Ordinal)), - StringComparison.Ordinal); + "0x89504e47", ViewerText(app, value => value.StartsWith("0x", StringComparison.Ordinal)), StringComparison.Ordinal); app.Screenshot("83-value-viewer-hex"); app.CloseDialog(); } + + // The viewer's TextBox holds the value; its Name is the column's. + private static string ViewerText(AppSession app, Func done) + { + var text = string.Empty; + Retry.WhileFalse( + () => done(text = app.Find("ValueViewerText").AsTextBox().Text), + AppSession.Wait, + throwOnTimeout: false); + return text; + } } From bf6b2dd5906719a17c015b8b3404bbd300d06c09 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 15 Nov 2026 00:34:40 +0700 Subject: [PATCH 13/13] Revert "fix(core): read each child's CREATE TABLE once when listing the SQLite keys that point at a table" This reverts commit 9f834be7781542f3fb076c3f8f639e8ee3becb9d. --- core/crates/drivers/sqlite/src/catalog/mod.rs | 2 +- .../sqlite/src/catalog/table_definition.rs | 25 +++++++++---------- core/crates/drivers/sqlite/src/metadata.rs | 16 +++++------- 3 files changed, 19 insertions(+), 24 deletions(-) diff --git a/core/crates/drivers/sqlite/src/catalog/mod.rs b/core/crates/drivers/sqlite/src/catalog/mod.rs index a73e5cae48..f2e278239f 100644 --- a/core/crates/drivers/sqlite/src/catalog/mod.rs +++ b/core/crates/drivers/sqlite/src/catalog/mod.rs @@ -86,7 +86,7 @@ pub(crate) fn dependents_sql(schema_sql: &str) -> String { /// the ids number them all. pub(crate) fn inbound_keys_sql(schema_sql: &str) -> String { format!( - "SELECT m.name AS child, \ + "SELECT m.name AS child, m.sql AS child_sql, \ (SELECT count(DISTINCT k.id) FROM pragma_foreign_key_list(m.name, ?2) k) AS child_keys, \ f.id AS id, f.\"from\" AS \"from\", f.\"to\" AS \"to\" \ FROM {schema_sql}.sqlite_schema m, pragma_foreign_key_list(m.name, ?2) f \ diff --git a/core/crates/drivers/sqlite/src/catalog/table_definition.rs b/core/crates/drivers/sqlite/src/catalog/table_definition.rs index 4e9becbc67..c21ce7d190 100644 --- a/core/crates/drivers/sqlite/src/catalog/table_definition.rs +++ b/core/crates/drivers/sqlite/src/catalog/table_definition.rs @@ -14,6 +14,8 @@ use crate::ddl::declared_foreign_key_names; #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) struct InboundKeyRow { pub child: String, + /// The child's CREATE TABLE, where the key's declared name is. + pub child_sql: Option, /// How many foreign keys the child has, here or elsewhere. pub child_keys: usize, pub id: i64, @@ -24,14 +26,11 @@ pub(crate) struct InboundKeyRow { } /// Group key columns into keys, in the order the query returned them. -/// A key that names no parent columns points at `primary_key`. A key's -/// declared name is in its child's CREATE TABLE, `child_sql`, read once -/// per child rather than once per key column. +/// A key that names no parent columns points at `primary_key`. pub(crate) fn inbound_foreign_keys( schema: Option<&str>, rows: Vec, primary_key: &[String], - child_sql: &HashMap>, ) -> Vec { let mut keys: Vec = Vec::new(); let mut positions: HashMap<(String, i64), usize> = HashMap::new(); @@ -39,10 +38,7 @@ pub(crate) fn inbound_foreign_keys( let mut names: HashMap> = HashMap::new(); for row in rows { let child_names = names.entry(row.child.clone()).or_insert_with(|| { - let declared = child_sql - .get(&row.child) - .and_then(Option::as_deref) - .and_then(declared_foreign_key_names); + let declared = row.child_sql.as_deref().and_then(declared_foreign_key_names); foreign_key_names(&row.child, declared, row.child_keys) }); let name = usize::try_from(row.id) @@ -142,6 +138,7 @@ mod tests { fn key_row(child: &str, id: i64, from: &str, to: Option<&str>) -> InboundKeyRow { InboundKeyRow { child: child.to_owned(), + child_sql: None, child_keys: 3, id, from: from.to_owned(), @@ -157,7 +154,7 @@ mod tests { key_row("notes", 0, "order_b", Some("b")), ]; - let keys = inbound_foreign_keys(None, rows, &["id".to_owned()], &HashMap::new()); + let keys = inbound_foreign_keys(None, rows, &["id".to_owned()]); assert_eq!(keys.len(), 2); assert_eq!(keys[0].name, "fk_lines_0"); @@ -171,10 +168,12 @@ mod tests { fn a_declared_constraint_name_is_the_key_name() { let child_sql = "CREATE TABLE lines (a INTEGER CONSTRAINT to_orders REFERENCES orders, b INTEGER REFERENCES \ orders, CONSTRAINT to_orders FOREIGN KEY (a) REFERENCES orders)"; - let rows = [(0, "a"), (1, "b"), (2, "a")].map(|(id, from)| key_row("lines", id, from, None)); - let sql = HashMap::from([("lines".to_owned(), Some(child_sql.to_owned()))]); + let rows = [(0, "a"), (1, "b"), (2, "a")].map(|(id, from)| InboundKeyRow { + child_sql: Some(child_sql.to_owned()), + ..key_row("lines", id, from, None) + }); - let keys = inbound_foreign_keys(None, rows.to_vec(), &["id".to_owned()], &sql); + let keys = inbound_foreign_keys(None, rows.to_vec(), &["id".to_owned()]); let names: Vec<&str> = keys.iter().map(|key| key.name.as_str()).collect(); assert_eq!(names, ["to_orders", "fk_lines_1", "fk_lines_2"]); @@ -185,7 +184,7 @@ mod tests { ..row.clone() }) .collect(); - let unsure: Vec = inbound_foreign_keys(None, miscounted, &["id".to_owned()], &sql) + let unsure: Vec = inbound_foreign_keys(None, miscounted, &["id".to_owned()]) .into_iter() .map(|key| key.name) .collect(); diff --git a/core/crates/drivers/sqlite/src/metadata.rs b/core/crates/drivers/sqlite/src/metadata.rs index a51a46a5d0..8745ac145b 100644 --- a/core/crates/drivers/sqlite/src/metadata.rs +++ b/core/crates/drivers/sqlite/src/metadata.rs @@ -348,6 +348,7 @@ async fn inbound_keys( .map(|row| { Ok(InboundKeyRow { child: text(row, "child")?, + child_sql: row.try_get("child_sql").map_err(map_error)?, child_keys: usize::try_from(row.try_get::("child_keys").map_err(map_error)?).unwrap_or(0), id: row.try_get("id").map_err(map_error)?, from: text(row, "from")?, @@ -355,20 +356,15 @@ async fn inbound_keys( }) }) .collect::, DriverError>>()?; - // Read once per child, not on every key column's row: a child declaring thousands of keys would repeat its - // whole CREATE TABLE in each. - let mut child_sql: HashMap> = HashMap::new(); - for row in &rows { - if !child_sql.contains_key(&row.child) { - let child = TableRef::new(table.schema.clone(), row.child.clone()); - child_sql.insert(row.child.clone(), create_statement(connection, &child).await?); - } - } + let child_sql: HashMap> = rows + .iter() + .map(|row| (row.child.clone(), row.child_sql.clone())) + .collect(); let parent_sql = match rows.is_empty() { true => None, false => create_statement(connection, table).await?, }; - let mut keys = inbound_foreign_keys(table.schema.as_deref(), rows, &shape.primary_key(), &child_sql); + let mut keys = inbound_foreign_keys(table.schema.as_deref(), rows, &shape.primary_key()); for key in &mut keys { for column in &mut key.referenced_columns { *column = declared_spelling(column, shape.columns.iter().map(|declared| declared.name.as_str()));