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..1f58c984e6 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,7 +67,8 @@ pub use masking::{ ShareColumnMasking, ShareRefusal, ShareSummary, }; pub use prompter::{HostPrompter, PromptAnswer, PromptFieldInfo, PromptPurposeTag, PromptReasonTag, PromptRequest}; -pub use results::{ResultColumnInfo, ResultSet, ValueKind}; +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, SaveGate, TableEditor, diff --git a/core/crates/ffi/src/references.rs b/core/crates/ffi/src/references.rs new file mode 100644 index 0000000000..963c24c841 --- /dev/null +++ b/core/crates/ffi/src/references.rs @@ -0,0 +1,259 @@ +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 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 { + 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 }, +} + +// 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. +#[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, +} + +// 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, +} + +// 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. + 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`. + // 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 { + in_range(&rows, row)?; + let read = rows.result_columns(); + let referenced = self + .outbound + .iter() + .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() + .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 { + referenced, + 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") +} + +// 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 +// 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() }); + }; + 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) => { + 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() }, + }), + } +} 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 203a24f0da..e731b0862c 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, @@ -40,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) } @@ -84,6 +101,28 @@ impl ResultSet { .ok_or_else(|| CoreError::failed("ffi.out_of_range", format!("no cell at row {row}, column {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. `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, 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}"))) + } + // 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..a495b626ef 100644 --- a/core/crates/ffi/src/results/store.rs +++ b/core/crates/ffi/src/results/store.rs @@ -167,6 +167,23 @@ impl ResultStore { let cell = state.cell(row, column)?; Some(cell.kind.map(|kind| cell_text::full(kind, cell.bytes))) } + + // `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.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) + })) + } } impl ResultStore { @@ -177,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 1e60a1f88a..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, 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; @@ -548,3 +548,240 @@ 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() +} + +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(); + 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!(!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!( + filter.rules, + [ + rule("code", FilterOpTag::Eq, Some("x' OR 1=1 --")), + rule("region", FilterOpTag::Eq, Some("7")), + ] + ); + + let parents = page_rows(&session, "parent", Some(filter)).await; + assert_eq!(parents.row_count(), 1); + 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, Some(filter), 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.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!( + 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" + ); + session.close().await.unwrap(); +} + +#[tokio::test] +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(), + "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)); \ + 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 big VALUES (printf('%.9000c', 'x')); INSERT INTO small SELECT code FROM big", + ) + .await; + 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!( + 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!( + 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 references = session + .table_keys(table("parent"), None) + .await + .unwrap() + .row_references(parents, 0, None) + .unwrap(); + + assert_eq!(references.referencing.len(), 64); + session.close().await.unwrap(); +} + +#[tokio::test] +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', 'line one' || char(10) || 'line two'), (2, NULL, NULL)", + ) + .await; + let rows = page_rows(&session, "files", None).await; + + 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 a7a76a24d7..f505ea83fb 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. `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. ## Rationale diff --git a/windows/docs/decisions/0003-data-grid-control.md b/windows/docs/decisions/0003-data-grid-control.md index bb1bd48e99..ed0ba50172 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. 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. @@ -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..909aef5b41 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 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. + ### 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..2d0e7b391d --- /dev/null +++ b/windows/src/TablePro.App.Model/CellValue.cs @@ -0,0 +1,198 @@ +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, 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. + 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; + + // 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); + 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, false, null, 0, IsDefault: true); + } + + var pending = (state & (CellState.Modified | CellState.Inserted)) != 0; + if (pending || rows is null || row >= rows.RowCount) + { + // Text the user typed, or text the app holds itself, is in memory already. + return Of(name, reader.ReadWhole(row, column)); + } + + if (rows.GetCellBytes(row, column, MaximumPictureBytes) is { } binary) + { + return new CellValue(name, null, false, binary.Bytes, binary.Length, IsDefault: false); + } + + 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 static CellValue Of(string column, string? text) + { + ArgumentNullException.ThrowIfNull(column); + if (text is not { Length: > MaximumShownCharacters }) + { + return new CellValue(column, text, false, null, 0, IsDefault: false); + } + + var end = char.IsHighSurrogate(text[MaximumShownCharacters - 1]) ? MaximumShownCharacters - 1 : MaximumShownCharacters; + 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() + { + if (Bytes is not { } bytes) + { + return (string.Empty, false); + } + + var shown = bytes.Span[..Math.Min(bytes.Length, MaximumHexBytes)]; + return ("0x" + Convert.ToHexStringLower(shown), shown.Length < ByteLength); + } + + // 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 +// 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 5f39722dfc..24c79f80ef 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(); } @@ -70,6 +72,15 @@ 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); + + FollowedReference Follow(ResultSet? rows, long row, RowReferenceChoice choice); +} + // One save, which runs only the statements it was planned with. public interface IRowSave : IDisposable { @@ -171,9 +182,26 @@ 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 FollowedReference Follow(ResultSet? rows, long row, RowReferenceChoice choice) + { + ArgumentNullException.ThrowIfNull(rows); + return keys.Follow(rows, row, choice); + } + + public void Dispose() => keys.Dispose(); +} + internal sealed class CoreTableEditor(TableEditor editor) : ITableEditor { // Rows read at a time for their kinds, so a page of any size takes a bounded window. 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 b459bc4532..198a0d20b3 100644 --- a/windows/src/TablePro.App.Model/TableTab.cs +++ b/windows/src/TablePro.App.Model/TableTab.cs @@ -174,6 +174,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); @@ -317,6 +323,85 @@ 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 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) + && (!_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. + public static SessionTab TabFor(FollowedReference.Rows reference) + { + ArgumentNullException.ThrowIfNull(reference); + 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 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 ReferenceMenu.None; + } + + var rows = _results.ShownSet; + RowReferences references; + try + { + references = keys.ReferencesAt(rows, row, _results.Columns[column].Name); + } + catch (TableProException) + { + return ReferenceMenu.None; + } + + if (Edits is { } edits) + { + references = references with + { + Referenced = [.. references.Referenced.Where(reference => + !reference.Columns.Any(name => IsChanged(edits, row, name)))], + }; + } + + 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) + { + return null; + } + + try + { + return keys.Follow(menu.Rows, menu.Row, choice); + } + catch (TableProException) + { + return null; + } + } + // Recovered changes not yet put back go along, since nothing has asked about them. public SessionTab Snapshot() => new() { @@ -415,6 +500,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); @@ -749,6 +839,8 @@ private async Task CloseOnceAsync() SetEdits(null, null); _tableEditor?.Dispose(); _tableEditor = null; + _keys?.Dispose(); + _keys = null; await _session.ReleaseAsync().ConfigureAwait(true); } @@ -876,6 +968,7 @@ await _results.ShowRunAsync(_run, _sort, read.VisibleColumns, keptSets: 0, cance BindEdits(); RestoreRecovered(); CountIfNeeded(); + ReadKeysIfNeeded(); } catch (TableProException exception) { @@ -1276,6 +1369,68 @@ 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 (Exception exception) when (exception is TableProException or OperationCanceledException) + { + // An engine without foreign keys, a read that failed or one the server stopped; 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); @@ -1462,3 +1617,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/Strings/en-US/Resources.resw b/windows/src/TablePro.App/Strings/en-US/Resources.resw index bef28b743a..68b3a4293f 100644 --- a/windows/src/TablePro.App/Strings/en-US/Resources.resw +++ b/windows/src/TablePro.App/Strings/en-US/Resources.resw @@ -1800,6 +1800,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, and Copy takes that part. + + + 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..a4259a62e0 --- /dev/null +++ b/windows/src/TablePro.App/Views/CellValueViewer.cs @@ -0,0 +1,266 @@ +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); + using 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) + { + 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?.Source, + Stretch = Stretch.Uniform, + HorizontalAlignment = HorizontalAlignment.Left, + MaxWidth = picture?.Width ?? 0, + MaxHeight = Math.Min(ViewerHeight, picture?.Height ?? 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 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 += 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) + { + var (shown, cut) = mode switch + { + Mode.Json => json!.Value, + Mode.Hex => value.Hex(), + Mode.Text => (value.Text ?? string.Empty, value.TextCut), + _ => (string.Empty, false), + }; + 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; + } + + 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(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); + 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. 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)) + { + 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 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 + { + 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); + } + catch + { + source.Dispose(); + throw; + } + + 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(); + } +} 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 cb2070c2bc..d8ef31a87b 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; @@ -68,6 +67,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; @@ -224,37 +225,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 675df766f5..f581391439 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; @@ -75,6 +76,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; + // The open cell editor's text changed, which the session file keeps as a draft. public event EventHandler? DraftChanged; @@ -643,31 +649,99 @@ 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, ReferenceMenu references) + { + if (references.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.References.Referenced); + if (open.Count == 1) { - menu.ShowAt(grid, new FlyoutShowOptions { Position = point }); + menu.Items.Add(ReferenceItem(Strings.Get("GridMenuOpenReferenced"), references, open[0].Choice, "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, choice) in open) + { + choose.Items.Add(ReferenceItem(label, references, choice, null)); + } + + menu.Items.Add(choose); } - else + + var pointing = Labels(references.References.Referencing); + if (pointing.Count > 0) + { + var show = new MenuFlyoutSubItem { Text = Strings.Get("GridMenuShowReferencing") }; + foreach (var (label, choice) in pointing) + { + show.Items.Add(ReferenceItem(label, references, choice, null)); + } + + menu.Items.Add(show); + } + } + + private MenuFlyoutItem ReferenceItem(string label, ReferenceMenu references, RowReferenceChoice choice, string? automationId) + { + var item = new MenuFlyoutItem { Text = label }; + if (automationId is not null) { - menu.ShowAt(grid); + AutomationProperties.SetAutomationId(item, automationId); } + + item.Click += (_, _) => FollowReference(references, choice); + return item; + } + + // A key that cannot be followed is still offered, so choosing it says why. + private void FollowReference(ReferenceMenu references, RowReferenceChoice choice) + { + switch (_model.Follow(references, choice)) + { + 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; + } + } + + private List<(string Label, RowReferenceChoice Choice)> Labels(IReadOnlyList choices) + { + var shorts = choices.Select(choice => + { + 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(); + 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 f31acfd912..6d138db3cc 100644 --- a/windows/src/TablePro.App/Views/WorkspaceView.xaml.cs +++ b/windows/src/TablePro.App/Views/WorkspaceView.xaml.cs @@ -623,6 +623,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, FollowedReference.Rows reference) + { + if (_share is null) + { + return; + } + + int? index = null; + foreach (var item in Tabs.TabItems.OfType().ToList()) + { + if (item.Content is TableTabView view && view.Model.ShowsReference(reference)) + { + view.ShowData(); + 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, TableTab.TabFor(reference)); + } + private async void OnShareRequested(object? sender, ShareKind kind) => await ShareAsync(sender as ITabContent, kind).ConfigureAwait(true); @@ -748,8 +784,14 @@ 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 tableTab) { + tableTab.ReferenceRequested += OnReferenceRequested; tableTab.DraftChanged += OnEditorTextChanged; tableTab.SessionWriteRequested += OnSessionWriteRequested; } @@ -798,8 +840,14 @@ internal void Release(TabViewItem item) source.ShareRequested -= OnShareRequested; } + if (item.Content is IExportSource exports) + { + exports.ExportRequested -= OnExportRequested; + } + if (item.Content is TableTabView tableTab) { + tableTab.ReferenceRequested -= OnReferenceRequested; tableTab.DraftChanged -= OnEditorTextChanged; tableTab.SessionWriteRequested -= OnSessionWriteRequested; } 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 75ca8a3edc..0a7259b3a5 100644 --- a/windows/src/TablePro.DataGrid/DataGridView.Editing.cs +++ b/windows/src/TablePro.DataGrid/DataGridView.Editing.cs @@ -116,6 +116,7 @@ public void BeginEdit() public void EditsChanged() { + ClearCellTip(); if (_data is null) { return; @@ -325,6 +326,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..cfd3ffc5d3 --- /dev/null +++ b/windows/src/TablePro.DataGrid/DataGridView.Tips.cs @@ -0,0 +1,140 @@ +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 UIElement? _tipOwner; + 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; + } + } + if (_tipOwner is { } owner) + { + _tipOwner = null; + ToolTipService.SetToolTip(owner, null); + } + } + + // 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. 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, + 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; + } + + // 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..3021feb577 100644 --- a/windows/src/TablePro.Interop/Generated/tablepro_ffi.cs +++ b/windows/src/TablePro.Interop/Generated/tablepro_ffi.cs @@ -1150,6 +1150,18 @@ public struct UniffiVTableCallbackInterfaceRunListener + + + + + + + + + + + + @@ -1912,6 +1924,50 @@ 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_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) })] + 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 +2023,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,ulong @maxBytes,ref UniffiRustCallStatus _uniffi_out_err + ); + #if NET8_0_OR_GREATER [LibraryImport("tablepro_ffi")] [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] @@ -1978,6 +2045,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) })] @@ -2319,6 +2397,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 +4047,28 @@ 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) })] + 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 +4102,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) })] @@ -4002,6 +4124,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) })] @@ -4255,6 +4388,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 +5234,18 @@ 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) { + 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,12 +5264,24 @@ 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 != 40157) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_resultset_cell_bytes` checksum `40157`, library returned `{checksum}`"); + } + } { var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_resultset_cell_text(); if (checksum != 54600) { 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) { @@ -5252,6 +5420,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 +5879,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 +7308,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 +7482,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,7 +8555,11 @@ internal interface IResultSet { /// Task ShareSummary(uint @visibleColumns, uint @maxRows, ShareColumnChoice[] @columns); /// + 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. @@ -8506,6 +8729,15 @@ public async Task ShareSummary(uint @visibleColumns, uint @maxRows ); } + /// + 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), FfiConverterUInt64.INSTANCE.Lower(@maxBytes), ref _status) +))); + } + + /// public string? CellText(ulong @row, uint @column) { return CallWithPointer(thisPtr => FfiConverterOptionalString.INSTANCE.Lift( @@ -8515,6 +8747,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) => @@ -8916,10 +9157,153 @@ public EditStart EditStart(ResultSet @rows, ulong @row, uint @column) { /// - public RowSave Plan(ResultSet @rows, RowEdit[] @edits) { - return CallWithPointer(thisPtr => FfiConverterTypeRowSave.INSTANCE.Lift( + public RowSave Plan(ResultSet @rows, RowEdit[] @edits) { + return CallWithPointer(thisPtr => FfiConverterTypeRowSave.INSTANCE.Lift( + _UniffiHelpers.RustCallWithError(FfiConverterTypeCoreError.INSTANCE, (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_tableeditor_plan(thisPtr, FfiConverterTypeResultSet.INSTANCE.Lower(@rows), FfiConverterSequenceTypeRowEdit.INSTANCE.Lower(@edits), ref _status) +))); + } + + + + +} +class FfiConverterTypeTableEditor: FfiConverter { + public static FfiConverterTypeTableEditor INSTANCE = new FfiConverterTypeTableEditor(); + + + public override ulong Lower(TableEditor value) { + return value.CallWithPointer(thisPtr => thisPtr); + } + + public override TableEditor Lift(ulong value) { + return new TableEditor(value); + } + + public override TableEditor Read(BigEndianStream stream) { + return Lift(stream.ReadULong()); + } + + public override int AllocationSize(TableEditor value) { + return 8; + } + + public override void Write(TableEditor value, BigEndianStream stream) { + stream.WriteULong(Lower(value)); + } +} + + + +internal interface ITableKeys { + /// + FollowedReference FollowReference(ResultSet @rows, ulong @row, bool @referencing, uint @key); + /// + 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 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( _UniffiHelpers.RustCallWithError(FfiConverterTypeCoreError.INSTANCE, (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_tableeditor_plan(thisPtr, FfiConverterTypeResultSet.INSTANCE.Lower(@rows), FfiConverterSequenceTypeRowEdit.INSTANCE.Lower(@edits), ref _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) ))); } @@ -8927,27 +9311,27 @@ public RowSave Plan(ResultSet @rows, RowEdit[] @edits) { } -class FfiConverterTypeTableEditor: FfiConverter { - public static FfiConverterTypeTableEditor INSTANCE = new FfiConverterTypeTableEditor(); +class FfiConverterTypeTableKeys: FfiConverter { + public static FfiConverterTypeTableKeys INSTANCE = new FfiConverterTypeTableKeys(); - public override ulong Lower(TableEditor value) { + public override ulong Lower(TableKeys value) { return value.CallWithPointer(thisPtr => thisPtr); } - public override TableEditor Lift(ulong value) { - return new TableEditor(value); + public override TableKeys Lift(ulong value) { + return new TableKeys(value); } - public override TableEditor Read(BigEndianStream stream) { + public override TableKeys Read(BigEndianStream stream) { return Lift(stream.ReadULong()); } - public override int AllocationSize(TableEditor value) { + public override int AllocationSize(TableKeys value) { return 8; } - public override void Write(TableEditor value, BigEndianStream stream) { + public override void Write(TableKeys value, BigEndianStream stream) { stream.WriteULong(Lower(value)); } } @@ -9231,6 +9615,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 @@ -9261,6 +9675,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, @@ -10902,6 +11346,78 @@ public override void Write(ResultColumnInfo value, BigEndianStream stream) { +internal record RowReferenceChoice ( + uint Key, + bool Referencing, + string KeyName, + TableName Table, + string[] Columns +) { +} + +class FfiConverterTypeRowReferenceChoice: FfiConverterRustBuffer { + public static FfiConverterTypeRowReferenceChoice INSTANCE = new FfiConverterTypeRowReferenceChoice(); + + public override RowReferenceChoice Read(BigEndianStream stream) { + return new RowReferenceChoice( + Key: FfiConverterUInt32.INSTANCE.Read(stream), + Referencing: FfiConverterBoolean.INSTANCE.Read(stream), + KeyName: FfiConverterString.INSTANCE.Read(stream), + Table: FfiConverterTypeTableName.INSTANCE.Read(stream), + Columns: FfiConverterSequenceString.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(RowReferenceChoice value) { + return 0 + + FfiConverterUInt32.INSTANCE.AllocationSize(value.Key) + + FfiConverterBoolean.INSTANCE.AllocationSize(value.Referencing) + + FfiConverterString.INSTANCE.AllocationSize(value.KeyName) + + FfiConverterTypeTableName.INSTANCE.AllocationSize(value.Table) + + FfiConverterSequenceString.INSTANCE.AllocationSize(value.Columns); + } + + public override void Write(RowReferenceChoice value, BigEndianStream stream) { + FfiConverterUInt32.INSTANCE.Write(value.Key, stream); + FfiConverterBoolean.INSTANCE.Write(value.Referencing, stream); + FfiConverterString.INSTANCE.Write(value.KeyName, stream); + FfiConverterTypeTableName.INSTANCE.Write(value.Table, stream); + FfiConverterSequenceString.INSTANCE.Write(value.Columns, 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, @@ -12911,6 +13427,78 @@ public override void Write(FilterValueArg value, BigEndianStream stream) { +internal record FollowedReference { + + public record Rows ( + TableName Table, + TableFilterArg Filter + ) : FollowedReference {} + + public record Refused ( + ReferenceRefusal Refusal + ) : FollowedReference {} + + + +} + +class FfiConverterTypeFollowedReference : 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 {} @@ -13725,6 +14313,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 ( @@ -16475,6 +17161,68 @@ public override void Write(ResultSet? value, BigEndianStream stream) { +class FfiConverterOptionalTypeCellBytes: FfiConverterRustBuffer { + public static FfiConverterOptionalTypeCellBytes INSTANCE = new FfiConverterOptionalTypeCellBytes(); + + public override CellBytes? Read(BigEndianStream stream) { + if (stream.ReadByte() == 0) { + return null; + } + return FfiConverterTypeCellBytes.INSTANCE.Read(stream); + } + + public override int AllocationSize(CellBytes? value) { + if (value == null) { + return 1; + } else { + return 1 + FfiConverterTypeCellBytes.INSTANCE.AllocationSize((CellBytes)value); + } + } + + public override void Write(CellBytes? value, BigEndianStream stream) { + if (value == null) { + stream.WriteByte(0); + } else { + stream.WriteByte(1); + 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); + } + } +} + + + + class FfiConverterOptionalTypeColumnSort: FfiConverterRustBuffer { public static FfiConverterOptionalTypeColumnSort INSTANCE = new FfiConverterOptionalTypeColumnSort(); @@ -18200,6 +18948,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..630741b351 --- /dev/null +++ b/windows/src/TablePro.Interop/Mapping.References.cs @@ -0,0 +1,43 @@ +using Native = TablePro.Interop.Native; + +namespace TablePro.Interop; + +internal static partial class Mapping +{ + 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 + { + 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 => 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, + [.. 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..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,6 +36,27 @@ internal ResultSet(Native.ResultSet set, int index) return CoreCall.Run(() => _set.CellText(checked((ulong)row), checked((uint)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); + 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. 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..6cfeb38515 --- /dev/null +++ b/windows/src/TablePro.Interop/RowReference.cs @@ -0,0 +1,41 @@ +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, +} + +// 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); + +// 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) +{ + public static RowReferences None { get; } = new([], []); + + 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 new file mode 100644 index 0000000000..b7e3025412 --- /dev/null +++ b/windows/src/TablePro.Interop/TableKeys.cs @@ -0,0 +1,38 @@ +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; 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); + 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)]); + } + + // 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/CellValueTests.cs b/windows/tests/TablePro.App.Model.Tests/CellValueTests.cs new file mode 100644 index 0000000000..d0f958f71c --- /dev/null +++ b/windows/tests/TablePro.App.Model.Tests/CellValueTests.cs @@ -0,0 +1,104 @@ +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 BinaryShowsAndCopiesItsHexUpToItsLimitAndOnlyAWholeValueIsAPicture() + { + 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(hex, large.CopyText()); + Assert.False(large.IsWholeBinary); + Assert.False(small.IsNull); + Assert.Null(small.Json()); + } + + [Fact] + public void LongTextKeepsItsStartWithoutSplittingACharacterAndHasNoJsonLayout() + { + var text = "[" + new string('1', CellValue.MaximumShownCharacters - 2) + "👋" + "]"; + + var value = CellValue.Of("note", text); + + 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 ACellTheAppHoldsReadsThroughTheGridsData() + { + var data = new TextGridData(["doc", "note"], [["{\"a\":1}", null]]); + + var doc = CellValue.Read(data, null, 0, 0)!; + + 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)); + 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 06485cfa11..38ccf184bb 100644 --- a/windows/tests/TablePro.App.Model.Tests/TabFakes.cs +++ b/windows/tests/TablePro.App.Model.Tests/TabFakes.cs @@ -128,6 +128,18 @@ 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 FollowedReference Followed { get; set; } = new FollowedReference.Refused(ReferenceRefusal.UnevenKey, "fk"); + + 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. public FakeTableEditor TableEditor { get; } = new(); @@ -292,6 +304,23 @@ 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)); + } + + if (KeysStopped) + { + return Task.FromException(new OperationCanceledException()); + } + + var keys = new FakeKeys(this); + KeyReads.Add(keys); + return Task.FromResult(keys); + } + public ValueTask ReleaseAsync() { Releases++; @@ -301,6 +330,29 @@ 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 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; +} + 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..e7b2ec3164 --- /dev/null +++ b/windows/tests/TablePro.App.Model.Tests/TableTabReferenceTests.cs @@ -0,0 +1,196 @@ +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 FollowedReference.Rows ArtistRows = new(Artist, ToArtist); + + 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 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).References.IsEmpty); + + await _tab.RunAsync(); + var menu = _tab.ReferencesAt(0, 1); + await _tab.RunAsync(); + + 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)); + + 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).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] + public async Task APendingChangeInAKeysColumnHidesThatKeyButNotTheRowsPointingAtTheRow() + { + await _tab.RunAsync(); + + Assert.Null(_tab.CommitEdit(0, 1, "renamed")); + 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).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).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).References.IsEmpty); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task AKeyReadThatFailsOrIsStoppedLeavesTheRowsWithoutReferences(bool stopped) + { + _session.KeysFailure = stopped ? null : Errors.Of("driver.unsupported"); + _session.KeysStopped = stopped; + + await _tab.RunAsync(); + + Assert.Equal(3, _results.RowCount); + Assert.True(_tab.ReferencesAt(0, 1).References.IsEmpty); + Assert.DoesNotContain("error driver.unsupported", _results.Shown); + } + + [Fact] + public void AReferenceOpensAsATableTabOnItsFilterWhichATabReadWithTheSameFilterShows() + { + var spec = TableTab.TabFor(ArtistRows); + 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(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(ArtistRows)); + Assert.False(other.ShowsReference(ArtistRows)); + Assert.False(_tab.ShowsReference(ArtistRows)); + } + + [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(ArtistRows)); + view.Tab = target; + await target.RunAsync(); + 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(ArtistRows)); + querying.Open(); + await applying; + + Assert.Equal((false, false), whileReading); + Assert.False(target.ShowsReference(second)); + 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() + { + 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)); + } + + private static TableFilter SecondArtist => + ToArtist with { Rules = [new FilterRule("ArtistId", FilterOperator.Equal, new FilterValue.One("2"))] }; +} 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..6b7cfb8f07 --- /dev/null +++ b/windows/tests/TablePro.App.UITests/GridValueTests.cs @@ -0,0 +1,63 @@ +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 = 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(); + 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", 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; + } +} 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..16b7f96a5c --- /dev/null +++ b/windows/tests/TablePro.Interop.Tests/RowReferenceTests.cs @@ -0,0 +1,123 @@ +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.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")), + ], rows.Filter.Rules); + + 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(rows.Table, cancel); + var incoming = Assert.Single(parentKeys.GetRowReferences(parent, 0, null).Referencing); + Assert.Equal(Child, incoming.Table); + 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)); + } + + [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); + 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)); + 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 AKeyThatComparesOtherwiseIsOfferedAndRefusedNamingTheTable() + { + 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( + new FollowedReference.Refused(ReferenceRefusal.ComparedOtherwise, "child"), + keys.Follow(parents, 0, choice)); + } + + [Fact] + 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', 'line one' || char(10) || 'line two'), (2, NULL, NULL); + """); + using var files = await ReadAsync(database.Session, new TableName(null, "files"), null, cancel); + + 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( + 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)); + } +}