diff --git a/core/ARCHITECTURE.md b/core/ARCHITECTURE.md index 2998edc0e1..ef8f437f68 100644 --- a/core/ARCHITECTURE.md +++ b/core/ARCHITECTURE.md @@ -111,7 +111,7 @@ Each boundary error has a stable `code()`, such as `driver.timeout` or `ssh.host `ffi` is the library an app outside Rust loads: the Windows app as a DLL, the Apple apps as a static library in an XCFramework, built without the `engines` feature by `apple/scripts/build-core.sh`. Core ADRs 0002, on the bindings, 0003, on result windows, and 0009, on the macOS slices, hold the reasons. -- One UniFFI API. `Core` lists the engines with the family each is listed under, opens a file, connects a saved connection or tests one from a form, and parses a connection URL with `tablepro_core::connection_url`, refusing one that needs a setting its record has no field for. Its `ConnectionLibrary` reads and changes the saved connections, groups, favourites and tags in `connections.json` and stores their secrets, and gives the Apple apps the library's CloudKit records and merges a pull into it (`tablepro_storage::cloudkit`). A `DatabaseSession` reads the catalog one level at a time, writes a table's sorted page at an offset and counts the table, writes a query re-run with a sort (`docs/decisions/0007-sorting-a-result.md`), picks the statement at a caret with the session's grammar (`statement_at`), says what Safe Mode lets an editor run do at the session's level and takes a level saved while it is open (`gate_run`, over `SafeModeLevel::gate`, and `set_safe_mode`), reports and waits on the session's health, and opens a `QueryEditor`. `QueryEditor::run` returns a `QueryRun` at once; the app drains its events after a `RunListener` call, which comes only when no earlier one is waiting to be drained, and the last says which transaction the editor is left in. Each result set is a `ResultSet`, whose `sorted` gives the rows it holds in a column's order. +- One UniFFI API. `Core` lists the engines with the family each is listed under, opens a file, connects a saved connection or tests one from a form, and parses a connection URL with `tablepro_core::connection_url`, refusing one that needs a setting its record has no field for. Its `ConnectionLibrary` reads and changes the saved connections, groups, favourites and tags in `connections.json` and stores their secrets, and gives the Apple apps the library's CloudKit records and merges a pull into it (`tablepro_storage::cloudkit`). A `DatabaseSession` reads the catalog one level at a time, writes a table's sorted page at an offset and counts the table, writes a query re-run with a sort (`docs/decisions/0007-sorting-a-result.md`), picks the statement at a caret with the session's grammar (`statement_at`), says what Safe Mode lets an editor run do at the session's level and takes a level saved while it is open (`gate_run`, over `SafeModeLevel::gate`, and `set_safe_mode`), reports and waits on the session's health, opens a `QueryEditor`, and opens a `TableEditor`, which plans a table tab's typed edits into a `RowSave` and runs it (`docs/decisions/0019-row-edits-through-the-ffi.md`). `QueryEditor::run` returns a `QueryRun` at once; the app drains its events after a `RunListener` call, which comes only when no earlier one is waiting to be drained, and the last says which transaction the editor is left in. Each result set is a `ResultSet`, whose `sorted` gives the rows it holds in a column's order. - The grid reads a `ResultSet` through the C ABI in `src/window_abi.rs`: `tablepro_cursor_fetch` packs the display text of one visible range, and `tablepro_cursor_free` ends the cursor. - The library owns one tokio runtime. Each async export runs on it and is aborted when the foreign side drops the call; a `CancelToken` stops it sooner, since UniFFI cannot cancel. - A result set takes rows as the driver reads them. Each column keeps a kind byte, a raw `i64` and the exact text `tablepro_core::export::value_text` writes, or a binary value's bytes, in chunks of 65,536 rows. A window only cuts and copies. diff --git a/core/crates/core/src/dml/build_sql_error.rs b/core/crates/core/src/dml/build_sql_error.rs index 818eb6543c..7771ded689 100644 --- a/core/crates/core/src/dml/build_sql_error.rs +++ b/core/crates/core/src/dml/build_sql_error.rs @@ -30,3 +30,35 @@ pub enum BuildSqlError { #[error(transparent)] Bind(#[from] BindError), } + +impl BuildSqlError { + // Stable across releases, for an app outside Rust that words the error itself. + pub fn code(&self) -> &'static str { + match self { + Self::NoRowIdentity => "build.no_row_identity", + Self::ReadOnlyRows => "build.read_only_rows", + Self::UnknownKeyColumn { .. } => "build.unknown_key_column", + Self::NothingToUpdate => "build.nothing_to_update", + Self::NoInsertValues => "build.no_insert_values", + Self::LengthMismatch { .. } => "build.length_mismatch", + Self::UndecodableKey => "build.undecodable_key", + Self::UnaddressableField { .. } => "build.unaddressable_field", + Self::ServerComputedValue { .. } => "build.server_computed_value", + Self::Bind(_) => "build.bind", + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn each_code_names_its_variant_under_build() { + assert_eq!(BuildSqlError::NoRowIdentity.code(), "build.no_row_identity"); + assert_eq!( + BuildSqlError::ServerComputedValue { name: "id".to_owned() }.code(), + "build.server_computed_value" + ); + } +} diff --git a/core/crates/core/src/edit/edit_parse_error.rs b/core/crates/core/src/edit/edit_parse_error.rs index 3db143ecb8..aaadce8629 100644 --- a/core/crates/core/src/edit/edit_parse_error.rs +++ b/core/crates/core/src/edit/edit_parse_error.rs @@ -67,3 +67,65 @@ pub enum ReadOnlyReason { Composite, Variant, } + +impl EditParseError { + // Stable across releases, for an app outside Rust that words the error itself. + pub fn code(&self) -> &'static str { + match self { + Self::Required => "edit.required", + Self::InvalidInteger => "edit.invalid_integer", + Self::IntegerOutOfRange { .. } => "edit.integer_out_of_range", + Self::InvalidFloat => "edit.invalid_float", + Self::InvalidDecimal(_) => "edit.invalid_decimal", + Self::PrecisionExceeded { .. } => "edit.precision_exceeded", + Self::ScaleExceeded { .. } => "edit.scale_exceeded", + Self::InvalidBoolean => "edit.invalid_boolean", + Self::InvalidUuid => "edit.invalid_uuid", + Self::InvalidJson(_) => "edit.invalid_json", + Self::InvalidDate => "edit.invalid_date", + Self::InvalidTime => "edit.invalid_time", + Self::TimeOutOfRange => "edit.time_out_of_range", + Self::InvalidTimestamp => "edit.invalid_timestamp", + Self::OffsetRequired => "edit.offset_required", + Self::InvalidInterval => "edit.invalid_interval", + Self::InvalidBits => "edit.invalid_bits", + Self::InvalidBytes => "edit.invalid_bytes", + Self::BitLengthMismatch { .. } => "edit.bit_length_mismatch", + Self::UnknownEnumLabel => "edit.unknown_enum_label", + Self::NotEditable(_) => "edit.not_editable", + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn each_code_names_its_variant_under_edit() { + let codes = [ + EditParseError::Required.code(), + EditParseError::InvalidInteger.code(), + EditParseError::IntegerOutOfRange { + kind: IntegerKind { + width: crate::column::IntegerWidth::W32, + signed: true, + }, + } + .code(), + EditParseError::UnknownEnumLabel.code(), + EditParseError::NotEditable(ReadOnlyReason::Bytes).code(), + ]; + + assert_eq!( + codes, + [ + "edit.required", + "edit.invalid_integer", + "edit.integer_out_of_range", + "edit.unknown_enum_label", + "edit.not_editable" + ] + ); + } +} diff --git a/core/crates/ffi/src/error.rs b/core/crates/ffi/src/error.rs index e928ca7970..645e35b115 100644 --- a/core/crates/ffi/src/error.rs +++ b/core/crates/ffi/src/error.rs @@ -122,6 +122,14 @@ impl CoreError { Self::Failed { info } => &info.code, } } + + // As a record, a cancel included, for an outcome that reports the error instead of failing the call. + pub(crate) fn into_info(self) -> BoxedErrorInfo { + match self { + Self::Failed { info } => info, + Self::Cancelled => Box::new(ErrorInfo::plain(&["cancelled"], "cancelled".to_owned())), + } + } } impl ErrorInfo { diff --git a/core/crates/ffi/src/lib.rs b/core/crates/ffi/src/lib.rs index 0ac0879f76..018bf0c4b0 100644 --- a/core/crates/ffi/src/lib.rs +++ b/core/crates/ffi/src/lib.rs @@ -15,6 +15,7 @@ mod host_key; mod library; mod prompter; mod results; +mod row_edits; mod run; mod runtime; mod safe_mode_gate; @@ -38,6 +39,10 @@ pub use library::{ }; pub use prompter::{HostPrompter, PromptAnswer, PromptFieldInfo, PromptPurposeTag, PromptReasonTag, PromptRequest}; pub use results::{ResultColumnInfo, ResultSet, ValueKind}; +pub use row_edits::{ + CellChange, CellEdit, EditColumnInfo, EditLock, EditStart, PlannedStatement, RowEdit, RowSave, RowSaveOutcome, + SaveGate, TableEditor, +}; pub use run::{QueryRun, RunEvent, RunListener, RunOutcome, TransactionStateTag, TruncationTag}; pub use safe_mode_gate::RunGate; pub use session::{ColumnSort, DatabaseSession, FailureCauseTag, SessionHealthTag, TableQuery}; diff --git a/core/crates/ffi/src/results/column_cells.rs b/core/crates/ffi/src/results/column_cells.rs index d3c1d4518f..c9c111e48a 100644 --- a/core/crates/ffi/src/results/column_cells.rs +++ b/core/crates/ffi/src/results/column_cells.rs @@ -175,6 +175,46 @@ pub(super) fn cell_value(cell: Cell<'_>) -> Value { }) } +// The value a row was read with, for a key or an unchanged edit: what `push` kept exactly, or the text it wrote read back +// as the column it was read as, which `value_text` writes for that. `None` where neither names the stored value. +pub(super) fn stored_value(cell: Cell<'_>, column: &ColumnType) -> Option { + let Some(kind) = cell.kind else { + return Some(Value::Null); + }; + match kind { + ValueKind::Bool + | ValueKind::Integer + | ValueKind::UnsignedInteger + | ValueKind::WideInteger + | ValueKind::Decimal + | ValueKind::Text + | ValueKind::Bytes + | ValueKind::Uuid + | ValueKind::Date => match cell_value(cell) { + Value::Other(_) => None, + value => Some(value), + }, + ValueKind::Time + | ValueKind::TimeWithOffset + | ValueKind::Timestamp + | ValueKind::TimestampWithOffset + | ValueKind::Interval + | ValueKind::Bits => { + let text = std::str::from_utf8(cell.bytes).ok()?; + tablepro_core::edit::parse_literal_text(text, column).ok() + } + // A float widened to a double binds digits the column may not hold. + ValueKind::Float + | ValueKind::Json + | ValueKind::Xml + | ValueKind::Array + | ValueKind::Network + | ValueKind::Spatial + | ValueKind::Other + | ValueKind::Undecodable => None, + } +} + fn from_raw(raw: i64, finite: impl FnOnce(i64) -> Option) -> Temporal { match raw { i64::MAX => Temporal::Infinity, @@ -409,4 +449,43 @@ mod tests { assert_eq!(target.cell(3).bytes, [0xde, 0xad]); assert_eq!(target.cell(3).raw, 2); } + + #[test] + fn a_stored_value_is_exact_or_absent() { + use tablepro_core::column::{ColumnKind, ReadForm, TemporalZone}; + use tablepro_core::value::Temporal; + + let stamp_type = ColumnType { + name: "datetime2".to_owned(), + kind: ColumnKind::Timestamp { + fractional_digits: Some(7), + zone: TemporalZone::Naive, + }, + catalog: None, + dynamic_storage: false, + read_form: ReadForm::Native, + }; + let stamp = Value::Timestamp(Temporal::Finite( + NaiveDate::from_ymd_opt(2024, 6, 15) + .and_then(|date| date.and_hms_nano_opt(12, 0, 0, 123_456_700)) + .expect("a timestamp"), + )); + let mut timestamps = ColumnCells::default(); + timestamps.push(&stamp, &stamp_type); + let held = cells(&[ + Value::Int(-7), + Value::Text(" 2024-01-01 ".to_owned()), + Value::Float64(0.1), + Value::Null, + ]); + + assert_eq!(stored_value(held.cell(0), &column()), Some(Value::Int(-7))); + assert_eq!( + stored_value(held.cell(1), &column()), + Some(Value::Text(" 2024-01-01 ".to_owned())) + ); + assert_eq!(stored_value(held.cell(2), &column()), None); + assert_eq!(stored_value(held.cell(3), &column()), Some(Value::Null)); + assert_eq!(stored_value(timestamps.cell(0), &stamp_type), Some(stamp)); + } } diff --git a/core/crates/ffi/src/results/result_set.rs b/core/crates/ffi/src/results/result_set.rs index 081676ae0a..6b00c83580 100644 --- a/core/crates/ffi/src/results/result_set.rs +++ b/core/crates/ffi/src/results/result_set.rs @@ -28,6 +28,22 @@ impl ResultSet { } } + pub(crate) fn result_columns(&self) -> Arc<[tablepro_core::column::ResultColumn]> { + self.store.columns() + } + + pub(crate) fn stored_value(&self, row: u64, column: usize) -> Option { + self.store.stored_value(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) + } + + pub(crate) fn full_text(&self, row: u64, column: usize) -> Option> { + self.store.full_text(self.stored_row(row), column) + } + fn stored_row(&self, row: u64) -> u64 { self.order .as_ref() diff --git a/core/crates/ffi/src/results/store.rs b/core/crates/ffi/src/results/store.rs index dfa5f9be89..087389c75f 100644 --- a/core/crates/ffi/src/results/store.rs +++ b/core/crates/ffi/src/results/store.rs @@ -4,7 +4,7 @@ use tablepro_core::Value; use tablepro_core::column::ResultColumn; use tablepro_core::value::order::{row_order, sorts_as_text}; -use super::column_cells::{Cell, ColumnCells, cell_value}; +use super::column_cells::{Cell, ColumnCells, cell_value, stored_value}; use super::{ValueKind, cell_text}; // A full chunk is never written again, so an append copies at most one chunk's arrays when they grow. @@ -130,6 +130,20 @@ impl ResultStore { } } +impl ResultStore { + // `None` when the cell is not there or its value cannot be named exactly (`stored_value`). + pub(crate) fn stored_value(&self, row: u64, column: usize) -> Option { + let state = self.read(); + let read = &state.columns.get(column)?.column_type; + stored_value(state.cell(row, column)?, read) + } + + // 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) + } +} + impl ResultStore { // The rows held now, in a column's order. Rows that arrive later follow them as they came. pub(crate) fn row_order(&self, column: usize, ascending: bool) -> Option> { diff --git a/core/crates/ffi/src/row_edits.rs b/core/crates/ffi/src/row_edits.rs new file mode 100644 index 0000000000..fafb30372e --- /dev/null +++ b/core/crates/ffi/src/row_edits.rs @@ -0,0 +1,789 @@ +use std::collections::{HashMap, HashSet}; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; + +use tablepro_core::column::{ColumnInfo, ResultColumn}; +use tablepro_core::dialect::SqlDialect; +use tablepro_core::dml::BuildSqlError; +use tablepro_core::edit::{ + CellInput, EditContext, EditParseError, is_unchanged, new_draft_cell, parse_edit_text, read_only_reason, + value_for_column, +}; +use tablepro_core::export::value_to_text; +use tablepro_core::meta::{RowIdentity, TableRef}; +use tablepro_core::save::{ChangeSet, RowChange, RowUpdate, SavePlan, plan_save}; +use tablepro_core::sql_syntax::StatementAccess; +use tablepro_core::statement::Statement; +use tablepro_core::value::same_value; +use tablepro_core::{ + CommitResolution, DriverError, ErrorCategory, SafeModeLevel, Value, WriteGate, WriteKind, WriteReport, +}; +use tablepro_session::runtime::Tasks; +use tablepro_session::{OperationError, OperationKind, Session}; + +use crate::cancel_token::{CancelToken, token}; +use crate::catalog::TableName; +use crate::error::{BoxedErrorInfo, CoreError}; +use crate::results::{ResultSet, ValueKind}; +use crate::runtime::on_runtime; + +// What the user put in a cell. An empty text means what `parse_edit_text` says it means for the column. +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Enum)] +pub enum CellEdit { + Text { text: String }, + Null, + // The server's value: an insert leaves the column out, an update sets it to DEFAULT. + Default, +} + +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct CellChange { + pub column: u32, + pub edit: CellEdit, +} + +// A row of the page, by its place in the result set the page was read into. +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Enum)] +pub enum RowEdit { + Update { row: u64, cells: Vec }, + // One cell per column, in the table's order. + Insert { cells: Vec }, + Delete { row: u64 }, +} + +// Why no row of the table, or of the page, can be changed. +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Enum)] +pub enum EditLock { + ReadOnlyConnection, + NoPrimaryKey, + // A key the page holds cannot be named exactly, such as a float or PostgreSQL's server text for a date. + KeyUnreadable { column: String }, + // The page was read with other columns than the editor's catalog. + ColumnsChanged, +} + +// The Linux grid's rules: a saved row's key and a column the server fills are locked, a new row may set its key. +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct EditColumnInfo { + pub name: String, + pub editable: bool, + pub editable_in_new_row: bool, + // What a new row holds until the user types: the server's value where it has one, else NULL. + pub new_row: CellEdit, + pub nullable: bool, + pub primary_key: bool, + pub takes_empty: bool, + // A saved row's cell can be set to DEFAULT: a declared default, on an engine whose UPDATE takes one. + pub takes_default: bool, +} + +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Enum)] +pub enum EditStart { + // The whole value, never the grid's cut text; empty for NULL. + Editable { text: String, is_null: bool }, + ReadOnly, +} + +// One statement of a save, with the values it binds as they would be written, NULL included. +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct PlannedStatement { + pub sql: String, + pub values: Vec, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)] +pub enum SaveGate { + Run, + // Safe Mode asks before every write: the statements are shown first. + Confirm, + Refuse, +} + +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Enum)] +pub enum RowSaveOutcome { + Saved { rows: Option }, + // Nothing was written. `edit` is the place in the edits of the change the save stopped at, when the engine said. + RolledBack { error: BoxedErrorInfo, edit: Option }, + // The save may have landed in part or in full; saving again could write it twice. + Unknown { error: BoxedErrorInfo, edit: Option }, +} + +// A table tab's rows as the save sees them: the catalog's columns, keyed by the primary key, as the Linux tracker keys +// them. +#[derive(uniffi::Object)] +pub struct TableEditor { + session: Arc, + tasks: Tasks, + table: TableRef, + columns: Arc<[ColumnInfo]>, + lock: Option, +} + +impl TableEditor { + pub(crate) async fn open( + session: Arc, + tasks: Tasks, + table: TableName, + refresh: bool, + cancel: Option>, + ) -> Result, CoreError> { + let cancel = token(cancel); + let runtime = tasks.clone(); + on_runtime(&runtime, async move { + let table: TableRef = table.into(); + let read = async { + match refresh { + true => session.refresh_columns(table.clone()).await, + false => session.columns(table.clone()).await, + } + }; + let columns = tokio::select! { + biased; + () = cancel.cancelled() => return Err(CoreError::Cancelled), + columns = read => columns?, + }; + let lock = if session.read_only() { + Some(EditLock::ReadOnlyConnection) + } else if !columns.iter().any(|column| column.primary_key) { + Some(EditLock::NoPrimaryKey) + } else { + None + }; + Ok(Arc::new(Self { + session, + tasks, + table, + columns, + lock, + })) + }) + .await + } + + fn column(&self, column: u32) -> Result<&ColumnInfo, CoreError> { + usize::try_from(column) + .ok() + .and_then(|index| self.columns.get(index)) + .ok_or_else(|| CoreError::failed("edit.out_of_range", format!("no column {column}"))) + } + + fn require_unlocked(&self) -> Result<(), CoreError> { + match &self.lock { + None if self.session.read_only() => Err(lock_error(&EditLock::ReadOnlyConnection)), + None => Ok(()), + Some(lock) => Err(lock_error(lock)), + } + } + + // The result set holds the page's columns first, which build_page lays out in the catalog's order. + fn check_layout(&self, rows: &[ResultColumn]) -> Result<(), CoreError> { + let same = rows.len() >= self.columns.len() + && self + .columns + .iter() + .zip(rows) + .all(|(catalog, read)| catalog.name == read.name); + match same { + true => Ok(()), + false => Err(CoreError::failed( + "edit.columns_changed", + "the rows were read with other columns than the table has now", + )), + } + } + + fn key(&self, rows: &ResultSet, read: &[ResultColumn], row: u64) -> Result, CoreError> { + let mut key = Vec::new(); + for (index, column) in self.columns.iter().enumerate().filter(|(_, column)| column.primary_key) { + let value = key_value(rows, read, row, index, column).ok_or_else(|| { + CoreError::failed( + "edit.key_unreadable", + format!( + "the key column {} of row {row} cannot be read back exactly", + column.name + ), + ) + })?; + key.push(value); + } + Ok(key) + } + + fn unreadable_key(&self, rows: &ResultSet, read: &[ResultColumn], row: u64) -> Option { + self.columns + .iter() + .enumerate() + .filter(|(_, column)| column.primary_key) + .find(|(index, column)| key_value(rows, read, row, *index, column).is_none()) + .map(|(_, column)| column.name.clone()) + } + + fn input(&self, column: &ColumnInfo, edit: &CellEdit, context: EditContext) -> Result { + let input = match edit { + CellEdit::Text { text } => parse_edit_text(text, column, context).map_err(parse_error)?, + CellEdit::Null if column.nullable => CellInput::Value(Value::Null), + CellEdit::Null => return Err(parse_error(EditParseError::Required)), + CellEdit::Default => CellInput::Default, + }; + Ok(input) + } + + // In the host's order, which is the order the changes were made, as the Linux tracker keeps it, so a new parent + // row saves before the child pointed at it. A row is written once: a deleted row's updates go, one row's updates + // merge, later cells winning. + fn change_set( + &self, + dialect: &dyn SqlDialect, + rows: &ResultSet, + edits: &[RowEdit], + ) -> Result<(ChangeSet, Vec), CoreError> { + let read = rows.result_columns(); + let reads_rows = edits.iter().any(|edit| !matches!(edit, RowEdit::Insert { .. })); + if reads_rows { + self.check_layout(&read)?; + } + let deleted: HashSet = edits + .iter() + .filter_map(|edit| match edit { + RowEdit::Delete { row } => Some(*row), + _ => None, + }) + .collect(); + let mut updates: HashMap> = HashMap::new(); + for edit in edits { + if let RowEdit::Update { row, cells } = edit { + updates.entry(*row).or_default().extend(cells.iter().cloned()); + } + } + let mut written = HashSet::new(); + let mut changes = Vec::with_capacity(edits.len()); + let mut origins = Vec::with_capacity(edits.len()); + for (index, edit) in edits.iter().enumerate() { + let change = match edit { + RowEdit::Delete { row } if written.insert(*row) => Some(RowChange::Delete { + key: self.key(rows, &read, *row)?, + }), + RowEdit::Update { row, .. } if !deleted.contains(row) && written.insert(*row) => { + let cells = updates.get(row).map(Vec::as_slice).unwrap_or_default(); + self.update(dialect, rows, &read, *row, cells)? + } + RowEdit::Insert { cells } => Some(self.insert(cells)?), + RowEdit::Delete { .. } | RowEdit::Update { .. } => None, + }; + if let Some(change) = change { + changes.push(change); + origins.push(u32::try_from(index).unwrap_or(u32::MAX)); + } + } + Ok((ChangeSet { changes }, origins)) + } + + fn check_cell( + &self, + dialect: Option<&dyn SqlDialect>, + column: &ColumnInfo, + edit: &CellEdit, + new_row: bool, + ) -> Result { + let open = match new_row { + true => editable_in_new_row(column), + false => editable(column), + }; + if !open { + return Err(parse_error(EditParseError::NotEditable( + read_only_reason(&column.column_type.kind).unwrap_or(tablepro_core::edit::ReadOnlyReason::Undecodable), + ))); + } + if !new_row && matches!(edit, CellEdit::Default) && !takes_default(column, dialect) { + return Err(CoreError::failed( + "edit.no_default", + format!("column {} has no default an update can set", column.name), + )); + } + let context = match new_row { + true => EditContext::InsertDraft, + false => EditContext::UpdateRow, + }; + self.input(column, edit, context) + } + + fn update( + &self, + dialect: &dyn SqlDialect, + rows: &ResultSet, + read: &[ResultColumn], + row: u64, + cells: &[CellChange], + ) -> Result, CoreError> { + let mut assignments: Vec<(usize, CellInput)> = Vec::with_capacity(cells.len()); + for cell in cells { + let column = self.column(cell.column)?; + let index = cell.column as usize; + let input = self.check_cell(Some(dialect), column, &cell.edit, false)?; + let original = rows + .stored_value(row, index) + .and_then(|value| value_for_column(&value, &read[index].column_type, &column.column_type)); + let unchanged = match (&input, &original) { + (CellInput::Value(edited), Some(original)) => is_unchanged(original, edited, &column.column_type), + _ => false, + }; + // A later edit of the same cell is the one that counts, also when it puts the value back. + assignments.retain(|(position, _)| *position != index); + if !unchanged { + assignments.push((index, input)); + } + } + if assignments.is_empty() { + return Ok(None); + } + Ok(Some(RowChange::Update(RowUpdate { + key: self.key(rows, read, row)?, + assignments, + }))) + } + + fn insert(&self, cells: &[CellEdit]) -> Result { + if cells.len() != self.columns.len() { + return Err(CoreError::failed( + "edit.columns_changed", + format!( + "a new row has {} cells and the table {} columns", + cells.len(), + self.columns.len() + ), + )); + } + let mut inputs = Vec::with_capacity(cells.len()); + for (column, edit) in self.columns.iter().zip(cells) { + // SQL Server IDENTITY and PostgreSQL GENERATED ALWAYS refuse a value, so the server fills them. + if column.is_auto_increment || column.is_generated { + inputs.push(CellInput::Default); + continue; + } + // A column with no text to type, such as a blob, still takes NULL or the server's value in a new row. + let input = match edit { + CellEdit::Text { .. } => self.check_cell(None, column, edit, true)?, + CellEdit::Null | CellEdit::Default => self.input(column, edit, EditContext::InsertDraft)?, + }; + inputs.push(input); + } + Ok(RowChange::Insert { cells: inputs }) + } +} + +#[uniffi::export] +impl TableEditor { + pub fn lock(&self) -> Option { + match &self.lock { + None if self.session.read_only() => Some(EditLock::ReadOnlyConnection), + lock => lock.clone(), + } + } + + // The page's own locks too: a lock here leaves every row of `rows` as it is. + pub fn lock_for(&self, rows: Arc) -> Option { + if let Some(lock) = self.lock() { + return Some(lock); + } + let read = rows.result_columns(); + if self.check_layout(&read).is_err() { + return Some(EditLock::ColumnsChanged); + } + if rows.row_count() == 0 { + return None; + } + self.unreadable_key(&rows, &read, 0) + .map(|column| EditLock::KeyUnreadable { column }) + } + + pub fn columns(&self) -> Vec { + let dialect = self.session.current_dialect(); + self.columns + .iter() + .map(|column| EditColumnInfo { + name: column.name.clone(), + editable: editable(column), + editable_in_new_row: editable_in_new_row(column), + new_row: match new_draft_cell(column) { + CellInput::Value(Value::Null) => CellEdit::Null, + _ => CellEdit::Default, + }, + nullable: column.nullable, + primary_key: column.primary_key, + takes_empty: column.column_type.kind.accepts_empty_string(), + takes_default: takes_default(column, dialect.as_deref()), + }) + .collect() + } + + // The text a cell's editor starts from: the whole value, which the grid shows cut. + pub fn edit_start(&self, rows: Arc, row: u64, column: u32) -> Result { + let info = self.column(column)?; + if !editable(info) { + return Ok(EditStart::ReadOnly); + } + let index = column as usize; + let kind = rows + .cell_kind(row, index) + .ok_or_else(|| CoreError::failed("edit.out_of_range", format!("no cell at row {row}, column {column}")))?; + // A value the driver could not read, or bytes, have no text that writes them back. + if matches!(kind, Some(ValueKind::Undecodable | ValueKind::Bytes)) { + return Ok(EditStart::ReadOnly); + } + let text = rows.full_text(row, index).flatten(); + Ok(EditStart::Editable { + is_null: text.is_none(), + text: text.unwrap_or_default(), + }) + } + + // Reads the text as the save will, so a cell the user leaves can say why it would not save. + pub fn check(&self, column: u32, edit: CellEdit, new_row: bool) -> Result<(), CoreError> { + let info = self.column(column)?; + let dialect = self.session.current_dialect(); + self.check_cell(dialect.as_deref(), info, &edit, new_row).map(|_| ()) + } + + // The statements the edits save as, at the session's Safe Mode level now. `rows` is the result set the rows were + // read into; a cell edited back to its value is left out. + pub fn plan(&self, rows: Arc, edits: Vec) -> Result, CoreError> { + self.require_unlocked()?; + let dialect = self + .session + .current_dialect() + .ok_or_else(|| CoreError::failed("ffi.not_connected", "the session has no connection"))?; + let (changes, origins) = self.change_set(&*dialect, &rows, &edits)?; + let identity = pk_identity(&self.columns); + let plan = plan_save(&*dialect, &self.table, &self.columns, &identity, &changes).map_err(build_error)?; + let level = self.session.safe_mode(); + Ok(Arc::new(RowSave { + session: self.session.clone(), + tasks: self.tasks.clone(), + table: self.table.clone(), + columns: self.columns.clone(), + identity, + changes, + origins, + plan, + level, + started: AtomicBool::new(false), + })) + } +} + +// One save, which runs only the statements it was planned with. +#[derive(uniffi::Object)] +pub struct RowSave { + session: Arc, + tasks: Tasks, + table: TableRef, + columns: Arc<[ColumnInfo]>, + identity: RowIdentity, + changes: ChangeSet, + origins: Vec, + plan: SavePlan, + level: SafeModeLevel, + started: AtomicBool, +} + +#[uniffi::export] +impl RowSave { + pub fn statements(&self) -> Vec { + self.plan + .batch + .steps + .iter() + .map(|step| planned(&step.statement)) + .collect() + } + + pub fn is_empty(&self) -> bool { + self.plan.batch.steps.is_empty() + } + + // Row changes are writes, so Off saves, Confirm writes asks first and Read only refuses. + pub fn gate(&self) -> SaveGate { + save_gate(self.level) + } + + // Runs the statements shown, planned again on the connection that writes them. `confirmed` says the user answered + // Safe Mode's question. Another level than the one planned at, or another plan, refuses before anything is sent. + pub async fn run(&self, confirmed: bool, cancel: Option>) -> Result { + let planned_gate = self.gate(); + if planned_gate == SaveGate::Confirm && !confirmed { + return Err(CoreError::failed( + "edit.not_confirmed", + "Safe Mode asks before this save and it was not answered", + )); + } + let now = save_gate(self.session.safe_mode()); + if now == SaveGate::Refuse { + return Err(lock_error(&EditLock::ReadOnlyConnection)); + } + if now != planned_gate { + return Err(safe_mode_changed()); + } + if self.is_empty() { + return Ok(RowSaveOutcome::Saved { rows: Some(0) }); + } + // A second run would write the same rows twice. + if self.started.swap(true, Ordering::AcqRel) { + return Err(CoreError::failed("edit.already_saved", "this save already ran")); + } + let session = self.session.clone(); + let cancel = token(cancel); + let table = self.table.clone(); + let columns = self.columns.clone(); + let identity = self.identity.clone(); + let changes = self.changes.clone(); + let shown = self.plan.clone(); + let planned = self.plan.clone(); + let origins = self.origins.clone(); + on_runtime(&self.tasks, async move { + let gated = session.clone(); + let written = session + .run_cancellable( + OperationKind::Save(WriteKind::RowChanges), + &cancel, + move |lease, options| { + let (table, columns, identity, changes, shown, gated) = ( + table.clone(), + columns.clone(), + identity.clone(), + changes.clone(), + shown.clone(), + gated.clone(), + ); + async move { + // Checked again on the lease, so a level saved while the save waited for it holds. + if save_gate(gated.safe_mode()) != planned_gate { + return Ok(Err(safe_mode_changed())); + } + let plan = plan_save(&*lease.dialect(), &table, &columns, &identity, &changes)?; + // A connection replaced since the plan can write other SQL than the user was shown. + if !same_plan(&plan, &shown) { + return Ok(Err(CoreError::failed( + "edit.not_as_planned", + "the connection would save other statements than the ones planned", + ))); + } + Ok(Ok(lease.write_batch(&plan.batch, options).await?)) + } + }, + ) + .await; + let written = match written { + Ok(Err(refused)) => return Err(refused), + Ok(Ok(report)) => Ok(report), + Err(error) => Err(error), + }; + let resolution = resolve_commit(&session, &written).await; + Ok(outcome(written, resolution, &planned, &origins)) + }) + .await + } +} + +fn save_gate(level: SafeModeLevel) -> SaveGate { + match level.gate(StatementAccess::Write) { + WriteGate::Run => SaveGate::Run, + WriteGate::Confirm => SaveGate::Confirm, + WriteGate::Refuse => SaveGate::Refuse, + } +} + +// The primary key columns in the table's order, the order a key is read in. +fn pk_identity(columns: &[ColumnInfo]) -> RowIdentity { + RowIdentity::UniqueKey { + columns: columns + .iter() + .filter(|column| column.primary_key) + .map(|column| column.name.clone()) + .collect(), + } +} + +fn editable(column: &ColumnInfo) -> bool { + !column.primary_key && editable_in_new_row(column) +} + +fn editable_in_new_row(column: &ColumnInfo) -> bool { + !column.is_generated && !column.is_auto_increment && read_only_reason(&column.column_type.kind).is_none() +} + +// SQLite and a ClickHouse mutation have no `SET c = DEFAULT`, so only a dialect that parses it offers one. +fn takes_default(column: &ColumnInfo, dialect: Option<&dyn SqlDialect>) -> bool { + !column.default.is_none() && !column.is_generated && dialect.is_some_and(SqlDialect::update_sets_default) +} + +fn key_value(rows: &ResultSet, read: &[ResultColumn], row: u64, index: usize, column: &ColumnInfo) -> Option { + rows.stored_value(row, index) + .and_then(|value| value_for_column(&value, &read.get(index)?.column_type, &column.column_type)) + .filter(|value| !matches!(value, Value::Null)) +} + +fn safe_mode_changed() -> CoreError { + CoreError::failed( + "edit.safe_mode_changed", + "the connection's Safe Mode changed after the save was planned", + ) +} + +fn planned(statement: &Statement) -> PlannedStatement { + PlannedStatement { + sql: statement.sql().to_owned(), + values: statement + .params() + .iter() + .map(|param| shown_value(param.value())) + .collect(), + } +} + +// A bound value as the user would write it, on one line. +fn shown_value(value: &Value) -> String { + let Some(text) = value_to_text(value) else { + return "NULL".to_owned(); + }; + let text = text.replace(['\n', '\r'], " "); + match value { + Value::Bool(_) + | Value::Int(_) + | Value::UInt(_) + | Value::WideInt(_) + | Value::Float32(_) + | Value::Float64(_) + | Value::Decimal(_) => text, + _ => format!("'{}'", text.replace('\'', "''")), + } +} + +// Statement by statement, the same SQL binding the same values. A NaN is the same NaN, which `==` on floats denies. +fn same_plan(left: &SavePlan, right: &SavePlan) -> bool { + left.batch.steps.len() == right.batch.steps.len() + && left.batch.steps.iter().zip(&right.batch.steps).all(|(left, right)| { + let (left, right) = (&left.statement, &right.statement); + left.sql() == right.sql() + && left.params().len() == right.params().len() + && left.params().iter().zip(right.params()).all(|(left, right)| { + left.param_type() == right.param_type() && same_value(left.value(), right.value()) + }) + }) +} + +// Ask the server what became of a commit whose acknowledgement was lost, where the engine left a way to ask. +async fn resolve_commit( + session: &Session, + written: &Result, +) -> Option> { + let Err(OperationError::Driver(DriverError::CommitOutcomeUnknown { token: Some(token), .. })) = written else { + return None; + }; + let token = token.clone(); + let resolved = session + .run(OperationKind::Metadata, move |lease, options| { + let token = token.clone(); + async move { + lease + .resolve_commit(&token, options) + .await + .map_err(OperationError::from) + } + }) + .await; + if let Err(error) = &resolved { + tracing::warn!(%error, "could not ask the server whether a save landed"); + } + Some(resolved) +} + +// As the Linux app reads a save's result: what is in the database now decides. +fn outcome( + written: Result, + resolution: Option>, + plan: &SavePlan, + origins: &[u32], +) -> RowSaveOutcome { + let error = match written { + Ok(report) => { + return RowSaveOutcome::Saved { + rows: report.total_rows(), + }; + } + Err(error) => error, + }; + let info = || CoreError::from(&error).into_info(); + let edit = |step: usize| plan.origin(step).and_then(|change| origins.get(change).copied()); + match &error { + OperationError::Driver(driver) => match driver { + DriverError::RolledBack { statement_index, .. } + | DriverError::RowGuardFailed { statement_index, .. } + | DriverError::GuardUnsupported { statement_index } => RowSaveOutcome::RolledBack { + error: info(), + edit: edit(*statement_index), + }, + DriverError::ReadOnly(_) => RowSaveOutcome::RolledBack { + error: info(), + edit: None, + }, + DriverError::CommitOutcomeUnknown { .. } => match resolution { + Some(Ok(CommitResolution::Applied)) => RowSaveOutcome::Saved { rows: None }, + Some(Ok(CommitResolution::NotApplied)) => RowSaveOutcome::RolledBack { + error: info(), + edit: None, + }, + _ => RowSaveOutcome::Unknown { + error: info(), + edit: None, + }, + }, + DriverError::PartiallyApplied { statement_index, .. } => RowSaveOutcome::Unknown { + error: info(), + edit: edit(*statement_index), + }, + other => match other.category() { + ErrorCategory::Interrupted | ErrorCategory::Timeout | ErrorCategory::ConnectionLost => { + RowSaveOutcome::Unknown { + error: info(), + edit: None, + } + } + _ => RowSaveOutcome::RolledBack { + error: info(), + edit: None, + }, + }, + }, + OperationError::Sql(_) | OperationError::Build(_) | OperationError::Browse(_) => RowSaveOutcome::RolledBack { + error: info(), + edit: None, + }, + OperationError::Cancelled | OperationError::Panicked(_) | OperationError::Closed => RowSaveOutcome::Unknown { + error: info(), + edit: None, + }, + } +} + +fn lock_error(lock: &EditLock) -> CoreError { + match lock { + EditLock::ReadOnlyConnection => CoreError::failed("edit.read_only_connection", "the connection is read-only"), + EditLock::NoPrimaryKey => CoreError::failed("edit.no_primary_key", "the table has no primary key"), + EditLock::KeyUnreadable { column } => CoreError::failed( + "edit.key_unreadable", + format!("the key column {column} cannot be read back exactly"), + ), + EditLock::ColumnsChanged => CoreError::failed( + "edit.columns_changed", + "the rows were read with other columns than the table has now", + ), + } +} + +fn parse_error(error: EditParseError) -> CoreError { + CoreError::failed(error.code(), error.to_string()) +} + +fn build_error(error: BuildSqlError) -> CoreError { + CoreError::failed(error.code(), error.to_string()) +} diff --git a/core/crates/ffi/src/session.rs b/core/crates/ffi/src/session.rs index c77a71ec81..ebc122001b 100644 --- a/core/crates/ffi/src/session.rs +++ b/core/crates/ffi/src/session.rs @@ -13,6 +13,7 @@ use crate::catalog::{ColumnEntry, ObjectEntry, ObjectScopeArg, SchemaEntry, Tabl use crate::editor::QueryEditor; use crate::error::{BoxedErrorInfo, CoreError}; use crate::library::SafeModeTag; +use crate::row_edits::TableEditor; use crate::runtime::on_runtime; use crate::safe_mode_gate::{self, RunGate}; use crate::statement_at::{self, StatementSpan}; @@ -328,6 +329,17 @@ impl DatabaseSession { self.session.set_safe_mode(level.into()) } + // The table's rows as a save sees them, for a table tab that edits. `refresh` reads the catalog again, as a + // tab's Refresh does, so the page that follows is read with the same columns. + pub async fn table_editor( + &self, + table: TableName, + refresh: bool, + cancel: Option>, + ) -> Result, CoreError> { + TableEditor::open(self.session.clone(), self.tasks.clone(), table, refresh, cancel).await + } + pub async fn open_editor(&self, cancel: Option>) -> Result, CoreError> { let session = self.session.clone(); let tasks = self.tasks.clone(); diff --git a/core/crates/ffi/tests/row_edits.rs b/core/crates/ffi/tests/row_edits.rs new file mode 100644 index 0000000000..b51a85ea45 --- /dev/null +++ b/core/crates/ffi/tests/row_edits.rs @@ -0,0 +1,549 @@ +#![cfg(feature = "engines")] +#![expect( + clippy::unwrap_used, + reason = "the setup helpers fail a test the way the test functions themselves do" +)] + +use std::path::Path; +use std::sync::Arc; + +use tablepro_ffi::{ + CellChange, CellEdit, ConnectionRecord, ConnectionSecrets, Core, DatabaseSession, EditLock, EditStart, + FileOpenRequest, HostConfig, HostSecretError, HostSecrets, ResultSet, RowEdit, RowSaveOutcome, RunListener, + RunOutcome, RunSettings, SafeModeTag, SaveGate, SecretItemTag, SecretKindTag, TableName, TlsModeTag, TlsSettings, +}; + +struct NoSecrets; + +impl HostSecrets for NoSecrets { + fn load(&self, _: String, _: SecretKindTag) -> Result, HostSecretError> { + Ok(None) + } + + fn store(&self, _: String, _: SecretKindTag, _: String, _: String) -> Result<(), HostSecretError> { + Ok(()) + } + + fn relabel(&self, _: String, _: SecretKindTag, _: String) -> Result<(), HostSecretError> { + Ok(()) + } + + fn delete(&self, _: String, _: SecretKindTag) -> Result<(), HostSecretError> { + Ok(()) + } + + fn delete_connection(&self, _: String) -> Result<(), HostSecretError> { + Ok(()) + } + + fn load_item(&self, _: SecretItemTag) -> Result, HostSecretError> { + Ok(None) + } + + fn store_item(&self, _: SecretItemTag, _: String) -> Result<(), HostSecretError> { + Ok(()) + } + + fn delete_item(&self, _: SecretItemTag) -> Result<(), HostSecretError> { + Ok(()) + } +} + +struct Quiet; + +impl RunListener for Quiet { + fn events_pending(&self) {} +} + +fn core(dir: &Path) -> Arc { + Core::new( + HostConfig { + client_version: "test".to_owned(), + storage_dir: Some(dir.display().to_string()), + }, + Box::new(NoSecrets), + ) + .unwrap() +} + +fn file(path: &Path, read_only: bool) -> FileOpenRequest { + FileOpenRequest { + path: path.display().to_string(), + driver_id: None, + read_only, + create: false, + } +} + +fn people() -> TableName { + TableName { + schema: None, + name: "people".to_owned(), + } +} + +async fn run(session: &DatabaseSession, sql: &str) -> Option> { + let editor = session.open_editor(None).await.unwrap(); + let run = editor.run(sql.to_owned(), RunSettings::default(), Box::new(Quiet)); + assert!(matches!(run.outcome().await.unwrap(), RunOutcome::Completed { .. })); + let set = run.result_set(0); + editor.close().await.unwrap(); + set +} + +async fn seeded(core: &Core, path: &Path) { + let create = FileOpenRequest { + create: true, + ..file(path, false) + }; + let session = core.open_file(create, None).await.unwrap(); + run( + &session, + "CREATE TABLE people (id INTEGER PRIMARY KEY, name TEXT NOT NULL, age INTEGER, \ + joined TEXT DEFAULT 'today'); \ + INSERT INTO people (id, name, age) VALUES (1, 'Ada', 36), (2, 'Grace', 45), (3, 'Linus', 21); \ + CREATE TABLE notes (body TEXT)", + ) + .await; + session.close().await.unwrap(); +} + +// The page as a table tab reads it, through the core's own statement. +async fn page(session: &DatabaseSession) -> Arc { + let query = session.table_query(people(), None, 100, 0, None).await.unwrap(); + run(session, &query.sql).await.unwrap() +} + +async fn rows(session: &DatabaseSession) -> Vec>> { + let set = run(session, "SELECT id, name, age, joined FROM people ORDER BY id") + .await + .unwrap(); + (0..set.row_count()) + .map(|row| (0..4).map(|column| set.cell_text(row, column).unwrap()).collect()) + .collect() +} + +fn text(value: &str) -> CellEdit { + CellEdit::Text { text: value.to_owned() } +} + +fn row(values: [Option<&str>; 4]) -> Vec> { + values.iter().map(|value| value.map(str::to_owned)).collect() +} + +async fn saved(core: &Core, path: &Path, safe_mode: SafeModeTag) -> Arc { + let record = ConnectionRecord { + id: String::new(), + name: "people".to_owned(), + driver_id: "sqlite".to_owned(), + host: String::new(), + port: 0, + database: path.display().to_string(), + username: String::new(), + integrated_auth: false, + tls: TlsSettings { + mode: TlsModeTag::Disable, + ca_file: None, + client_certificate: None, + client_key: None, + server_name: None, + }, + ssh: None, + safe_mode, + query_timeout_secs: None, + color: None, + group_id: None, + last_opened_ms: None, + tags: Vec::new(), + }; + let saved = core + .library() + .unwrap() + .save(record, ConnectionSecrets::default()) + .await + .unwrap(); + core.connect_saved(saved.id, ConnectionSecrets::default(), None, None) + .await + .unwrap() +} + +#[tokio::test] +async fn an_update_an_insert_and_a_delete_save_as_one_batch() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("people.sqlite"); + let core = core(dir.path()); + seeded(&core, &path).await; + let session = core.open_file(file(&path, false), None).await.unwrap(); + let editor = session.table_editor(people(), false, None).await.unwrap(); + let shown = page(&session).await; + + let save = editor + .plan( + shown, + vec![ + RowEdit::Update { + row: 0, + cells: vec![CellChange { + column: 1, + edit: text("Ada Lovelace"), + }], + }, + RowEdit::Insert { + cells: vec![CellEdit::Default, text("Edsger"), CellEdit::Null, CellEdit::Default], + }, + RowEdit::Delete { row: 2 }, + ], + ) + .unwrap(); + let statements = save.statements(); + let outcome = save.run(false, None).await.unwrap(); + let again = save.run(false, None).await.err().unwrap(); + let after = rows(&session).await; + session.close().await.unwrap(); + + assert_eq!(again.code(), "edit.already_saved"); + assert_eq!(save.gate(), SaveGate::Run); + assert_eq!(statements.len(), 3); + assert!(statements[0].sql.starts_with("UPDATE"), "{statements:?}"); + assert_eq!(statements[0].values, ["'Ada Lovelace'", "1"]); + assert!(statements[1].sql.starts_with("INSERT"), "{statements:?}"); + assert!(statements[2].sql.starts_with("DELETE"), "{statements:?}"); + assert_eq!(statements[2].values, ["3"]); + assert_eq!(outcome, RowSaveOutcome::Saved { rows: Some(3) }); + assert_eq!( + after, + [ + row([Some("1"), Some("Ada Lovelace"), Some("36"), Some("today")]), + row([Some("2"), Some("Grace"), Some("45"), Some("today")]), + row([Some("4"), Some("Edsger"), None, Some("today")]), + ] + ); +} + +#[tokio::test] +async fn a_cell_edited_back_to_its_value_saves_nothing() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("people.sqlite"); + let core = core(dir.path()); + seeded(&core, &path).await; + let session = core.open_file(file(&path, false), None).await.unwrap(); + let editor = session.table_editor(people(), false, None).await.unwrap(); + let shown = page(&session).await; + + let save = editor + .plan( + shown, + vec![RowEdit::Update { + row: 1, + cells: vec![ + CellChange { + column: 1, + edit: text("Grace"), + }, + CellChange { + column: 2, + edit: text("45"), + }, + ], + }], + ) + .unwrap(); + session.close().await.unwrap(); + + assert!(save.is_empty()); +} + +#[tokio::test] +async fn text_the_column_cannot_hold_is_refused_with_its_code() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("people.sqlite"); + let core = core(dir.path()); + seeded(&core, &path).await; + let session = core.open_file(file(&path, false), None).await.unwrap(); + let editor = session.table_editor(people(), false, None).await.unwrap(); + + let number = editor.check(2, text("forty"), false).unwrap_err(); + let required = editor.check(1, CellEdit::Null, false).unwrap_err(); + let fine = editor.check(2, text("40"), false); + session.close().await.unwrap(); + + assert_eq!(number.code(), "edit.invalid_integer"); + assert_eq!(required.code(), "edit.required"); + assert!(fine.is_ok()); +} + +#[tokio::test] +async fn the_editor_starts_from_the_whole_value_and_a_new_row_from_the_server_s_values() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("people.sqlite"); + let core = core(dir.path()); + seeded(&core, &path).await; + let session = core.open_file(file(&path, false), None).await.unwrap(); + let editor = session.table_editor(people(), false, None).await.unwrap(); + let shown = page(&session).await; + + let name = editor.edit_start(shown.clone(), 0, 1).unwrap(); + let columns = editor.columns(); + session.close().await.unwrap(); + + assert_eq!( + name, + EditStart::Editable { + text: "Ada".to_owned(), + is_null: false + } + ); + assert_eq!(editor.lock(), None); + let news: Vec = columns.iter().map(|column| column.new_row.clone()).collect(); + assert_eq!( + news, + [CellEdit::Default, CellEdit::Null, CellEdit::Null, CellEdit::Default] + ); + assert!(columns[0].primary_key); + assert!(!columns[0].editable); + assert!(columns[1].editable); + assert!(columns[1].takes_empty); + assert!(!columns[3].takes_default); +} + +#[tokio::test] +async fn a_table_with_no_primary_key_and_a_read_only_file_lock_every_row() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("people.sqlite"); + let core = core(dir.path()); + seeded(&core, &path).await; + let session = core.open_file(file(&path, false), None).await.unwrap(); + let notes = session + .table_editor( + TableName { + schema: None, + name: "notes".to_owned(), + }, + false, + None, + ) + .await + .unwrap(); + let no_key = notes.lock(); + session.close().await.unwrap(); + let read_only = core.open_file(file(&path, true), None).await.unwrap(); + let locked = read_only.table_editor(people(), false, None).await.unwrap(); + let shown = page(&read_only).await; + let refused = locked.plan(shown, vec![RowEdit::Delete { row: 0 }]); + read_only.close().await.unwrap(); + + assert_eq!(no_key, Some(EditLock::NoPrimaryKey)); + assert_eq!(locked.lock(), Some(EditLock::ReadOnlyConnection)); + assert_eq!(refused.err().unwrap().code(), "edit.read_only_connection"); +} + +#[tokio::test] +async fn confirm_writes_shows_a_save_first_and_a_stricter_level_refuses_it() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("people.sqlite"); + let core = core(dir.path()); + seeded(&core, &path).await; + let session = saved(&core, &path, SafeModeTag::Off).await; + let editor = session.table_editor(people(), false, None).await.unwrap(); + let shown = page(&session).await; + let delete = vec![RowEdit::Delete { row: 0 }]; + + let at_off = editor.plan(shown.clone(), delete.clone()).unwrap(); + assert!(session.set_safe_mode(SafeModeTag::ConfirmWrites)); + let refused = at_off.run(false, None).await.err().unwrap(); + let asked = editor.plan(shown, delete).unwrap(); + let unanswered = asked.run(false, None).await.err().unwrap(); + let outcome = asked.run(true, None).await.unwrap(); + let after = rows(&session).await; + session.close().await.unwrap(); + + assert_eq!(at_off.gate(), SaveGate::Run); + assert_eq!(refused.code(), "edit.safe_mode_changed"); + assert_eq!(asked.gate(), SaveGate::Confirm); + assert_eq!(unanswered.code(), "edit.not_confirmed"); + assert_eq!(outcome, RowSaveOutcome::Saved { rows: Some(1) }); + assert_eq!(after.len(), 2); +} + +#[tokio::test] +async fn a_row_that_changed_under_the_save_rolls_every_change_back() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("people.sqlite"); + let core = core(dir.path()); + seeded(&core, &path).await; + let session = core.open_file(file(&path, false), None).await.unwrap(); + let editor = session.table_editor(people(), false, None).await.unwrap(); + let shown = page(&session).await; + run(&session, "DELETE FROM people WHERE id = 2").await; + + let save = editor + .plan( + shown, + vec![ + RowEdit::Update { + row: 0, + cells: vec![CellChange { + column: 2, + edit: text("37"), + }], + }, + RowEdit::Update { + row: 1, + cells: vec![CellChange { + column: 2, + edit: text("46"), + }], + }, + ], + ) + .unwrap(); + let outcome = save.run(false, None).await.unwrap(); + let after = rows(&session).await; + session.close().await.unwrap(); + + match outcome { + RowSaveOutcome::RolledBack { error, edit } => { + assert_eq!(error.code, "driver.row_guard_failed"); + assert_eq!(edit, Some(1)); + } + other => panic!("expected a rollback, got {other:?}"), + } + assert_eq!(after[0][2].as_deref(), Some("36")); +} + +#[tokio::test] +async fn a_saved_row_is_written_once_and_its_key_and_default_are_refused() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("people.sqlite"); + let core = core(dir.path()); + seeded(&core, &path).await; + let session = core.open_file(file(&path, false), None).await.unwrap(); + let editor = session.table_editor(people(), false, None).await.unwrap(); + let shown = page(&session).await; + + let key = editor.check(0, text("9"), false).unwrap_err(); + let rowid_in_new_row = editor.check(0, text("9"), true).unwrap_err(); + let default = editor.check(3, CellEdit::Default, false).unwrap_err(); + let save = editor + .plan( + shown, + vec![ + RowEdit::Update { + row: 0, + cells: vec![CellChange { + column: 1, + edit: text("first"), + }], + }, + RowEdit::Update { + row: 1, + cells: vec![CellChange { + column: 1, + edit: text("gone anyway"), + }], + }, + RowEdit::Delete { row: 1 }, + RowEdit::Update { + row: 0, + cells: vec![ + CellChange { + column: 1, + edit: text("Ada"), + }, + CellChange { + column: 2, + edit: text("37"), + }, + ], + }, + ], + ) + .unwrap(); + let statements = save.statements(); + session.close().await.unwrap(); + + assert_eq!(key.code(), "edit.not_editable"); + // A rowid alias is the server's to fill, as the Linux grid locks an auto-increment key in a new row. + assert_eq!(rowid_in_new_row.code(), "edit.not_editable"); + assert_eq!(default.code(), "edit.no_default"); + assert_eq!(statements.len(), 2, "{statements:?}"); + assert!(statements[0].sql.starts_with("UPDATE"), "{statements:?}"); + assert_eq!(statements[0].values, ["37", "1"]); + assert!(statements[1].sql.starts_with("DELETE"), "{statements:?}"); +} + +#[tokio::test] +async fn a_page_whose_key_cannot_be_named_exactly_is_locked() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("people.sqlite"); + let core = core(dir.path()); + seeded(&core, &path).await; + let session = core.open_file(file(&path, false), None).await.unwrap(); + run( + &session, + "CREATE TABLE readings (at REAL PRIMARY KEY, value TEXT); INSERT INTO readings VALUES (0.1, 'a')", + ) + .await; + let readings = TableName { + schema: None, + name: "readings".to_owned(), + }; + let editor = session.table_editor(readings.clone(), false, None).await.unwrap(); + let query = session.table_query(readings, None, 100, 0, None).await.unwrap(); + let shown = run(&session, &query.sql).await.unwrap(); + let people_editor = session.table_editor(people(), false, None).await.unwrap(); + let people_page = page(&session).await; + + let lock = editor.lock_for(shown); + let open = people_editor.lock_for(people_page); + session.close().await.unwrap(); + + assert_eq!( + lock, + Some(EditLock::KeyUnreadable { + column: "at".to_owned() + }) + ); + assert_eq!(open, None); +} + +#[tokio::test] +async fn a_new_row_leaves_a_blob_null_and_a_refresh_reads_the_columns_again() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("people.sqlite"); + let core = core(dir.path()); + seeded(&core, &path).await; + let session = core.open_file(file(&path, false), None).await.unwrap(); + run( + &session, + "CREATE TABLE files (id INTEGER PRIMARY KEY, name TEXT, body BLOB)", + ) + .await; + let files = TableName { + schema: None, + name: "files".to_owned(), + }; + let editor = session.table_editor(files.clone(), false, None).await.unwrap(); + let query = session.table_query(files.clone(), None, 100, 0, None).await.unwrap(); + let shown = run(&session, &query.sql).await.unwrap(); + + let typed = editor.check(2, text("0x00"), true).unwrap_err(); + let save = editor + .plan( + shown, + vec![RowEdit::Insert { + cells: vec![CellEdit::Default, text("notes.txt"), CellEdit::Null], + }], + ) + .unwrap(); + let outcome = save.run(false, None).await.unwrap(); + run(&session, "ALTER TABLE files ADD COLUMN size INTEGER").await; + let cached = session.table_editor(files.clone(), false, None).await.unwrap(); + let refreshed = session.table_editor(files, true, None).await.unwrap(); + session.close().await.unwrap(); + + assert_eq!(typed.code(), "edit.not_editable"); + assert_eq!(outcome, RowSaveOutcome::Saved { rows: Some(1) }); + assert_eq!(cached.columns().len(), 3); + assert_eq!(refreshed.columns().len(), 4); +} diff --git a/core/docs/decisions/0019-row-edits-through-the-ffi.md b/core/docs/decisions/0019-row-edits-through-the-ffi.md new file mode 100644 index 0000000000..32185689f7 --- /dev/null +++ b/core/docs/decisions/0019-row-edits-through-the-ffi.md @@ -0,0 +1,41 @@ +# 0019: A table tab's row edits cross the FFI as typed text, and the core plans and runs the save + +- **Status**: Accepted +- **Date**: 2026-11-11 + +## Context + +The Windows app shows a table page from a `ResultSet` the core holds, read as windows of text ([0003](0003-result-windows-for-native-grids.md)). Editing it writes rows back. The Linux app keeps its pending edits as `Value`s in its own tracker and saves through `save::plan_save` with the primary key as the row identity. An app on the FFI holds no `Value`: only display text and cell kinds cross. + +The result store keeps each value formatted once, on arrival. Integers, booleans, wide integers, decimals, text, bytes, UUIDs and dates keep what names the value exactly. A float keeps its double's bits, which for a `real` column binds digits the column never held. A time, timestamp or interval keeps the text `value_text` wrote for it, which `parse_literal_text` reads back as the same value for the column it was read as. PostgreSQL's editor reads every column as server text, which `edit::value_for_column` turns into the catalog's type where that text is exact (0015). + +## Decision + +The app sends what the user typed; the core reads every key and stored value from the result set and plans, previews and runs the save. + +- `DatabaseSession::table_editor` gives a `TableEditor` over the catalog's columns, read again when the host asks (a tab's Refresh), locked for a read-only connection or a table with no primary key, as the Linux tracker keys rows by `pk_identity`. `lock_for` adds a page's own locks: columns that are not the catalog's, in order, and a key the page holds that cannot be named exactly. +- A column follows the Linux grid's rules (`cell_editability`, `cell_presets`): a saved row's key, a generated or auto-increment column and a kind with no text are locked to typing; a new row may set its key, the server fills a generated or auto-increment column whatever the row holds, and a kind with no text takes NULL or the server's value in a new row. DEFAULT goes into a saved row only for a declared default on an engine whose UPDATE takes one. +- An edit is `CellEdit::Text`, `Null` or `Default`, per row of the page by its place in the set (`RowEdit::Update`, `Delete`) or as a new row (`Insert`, one cell per column). Text is read with `parse_edit_text`, so an empty cell means what it means on Linux; `check` reads one cell the same way, with the `EditParseError` code. +- `TableEditor::plan` reads each key column back (`stored_value`, then `value_for_column`) and refuses a key it cannot name exactly (`edit.key_unreadable`). The edits keep the host's order, which places each row at its latest change, as the Linux tracker orders its rows, so a parent row added before a child is pointed at it saves first, unless the parent changed again after. A row is written once: a deleted row's updates go, one row's updates merge with later cells winning, and a cell edited back to its value is dropped (`is_unchanged`). +- A `RowSave` holds the plan. `statements` gives each statement with its bound values as the user would write them, as the Linux confirmation lists them. `gate` is `SafeModeLevel::gate(Write)`: Off saves, Confirm writes shows the statements first, Read only refuses. +- `RowSave::run(confirmed)` refuses a Confirm writes save the user did not answer (`edit.not_confirmed`), a level other than the one planned at, checked again on the writing lease (`edit.safe_mode_changed`), and a plan the lease makes differently from the one shown (`edit.not_as_planned`). It runs once, as one `WriteBatch`, asks the server about a lost commit acknowledgement, and reports `Saved`, `RolledBack` or `Unknown` with the edit it stopped at, as the Linux app's `SaveOutcome::classify` reads a write. +- `EditParseError` and `BuildSqlError` gain stable `code()`s, `edit.*` and `build.*`. + +## Rationale + +- Values never cross the boundary, so nothing is lost to a round trip through display text, and the SQL is the core's, as on Linux. +- The pending edits are what the user typed against rows of one page, which the app already holds, so the app needs no copy of the core's value types. +- Planning again on the writing lease is the guard the Linux structure save keeps: the statements shown are the statements sent. + +## Consequences + +- An edit names a row by its place in the set the page was read into, so an app asks before anything replaces that set (a sort, a page, a refresh) while edits are pending, as macOS does, and opens the editor again on a refresh with `refresh`, which reads the catalog again before the page. +- A table whose primary key is a float, or a type the store keeps only as other text, is read-only. +- A table with no primary key is read-only, where macOS matches every column. +- A query result edits through 0015 later; this API covers a table tab. + +## Alternatives considered + +- **The tracker in the core.** The Linux tracker is the Linux app's, with its undo and its relayout; an app on the FFI needs only typed text per row, which it already holds. +- **Keys as display text.** A cut or locale-free text that is not the stored value could name another row. +- **Keeping the page's `Value`s in the store.** Twice the memory for every page, for the few columns a key needs. diff --git a/core/docs/decisions/README.md b/core/docs/decisions/README.md index eec617ac43..776cfa3b6f 100644 --- a/core/docs/decisions/README.md +++ b/core/docs/decisions/README.md @@ -26,3 +26,4 @@ The format, the statuses and how a later ADR changes an earlier one follow [the | [0016](0016-tablepro-accounts.md) | TablePro accounts live in the core, with features gated by the entitlement | Accepted | `tablepro-account` signs in through the browser with OAuth and a loopback redirect, registers the device, verifies the Ed25519 entitlement and gates features by its codes; each app passes its keyring, browser, machine ID and OAuth client in. | | [0017](0017-favourites.md) | Favourites keep folders and keywords on saved queries, and the tables and databases a user marks | Accepted | One migration in the history's database adds per-connection folders that nest, a keyword and an order on saved queries, and favourite tables and databases with the four macOS environments; stable error codes, no UUID ids, and a database an older build wrote is copied first. | | [0018](0018-command-line.md) | One command line for the apps on the core | Accepted | `tablepro-cli` parses with clap, writes the macOS command's formats and exit status, and reaches the app's MCP server with the token the app's host reads; `classify` leaves files, links and GUI options to the app. | +| [0019](0019-row-edits-through-the-ffi.md) | A table tab's row edits cross the FFI as typed text, and the core plans and runs the save | Accepted | `TableEditor` over the catalog's primary key reads keys and stored values from the result set, parses typed text with `parse_edit_text` and plans with `plan_save`; `RowSave` shows its statements with their values, gates at `SafeModeLevel::gate(Write)`, plans again on the writing lease and reports saved, rolled back or unknown. | diff --git a/windows/AGENTS.md b/windows/AGENTS.md index 549859b2e4..6740cccc03 100644 --- a/windows/AGENTS.md +++ b/windows/AGENTS.md @@ -19,12 +19,12 @@ This is the guide for work under `windows/`. The root `AGENTS.md` holds the rule - `src/TablePro.Editor.Model`: the editor's text, carets, undo history, find and line-state highlighter. Plain `net10.0` with no WinUI, so `tests/TablePro.Editor.Model.Tests` runs anywhere. - `src/TablePro.Graphics`: the one text and drawing stack the controls share: Direct3D, Direct2D and DirectWrite through TerraFX, the editor's swap chain and line layouts, theme colors, and the font fallback warm-up. Its types are internal to the controls. - `src/TablePro.Editor`: the `SqlEditor` control over that model: Direct2D and DirectWrite in a SwapChainPanel, TSF, the UIA text provider, and the core's lexer through `CoreSqlLexer`. -- `src/TablePro.DataGrid.Model`: the grid's columns, selection, keys, cell blocks read from the core (`ResultSetData`) and Excel-style copy. Plain `net10.0`, so `tests/TablePro.DataGrid.Model.Tests` runs anywhere; its `Needs=Core` tests load the real core. -- `src/TablePro.DataGrid`: the read-only `DataGridView` control: ItemsRepeater rows that draw their cells with DirectWrite into composition surfaces, frozen columns, the header row, and UIA peers. +- `src/TablePro.DataGrid.Model`: the grid's columns, selection, keys, cell blocks read from the core (`ResultSetData`), pending edits laid over them (`EditedGridData`) and Excel-style copy. Plain `net10.0`, so `tests/TablePro.DataGrid.Model.Tests` runs anywhere; its `Needs=Core` tests load the real core. +- `src/TablePro.DataGrid`: the `DataGridView` control: ItemsRepeater rows that draw their cells with DirectWrite into composition surfaces, frozen columns, the header row, in-place cell editing with pending-change marks, and UIA peers. - `tests/TablePro.DataGrid.Tests`: the control in a real WinUI window on a thread of its own. It runs on Windows and only compiles elsewhere. - `tests/TablePro.DataGrid.Gate` and `tests/TablePro.DataGrid.Gate.Uia`: the grid's timing and behavior gate, outside the solution. `ci/run-gate.ps1` builds and runs it; `.github/workflows/windows-grid-gate.yml` runs it by dispatch. - `src/TablePro.App`: the WinUI app: one window, the rail, the Connections page, the connection form window, Settings and a workspace per connection (`docs/decisions/0004-app-shell.md`). Strings are in `Strings/en-US/Resources.resw`. -- `src/TablePro.App.Model`: the app's settings and session files, the library tree, the connection form's fields and the object folders. Plain `net10.0`, so `tests/TablePro.App.Model.Tests` runs anywhere. +- `src/TablePro.App.Model`: the app's settings and session files, the library tree, the connection form's fields, the object folders, the tab and connection lifecycles over small session, editor and run interfaces, and a table tab's pending edits. Plain `net10.0`, so `tests/TablePro.App.Model.Tests` runs anywhere. - `tests/TablePro.App.UITests`: UI Automation tests (FlaUI) that launch the built app with a data folder of their own, and the installed MSIX once `TABLEPRO_PACKAGE` names its family. - `ci/desktop.ps1`: readies a hosted runner's desktop for UI work (privacy settings window, WSL console, display size, window dragging), for `windows.yml`, `release-windows.yml` and the grid gate. - `ci/winget-manifest.py`: writes a release's winget manifest, for `release-windows.yml`. @@ -42,6 +42,7 @@ This is the guide for work under `windows/`. The root `AGENTS.md` holds the rule - A grid reads a `ResultSet` through `ResultCursor.Fetch`, one window per visible range. A cursor belongs to one thread, and a window cannot be read after the cursor's next fetch. - `DataGridView.SetData(new ResultSetData(set, columns))` shows a set. Call the grid's `RowsChanged` after each `RowsAppended`. Sorting is the host's: the grid raises `SortRequested` and shows `Sort`. - The core writes every sorted statement: `GetTableQueryAsync` for a table, `SortedQuery` for a query result, null when the statement cannot run again or the engine cannot name the column. `ResultSet.SortedAsync` then sorts the rows held (`core/docs/decisions/0007-sorting-a-result.md`). `GetTableQueryAsync` takes the page's offset, and `CanSeek` says whether the engine has later pages; `CountRowsAsync` counts the table. +- A table tab edits through `DatabaseSession.OpenTableEditorAsync`: the app sends what was typed (`CellEdit`) per row of the page's `ResultSet`, and `TableEditor.Plan` gives a `RowSave` with its statements and Safe Mode gate, which `RunAsync` saves (`core/docs/decisions/0019-row-edits-through-the-ffi.md`). - `QueryEvent.Finished.Transaction` is the transaction the editor's connection is left in. A session's `Health` is waited on with `WaitForHealthChangeAsync`, which returns once it differs from the one passed in. - The app starts the core with `TableProCore.CreateWithSystemSecrets`, so the core keeps secrets in Credential Manager itself. `ISecretStore` is for tests and hosts with a store of their own; the core calls it on a thread of its own. - `TableProCore.Library` reads and writes the saved connections in the storage directory the configuration names. A list the app shows is rebuilt from `GetSnapshotAsync` after each change. diff --git a/windows/docs/decisions/0003-data-grid-control.md b/windows/docs/decisions/0003-data-grid-control.md index fd6e096087..bb1bd48e99 100644 --- a/windows/docs/decisions/0003-data-grid-control.md +++ b/windows/docs/decisions/0003-data-grid-control.md @@ -14,7 +14,7 @@ ## Decision -`TablePro.DataGrid` is a read-only WinUI 3 control of our own. ItemsRepeater virtualizes the rows, and each row draws its visible cells' text with DirectWrite into a composition surface, through `TablePro.Graphics`, the one drawing layer the editor uses too. Cells are UIA peers with no element. The data comes from the core through `TablePro.Interop`, formatted there. +`TablePro.DataGrid` is a WinUI 3 control of our own. ItemsRepeater virtualizes the rows, and each row draws its visible cells' text with DirectWrite into a composition surface, through `TablePro.Graphics`, the one drawing layer the editor uses too. Cells are UIA peers with no element. The data comes from the core through `TablePro.Interop`, formatted there. The grid edits in place with a stock TextBox and shows the changes the host holds; the host checks, keeps and saves them. ## Design @@ -28,6 +28,10 @@ - `GridSelection` is an anchor and a focused cell, as cells, whole rows or everything, so a selection of any size is two numbers. - `GridNavigation` moves as Excel does in a block with no empty cells: arrows, Page Up and Down, Home and End, Ctrl to the edges, Shift to extend. - `GridCopy` writes Excel's TSV: tabs, CRLF, values with a tab, line break or quote quoted with quotes doubled, NULL as an empty cell. It streams blocks of 16,384 cells from a reader of its own, at a 4,096-character cap, and reads a cut value whole. The core shows control characters as spaces, so a text value with a space is read whole too. +- `EditedGridData` lays the host's `GridEdits` over the data: the data's rows, then the new rows. `GridEdits` is immutable, and a reader keeps the edits it opened with. A copy takes the edits on the UI thread with its range and opens its reader over them on the pool thread. +- Its reader reads the data's rows into a block of its own, then copies each cell on, a pending one in its place. Pending text is cut and its control characters shown as spaces, as the core shows a value. New rows are never asked of the data. +- A cell's state carries Modified, Inserted, Deleted or Default. A deleted row keeps the data's text. `ReadWhole` gives the pending text, null for NULL and empty for DEFAULT, so a copy takes what the user typed. +- A grid of plain `ResultSetData` reads as before, and its scroll test still measures 0 bytes. ### Virtualization (`src/TablePro.DataGrid`) @@ -47,6 +51,9 @@ - A row keeps an `IDWriteTextLayout` per visible cell while it stays on screen, and lays out only the columns that come into view. Layouts are made from the block's spans: no string, wrapper or closure per cell. - The font is what a TextBlock cell would use: Segoe UI Variable Text at the content size (Segoe UI before Windows 11), one line, cut with an ellipsis, centered, grayscale antialiased on a clear surface. The locale is the UI language's, so Han glyphs follow it. - NULL is the word NULL in italic in the tertiary text color. A value the core cut ends with an ellipsis in the tertiary color. +- Pending changes, as on macOS. A changed cell has underlined text on `SystemFillColorCautionBackground`, and a new row underlined text on `SystemFillColorSuccessBackground`. A row marked for delete, its number too, has struck-through text in `SystemFillColorCritical` on `SystemFillColorCriticalBackground`. DEFAULT is `DefaultText` in semibold `AccentTextFillColorPrimary`. +- Underline and strike-through are the layout's own, over the whole text. A wash covers the selection rectangle beneath the row, so a row with one draws the selection's tint over it and redraws when the selection moves. +- High contrast draws no washes; underline and strike-through stay. - A value whose first strong character is right to left reads right to left from the cell's right edge, as TextBlock's `DetectFromContent` does. - Color fonts draw in color: `D2D1_DRAW_TEXT_OPTIONS_ENABLE_COLOR_FONT` on each layout's draw. - Device loss: `D2DERR_RECREATE_TARGET` or a removed device from `BeginDraw` or `EndDraw` moves the composition device to a new Direct2D device (`ICompositionGraphicsDeviceInterop::SetRenderingDevice`), makes the brushes again and redraws every row. @@ -61,6 +68,22 @@ - A click picks a cell and Shift+click extends; a drag extends; a click on a row number picks the row, and on the corner, everything. - The selection and the focused cell are a Rectangle and a Border in each pane, cut to the realized rows. - Ctrl+C builds the TSV on a pool thread, so the UI thread does not wait for a selection of any size, then sets the clipboard. A later copy cancels one still running. +- A right-click, pen press or touch hold outside the selection selects the cell under it, or the row on the row numbers, as File Explorer and Excel do. It does so before `ContextRequested` reaches the host, so the host's menu acts on that cell. Inside the selection, and from Shift+F10 or the menu key, the selection stays. + +### Editing + +- Off until the host sets `IsEditable`. F2, Enter or a double-click on a cell opens the editor; typing does not, as on macOS. `CellEditStarting` gives the host the cell, and the host sets the text or cancels. Text with NUL opens nothing, since a TextBox cannot hold it. +- F2 and Enter, and Tab in the editor, open the editor once the key is done, so the key's character does not reach the new TextBox. +- The editor is a stock TextBox in the cell's pane, the frozen one or the scrolling one, so it scrolls with the rows. It takes the cells' font, gets focus and selects its text. A value with a line break opens with AcceptsReturn and grows to four rows. +- Enter commits and stays. Tab and Shift+Tab commit and edit the next cell to the right or left, as NSTableView does. Escape cancels. Ctrl+Enter commits a value with line breaks. +- Losing focus commits, and a refused commit then cancels. Focus that moves to the TextBox's own menus does not. Unloading the grid and setting `FrozenColumnCount` do the same. +- On those paths the editor's ToolTip closes with it, so the host shows a refused commit's Error itself. +- `CellEditCommitting` gives the host the typed text. The text the TextBox holds once opened is no change and raises nothing, so a NULL cell or a value with mixed line breaks left as it was stays as it was. +- A host that sets `Error` keeps the editor open. The error shows in a ToolTip, as the editor's FullDescription and as a UIA notification. +- Delete with no editor open raises `DeleteRequested`. +- The host swaps `EditedGridData.Edits` and calls `EditsChanged`. The grid opens a new reader, reads RowCount again and redraws; when rows go, it gives the repeaters a new source, as `SetData` does (trap 5). +- When the row count changes, an editor open on a data row commits, or cancels when refused. One on a new row cancels: the host's new rows have moved already, so its index may name another row. The host commits before an edit command to keep that text. +- `SetData` cancels an open editor. ### Header @@ -80,6 +103,8 @@ - `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 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. ## Rationale @@ -94,7 +119,7 @@ - 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: editing, column reorder, row header peers, find, tooltips for cut cells. +- Not yet: column reorder, row header peers, find, tooltips for cut cells. ## Alternatives considered diff --git a/windows/docs/decisions/0004-app-shell.md b/windows/docs/decisions/0004-app-shell.md index 26d8a47ef2..81d03c8015 100644 --- a/windows/docs/decisions/0004-app-shell.md +++ b/windows/docs/decisions/0004-app-shell.md @@ -124,6 +124,8 @@ On 2026-11-05 the maintainer had the app show what the server prints, PostgreSQL - Go to page: between Previous and Next, "Page 3 of 36" opens a flyout with a `NumberBox` from 1 to the page count, as macOS asks in a popover. It is offered once the table is counted, as on macOS, and the box keeps a typed number inside that range (`InvalidInputOverwritten`). - An open transaction: each run's `Finished` event carries the transaction the editor's connection is left in (the core's `RunSummary.transaction_state`). The tab that holds one shows a Warning `InfoBar` above its results, "Transaction open", with Roll back, which asks first, and Commit, hidden on a read-only connection; a failed one is an Error bar with Roll back only. Both send COMMIT or ROLLBACK as typed SQL, EXEC or DISCARD for a key-value engine, as the Linux app does. Over the tabs, a bar names another tab that holds one, with Show; macOS shows its bar above every tab of the connection, and here the owning tab carries the actions, since the transaction lives on that tab's own connection. Closing a tab that holds one asks first, since closing rolls it back. Window close and Exit confirm every affected held transaction before closing any tabs; cancelling keeps them open. Then one dialog lists every query tab still running, as macOS asks before it quits, and says closing rolls back a transaction a run has open; a table tab loading a page is not asked about. Exit then hides the windows and closes every connection, each tab stopping its run, for up to 5 seconds before the process ends. Disconnect, Reconnect and connecting an edited connection ask about held transactions the same way first, in the primary and in a tab window, but not about a running query, which they stop, and Reconnect and an edited connection bring the tabs back with their text on the new session. Cancelling that connect keeps the connection with Retry, so the tabs still come back. A window with a dialog already open waits for it to be dismissed before accepting a close request. WinUI opens one `ContentDialog` per thread, even across windows, so a question asked while another window shows one is declined, as Cancel would decline it (`WindowDialogs`). - Safe Mode: before a typed run the core judges each statement at the connection's level (`DatabaseSession.gate_run`, over `SafeModeLevel::gate`, as the Linux editor judges its batches). Confirm writes asks before any write, and Off before a DROP, a TRUNCATE, or a DELETE or UPDATE with no WHERE. The question is a `ContentDialog` that lists each statement in full, with Cancel as the default. Read only keeps the whole run back, since the editor sends the text it runs whole: the selection, the whole text, or with Run statement the one statement. The driver splits that text with the session's own settings, so when the whole text reads stricter than every statement, the question shows the whole text. A MySQL script with DELIMITER lines is judged statement by statement, since the driver sends its statements apart. A level saved while the connection is open applies at once to its sessions in every window (`set_safe_mode`), as on Linux; a change to or from Read only takes a new connection, so those sessions reconnect once their held transactions are confirmed. A session that keeps its connection shows "Changes apply the next time you connect", as Linux says it, and one that cannot take Read only asks before every write until then. Statements are judged by the connection's own engine, also while its link is down and a tab's own connection still runs (`Session::grammar`). Commit, Roll back and a sort's rerun are not asked about. Closing a tab stops its run and waits for it to end before its connection closes. +- Lifecycle: running, closing, paging, sorting, a lost editor, the session share and connecting are plain types in `src/TablePro.App.Model` (`QueryTab`, `TableTab`, `WorkspaceTabs`, `ConnectionLife`, `SessionShare`) over `ITabSession`, `ITabEditor` and `ITabRun`, with the core's adapters beside them. The views draw and ask through small view interfaces (`IQueryTabView`, `ITableTabView`, `IResultsView`, `IWorkspaceTabsView`, `IConnectionView`), so the model tests run them with fakes. +- A table tab edits its page's rows, keeps the changes pending until Save, and asks before a reload or a close would lose them ([0006](0006-editing-table-rows.md)). - Reconnecting: the workspace waits on the core's session health (`health_change`) and shows a bar over the tabs while it is not online: Warning while it reconnects, with the attempt, or while the server cannot be reached, and Error once the session parks with the reason the core gives, with Reconnect (`reconnect`, the monitor's retry). An editor connection is never opened again by itself, since its transaction would not come back with it: a query tab whose connection was lost opens a new one on its next run and says that an open transaction went with it. ### Settings @@ -182,7 +184,7 @@ Facts the CI runs on `windows-2025` and `windows-11-arm` established, which the - The core gained the library and connecting through it: `Core::library`, `connect_saved`, `test_connection`, `parse_connection_url`, `DatabaseSession::table_query` and `sorted_query` with `sql_syntax::with_order_by` and `sort_reference`, `ResultSet::sorted` over `value::order`, and `Core::with_system_secrets`, which keeps secrets in Credential Manager on Windows (`core/ARCHITECTURE.md`, Platforms). - Then what the shell's second pass needed: `DatabaseDriver::category` (`EngineCategory`) and `DriverInfo.category`; in the library, tags (`create_tag`, `update_tag`, `delete_tag`, `tag_connections`, and the tags in the snapshot), `rename_connection`, `add_favorites` and `remove_favorites` with a place, `move_to_group` with a place and `move_groups`; `ErrorInfo.secret`; `table_query` with an offset and `can_seek`, `table_row_count`; `health`, `health_change` and `reconnect` on the session; `QueryEditor::is_lost`; the transaction in `RunEvent::Finished`; and `gate_run` and `set_safe_mode` on the session. Each has its test in `core/crates/ffi/tests`. -- `tests/TablePro.App.Model.Tests` covers settings, the session file with the window, the pane and the tab windows, the library tree with tags and search, selection by connection, drops, the engine families, closed tabs, the pager with its page sizes and Go to page, and the workspace bars, a run's messages, the form's fields and the object folders on any machine. `tests/TablePro.App.UITests` drives the unpackaged build through UI Automation (FlaUI): first run, Settings, the form and its engine families, connecting to a SQLite file, opening, sorting and paging a table with a width set through Transform and the header's ItemStatus, a table's page size and Go to page kept across a relaunch, a tab moved to its own window that comes back with its place and merges back by drag, a tab dragged out whose window closes with its last tab, a query and its sort, a script's rows sorted where they are, a failed connect, a password asked for, session restore, the rail's mark, the pane's width and the window's place across a relaunch, Reopen closed tab, an open transaction's bars, a PostgreSQL notice under Messages, and rename, tags, a drop and selection mode on the Connections page, in light and dark, with screenshots. +- `tests/TablePro.App.Model.Tests` covers settings, the session file with the window, the pane and the tab windows, the library tree with tags and search, selection by connection, drops, the engine families, closed tabs, the pager with its page sizes and Go to page, and the workspace bars, a run's messages, the form's fields and the object folders on any machine. With fakes for the session, the editor and the run, it also covers the lifecycle models: a tab closed during each await of a run, a page load or a count, which lets go of its editor and session once and shows nothing after; a lost editor that held a transaction; Safe Mode, where Commit, Roll back and a sort's rerun are never asked about; sorting the rows held; closing a tab that holds a transaction; reconnecting with tabs, a cancelled reconnect kept to retry, and a share an adopting window holds. `tests/TablePro.App.UITests` drives the unpackaged build through UI Automation (FlaUI): first run, Settings, the form and its engine families, connecting to a SQLite file, opening, sorting and paging a table with a width set through Transform and the header's ItemStatus, a table's page size and Go to page kept across a relaunch, a tab moved to its own window that comes back with its place and merges back by drag, a tab dragged out whose window closes with its last tab, a query and its sort, a script's rows sorted where they are, a failed connect, a password asked for, session restore, the rail's mark, the pane's width and the window's place across a relaunch, Reopen closed tab, an open transaction's bars, a PostgreSQL notice under Messages, and rename, tags, a drop and selection mode on the Connections page, in light and dark, with screenshots. - SSH connections use the core's in-process transport (core ADR 0009). Host-key, passphrase and interactive login prompts use native ContentDialogs. A changed host key requires confirmation to remove its old entry, then separate confirmation of the replacement key on retry. - Not built yet: importing from other apps (the importers move to the core first). - Unverified: Native AOT publishing of the app, and the app on a real Windows 10 machine. diff --git a/windows/docs/decisions/0006-editing-table-rows.md b/windows/docs/decisions/0006-editing-table-rows.md new file mode 100644 index 0000000000..21ae760963 --- /dev/null +++ b/windows/docs/decisions/0006-editing-table-rows.md @@ -0,0 +1,50 @@ +# 0006: Editing a table's rows + +- **Status**: Accepted +- **Date**: 2026-11-11 + +## Context + +A table tab only read its rows (audit item WN-08). The macOS app edits cells, adds, duplicates and deletes rows, keeps every change pending until Save, previews the SQL and asks Safe Mode first. The core already plans row saves for the Linux app (`save::plan_save`), and the FFI now carries the edits ([core 0019](../../../core/docs/decisions/0019-row-edits-through-the-ffi.md)). The grid had no editor ([0003](0003-data-grid-control.md)). + +## Decision + +A table tab edits its page as the macOS app does, with the commands and words of the macOS app in Windows sentence case, through the core's `TableEditor`. The pending changes are typed text per row of the page, in `TableEdits` (`src/TablePro.App.Model`), which the grid shows through `EditedGridData`. `TableTab` holds the edit commands, the questions and the save over `ITableEditor` and `IRowSave`, so `tests/TablePro.App.Model.Tests` runs every path with fakes; `TableTabView` draws and asks. + +## Design + +### Editing + +- F2, Enter or a double-click edits the focused cell in a `TextBox` over it; typing does not start an edit, as on macOS. Enter keeps the edit, Tab and Shift+Tab keep it and move, Escape cancels. A value with a line break edits on several lines, and Ctrl+Enter keeps it. +- The editor starts from the pending edit or the whole stored value (`TableEditor.GetEditStart`), never the grid's cut text. A cell the column cannot take back (bytes, a value the driver could not read, a key or a column the server fills) does not open, and the status says so. +- A kept edit is read as the save will read it (`TableEditor.Check`). A refusal keeps the editor open with the reason in its tooltip and its accessible description, and the status says it too, since a focus loss closes the editor. An edit back to the stored value is no change. +- A right-click outside the selection selects the cell under it; inside it, the selection stays. The grid's menu acts on the focused cell and the selected rows, and a right-click while a cell is edited keeps the edit first. It has Set value (Empty where the column takes it, NULL where it is nullable, Default in a new row where the server fills the column and in a saved row where the engine sets a declared default), Add row, Duplicate, Delete, and Copy. On a row marked for delete it offers Undo delete and Copy, as macOS does. +- Add row (Ctrl+Shift+N) adds a row after the page's rows, holding the server's value where it has one and NULL elsewhere, and opens the editor on the first column the server does not fill. Duplicate row (Ctrl+Shift+D) copies the selected rows, with the key and the columns the server fills as a new row starts them. Delete marks the selected rows; a new row goes at once. +- A lock keeps every edit back and the status names it when the grid is asked to edit: a read-only connection, a table with no primary key, a page whose keys cannot be read back exactly, or columns that changed since the page was read. Refresh reads the table's columns from the server again. + +### Pending changes + +- An edited cell is underlined on the caution fill, a new row on the success fill, and a row marked for delete is struck through on the critical fill, from WinUI's theme resources; high contrast keeps the underline and the strike-through. A cell's UIA ItemStatus says "edited", "new row" or "marked for deletion". +- A value still in the open editor counts as a pending change: Save takes it, and every close asks about it. +- A sort, a page, a page size or Refresh asks "Discard unsaved changes?" while changes are pending, as macOS asks, since the edits name rows of the page shown. An open edit is kept first; one the grid cannot keep holds the reload back. +- Closing the tab, Disconnect, Reconnect, connecting an edited connection, closing the window and Exit show the tab and ask "Do you want to save changes to name?" with Save, Don't save and Cancel, beside the questions about held transactions. The workspace asks, since a tab that is not shown is out of the tree. A save that fails keeps the tab open and the window with it. A close while a save runs waits for it and asks only about what it left pending. Making the connection read only asks with Don't save and Cancel alone, since the changes would not be written there. + +### Saving + +- Save (Ctrl+S) keeps an open edit, plans the save, and asks before deleting rows at every Safe Mode level ("Delete 3 rows from Track?"). At Confirm writes it then shows every statement with the values it binds and Execute or Cancel, Cancel the default, and only an Execute lets the save run. Read only locks editing, and the commands are off. +- The save runs as one batch through the core, with each row at its latest change, as the Linux app orders a save, so a parent row added before a child is pointed at it saves first; a parent edited again after that saves after the child, and its foreign key refuses the save. A close waits for a save in flight and never stops it halfway. +- A save that writes reloads the page and counts the table again. One the server rolled back says "Save failed", keeps every change pending and selects the row it stopped at. One whose outcome is unknown says "Save incomplete", keeps the changes, selects the row and refuses another save until the page is read again or the changes are discarded. One the core refuses before it sends anything, as when Safe Mode changed, says why and keeps the changes; any other failure counts as an unknown outcome. Discarding the changes, or a reload that discards them, lifts the block. +- Preview SQL (Ctrl+Shift+P) shows the same statements, with Copy all and Done, or why the edits cannot be planned. Discard changes asks first. +- Save, Discard changes and Preview SQL are in the tab's command bar and the File and Query menus; Add row, Duplicate row and Delete in the command bar and the Edit menu. The keys belong to the menu items alone, so a press never runs twice. The command bar holds them after Refresh and Stop, so a narrow bar moves them to its overflow first and keeps the pager. A query tab has none of them. + +## Rationale + +- The core plans and runs the save, so Windows writes nothing Linux would not, and the SQL generation has one home. +- Typed text against the page's rows is all the app holds, so a page reload has to be asked about; macOS asks the same question for the same actions. +- A table with no primary key stays read-only, as on Linux. macOS matches every column; that choice is the maintainer's, and read-only is the state the app was in. + +## Consequences + +- No undo of a pending edit yet; Discard changes drops them all. +- A query result does not edit yet (core 0015). +- The core's three Safe Mode levels stand for macOS's six: Off saves, Confirm writes shows the statements, Read only locks. diff --git a/windows/docs/decisions/README.md b/windows/docs/decisions/README.md index 9c07b67259..c20ab1f7f8 100644 --- a/windows/docs/decisions/README.md +++ b/windows/docs/decisions/README.md @@ -10,6 +10,7 @@ The format, the statuses and how a later ADR changes an earlier one follow [the |---|---|---|---| | [0001](0001-toolchain-baseline.md) | Windows toolchain and build baseline | Accepted; amended by 0005 | Build Tools for Visual Studio 2026 with MSVC for x64 and Arm64, Windows SDK 10.0.26100, .NET 10 and Rust with both MSVC targets; cargo runs from the csproj; Native AOT; Windows 10 1809 as the floor, with runtime checks for Windows 11 behavior. | | [0002](0002-sql-editor-control.md) | TablePro's own SQL editor control | Accepted | A rope with its own undo in a plain .NET model, drawn with Direct2D and DirectWrite into a SwapChainPanel, TSF as Windows Terminal does it, a UIA text provider, and the core's lexer for colors. | -| [0003](0003-data-grid-control.md) | TablePro's own data grid control | Accepted | A read-only WinUI 3 control: ItemsRepeater rows that draw their visible cells with DirectWrite into composition surfaces through the editor's drawing layer, cells as UIA peers with no element, data read from the core in windows of cells. | +| [0003](0003-data-grid-control.md) | TablePro's own data grid control | Accepted | A WinUI 3 control that edits cells in place: ItemsRepeater rows that draw their visible cells with DirectWrite into composition surfaces through the editor's drawing layer, cells as UIA peers with no element, data read from the core in windows of cells with the host's pending changes laid over them. | | [0004](0004-app-shell.md) | The app shell | Accepted; packaging amended by 0005 | One window with the TitleBar, a MenuBar and a NavigationView rail of open connections, each with its own TabView; the Connections page, an owned connection form window, Settings as a page; the core keeps connections and Credential Manager secrets, the app its settings and session in LocalState. | | [0005](0005-distribution.md) | Shipping the app | Accepted | One self-contained Native AOT MSIX per architecture in an `.msixbundle` signed with Azure Artifact Signing, on GitHub Releases and winget; the core on the hybrid CRT; the 1809 floor checked in the package and on Windows Server 2022. | +| [0006](0006-editing-table-rows.md) | Editing a table's rows | Accepted | A table tab edits as the macOS app does: F2, Enter or a double-click edits a cell, rows are added, duplicated and deleted, every change stays pending until Save, reloads and closes ask first, Safe Mode's Confirm writes shows the statements, and the core plans and runs the save (core 0019). | diff --git a/windows/src/TablePro.App.Model/ConnectionLife.cs b/windows/src/TablePro.App.Model/ConnectionLife.cs new file mode 100644 index 0000000000..5ffcf44f29 --- /dev/null +++ b/windows/src/TablePro.App.Model/ConnectionLife.cs @@ -0,0 +1,288 @@ +using TablePro.Interop; + +namespace TablePro.App.Model; + +public enum ConnectionState +{ + NotConnected, + Connecting, + Connected, + Failed, +} + +public sealed record SecretAnswer(string Secret, bool Save); + +// The core calls a connect makes. +public interface IConnector +{ + Task ConnectSavedAsync(Guid id, ConnectionSecrets secrets, CancellationToken cancellationToken); + + Task OpenFileAsync(string path, string? engineId, CancellationToken cancellationToken); + + Task SaveSecretsAsync(Guid id, ConnectionSecrets secrets); +} + +// What an open connection shows and asks while it connects and closes; its tabs live in the view. +public interface IConnectionView + where TSession : class, IAsyncDisposable +{ + void ShowState(ConnectionState state); + + void ShowConnecting(); + + // Adopted: a session another window's workspace opened, for a tab moved here. + void ShowConnected(SessionShare share, SessionConnection? restore, bool adopted); + + void ShowFailed(CoreError failure); + + void ShowCancelledKeepsTabs(); + + // Null when the dialog was closed, which cancels the connect. + Task AskSecretAsync(SecretKind kind, CancellationToken cancellationToken); + + // True once the changed key is forgotten, so the connect is tried again and asks about the new one. + Task RecoverHostKeyAsync(Guid id, HostKeyFailure failure, CancellationToken cancellationToken); + + void CancelRecovery(); + + Task CloseTabsAsync(bool keepClosed); + + // Until it connects, the tabs it was saved with are still to come; once connected, the strip is the truth. + SessionConnection Snapshot(SessionConnection origin); +} + +// A saved connection is reopened by id, a file opened without saving by its path. +public sealed class ConnectionLife + where TSession : class, IAsyncDisposable +{ + private readonly IConnectionView _view; + private readonly IConnector _connector; + private CancellationTokenSource? _connecting; + private SessionConnection? _restore; + // A reconnect's tabs wait in _restore, so cancelling its connect keeps the item to retry instead of closing it. + private bool _keepOnCancel; + + public ConnectionLife(SessionConnection origin, IConnectionView view, IConnector connector) + { + ArgumentNullException.ThrowIfNull(origin); + ArgumentNullException.ThrowIfNull(view); + ArgumentNullException.ThrowIfNull(connector); + Origin = origin; + _restore = origin.Tabs.Count > 0 ? origin : null; + _view = view; + _connector = connector; + } + + // Raised when a connect the user cancelled is over, so the window can take the connection away. + public event EventHandler? Cancelled; + + public SessionConnection Origin { get; private set; } + + public ConnectionState State { get; private set; } + + public SessionShare? Share { get; private set; } + + public TSession? Session => Share?.Session; + + public bool Matches(Guid? connectionId, string? filePath) => + connectionId is not null + ? connectionId == Origin.ConnectionId + : filePath is not null && string.Equals(filePath, Origin.FilePath, StringComparison.OrdinalIgnoreCase); + + public void Rename(string name) => Origin = Origin with { Name = name }; + + public void SetEngine(string engineId) => Origin = Origin with { EngineId = engineId }; + + public async Task ConnectAsync() + { + if (State is ConnectionState.Connecting or ConnectionState.Connected) + { + return; + } + + using var connecting = new CancellationTokenSource(); + _connecting = connecting; + SetState(ConnectionState.Connecting); + _view.ShowConnecting(); + try + { + var session = Origin.ConnectionId is { } id + ? await ConnectSavedAsync(id, connecting.Token).ConfigureAwait(true) + : await _connector.OpenFileAsync( + Origin.FilePath!, + string.IsNullOrEmpty(Origin.EngineId) ? null : Origin.EngineId, + connecting.Token).ConfigureAwait(true); + var share = new SessionShare(session); + Share = share; + SetState(ConnectionState.Connected); + _view.ShowConnected(share, _restore, adopted: false); + _restore = null; + _keepOnCancel = false; + } + catch (OperationCanceledException) + { + SetState(ConnectionState.NotConnected); + if (_keepOnCancel) + { + _view.ShowCancelledKeepsTabs(); + } + else + { + Cancelled?.Invoke(this, EventArgs.Empty); + } + } + catch (TableProException exception) + { + SetState(ConnectionState.Failed); + _view.ShowFailed(exception.Error); + } + finally + { + _connecting = null; + } + } + + public void CancelConnect() + { + _connecting?.Cancel(); + _view.CancelRecovery(); + } + + // The same connection in another window, on the same session, ready for the tab moved into it. + public void Adopt(ConnectionLife connected) + { + ArgumentNullException.ThrowIfNull(connected); + var share = connected.Share ?? throw new InvalidOperationException("Only a connected workspace gives up a tab."); + Share = share.Hold(); + SetState(ConnectionState.Connected); + _view.ShowConnected(share, null, adopted: true); + } + + // A reconnect keeps the tabs and the closed tabs for the next session; only their own connections end with it. + public async Task DisconnectAsync(bool keepTabs = false) + { + CancelConnect(); + _keepOnCancel = keepTabs; + if (keepTabs && State == ConnectionState.Connected && Snapshot() is { Tabs.Count: > 0 } tabs) + { + _restore = tabs; + } + + var share = Share; + Share = null; + await _view.CloseTabsAsync(keepClosed: keepTabs).ConfigureAwait(true); + if (share is not null) + { + await share.ReleaseAsync().ConfigureAwait(true); + } + + SetState(ConnectionState.NotConnected); + } + + public SessionConnection Snapshot() => _view.Snapshot(_restore ?? Origin); + + // A secret with none saved is asked for, as macOS asks; closing the dialog cancels the connect. + private async Task ConnectSavedAsync(Guid id, CancellationToken cancellationToken) + { + var secrets = ConnectionSecrets.None; + var remembered = ConnectionSecrets.None; + var prompted = new HashSet(); + var replaced = new HashSet(StringComparer.Ordinal); + while (true) + { + try + { + var session = await _connector.ConnectSavedAsync(id, secrets, cancellationToken).ConfigureAwait(true); + if (remembered != ConnectionSecrets.None) + { + await SaveSecretsAsync(id, remembered).ConfigureAwait(true); + } + + return session; + } + catch (TableProException exception) + when (exception.Error.HostKey is { TrustAllowed: true } key && replaced.Add(key.Host)) + { + if (!await _view.RecoverHostKeyAsync(id, exception.Error.HostKey!, cancellationToken) + .ConfigureAwait(true)) + { + throw; + } + } + catch (TableProException exception) when (exception.Code == "keyring.secret_not_stored") + { + var kind = exception.Error.Secret ?? SecretKind.DatabasePassword; + if (!prompted.Add(kind)) + { + throw; + } + + var answer = await _view.AskSecretAsync(kind, cancellationToken).ConfigureAwait(true) + ?? throw new OperationCanceledException(cancellationToken); + secrets = WithSecret(secrets, kind, answer.Secret); + if (answer.Save) + { + remembered = WithSecret(remembered, kind, answer.Secret); + } + } + } + } + + private static ConnectionSecrets WithSecret(ConnectionSecrets secrets, SecretKind kind, string value) => kind switch + { + SecretKind.SshPassword => secrets with { SshPassword = value }, + SecretKind.SshPassphrase => secrets with { SshPassphrase = value }, + _ => secrets with { DatabasePassword = value }, + }; + + private async Task SaveSecretsAsync(Guid id, ConnectionSecrets secrets) + { + try + { + await _connector.SaveSecretsAsync(id, secrets).ConfigureAwait(true); + } + catch (TableProException) + { + // The connect worked; a secret that could not be saved is asked for again next time. + } + } + + private void SetState(ConnectionState state) + { + State = state; + _view.ShowState(state); + } +} + +// Connects through the core, asking for secrets and SSH answers through the prompter. +public sealed class CoreConnector : IConnector +{ + private readonly TableProCore _core; + private readonly ICredentialPrompter _prompter; + + public CoreConnector(TableProCore core, ICredentialPrompter prompter) + { + ArgumentNullException.ThrowIfNull(core); + ArgumentNullException.ThrowIfNull(prompter); + _core = core; + _prompter = prompter; + } + + public Task ConnectSavedAsync( + Guid id, + ConnectionSecrets secrets, + CancellationToken cancellationToken) => + _core.ConnectAsync(id, secrets, _prompter, cancellationToken); + + public Task OpenFileAsync(string path, string? engineId, CancellationToken cancellationToken) => + _core.OpenFileAsync(new FileOpenOptions(path, engineId), cancellationToken); + + public async Task SaveSecretsAsync(Guid id, ConnectionSecrets secrets) + { + var snapshot = await _core.Library.GetSnapshotAsync().ConfigureAwait(true); + if (snapshot.Connections.FirstOrDefault(connection => connection.Id == id) is { } saved) + { + await _core.Library.SaveAsync(saved, secrets).ConfigureAwait(true); + } + } +} diff --git a/windows/src/TablePro.App.Model/IResultsView.cs b/windows/src/TablePro.App.Model/IResultsView.cs new file mode 100644 index 0000000000..af8997e6a9 --- /dev/null +++ b/windows/src/TablePro.App.Model/IResultsView.cs @@ -0,0 +1,35 @@ +using TablePro.DataGrid.Model; +using TablePro.Interop; + +namespace TablePro.App.Model; + +// The results pane under a tab: it reads a run's events and owns the sets it shows. +public interface IResultsView +{ + // The grid shows a clicked sort at once, so a tab that does not run it sets this back. + GridSort Sort { get; set; } + + IReadOnlyList Columns { get; } + + int ResultSetCount { get; } + + long RowCount { get; } + + // A sort of the rows held shows a copy, so its count is the shown set's, not the run's. + long ShownRowCount { get; } + + TransactionState Transaction { get; } + + ResultSet? ShownSet { get; } + + event EventHandler? ShownSetChanged; + + Task ShowRunAsync(ITabRun run, GridSort sort, int visibleColumns, CancellationToken cancellationToken); + + // False when no set is shown, or a run or a pick replaced it while the rows were being sorted. + Task SortHeldRowsAsync(GridSort sort); + + void ShowError(CoreError failure); + + void Clear(); +} diff --git a/windows/src/TablePro.App.Model/QueryTab.cs b/windows/src/TablePro.App.Model/QueryTab.cs new file mode 100644 index 0000000000..b9cd2ba3c2 --- /dev/null +++ b/windows/src/TablePro.App.Model/QueryTab.cs @@ -0,0 +1,375 @@ +using TablePro.DataGrid.Model; +using TablePro.Interop; + +namespace TablePro.App.Model; + +// What a query tab shows and asks, which its view words. +public interface IQueryTabView +{ + string SelectedText { get; } + + string WholeText { get; } + + // The editor's own text, which the caret and a statement's place count in. + string DocumentText { get; } + + int Caret { get; } + + void SelectStatement(int start, int length); + + void ShowNoStatement(); + + void ShowRefused(); + + void ShowTransactionLost(); + + void ShowSortedHeld(long rows); + + // A changed state opens the bar again, since Narrator reads an InfoBar when it opens. + void ShowTransaction(TransactionState state, bool changed, bool canCommit); + + void ShowRunning(bool running); + + Task ConfirmWritesAsync(RunGate gate, string connection); + + Task ConfirmRollBackAsync(); + + void CloseEditor(); +} + +// One editor connection for the tab, so a transaction holds from one run to the next. +public sealed class QueryTab : IWorkspaceTab +{ + private readonly ITabSession _session; + private readonly IQueryTabView _view; + private readonly IResultsView _results; + private readonly DataModel _dataModel; + private readonly Func _settings; + private readonly TabWork _work = new(); + private ITabEditor? _editor; + private Task? _closing; + private ITabRun? _run; + private string? _statement; + private GridSort _sort = GridSort.None; + private bool _sorting; + private bool _confirming; + + public QueryTab( + string title, + ITabSession session, + IQueryTabView view, + IResultsView results, + DataModel dataModel, + Func settings) + { + ArgumentNullException.ThrowIfNull(title); + ArgumentNullException.ThrowIfNull(session); + ArgumentNullException.ThrowIfNull(view); + ArgumentNullException.ThrowIfNull(results); + ArgumentNullException.ThrowIfNull(settings); + Title = title; + _session = session; + _view = view; + _results = results; + _dataModel = dataModel; + _settings = settings; + } + + public event EventHandler? StateChanged; + + public string Title { get; } + + public TabKind Kind => TabKind.Query; + + public bool IsRunning { get; private set; } + + public TransactionState Transaction { get; private set; } + + public bool HasUnsavedChanges => false; + + // A query tab's text is kept in the session, so closing loses nothing to ask about. + public Task ConfirmCloseAsync(bool offerSave) => Task.FromResult(true); + + public SessionTab Snapshot() => new() { Kind = TabKind.Query, Title = Title, Sql = _view.WholeText }; + + public async Task RunAsync() + { + if (IsRunning || _confirming || _work.IsClosed) + { + return; + } + + var sql = _view.SelectedText; + if (string.IsNullOrWhiteSpace(sql)) + { + sql = _view.WholeText; + } + + await RunTypedAsync(sql).ConfigureAwait(true); + } + + // The statement is selected first so the tab shows which of its statements ran, as the Linux app does. + public async Task RunStatementAsync() + { + if (IsRunning || _confirming || _work.IsClosed) + { + return; + } + + var text = _view.DocumentText; + if (_session.StatementAt(text, _view.Caret) is not { } statement) + { + _view.ShowNoStatement(); + return; + } + + var (start, length) = statement.GetOffsetAndLength(text.Length); + _view.SelectStatement(start, length); + await RunTypedAsync(text[statement]).ConfigureAwait(true); + } + + public void Stop() => _run?.Cancel(); + + public Task CommitAsync() => EndTransactionAsync(commit: true); + + public async Task RollBackAsync() + { + if (await _view.ConfirmRollBackAsync().ConfigureAwait(true)) + { + await EndTransactionAsync(commit: false).ConfigureAwait(true); + } + } + + // Only one query that reads runs again: running a script or a write again would repeat it. + public async Task SortAsync(GridSort sort) + { + if (IsRunning || _sorting) + { + _results.Sort = _sort; + return; + } + + var columns = _results.Columns.Select(column => column.Name).ToList(); + var sorted = _statement is null || _results.ResultSetCount != 1 || sort.Column >= columns.Count + ? null + : SortedQuery(_statement, columns, sort.Column, sort.Direction == SortDirection.Ascending); + if (sorted is null) + { + // The close waits for it, since it clears the sets the sort reads. + await _work.RunAsync(_ => SortHeldRowsAsync(sort)).ConfigureAwait(true); + return; + } + + _sort = sort; + await RunSqlAsync(sorted).ConfigureAwait(true); + } + + // The grid shows another set of the run, unsorted. + public void ResultPicked() => _sort = GridSort.None; + + public Task CloseAsync() => _closing ??= CloseOnceAsync(); + + // The run in flight stops and ends before the run, the editor and the session it uses are let go. + private async Task CloseOnceAsync() + { + _run?.Cancel(); + await _work.CloseAsync().ConfigureAwait(true); + _run?.Dispose(); + _run = null; + _results.Clear(); + if (_editor is not null) + { + await _editor.DisposeAsync().ConfigureAwait(true); + _editor = null; + } + + _view.CloseEditor(); + await _session.ReleaseAsync().ConfigureAwait(true); + } + + // Safe Mode judges the text that is sent, whichever part of the editor it is. + private async Task RunTypedAsync(string sql) + { + if (string.IsNullOrWhiteSpace(sql)) + { + return; + } + + if (!await SafeModeAllowsAsync(sql).ConfigureAwait(true) || IsRunning || _work.IsClosed) + { + return; + } + + _statement = sql; + _sort = GridSort.None; + await RunSqlAsync(sql).ConfigureAwait(true); + } + + // Typed SQL only: Commit and Roll back end a transaction at every level, and a sort runs again only a read. + private async Task SafeModeAllowsAsync(string sql) + { + var gate = _session.GateRun(sql); + if (gate.Refused) + { + _view.ShowRefused(); + return false; + } + + if (gate.Confirm.Count == 0) + { + return true; + } + + _confirming = true; + try + { + return await _view.ConfirmWritesAsync(gate, _session.Name).ConfigureAwait(true); + } + finally + { + _confirming = false; + } + } + + private Task RunSqlAsync(string sql) => _work.RunAsync(token => RunOnEditorAsync(sql, token)); + + private async Task RunOnEditorAsync(string sql, CancellationToken cancellationToken) + { + SetRunning(true); + try + { + var held = WorkspaceNotices.Holds(Transaction); + if ((await ReleaseLostEditorAsync().ConfigureAwait(true) && held) || _work.IsClosed) + { + return; + } + + // An editor that opens as the tab closes stays in _editor, which the close disposes. + _editor ??= await _session.OpenEditorAsync(cancellationToken).ConfigureAwait(true); + if (_work.IsClosed) + { + return; + } + + _run?.Dispose(); + _run = _editor.Run(sql, RunOptions(_settings()), cancellationToken); + await _results.ShowRunAsync(_run, _sort, int.MaxValue, cancellationToken).ConfigureAwait(true); + if (!_work.IsClosed) + { + await AfterRunAsync().ConfigureAwait(true); + } + } + catch (TableProException exception) + { + if (!_work.IsClosed) + { + _results.ShowError(exception.Error); + } + } + finally + { + SetRunning(false); + } + } + + private static QueryOptions RunOptions(AppSettings settings) => new( + settings.RowLimit, + settings.QueryTimeoutSeconds > 0 ? TimeSpan.FromSeconds(settings.QueryTimeoutSeconds) : null); + + private async Task AfterRunAsync() + { + if (await ReleaseLostEditorAsync().ConfigureAwait(true)) + { + return; + } + + var state = _results.Transaction == TransactionState.Unknown ? Transaction : _results.Transaction; + ShowTransaction(WorkspaceNotices.Holds(state) ? state : TransactionState.Idle); + } + + // A new user run may open an idle editor, but must never continue a transaction whose connection was lost. + private async Task ReleaseLostEditorAsync() + { + if (_editor is not { IsLost: true } lost) + { + return false; + } + + _editor = null; + await lost.DisposeAsync().ConfigureAwait(true); + // A tab that closed meanwhile says nothing more. + if (WorkspaceNotices.Holds(Transaction) && !_work.IsClosed) + { + _view.ShowTransactionLost(); + } + + ShowTransaction(TransactionState.Idle); + return true; + } + + private void ShowTransaction(TransactionState state) + { + var changed = state != Transaction; + Transaction = state; + // Rolling back keeps nothing, so it is the way out at every safe mode; a read-only connection commits nothing. + var canCommit = WorkspaceNotices.Holds(state) && state != TransactionState.Failed && !_session.IsReadOnly; + _view.ShowTransaction(state, changed, canCommit); + } + + // Run as typed SQL is, so the results and the bar follow it, as the Linux app ends one. + private async Task EndTransactionAsync(bool commit) + { + if (IsRunning || _editor is null) + { + return; + } + + _statement = null; + await RunSqlAsync(WorkspaceNotices.EndTransaction(_dataModel, commit)).ConfigureAwait(true); + } + + private void SetRunning(bool running) + { + IsRunning = running; + _view.ShowRunning(running); + StateChanged?.Invoke(this, EventArgs.Empty); + } + + private async Task SortHeldRowsAsync(GridSort sort) + { + _sorting = true; + try + { + if (await _results.SortHeldRowsAsync(sort).ConfigureAwait(true)) + { + _sort = sort; + _view.ShowSortedHeld(_results.ShownRowCount); + } + else + { + _results.Sort = _sort; + } + } + catch (TableProException exception) + { + _results.Sort = _sort; + _results.ShowError(exception.Error); + } + finally + { + _sorting = false; + } + } + + private string? SortedQuery(string sql, IReadOnlyList columns, int column, bool ascending) + { + try + { + return _session.SortedQuery(sql, columns, column, ascending); + } + catch (TableProException) + { + return null; + } + } +} diff --git a/windows/src/TablePro.App.Model/SessionShare.cs b/windows/src/TablePro.App.Model/SessionShare.cs new file mode 100644 index 0000000000..efd0fa9d72 --- /dev/null +++ b/windows/src/TablePro.App.Model/SessionShare.cs @@ -0,0 +1,21 @@ +namespace TablePro.App.Model; + +// Held by each workspace and tab that uses the session, so a tab moved to another window keeps its own. +public sealed class SessionShare(T session) + where T : class, IAsyncDisposable +{ + private int _holders = 1; + + public T Session { get; } = session; + + public int Holders => _holders; + + public SessionShare Hold() + { + _holders++; + return this; + } + + // The last holder to let go disposes the session. + public ValueTask ReleaseAsync() => --_holders == 0 ? Session.DisposeAsync() : ValueTask.CompletedTask; +} diff --git a/windows/src/TablePro.App.Model/TabSession.cs b/windows/src/TablePro.App.Model/TabSession.cs new file mode 100644 index 0000000000..5110915991 --- /dev/null +++ b/windows/src/TablePro.App.Model/TabSession.cs @@ -0,0 +1,192 @@ +using TablePro.Interop; + +namespace TablePro.App.Model; + +// What a tab uses of its connection's session, with the one hold on it that the tab's close lets go. +public interface ITabSession +{ + string Name { get; } + + string EngineId { get; } + + bool IsReadOnly { get; } + + Task OpenEditorAsync(CancellationToken cancellationToken); + + Task GetTableQueryAsync( + TableName table, + ColumnSort? sort, + long limit, + long offset, + CancellationToken cancellationToken); + + Task CountRowsAsync(TableName table, CancellationToken cancellationToken); + + RunGate GateRun(string sql); + + Range? StatementAt(string sql, int caret); + + string? SortedQuery(string sql, IReadOnlyList columns, int column, bool ascending); + + // 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); + + ValueTask ReleaseAsync(); +} + +// A table's rows as a save sees them. `rows` is the set a page was read into, null when no set is shown. +public interface ITableEditor : IDisposable +{ + // The connection's and the table's lock, read again on each call: a level saved while connected can make it read only. + EditLock? Lock { get; } + + // What else locks one page's rows, as a key that cannot be read back exactly; asked once the page is read. + EditLock? LockFor(ResultSet? rows); + + IReadOnlyList Columns { get; } + + EditStart GetEditStart(ResultSet? rows, long row, int column); + + CoreError? Check(int column, CellEdit edit, bool newRow); + + IRowSave Plan(ResultSet? rows, IReadOnlyList edits); +} + +// One save, which runs only the statements it was planned with. +public interface IRowSave : IDisposable +{ + IReadOnlyList Statements { get; } + + bool IsEmpty { get; } + + SaveGate Gate { get; } + + // Confirmed: the gate runs, or the user answered Safe Mode's question with Execute. + Task RunAsync(bool confirmed, CancellationToken cancellationToken); +} + +// A tab's own connection, so a transaction holds from one run to the next. +public interface ITabEditor : IAsyncDisposable +{ + // Never opened again by itself, since its transaction would not come back with it. + bool IsLost { get; } + + ITabRun Run(string sql, QueryOptions options, CancellationToken cancellationToken); +} + +public interface ITabRun : IDisposable +{ + IAsyncEnumerable ReadEventsAsync(CancellationToken cancellationToken); + + ResultSet? GetResultSet(int index); + + void Cancel(); +} + +// A tab's hold on the session its workspace shares, taken here and let go by ReleaseAsync. +public sealed class CoreTabSession : ITabSession +{ + private readonly SessionShare _share; + + public CoreTabSession(SessionShare share) + { + ArgumentNullException.ThrowIfNull(share); + _share = share.Hold(); + } + + public string Name => _share.Session.Name; + + public string EngineId => _share.Session.EngineId; + + public bool IsReadOnly => _share.Session.IsReadOnly; + + public async Task OpenEditorAsync(CancellationToken cancellationToken) => + new CoreTabEditor(await _share.Session.OpenEditorAsync(cancellationToken).ConfigureAwait(true)); + + public Task GetTableQueryAsync( + TableName table, + ColumnSort? sort, + long limit, + long offset, + CancellationToken cancellationToken) => + _share.Session.GetTableQueryAsync(table, sort, limit, offset, cancellationToken); + + public Task CountRowsAsync(TableName table, CancellationToken cancellationToken) => + _share.Session.CountRowsAsync(table, cancellationToken); + + public RunGate GateRun(string sql) => _share.Session.GateRun(sql); + + public Range? StatementAt(string sql, int caret) => _share.Session.StatementAt(sql, caret); + + public string? SortedQuery(string sql, IReadOnlyList columns, int column, bool ascending) => + _share.Session.SortedQuery(sql, columns, column, ascending); + + public async Task OpenTableEditorAsync( + TableName table, + bool refresh, + CancellationToken cancellationToken) => + new CoreTableEditor( + await _share.Session.OpenTableEditorAsync(table, refresh, cancellationToken).ConfigureAwait(true)); + + public ValueTask ReleaseAsync() => _share.ReleaseAsync(); +} + +internal sealed class CoreTableEditor(TableEditor editor) : ITableEditor +{ + // The rows the edits name are gone, as when the page went before its save was planned. + private static readonly CoreError RowsGone = new( + "edit.out_of_range", ["edit.out_of_range"], "The page's rows are no longer held.", null, null); + + public EditLock? Lock => editor.Lock; + + // With no set shown there is no row to edit, so nothing of a page can lock it. + public EditLock? LockFor(ResultSet? rows) => rows is null ? null : editor.LockFor(rows); + + public IReadOnlyList Columns => editor.Columns; + + public EditStart GetEditStart(ResultSet? rows, long row, int column) => + rows is null ? EditStart.Locked.Instance : editor.GetEditStart(rows, row, column); + + public CoreError? Check(int column, CellEdit edit, bool newRow) => editor.Check(column, edit, newRow); + + public IRowSave Plan(ResultSet? rows, IReadOnlyList edits) => + rows is null ? throw new TableProException(RowsGone) : new CoreRowSave(editor.Plan(rows, edits)); + + public void Dispose() => editor.Dispose(); +} + +internal sealed class CoreRowSave(RowSave save) : IRowSave +{ + public IReadOnlyList Statements => save.Statements; + + public bool IsEmpty => save.IsEmpty; + + public SaveGate Gate => save.Gate; + + public Task RunAsync(bool confirmed, CancellationToken cancellationToken) => + save.RunAsync(confirmed, cancellationToken); + + public void Dispose() => save.Dispose(); +} + +internal sealed class CoreTabEditor(QueryEditor editor) : ITabEditor +{ + public bool IsLost => editor.IsLost; + + public ITabRun Run(string sql, QueryOptions options, CancellationToken cancellationToken) => + new CoreTabRun(editor.Run(sql, options, cancellationToken)); + + public ValueTask DisposeAsync() => editor.DisposeAsync(); +} + +internal sealed class CoreTabRun(QueryRun run) : ITabRun +{ + public IAsyncEnumerable ReadEventsAsync(CancellationToken cancellationToken) => + run.ReadEventsAsync(cancellationToken); + + public ResultSet? GetResultSet(int index) => run.GetResultSet(index); + + public void Cancel() => run.Cancel(); + + public void Dispose() => run.Dispose(); +} diff --git a/windows/src/TablePro.App.Model/TableEdits.cs b/windows/src/TablePro.App.Model/TableEdits.cs new file mode 100644 index 0000000000..726766eba6 --- /dev/null +++ b/windows/src/TablePro.App.Model/TableEdits.cs @@ -0,0 +1,331 @@ +using TablePro.DataGrid.Model; +using TablePro.Interop; + +namespace TablePro.App.Model; + +// What the user typed on a table tab's page, per row of the page's result set; the core reads keys from that set. +public sealed class TableEdits +{ + // A data row's changed cells by column, so a row's edits are found and dropped in one step. + private readonly Dictionary> _cells = []; + private readonly HashSet _deleted = []; + private readonly List _added = []; + + // Each changed row once, at its latest change, as the Linux tracker orders a save so foreign keys hold. + private readonly LinkedList _order = new(); + private readonly Dictionary> _placed = []; + private GridEdits? _snapshot; + + public TableEdits(IReadOnlyList columns, int dataRows) + { + ArgumentNullException.ThrowIfNull(columns); + ArgumentOutOfRangeException.ThrowIfNegative(dataRows); + Columns = columns; + DataRows = dataRows; + } + + public event EventHandler? Changed; + + public IReadOnlyList Columns { get; } + + public int DataRows { get; } + + public int RowCount => DataRows + _added.Count; + + public int AddedRows => _added.Count; + + public bool HasChanges => _order.Count > 0; + + public bool IsAdded(int row) => row >= DataRows && row < RowCount; + + public bool IsDeleted(int row) => _deleted.Contains(row); + + // What a cell holds now: the edit, or null for a data row's stored value. + public CellEdit? GetCell(int row, int column) + { + CheckColumn(column); + if (IsAdded(row)) + { + return _added[row - DataRows][column]; + } + + return _cells.TryGetValue(row, out var cells) && cells.TryGetValue(column, out var edit) ? edit : null; + } + + // `stored` is the data row's value as text, null for NULL; an edit back to it is no edit, as on macOS. + public void SetCell(int row, int column, CellEdit edit, string? stored) + { + ArgumentNullException.ThrowIfNull(edit); + CheckColumn(column); + if (IsAdded(row)) + { + var cells = _added[row - DataRows]; + cells[column] = edit; + Touch(new ChangedRow(-1, cells), pending: true); + OnChanged(); + return; + } + + CheckDataRow(row); + if (_deleted.Contains(row)) + { + return; + } + + var unchanged = edit switch + { + CellEdit.Text text => stored is not null && string.Equals(text.Value, stored, StringComparison.Ordinal), + CellEdit.Null => stored is null, + _ => false, + }; + if (unchanged) + { + if (_cells.TryGetValue(row, out var kept) && kept.Remove(column) && kept.Count == 0) + { + _cells.Remove(row); + } + } + else + { + if (!_cells.TryGetValue(row, out var cells)) + { + cells = []; + _cells[row] = cells; + } + + cells[column] = edit; + } + + TouchDataRow(row); + OnChanged(); + } + + // A new row holds the server's value where it has one, else NULL, until the user types. Returns its grid row. + public int AddRow() + { + Add([.. Columns.Select(column => column.NewRow)]); + OnChanged(); + return RowCount - 1; + } + + // A copy whose key and server-filled columns start as a new row's; `stored` reads a data row's cell, or null. + public int DuplicateRow(int row, Func stored) + { + ArgumentNullException.ThrowIfNull(stored); + Duplicate(row, stored); + OnChanged(); + return RowCount - 1; + } + + // Each row once, in grid order, with one change for them all; returns the last new row, or -1 when none was copied. + public int DuplicateRows(IReadOnlyList rows, Func stored) + { + ArgumentNullException.ThrowIfNull(rows); + ArgumentNullException.ThrowIfNull(stored); + var copies = rows.Where(each => each >= 0 && each < RowCount && !IsDeleted(each)).Distinct().Order().ToList(); + foreach (var row in copies) + { + Duplicate(row, column => stored(row, column)); + } + + if (copies.Count == 0) + { + return -1; + } + + OnChanged(); + return RowCount - 1; + } + + // A new row goes at once; a data row is marked, and its edits go with it. + public void DeleteRows(IEnumerable rows) + { + ArgumentNullException.ThrowIfNull(rows); + var wanted = rows.Distinct().Order().ToList(); + var added = new HashSet(wanted.Where(IsAdded).Select(row => _added[row - DataRows])); + var changed = added.Count > 0; + foreach (var row in wanted.Where(each => each >= 0 && each < DataRows)) + { + if (!_deleted.Add(row)) + { + continue; + } + + _cells.Remove(row); + TouchDataRow(row); + changed = true; + } + + if (added.Count > 0) + { + _added.RemoveAll(added.Contains); + foreach (var cells in added) + { + Touch(new ChangedRow(-1, cells), pending: false); + } + } + + if (changed) + { + OnChanged(); + } + } + + public void RestoreRows(IEnumerable rows) + { + ArgumentNullException.ThrowIfNull(rows); + var changed = false; + foreach (var row in rows) + { + if (_deleted.Remove(row)) + { + TouchDataRow(row); + changed = true; + } + } + + if (changed) + { + OnChanged(); + } + } + + public void Discard() + { + if (!HasChanges) + { + return; + } + + _cells.Clear(); + _deleted.Clear(); + _added.Clear(); + _order.Clear(); + _placed.Clear(); + OnChanged(); + } + + // The same object until the next change, so the grid swaps its edits only when something moved. + public GridEdits Snapshot() + { + if (_snapshot is { } snapshot) + { + return snapshot; + } + + var cells = new Dictionary<(int Row, int Column), PendingCell>(); + foreach (var (row, columns) in _cells) + { + foreach (var (column, edit) in columns) + { + cells[(row, column)] = Pending(edit); + } + } + + var added = _added.Select(row => (IReadOnlyList)[.. row.Select(Pending)]).ToList(); + return _snapshot = new GridEdits(cells, new HashSet(_deleted), added); + } + + // The edits for the core's plan, each row at its latest change, and the grid row each came from. + public PlannedEdits ToRowEdits() + { + var places = new Dictionary(ReferenceEqualityComparer.Instance); + for (var index = 0; index < _added.Count; index++) + { + places[_added[index]] = DataRows + index; + } + + var edits = new List(_order.Count); + var rows = new List(_order.Count); + foreach (var changed in _order) + { + if (changed.Added is { } cells) + { + edits.Add(new RowEdit.Insert([.. cells])); + rows.Add(places[cells]); + } + else if (_deleted.Contains(changed.DataRow)) + { + edits.Add(new RowEdit.Delete(changed.DataRow)); + rows.Add(changed.DataRow); + } + else + { + var columns = _cells[changed.DataRow]; + edits.Add(new RowEdit.Update( + changed.DataRow, + [.. columns.OrderBy(pair => pair.Key).Select(pair => new CellChange(pair.Key, pair.Value))])); + rows.Add(changed.DataRow); + } + } + + return new PlannedEdits(edits, rows); + } + + public static PendingCell Pending(CellEdit edit) => edit switch + { + CellEdit.Text text => new PendingCell(PendingKind.Value, text.Value), + CellEdit.Null => new PendingCell(PendingKind.Null, string.Empty), + _ => new PendingCell(PendingKind.Default, string.Empty), + }; + + private void Add(CellEdit[] cells) + { + _added.Add(cells); + Touch(new ChangedRow(-1, cells), pending: true); + } + + private void Duplicate(int row, Func stored) + { + if (!IsAdded(row)) + { + CheckDataRow(row); + } + + var cells = new CellEdit[Columns.Count]; + for (var column = 0; column < cells.Length; column++) + { + var info = Columns[column]; + cells[column] = info.PrimaryKey || !info.EditableInNewRow + ? info.NewRow + : GetCell(row, column) ?? stored(column) ?? info.NewRow; + } + + Add(cells); + } + + private void TouchDataRow(int row) => + Touch(new ChangedRow(row, null), _deleted.Contains(row) || _cells.ContainsKey(row)); + + // A row with anything pending moves to the end on each change; one with nothing pending leaves the order. + private void Touch(ChangedRow row, bool pending) + { + if (_placed.Remove(row, out var node)) + { + _order.Remove(node); + } + + if (pending) + { + _placed[row] = _order.AddLast(row); + } + } + + private void OnChanged() + { + _snapshot = null; + Changed?.Invoke(this, EventArgs.Empty); + } + + private void CheckColumn(int column) => + ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual((uint)column, (uint)Columns.Count, nameof(column)); + + private void CheckDataRow(int row) => + ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual((uint)row, (uint)DataRows, nameof(row)); + + // A data row by its place in the set, or a new row by its cells, which keep their identity as rows go before it. + private readonly record struct ChangedRow(int DataRow, CellEdit[]? Added); +} + +// Rows[i] is the grid row Edits[i] came from. +public sealed record PlannedEdits(IReadOnlyList Edits, IReadOnlyList Rows); diff --git a/windows/src/TablePro.App.Model/TablePro.App.Model.csproj b/windows/src/TablePro.App.Model/TablePro.App.Model.csproj index 3bc604c2fc..bace416515 100644 --- a/windows/src/TablePro.App.Model/TablePro.App.Model.csproj +++ b/windows/src/TablePro.App.Model/TablePro.App.Model.csproj @@ -8,6 +8,7 @@ + diff --git a/windows/src/TablePro.App.Model/TableTab.cs b/windows/src/TablePro.App.Model/TableTab.cs new file mode 100644 index 0000000000..6b7c482102 --- /dev/null +++ b/windows/src/TablePro.App.Model/TableTab.cs @@ -0,0 +1,1082 @@ +using TablePro.DataGrid.Model; +using TablePro.Interop; + +namespace TablePro.App.Model; + +public enum ReloadReason +{ + Refresh, + Sort, + Page, + PageSize, +} + +public enum SaveBeforeClose +{ + Save, + DontSave, + Cancel, +} + +// Set value's choices; CanSetValue says which a cell takes. +public enum CellValueKind +{ + Empty, + Null, + Default, +} + +// The run that read the page shown, which the status words with the page. +public readonly record struct PageRun(long Milliseconds, bool Truncated); + +// Why an edit did not open or was not kept, which the view words. +public abstract record EditRefusal +{ + private EditRefusal() + { + } + + // Between pages, running or saving: the grid takes no edit then, and nothing is said. + public sealed record Busy : EditRefusal + { + public static Busy Instance { get; } = new(); + } + + public sealed record TableLocked(EditLock Lock) : EditRefusal; + + // A value the column cannot take back, as bytes, or a column the server computes. + public sealed record CellLocked : EditRefusal + { + public static CellLocked Instance { get; } = new(); + } + + public sealed record RowDeleted : EditRefusal + { + public static RowDeleted Instance { get; } = new(); + } + + // The last save may have been written, so another waits for a reload or a discard. + public sealed record SaveBlocked : EditRefusal + { + public static SaveBlocked Instance { get; } = new(); + } + + public sealed record Invalid(CoreError Failure) : EditRefusal; +} + +// What a table tab shows and asks; the view words the pager from the tab's Page. +public interface ITableTabView +{ + void ShowRunning(bool running); + + void UpdatePager(); + + // Asked first, as macOS asks: a large table on one page takes a lot of memory. + Task ConfirmAllRowsAsync(long total); + + // The edits, or what may be edited, changed. + void ShowEdits(); + + void ShowSaving(bool saving); + + void ShowEditRefusal(EditRefusal refusal); + + void ShowSaveCancelled(); + + // The grid has an editor open, whose text counts as a change until it is kept or cancelled. + bool HasOpenEdit { get; } + + // The grid's open editor keeps its text first; false when the text was refused and the editor stays open. + bool CommitOpenEdit(); + + void FocusRow(int row); + + Task ConfirmDiscardForReloadAsync(ReloadReason reason); + + Task ConfirmDiscardAsync(); + + // Without Save when offerSave is off, as when the connection is being made read only. + Task AskSaveBeforeCloseAsync(string tab, bool offerSave); + + Task ConfirmDeleteAsync(string table, int rows); + + Task ConfirmSaveAsync(string connection, IReadOnlyList statements); + + // A failure takes the place of the statements when the edits cannot be planned. + Task ShowPreviewAsync(IReadOnlyList statements, CoreError? failure); + + Task ShowSaveFailedAsync(CoreError failure, bool incomplete); +} + +// A sort is an ORDER BY in the page's statement, so it orders the whole table, not the rows already read. +public sealed class TableTab : IWorkspaceTab +{ + // The refusals the core makes before it sends anything, so a save after one cannot write twice. + private static readonly HashSet NothingSent = new(StringComparer.Ordinal) + { + "edit.not_confirmed", + "edit.safe_mode_changed", + "edit.not_as_planned", + "edit.already_saved", + "edit.read_only_connection", + "ffi.not_connected", + }; + + private readonly ITabSession _session; + private readonly ITableTabView _view; + private readonly IResultsView _results; + private readonly Func _settings; + private readonly TabWork _work = new(); + private ITabEditor? _editor; + private ITableEditor? _tableEditor; + private bool _reopenTableEditor; + private Task? _closing; + private ITabRun? _run; + private GridSort _sort = GridSort.None; + private GridSort _shownSort = GridSort.None; + private TablePage _page; + + // The size this tab was given, as macOS keeps one per table tab; without one, Settings decides. + private int? _chosenSize; + private CancellationTokenSource? _counting; + + // The set the edits name rows of, which the core reads each key and stored value from. + private ResultSet? _editsRows; + private EditLock? _pageLock; + private bool _saveBlocked; + private Task _save = Task.FromResult(true); + + public TableTab( + ITabSession session, + ITableTabView view, + IResultsView results, + TableName table, + Func settings, + SessionTab? restore = null) + { + ArgumentNullException.ThrowIfNull(session); + ArgumentNullException.ThrowIfNull(view); + ArgumentNullException.ThrowIfNull(results); + ArgumentNullException.ThrowIfNull(table); + ArgumentNullException.ThrowIfNull(settings); + _session = session; + _view = view; + _results = results; + _settings = settings; + Table = table; + _chosenSize = restore?.PageSize is { } size ? Math.Clamp(size, 1, TablePage.LargestSize) : null; + var first = TablePage.First(PageSize); + _page = first.At((restore?.Offset ?? 0) / first.Size * first.Size); + _results.ShownSetChanged += OnShownSetChanged; + } + + public event EventHandler? StateChanged; + + // The grid shows another set: a page arrived, or the tab let go of its rows. + public event EventHandler? ShownRowsChanged; + + public TableName Table { get; } + + public string Title => Table.Name; + + public TabKind Kind => TabKind.Table; + + public bool IsRunning { get; private set; } + + public bool IsSaving { get; private set; } + + // A table tab only reads on its own connection; a save commits on the session's before it returns. + public TransactionState Transaction => TransactionState.Idle; + + public TablePage Page => _page; + + // Null until a run has read the page; a count that arrives later adds the total, as on macOS. + public PageRun? Finished { get; private set; } + + // The rows of the page shown, which are what an edit of the page changes. + public ResultSet? ShownRows => _results.ShownSet; + + public int PageSize => _chosenSize ?? _settings().PageSize; + + // The page's pending changes, made anew for each page read. + public TableEdits? Edits { get; private set; } + + // An open editor counts, so Save takes it and every close asks; both keep its text first. + public bool HasUnsavedChanges => Edits is { HasChanges: true } || (Edits is not null && _view.HasOpenEdit); + + // The connection's and the table's lock now, else what locked the page when it was read. + public EditLock? Lock => _tableEditor is { } editor ? editor.Lock ?? _pageLock : null; + + // The grid opens an editor, which a lock then refuses with its reason. + public bool AcceptsEdits => + Edits is not null && _tableEditor is not null && !IsRunning && !IsSaving && !_work.IsClosed; + + public bool CanEdit => AcceptsEdits && Lock is null; + + public bool CanSave => CanEdit && HasUnsavedChanges && !_saveBlocked; + + public bool CanDiscard => HasUnsavedChanges && !IsRunning && !IsSaving; + + public bool CanPreview => HasUnsavedChanges && _tableEditor is not null && !IsSaving; + + // A new row's editor opens on the first column the server does not fill. + public int FirstColumnToFill + { + get + { + if (_tableEditor is not { } editor) + { + return 0; + } + + var columns = editor.Columns; + for (var column = 0; column < columns.Count; column++) + { + if (columns[column] is { EditableInNewRow: true, NewRow: not CellEdit.ServerDefault }) + { + return column; + } + } + + return 0; + } + } + + public bool Shows(string? schema, string table) => + string.Equals(Table.Name, table, StringComparison.Ordinal) + && string.Equals(Table.Schema, schema, StringComparison.Ordinal); + + public SessionTab Snapshot() => new() + { + Kind = TabKind.Table, + Title = Title, + Schema = Table.Schema, + Table = Table.Name, + PageSize = _chosenSize, + Offset = _page.Offset > 0 ? _page.Offset : null, + }; + + // The edits name rows of the page shown, so a reload asks first while any is pending, as macOS asks. + public async Task MayReloadAsync(ReloadReason reason) + { + // An open edit is a change too; one the grid cannot keep holds the reload back while it shows why. + if (!_view.CommitOpenEdit()) + { + return false; + } + + if (!HasUnsavedChanges) + { + return true; + } + + if (!await _view.ConfirmDiscardForReloadAsync(reason).ConfigureAwait(true)) + { + return false; + } + + // The discarded edits took the blocked save with them, whether or not the reload then reads the page. + _saveBlocked = false; + Edits?.Discard(); + return true; + } + + public async Task RunAsync() + { + if (await MayReloadNowAsync(ReloadReason.Refresh).ConfigureAwait(true)) + { + await LoadAsync(_page.Offset).ConfigureAwait(true); + } + } + + // A refresh counts the table again and reads its columns again. + public async Task RefreshAsync() + { + if (await MayReloadNowAsync(ReloadReason.Refresh).ConfigureAwait(true)) + { + _page = _page with { Total = null }; + _reopenTableEditor = true; + await LoadAsync(_page.Offset).ConfigureAwait(true); + } + } + + public async Task SortAsync(GridSort sort) + { + if (IsRunning || !await MayReloadNowAsync(ReloadReason.Sort).ConfigureAwait(true)) + { + _results.Sort = _sort; + return; + } + + _sort = sort; + _page = _page.At(0); + await LoadAsync(_page.Offset).ConfigureAwait(true); + } + + public Task FirstPageAsync() => PageToAsync(_ => 0); + + public Task PreviousPageAsync() => PageToAsync(page => page.PreviousOffset); + + public Task NextPageAsync() => PageToAsync(page => page.NextOffset); + + public Task LastPageAsync() => PageToAsync(page => page.LastOffset); + + public async Task GoToPageAsync(long number) + { + if (_page.Accepts(number) && number != _page.Number) + { + await PageToAsync(page => page.OffsetOf(number)).ConfigureAwait(true); + } + } + + public Task ResizeAsync(int size) => ResizeToAsync(_page.Resized(size), size); + + public async Task ShowAllRowsAsync() + { + if (_page.Total is not { } total || !await _view.ConfirmAllRowsAsync(total).ConfigureAwait(true)) + { + return; + } + + var all = _page.AllRows(); + await ResizeToAsync(all, all.Size).ConfigureAwait(true); + } + + // The results pane read the page: its rows, and the run's time and cut for the status. + public void PageRead(long rows, long milliseconds, bool truncated) + { + Finished = new PageRun(milliseconds, truncated); + _page = _page with { Rows = rows }; + } + + public bool IsDeleted(int row) => Edits?.IsDeleted(row) == true; + + // The text a cell's editor opens with: the pending edit, else the whole stored value, never the grid's cut text. + public EditRefusal? StartEdit(int row, int column, out string text) + { + text = string.Empty; + if (Refusal() is { } refused) + { + return refused; + } + + var edits = Edits!; + if (CellRefusal(edits, row, column) is { } cell) + { + return cell; + } + + if (edits.GetCell(row, column) is { } pending) + { + text = pending is CellEdit.Text typed ? typed.Value : string.Empty; + return null; + } + + if (ReadStored(row, column, out var stored) is { } unreadable) + { + return unreadable; + } + + text = stored ?? string.Empty; + return null; + } + + // Read as the save will read it, so a cell the user leaves says why it would not save. + public EditRefusal? CommitEdit(int row, int column, string text) + { + ArgumentNullException.ThrowIfNull(text); + if (Refusal() is { } refused) + { + return refused; + } + + var edits = Edits!; + return CellRefusal(edits, row, column) ?? Apply(edits, row, column, new CellEdit.Text(text)); + } + + // As the core says the column takes each; in a new row, Default is where the server fills the column. + public bool CanSetValue(int row, int column, CellValueKind kind) + { + if (!CanEdit || Edits is not { } edits || CellRefusal(edits, row, column) is not null) + { + return false; + } + + var info = edits.Columns[column]; + return kind switch + { + CellValueKind.Empty => info.TakesEmpty, + CellValueKind.Null => info.Nullable, + _ => edits.IsAdded(row) ? info.NewRow is CellEdit.ServerDefault : info.TakesDefault, + }; + } + + public EditRefusal? SetValue(int row, int column, CellValueKind kind) + { + if (Refusal() is { } refused) + { + return refused; + } + + if (!CanSetValue(row, column, kind)) + { + return EditRefusal.CellLocked.Instance; + } + + CellEdit edit = kind switch + { + CellValueKind.Empty => new CellEdit.Text(string.Empty), + CellValueKind.Null => CellEdit.Null.Instance, + _ => CellEdit.ServerDefault.Instance, + }; + return Apply(Edits!, row, column, edit); + } + + // A new row holds the server's value where it has one, else NULL, until the user types. + public EditRefusal? AddRow(out int row) + { + row = -1; + if (Refusal() is { } refused) + { + return refused; + } + + row = Edits!.AddRow(); + return null; + } + + // Each copy starts its key and the columns the server computes as a new row would, as on macOS. + public EditRefusal? DuplicateRows(IReadOnlyList rows, out int last) + { + ArgumentNullException.ThrowIfNull(rows); + last = -1; + if (Refusal() is { } refused) + { + return refused; + } + + last = Edits!.DuplicateRows(rows, StoredEdit); + return null; + } + + // A new row goes at once; a data row is marked for the save to delete. + public EditRefusal? DeleteRows(IReadOnlyList rows) + { + ArgumentNullException.ThrowIfNull(rows); + if (Refusal() is { } refused) + { + return refused; + } + + Edits!.DeleteRows(rows); + return null; + } + + public EditRefusal? RestoreRows(IReadOnlyList rows) + { + ArgumentNullException.ThrowIfNull(rows); + if (Refusal() is { } refused) + { + return refused; + } + + Edits!.RestoreRows(rows); + return null; + } + + public async Task DiscardAsync() + { + // The open edit goes with the rest; kept or not, it is not saved. + _view.CommitOpenEdit(); + if (!CanDiscard || !await _view.ConfirmDiscardAsync().ConfigureAwait(true) || Edits is not { } edits) + { + return; + } + + _saveBlocked = false; + edits.Discard(); + } + + // The same plan a save makes, with the values it binds. + public async Task PreviewAsync() + { + if (!_view.CommitOpenEdit() || !CanPreview || Edits is not { } edits) + { + return; + } + + IReadOnlyList statements; + try + { + using var save = _tableEditor!.Plan(_editsRows, edits.ToRowEdits().Edits); + statements = save.Statements; + } + catch (TableProException exception) + { + await _view.ShowPreviewAsync([], exception.Error).ConfigureAwait(true); + return; + } + + await _view.ShowPreviewAsync(statements, null).ConfigureAwait(true); + } + + // True once every change is written, or there was nothing to write. + public Task SaveAsync() => Track(SaveEditsAsync(reload: true)); + + // Pending changes are asked about first: Save closes only once it saved, Don't save closes, Cancel keeps the tab. + public async Task ConfirmCloseAsync(bool offerSave) + { + // A save in flight is waited for, never asked about halfway; what it left pending is asked about after. + await _save.ConfigureAwait(true); + // An open edit the grid cannot keep holds the close back while it shows why. + if (!_view.CommitOpenEdit()) + { + return false; + } + + if (!HasUnsavedChanges) + { + return true; + } + + var answer = await _view.AskSaveBeforeCloseAsync(Title, offerSave).ConfigureAwait(true); + return answer switch + { + SaveBeforeClose.Save when offerSave => await Track(SaveEditsAsync(reload: false)).ConfigureAwait(true), + SaveBeforeClose.DontSave => true, + _ => false, + }; + } + + public void Stop() => _run?.Cancel(); + + public Task CloseAsync() => _closing ??= CloseOnceAsync(); + + private Task Track(Task save) + { + _save = save; + return save; + } + + // The page in flight, its count and a save stop or end before what they use is let go. + private async Task CloseOnceAsync() + { + _run?.Cancel(); + await _work.CloseAsync().ConfigureAwait(true); + _run?.Dispose(); + _run = null; + _results.Clear(); + SetEdits(null, null); + _tableEditor?.Dispose(); + _tableEditor = null; + if (_editor is not null) + { + await _editor.DisposeAsync().ConfigureAwait(true); + _editor = null; + } + + await _session.ReleaseAsync().ConfigureAwait(true); + } + + // Asked only when a reload can start, and checked again after the answer, which the user may take a while over. + private async Task MayReloadNowAsync(ReloadReason reason) => + !IsRunning + && !IsSaving + && !_work.IsClosed + && await MayReloadAsync(reason).ConfigureAwait(true) + && !IsRunning + && !IsSaving + && !_work.IsClosed; + + private async Task PageToAsync(Func offset) + { + if (await MayReloadNowAsync(ReloadReason.Page).ConfigureAwait(true)) + { + await LoadAsync(offset(_page)).ConfigureAwait(true); + } + } + + private async Task ResizeToAsync(TablePage page, int chosen) + { + if (IsRunning) + { + return; + } + + var reloads = page.Size != _page.Size || page.Offset != _page.Offset; + if (reloads && !await MayReloadNowAsync(ReloadReason.PageSize).ConfigureAwait(true)) + { + return; + } + + _chosenSize = chosen; + if (reloads) + { + _page = page; + await LoadAsync(_page.Offset).ConfigureAwait(true); + } + } + + private async Task LoadAsync(long offset) + { + if (!IsRunning) + { + await _work.RunAsync(token => LoadPageAsync(offset, token)).ConfigureAwait(true); + } + } + + private async Task LoadPageAsync(long offset, CancellationToken cancellationToken) + { + Finished = null; + // Every reload asked first or saved, so nothing pending is lost here. + SetEdits(null, null); + SetRunning(true); + try + { + if (_editor is { IsLost: true } lost) + { + _editor = null; + await lost.DisposeAsync().ConfigureAwait(true); + } + + // An editor that opens as the tab closes stays in _editor, which the close disposes. + _editor ??= await _session.OpenEditorAsync(cancellationToken).ConfigureAwait(true); + await OpenTableEditorAsync(cancellationToken).ConfigureAwait(true); + var page = _page.At(offset); + // A default changed in Settings applies from the page holding the first row shown. + if (_chosenSize is null && page.Size != PageSize) + { + page = page.Resized(PageSize); + } + + var sort = _sort.Direction == SortDirection.None + ? null + : new ColumnSort(_sort.Column, _sort.Direction == SortDirection.Ascending); + var query = await _session.GetTableQueryAsync(Table, sort, page.Size, page.Offset, cancellationToken) + .ConfigureAwait(true); + if (_work.IsClosed) + { + return; + } + + _run?.Dispose(); + _page = page with { CanSeek = query.CanSeek }; + // The statement holds the page; a run limit one past it keeps a full page from reading as cut short. + _run = _editor.Run(query.Sql, new QueryOptions(page.Size + 1), cancellationToken); + await _results.ShowRunAsync(_run, _sort, query.VisibleColumns, cancellationToken).ConfigureAwait(true); + if (_work.IsClosed) + { + return; + } + + _shownSort = _sort; + _page = _page with { Rows = _results.RowCount }; + // The server's rows are read again, so a save whose outcome was unknown may be judged by them now. + _saveBlocked = false; + BindEdits(); + CountIfNeeded(); + } + catch (TableProException exception) + { + if (!_work.IsClosed) + { + // An engine that reads a table only in its own order refuses the sort; the rows shown keep theirs. + _sort = _shownSort; + _results.Sort = _shownSort; + _results.ShowError(exception.Error); + BindEdits(); + } + } + finally + { + SetRunning(false); + } + } + + // Once per tab, and again on a refresh, since the table's columns can change. + private async Task OpenTableEditorAsync(CancellationToken cancellationToken) + { + if (_tableEditor is not null && !_reopenTableEditor) + { + return; + } + + // A refresh reads the table's columns from the server, so a column another client changed is seen. + var refresh = _reopenTableEditor; + _reopenTableEditor = false; + _tableEditor?.Dispose(); + _tableEditor = null; + try + { + // One that opens as the tab closes stays in _tableEditor, which the close disposes. + _tableEditor = await _session.OpenTableEditorAsync(Table, refresh, cancellationToken).ConfigureAwait(true); + } + catch (TableProException) + { + // The rows still show; without the catalog's columns the tab only reads them. + } + } + + // New edits for the set the page was read into, once a run read one, with what locks that page's rows. + private void BindEdits() + { + if (_tableEditor is not { } editor || _results.ResultSetCount == 0) + { + SetEdits(null, null); + return; + } + + var shown = _results.ShownSet; + try + { + _pageLock = editor.LockFor(shown); + } + catch (TableProException) + { + // Rows whose locks cannot be read are only read. + SetEdits(null, null); + return; + } + + var rows = (int)Math.Clamp(_results.RowCount, 0, int.MaxValue); + SetEdits(new TableEdits(editor.Columns, rows), shown); + } + + private void SetEdits(TableEdits? edits, ResultSet? rows) + { + if (Edits is null && edits is null) + { + _editsRows = null; + return; + } + + if (Edits is { } old) + { + old.Changed -= OnEditsChanged; + } + + Edits = edits; + _editsRows = rows; + if (edits is not null) + { + edits.Changed += OnEditsChanged; + } + + OnEditsChanged(this, EventArgs.Empty); + } + + private void OnEditsChanged(object? sender, EventArgs e) + { + _view.ShowEdits(); + StateChanged?.Invoke(this, EventArgs.Empty); + } + + // The edits name rows of one set; once the grid shows another, as when the tab lets go of its rows, they go. + private void OnShownSetChanged(object? sender, EventArgs e) + { + if (Edits is not null && !ReferenceEquals(_results.ShownSet, _editsRows)) + { + SetEdits(null, null); + } + + ShownRowsChanged?.Invoke(this, EventArgs.Empty); + } + + private EditRefusal? Refusal() + { + if (!AcceptsEdits) + { + return EditRefusal.Busy.Instance; + } + + return Lock is { } locked ? new EditRefusal.TableLocked(locked) : null; + } + + private static EditRefusal? CellRefusal(TableEdits edits, int row, int column) + { + if (row < 0 || row >= edits.RowCount || column < 0 || column >= edits.Columns.Count) + { + return EditRefusal.CellLocked.Instance; + } + + if (edits.IsDeleted(row)) + { + return EditRefusal.RowDeleted.Instance; + } + + // A saved row's key stays as it is; a new row leaves to the server what it fills. + var info = edits.Columns[column]; + return (edits.IsAdded(row) ? info.EditableInNewRow : info.Editable) ? null : EditRefusal.CellLocked.Instance; + } + + private EditRefusal? Apply(TableEdits edits, int row, int column, CellEdit edit) + { + var newRow = edits.IsAdded(row); + string? stored = null; + if (!newRow && ReadStored(row, column, out stored) is { } unreadable) + { + return unreadable; + } + + if (_tableEditor!.Check(column, edit, newRow) is { } failure) + { + return new EditRefusal.Invalid(failure); + } + + edits.SetCell(row, column, edit, stored); + return null; + } + + // The stored value as text, null for NULL; a value with no text that writes it back is refused. + private EditRefusal? ReadStored(int row, int column, out string? stored) + { + stored = null; + try + { + if (_tableEditor!.GetEditStart(_editsRows, row, column) is not EditStart.Editable editable) + { + return EditRefusal.CellLocked.Instance; + } + + stored = editable.IsNull ? null : editable.Text; + return null; + } + catch (TableProException exception) + { + return new EditRefusal.Invalid(exception.Error); + } + } + + // What a copy of a data row holds where it was not edited, or null where its value has no text to copy. + private CellEdit? StoredEdit(int row, int column) + { + if (ReadStored(row, column, out var stored) is not null) + { + return null; + } + + return stored is null ? CellEdit.Null.Instance : new CellEdit.Text(stored); + } + + private async Task SaveEditsAsync(bool reload) + { + if (!_view.CommitOpenEdit()) + { + return false; + } + + if (_saveBlocked || Lock is not null) + { + _view.ShowEditRefusal(_saveBlocked ? EditRefusal.SaveBlocked.Instance : Refusal()!); + return false; + } + + if (!CanSave || Edits is not { } edits) + { + return false; + } + + var planned = edits.ToRowEdits(); + IRowSave save; + try + { + save = _tableEditor!.Plan(_editsRows, planned.Edits); + } + catch (TableProException exception) + { + await _view.ShowSaveFailedAsync(exception.Error, incomplete: false).ConfigureAwait(true); + return false; + } + + using (save) + { + return await RunSaveAsync(save, edits, planned, reload).ConfigureAwait(true); + } + } + + // The delete question comes at every Safe Mode level, as on macOS, then the level's own. + private async Task RunSaveAsync(IRowSave save, TableEdits edits, PlannedEdits planned, bool reload) + { + if (save.IsEmpty) + { + edits.Discard(); + return true; + } + + if (save.Gate == SaveGate.Refuse) + { + _view.ShowEditRefusal(new EditRefusal.TableLocked(EditLock.ReadOnlyConnection)); + return false; + } + + var deletes = planned.Edits.Count(edit => edit is RowEdit.Delete); + if (deletes > 0 && !await _view.ConfirmDeleteAsync(Table.Name, deletes).ConfigureAwait(true)) + { + return false; + } + + var confirmed = save.Gate == SaveGate.Run; + if (save.Gate == SaveGate.Confirm) + { + if (!await _view.ConfirmSaveAsync(_session.Name, save.Statements).ConfigureAwait(true)) + { + _view.ShowSaveCancelled(); + return false; + } + + confirmed = true; + } + + // Asked while the tab closed or its rows went, the save no longer names what it was planned for. + if (!ReferenceEquals(edits, Edits) || !CanSave) + { + return false; + } + + RowSaveOutcome? outcome = null; + CoreError? failure = null; + // A save is not stopped halfway: a close waits for the server's answer and for what the answer changes here. + await _work.RunAsync(async _ => + { + SetSaving(true); + try + { + outcome = await save.RunAsync(confirmed, CancellationToken.None).ConfigureAwait(true); + } + catch (TableProException exception) when (exception.Error.Codes.Any(NothingSent.Contains)) + { + failure = exception.Error; + } + catch (TableProException exception) + { + // Any other failure may have come after the batch was sent, so saving again could write it twice. + outcome = new RowSaveOutcome.Unknown(exception.Error, null); + } + finally + { + SetSaving(false); + } + + if (outcome is RowSaveOutcome.Saved) + { + edits.Discard(); + } + else if (outcome is RowSaveOutcome.Unknown) + { + _saveBlocked = true; + OnEditsChanged(this, EventArgs.Empty); + } + }).ConfigureAwait(true); + + // A tab that closed meanwhile says nothing more. + if (_work.IsClosed) + { + return outcome is RowSaveOutcome.Saved; + } + + return await AfterSaveAsync(outcome, failure, planned, reload).ConfigureAwait(true); + } + + private async Task AfterSaveAsync( + RowSaveOutcome? outcome, CoreError? failure, PlannedEdits planned, bool reload) + { + switch (outcome) + { + case RowSaveOutcome.Saved: + if (reload) + { + // Rows came and went, so the page is read again and the table counted again, without asking. + _page = _page with { Total = null }; + await LoadAsync(_page.Offset).ConfigureAwait(true); + } + + return true; + case RowSaveOutcome.RolledBack rolledBack: + await _view.ShowSaveFailedAsync(rolledBack.Error, incomplete: false).ConfigureAwait(true); + FocusEdit(planned, rolledBack.Edit); + return false; + case RowSaveOutcome.Unknown unknown: + await _view.ShowSaveFailedAsync(unknown.Error, incomplete: true).ConfigureAwait(true); + FocusEdit(planned, unknown.Edit); + return false; + default: + if (failure is not null) + { + await _view.ShowSaveFailedAsync(failure, incomplete: false).ConfigureAwait(true); + } + + return false; + } + } + + // The row of the change the engine said the save stopped at. + private void FocusEdit(PlannedEdits planned, int? edit) + { + if (edit is { } index && index >= 0 && index < planned.Rows.Count) + { + _view.FocusRow(planned.Rows[index]); + } + } + + private void SetSaving(bool saving) + { + IsSaving = saving; + _view.ShowSaving(saving); + _view.ShowEdits(); + StateChanged?.Invoke(this, EventArgs.Empty); + } + + private async void CountIfNeeded() => await _work.RunAsync(CountAsync).ConfigureAwait(true); + + // A first page that is not full holds the whole table; otherwise the server counts it, in the background. + private async Task CountAsync(CancellationToken closing) + { + if (_page.Total is not null || !_page.CanSeek) + { + _view.UpdatePager(); + return; + } + + if (_page.Offset == 0 && _page.Rows < _page.Size) + { + _page = _page with { Total = _page.Rows }; + _view.UpdatePager(); + return; + } + + _view.UpdatePager(); + _counting?.Cancel(); + using var counting = CancellationTokenSource.CreateLinkedTokenSource(closing); + _counting = counting; + try + { + var total = await _session.CountRowsAsync(Table, counting.Token).ConfigureAwait(true); + // A count that lands as the tab closes is not shown. + if (_work.IsClosed) + { + return; + } + + _page = _page with { Total = total }; + _view.UpdatePager(); + } + catch (Exception exception) when (exception is TableProException or OperationCanceledException) + { + // Without a count the pager still pages forward while pages come back full. + } + finally + { + if (ReferenceEquals(_counting, counting)) + { + _counting = null; + } + } + } + + private void SetRunning(bool running) + { + IsRunning = running; + _view.ShowRunning(running); + StateChanged?.Invoke(this, EventArgs.Empty); + } +} diff --git a/windows/src/TablePro.App.Model/WorkspaceTabs.cs b/windows/src/TablePro.App.Model/WorkspaceTabs.cs new file mode 100644 index 0000000000..31d9d5fe7a --- /dev/null +++ b/windows/src/TablePro.App.Model/WorkspaceTabs.cs @@ -0,0 +1,194 @@ +using TablePro.Interop; + +namespace TablePro.App.Model; + +// What a workspace and its window read of a tab before they close it. +public interface IWorkspaceTab +{ + string Title { get; } + + TabKind Kind { get; } + + bool IsRunning { get; } + + // The transaction the tab's own connection holds; the workspace names a held one over the other tabs. + TransactionState Transaction { get; } + + bool HasUnsavedChanges { get; } + + // Asks about unsaved changes before a close and may save them, unless offerSave is off; false keeps the tab. + Task ConfirmCloseAsync(bool offerSave); + + SessionTab Snapshot(); + + // Once only, however often it is asked for: the tab lets go of its session exactly once. + Task CloseAsync(); +} + +// The tab strip in its order. TItem is the strip's own item, which can move to another window's strip. +public interface IWorkspaceTabsView +{ + IReadOnlyList Items { get; } + + IWorkspaceTab? ContentOf(TItem item); + + void SelectTab(TItem item); + + // Closing a tab ends its own connection, and its transaction with it. + Task ConfirmCloseHeldAsync(IWorkspaceTab tab); + + // The workspace lets go of the item; its content is closed or moves to another strip. + void Remove(TItem item); +} + +public sealed class WorkspaceTabs + where TItem : class +{ + private readonly IWorkspaceTabsView _view; + private readonly ClosedTabs _closed = new(); + private readonly HashSet _closing = []; + + public WorkspaceTabs(IWorkspaceTabsView view) + { + ArgumentNullException.ThrowIfNull(view); + _view = view; + } + + // The user closed the last tab; a window a tab was moved into closes with it. + public event EventHandler? Emptied; + + public int ClosedCount => _closed.Count; + + // A second request while the first is closing the tab, or asking about its transaction, does nothing. + public async Task CloseAsync(TItem item) + { + ArgumentNullException.ThrowIfNull(item); + if (!_closing.Add(item)) + { + return; + } + + try + { + if (_view.ContentOf(item) is { } content) + { + if (WorkspaceNotices.Holds(content.Transaction) + && !await _view.ConfirmCloseHeldAsync(content).ConfigureAwait(true)) + { + return; + } + + // The question names the tab, so it shows first. + if (content.HasUnsavedChanges) + { + _view.SelectTab(item); + if (!await content.ConfirmCloseAsync(offerSave: true).ConfigureAwait(true)) + { + return; + } + } + + _closed.Push(content.Snapshot(), IndexOf(item)); + await content.CloseAsync().ConfigureAwait(true); + } + } + finally + { + _closing.Remove(item); + } + + _view.Remove(item); + if (_view.Items.Count == 0) + { + Emptied?.Invoke(this, EventArgs.Empty); + } + } + + // A held transaction or unsaved changes not answered for yet. + public bool HasUnconfirmed(ISet confirmed) + { + ArgumentNullException.ThrowIfNull(confirmed); + return _view.Items.Any(item => _view.ContentOf(item) is { } content && Asks(content, confirmed)); + } + + // Each tab shows before its question, since the question names it. + public async Task ConfirmCloseAsync(ISet confirmed, bool offerSave = true) + { + ArgumentNullException.ThrowIfNull(confirmed); + foreach (var item in _view.Items.ToList()) + { + if (_view.ContentOf(item) is not { } content || !Asks(content, confirmed)) + { + continue; + } + + _view.SelectTab(item); + if (WorkspaceNotices.Holds(content.Transaction) + && !await _view.ConfirmCloseHeldAsync(content).ConfigureAwait(true)) + { + return false; + } + + if (content.HasUnsavedChanges && !await content.ConfirmCloseAsync(offerSave).ConfigureAwait(true)) + { + return false; + } + + confirmed.Add(content); + } + + return true; + } + + // A table tab loading a page is not work the user started, so only a query tab's run is asked about. + public IReadOnlyList RunningQueries() => + [ + .. _view.Items + .Select(_view.ContentOf) + .OfType() + .Where(tab => tab is { Kind: TabKind.Query, IsRunning: true }), + ]; + + // The tabs of a window that closed, so Reopen closed tab brings them back here in their order. + public void KeepClosed(IReadOnlyList tabs) + { + ArgumentNullException.ThrowIfNull(tabs); + for (var index = tabs.Count - 1; index >= 0; index--) + { + _closed.Push(tabs[index], int.MaxValue); + } + } + + public ClosedTab? TakeClosed() => _closed.Pop(); + + // A reconnect keeps the closed tabs, which hold only their text or table, to reopen on the next session. + public async Task CloseAllAsync(bool keepClosed) + { + if (!keepClosed) + { + _closed.Clear(); + } + + foreach (var tab in _view.Items.Select(_view.ContentOf).OfType().ToList()) + { + await tab.CloseAsync().ConfigureAwait(true); + } + } + + private static bool Asks(IWorkspaceTab tab, ISet confirmed) => + (WorkspaceNotices.Holds(tab.Transaction) || tab.HasUnsavedChanges) && !confirmed.Contains(tab); + + private int IndexOf(TItem item) + { + var items = _view.Items; + for (var index = 0; index < items.Count; index++) + { + if (ReferenceEquals(items[index], item)) + { + return index; + } + } + + return -1; + } +} diff --git a/windows/src/TablePro.App/MainWindow.xaml b/windows/src/TablePro.App/MainWindow.xaml index 24584493a7..57f8c7d935 100644 --- a/windows/src/TablePro.App/MainWindow.xaml +++ b/windows/src/TablePro.App/MainWindow.xaml @@ -59,6 +59,15 @@ + + + + + + + + + @@ -88,6 +97,23 @@ + + + + + + + + + + + + + + + + + @@ -142,6 +168,13 @@ + + + + + + + diff --git a/windows/src/TablePro.App/MainWindow.xaml.cs b/windows/src/TablePro.App/MainWindow.xaml.cs index 113f91de4d..c98d0ad783 100644 --- a/windows/src/TablePro.App/MainWindow.xaml.cs +++ b/windows/src/TablePro.App/MainWindow.xaml.cs @@ -702,7 +702,7 @@ private async Task OnFormCompletedAsync(FormResult result) if (reconnecting is not null) { - if (!await ConfirmDisconnectAsync(reconnecting)) + if (!await ConfirmDisconnectAsync(reconnecting, offerSave: result.Saved.SafeMode != SafeMode.ReadOnly)) { ShowChangesOnConnect(reconnecting, result.Saved); return; @@ -756,7 +756,8 @@ private async Task ApplySafeModeAsync(SavedConnection saved, OpenConnection? rec continue; } - if (await window.ConfirmDisconnectAsync(each)) + // Pending edits are not written on a connection the user is making read only. + if (await window.ConfirmDisconnectAsync(each, offerSave: saved.SafeMode != SafeMode.ReadOnly)) { DropSpare(); await each.DisconnectAsync(keepTabs: true); @@ -772,12 +773,12 @@ private async Task ApplySafeModeAsync(SavedConnection saved, OpenConnection? rec private static void ShowChangesOnConnect(OpenConnection open, SavedConnection saved) => open.View.ShowChangesOnConnect(saved.SafeMode == SafeMode.ReadOnly && open.Session is { IsReadOnly: false }); - // Disconnecting ends each tab's own connection, so a held transaction is asked about first, as closing its tab - // asks. The connection shows first, since the question names one of its tabs. - private async Task ConfirmDisconnectAsync(OpenConnection open) + // Disconnecting ends each tab's own connection and its pending edits, so both are asked about first, as closing a + // tab asks. The connection shows first, since the question names one of its tabs. + private async Task ConfirmDisconnectAsync(OpenConnection open, bool offerSave = true) { - var confirmed = new HashSet(); - if (!open.View.HasUnconfirmedTransactions(confirmed)) + var confirmed = new HashSet(); + if (!open.View.HasUnconfirmed(confirmed)) { return true; } @@ -792,7 +793,7 @@ private async Task ConfirmDisconnectAsync(OpenConnection open) Show(open); } - return await open.View.ConfirmCloseAsync(confirmed); + return await open.View.ConfirmCloseAsync(confirmed, offerSave); } private void OnRailSelectionChanged(NavigationView sender, NavigationViewSelectionChangedEventArgs args) @@ -857,12 +858,12 @@ private async Task RequestCloseAsync(bool askAboutRunning = true) RefreshTabTransfers(); try { - var confirmed = new HashSet(); + var confirmed = new HashSet(); // Apart from confirmed, so a run that ends during the question and leaves a transaction open is asked about. - var stopped = new HashSet(); + var stopped = new HashSet(); while (true) { - if (!await ConfirmTransactionsAsync(windows, confirmed)) + if (!await ConfirmTabsAsync(windows, confirmed)) { return; } @@ -900,13 +901,14 @@ private async Task RequestCloseAsync(bool askAboutRunning = true) } } - private static async Task ConfirmTransactionsAsync(List windows, HashSet confirmed) + // Held transactions and unsaved changes, tab by tab in every window; a save chosen there runs before the close. + private static async Task ConfirmTabsAsync(List windows, HashSet confirmed) { - while (windows.SelectMany(window => window._open).Any(open => open.View.HasUnconfirmedTransactions(confirmed))) + while (windows.SelectMany(window => window._open).Any(open => open.View.HasUnconfirmed(confirmed))) { foreach (var window in windows) { - foreach (var open in window._open.Where(open => open.View.HasUnconfirmedTransactions(confirmed)).ToList()) + foreach (var open in window._open.Where(open => open.View.HasUnconfirmed(confirmed)).ToList()) { window.Activate(); if (window.IsPrimary) @@ -929,15 +931,15 @@ private static async Task ConfirmTransactionsAsync(List window return true; } - private static List<(string Connection, ITabContent Tab)> RunningQueries( - List windows, HashSet confirmed, HashSet stopped) => + private static List<(string Connection, IWorkspaceTab Tab)> RunningQueries( + List windows, HashSet confirmed, HashSet stopped) => [.. windows.SelectMany(window => window._open) .SelectMany(open => open.View.RunningQueries() .Where(tab => !confirmed.Contains(tab) && !stopped.Contains(tab)) .Select(tab => (Connection: open.Name, Tab: tab)))]; // One question for every query still running, as the macOS app asks before it quits; Cancel keeps every window. - private async Task ConfirmStopRunningAsync(List<(string Connection, ITabContent Tab)> running) + private async Task ConfirmStopRunningAsync(List<(string Connection, IWorkspaceTab Tab)> running) { Activate(); var one = running.Count == 1; @@ -1196,6 +1198,14 @@ private void UpdateCommands() MenuCopy.IsEnabled = tab is not null; MenuSelectAll.IsEnabled = tab is not null; + // A query tab never edits; a table tab says what its page can do now. + var table = tab as TableTabView; + MenuSaveChanges.IsEnabled = table is { CanSave: true }; + MenuDiscardChanges.IsEnabled = table is { CanDiscard: true }; + MenuPreviewSql.IsEnabled = table is { CanPreview: true }; + MenuAddRow.IsEnabled = table is { CanAddRow: true }; + MenuDuplicateRow.IsEnabled = table is { CanChangeRows: true }; + MenuDeleteRows.IsEnabled = table is { CanChangeRows: true }; } private void OnNewConnection(object sender, RoutedEventArgs e) => NewConnection(); @@ -1341,6 +1351,36 @@ private async void OnDisconnect(object sender, RoutedEventArgs e) private void OnStop(object sender, RoutedEventArgs e) => Workspace?.ActiveTab?.Stop(); + private async void OnSaveChanges(object sender, RoutedEventArgs e) + { + if (Workspace?.ActiveTab is TableTabView table) + { + await table.SaveAsync(); + } + } + + private async void OnDiscardChanges(object sender, RoutedEventArgs e) + { + if (Workspace?.ActiveTab is TableTabView table) + { + await table.DiscardAsync(); + } + } + + private async void OnPreviewSql(object sender, RoutedEventArgs e) + { + if (Workspace?.ActiveTab is TableTabView table) + { + await table.PreviewAsync(); + } + } + + private void OnAddRow(object sender, RoutedEventArgs e) => (Workspace?.ActiveTab as TableTabView)?.AddRow(); + + private void OnDuplicateRow(object sender, RoutedEventArgs e) => (Workspace?.ActiveTab as TableTabView)?.DuplicateRows(); + + private void OnDeleteRows(object sender, RoutedEventArgs e) => (Workspace?.ActiveTab as TableTabView)?.DeleteRows(); + private async void OnDocumentation(object sender, RoutedEventArgs e) => await Launcher.LaunchUriAsync(SettingsView.DocumentationUri); diff --git a/windows/src/TablePro.App/Services/SessionShare.cs b/windows/src/TablePro.App/Services/SessionShare.cs deleted file mode 100644 index 6986c8c3d7..0000000000 --- a/windows/src/TablePro.App/Services/SessionShare.cs +++ /dev/null @@ -1,19 +0,0 @@ -using TablePro.Interop; - -namespace TablePro.App.Services; - -// A session held by each workspace and tab that uses it, so a tab moved to another window keeps its own. -internal sealed class SessionShare(DatabaseSession session) -{ - private int _holders = 1; - - public DatabaseSession Session { get; } = session; - - public SessionShare Hold() - { - _holders++; - return this; - } - - public ValueTask ReleaseAsync() => --_holders == 0 ? Session.DisposeAsync() : ValueTask.CompletedTask; -} diff --git a/windows/src/TablePro.App/Strings/en-US/Resources.resw b/windows/src/TablePro.App/Strings/en-US/Resources.resw index 2113dc86a8..2bce812887 100644 --- a/windows/src/TablePro.App/Strings/en-US/Resources.resw +++ b/windows/src/TablePro.App/Strings/en-US/Resources.resw @@ -1614,4 +1614,349 @@ New fingerprint: {2} A client certificate needs both a certificate file and a key file. + + Add row + + + Add row (Ctrl+Shift+N) + + + Duplicate row + + + Duplicate row (Ctrl+Shift+D) + + + Delete + + + Delete (Delete) + + + Save changes + + + Save changes (Ctrl+S) + + + Discard changes + + + Preview SQL + + + Preview SQL (Ctrl+Shift+P) + + + Save + + + Discard changes... + + + Preview SQL + + + Add row + + + Duplicate row + + + Delete + + + Set value + + + Empty + + + NULL + + + Default + + + Add row + + + Duplicate + + + Delete + + + Undo delete + + + Copy + + + DEFAULT + + + edited + + + new row + + + marked for deletion + + + Discard changes? + + + The changes you have not saved will be lost. + + + Discard changes + + + Discard unsaved changes? + + + Refreshing will discard all unsaved changes. + + + Sorting will reload data and discard all unsaved changes. + + + Navigating to another page will discard all unsaved changes. + + + Discard + + + Do you want to save changes? + + + Your changes will be lost if you don't save them. + + + Save + + + Don't save + + + Do you want to save changes to {0}? + + + Delete this row from {0}? + + + Delete {0} rows from {1}? + + + This permanently deletes the selected rows from the database and can't be undone. + + + Delete + + + Save changes + + + Runs on {0}, which asks before every change to the database. + + + Execute + + + 1 statement + + + {0} statements + + + Copy all + + + SQL preview + + + No pending changes + + + Done + + + Values: {0} + + + Save failed + + + Save incomplete + + + Nothing was saved, and every change is still pending. + + + The save may have been written. Refresh the table to see what is there before you save again. + + + The last save may have been written. Refresh the table before you save again. + + + Operation cancelled by user + + + Saving changes... + + + {0} has no primary key, so its rows cannot be told apart. Edit the rows with a query. + + + Rows of {0} cannot be edited here, because their key cannot be read back exactly. Edit them with a query. + + + The table's columns changed. Refresh the table to edit it. + + + This connection is read only. + + + This value cannot be edited here. + + + This column needs a value. + + + Enter a whole number. + + + This number is outside the range the column holds. + + + Enter a number. + + + Enter a number. + + + This column keeps fewer digits. + + + This column keeps fewer decimal places. + + + Enter true or false. + + + Enter a UUID. + + + Enter valid JSON. + + + Enter a date as YYYY-MM-DD. + + + Enter a time as HH:MM:SS. + + + This time is outside the range the column can hold. + + + Enter a date and time as YYYY-MM-DD HH:MM:SS. + + + This column needs a time zone offset. + + + Enter an interval. + + + Enter a bit string of 0 and 1. + + + Enter bytes as 0x and hex digits. + + + This column holds a different number of bits. + + + This is not one of the values this column allows. + + + This value cannot be edited here. + + + This connection is read only. + + + This table has no primary key, so its rows cannot be told apart. + + + A row's key cannot be read back exactly, so the row cannot be changed here. + + + The table's columns changed since the rows were read. Refresh the table and edit again. + + + The connection's Safe Mode changed. Save again to see what it asks. + + + The connection would save other statements than the ones planned. Save again. + + + Safe Mode asks before this save. Save again to answer it. + + + This column has no default a saved row can be set to. + + + This save already ran. + + + The rows changed since they were read. Refresh the table and edit again. + + + This table has no way to name a single row. + + + Rows of this table cannot be edited, because nothing identifies one. + + + There is nothing to save. + + + This database has no statement for a new row that sets no column. Enter a value in at least one column, or insert the row with a query. + + + Part of this row's key could not be read from the server, so the row cannot be changed. + + + A column here cannot be set to a value the server computes. + + + A value here cannot be sent to this database. + + + The row key names a column this table no longer has. + + + The row key does not fit the table's key. + + + A field here has a name an update cannot write. + + + Nothing was saved. + + + A row changed or went away since it was read, so nothing was saved. + + + This database cannot report how many rows a change touched, so nothing was saved. + + + Part of the save was written before it stopped. + + + The save was sent and no answer came back, so it may have been written. + diff --git a/windows/src/TablePro.App/Views/ITabContent.cs b/windows/src/TablePro.App/Views/ITabContent.cs index 2941c80104..915f550c0f 100644 --- a/windows/src/TablePro.App/Views/ITabContent.cs +++ b/windows/src/TablePro.App/Views/ITabContent.cs @@ -2,21 +2,14 @@ using TablePro.App.Model; using TablePro.DataGrid; using TablePro.Editor; -using TablePro.Interop; namespace TablePro.App.Views; -internal interface ITabContent +// A tab's content in the strip; its run, close and transaction are its model's (QueryTab, TableTab). +internal interface ITabContent : IWorkspaceTab { event EventHandler? StateChanged; - string Title { get; } - - bool IsRunning { get; } - - // The transaction the tab's own connection holds; the workspace names a held one over the other tabs. - TransactionState Transaction { get; } - SqlEditor? Editor { get; } DataGridView Grid { get; } @@ -32,8 +25,4 @@ internal interface ITabContent void Stop(); void FocusContent(); - - SessionTab Snapshot(); - - Task CloseAsync(); } diff --git a/windows/src/TablePro.App/Views/OpenConnection.cs b/windows/src/TablePro.App/Views/OpenConnection.cs index 69336512e4..7a710f0905 100644 --- a/windows/src/TablePro.App/Views/OpenConnection.cs +++ b/windows/src/TablePro.App/Views/OpenConnection.cs @@ -7,30 +7,19 @@ namespace TablePro.App.Views; -internal enum ConnectionState -{ - NotConnected, - Connecting, - Connected, - Failed, -} - -// A saved connection is reopened by id, a file opened without saving by its path. -internal sealed class OpenConnection +// The rail item and the workspace of one open connection; connecting and closing it are ConnectionLife's. +internal sealed class OpenConnection : IConnectionView { private readonly Workbench _workbench; - private CancellationTokenSource? _connecting; - private SessionConnection? _restore; - private SessionShare? _share; - // A reconnect's tabs wait in _restore, so cancelling its connect keeps the item to retry instead of closing it. - private bool _keepOnCancel; + private readonly ConnectionLife _life; public OpenConnection(Workbench workbench, SessionConnection origin) { _workbench = workbench; - Origin = origin; - _restore = origin.Tabs.Count > 0 ? origin : null; View = new WorkspaceView(workbench, this); + _life = new ConnectionLife( + origin, this, new CoreConnector(workbench.Core, View.CredentialPrompter)); + _life.Cancelled += (_, _) => Cancelled?.Invoke(this, EventArgs.Empty); RailItem = new NavigationViewItem { Content = origin.Name, @@ -51,7 +40,7 @@ public OpenConnection(Workbench workbench, SessionConnection origin) // Raised when a connect the user cancelled is over, so the window can take the connection away. public event EventHandler? Cancelled; - public SessionConnection Origin { get; private set; } + public SessionConnection Origin => _life.Origin; public string Name => Origin.Name; @@ -61,14 +50,11 @@ public OpenConnection(Workbench workbench, SessionConnection origin) public WorkspaceView View { get; } - public DatabaseSession? Session => _share?.Session; + public DatabaseSession? Session => _life.Session; - public ConnectionState State { get; private set; } = ConnectionState.NotConnected; + public ConnectionState State => _life.State; - public bool Matches(Guid? connectionId, string? filePath) => - connectionId is not null - ? connectionId == Origin.ConnectionId - : filePath is not null && string.Equals(filePath, Origin.FilePath, StringComparison.OrdinalIgnoreCase); + public bool Matches(Guid? connectionId, string? filePath) => _life.Matches(connectionId, filePath); public string? Color { get; private set; } @@ -80,7 +66,7 @@ public void Mark(string engineId, string? color) return; } - Origin = Origin with { EngineId = engineId }; + _life.SetEngine(engineId); Color = color; RailItem.Icon = EngineIcons.Mark(engineId, color); // The glyph says the engine to the eye; the item says it to a screen reader. @@ -89,187 +75,37 @@ public void Mark(string engineId, string? color) public void Rename(string name) { - Origin = Origin with { Name = name }; + _life.Rename(name); RailItem.Content = name; AutomationProperties.SetName(RailItem, name); ToolTipService.SetToolTip(RailItem, name); View.Rename(name); } - public async Task ConnectAsync() - { - if (State is ConnectionState.Connecting or ConnectionState.Connected) - { - return; - } + public Task ConnectAsync() => _life.ConnectAsync(); - using var connecting = new CancellationTokenSource(); - _connecting = connecting; - SetState(ConnectionState.Connecting); - View.ShowConnecting(); - try - { - var session = Origin.ConnectionId is { } id - ? await ConnectSavedAsync(id, connecting.Token).ConfigureAwait(true) - : await _workbench.Core.OpenFileAsync( - new FileOpenOptions(Origin.FilePath!, string.IsNullOrEmpty(Origin.EngineId) ? null : Origin.EngineId), - connecting.Token).ConfigureAwait(true); - _share = new SessionShare(session); - if (Origin.EngineId != session.EngineId) - { - Mark(session.EngineId, Color); - } - - SetState(ConnectionState.Connected); - View.ShowConnected(_share, _restore); - _restore = null; - _keepOnCancel = false; - if (Origin.ConnectionId is not null) - { - _workbench.NotifyLibraryChanged(); - } - } - catch (OperationCanceledException) - { - SetState(ConnectionState.NotConnected); - if (_keepOnCancel) - { - var message = Strings.Get("ConnectCancelledKeepsTabs"); - View.ShowFailed(message, message); - } - else - { - Cancelled?.Invoke(this, EventArgs.Empty); - } - } - catch (TableProException exception) - { - SetState(ConnectionState.Failed); - View.ShowFailed(Strings.Error(exception.Error), Details(exception.Error)); - } - finally - { - _connecting = null; - } - } - - public void CancelConnect() - { - _connecting?.Cancel(); - View.CancelRecovery(); - } + public void CancelConnect() => _life.CancelConnect(); // The same connection in another window, on the same session, ready for the tab moved into it. public OpenConnection Adopt() { - var share = _share ?? throw new InvalidOperationException("Only a connected workspace gives up a tab."); - var adopted = new OpenConnection(_workbench, Origin with { Tabs = [], SelectedTab = 0 }); - adopted.Mark(Origin.EngineId, Color); - adopted._share = share.Hold(); - adopted.SetState(ConnectionState.Connected); - adopted.View.ShowConnected(adopted._share, null, adopted: true); - return adopted; - } - - // A secret with none saved is asked for, as macOS asks; closing the dialog cancels the connect. - private async Task ConnectSavedAsync(Guid id, CancellationToken cancellationToken) - { - var secrets = ConnectionSecrets.None; - var remembered = ConnectionSecrets.None; - var prompted = new HashSet(); - var replaced = new HashSet(StringComparer.Ordinal); - while (true) + if (_life.Share is null) { - try - { - var session = await _workbench.Core.ConnectAsync( - id, secrets, View.CredentialPrompter, cancellationToken).ConfigureAwait(true); - if (remembered != ConnectionSecrets.None) - { - await SaveSecretAsync(id, remembered).ConfigureAwait(true); - } - - return session; - } - catch (TableProException exception) when (exception.Error.HostKey is { TrustAllowed: true } key && replaced.Add(key.Host)) - { - var snapshot = await _workbench.Library.GetSnapshotAsync().ConfigureAwait(true); - var saved = snapshot.Connections.FirstOrDefault(connection => connection.Id == id); - if (saved is null || !await View.CredentialPrompter.RecoverHostKeyAsync( - _workbench.Core, saved, exception.Error.HostKey!, cancellationToken).ConfigureAwait(true)) - { - throw; - } - } - catch (TableProException exception) when (exception.Code == "keyring.secret_not_stored") - { - var kind = exception.Error.Secret ?? SecretKind.DatabasePassword; - if (!prompted.Add(kind)) - { - throw; - } - - var answer = await View.AskSecretAsync(kind, cancellationToken).ConfigureAwait(true) - ?? throw new OperationCanceledException(cancellationToken); - secrets = WithSecret(secrets, kind, answer.Secret); - if (answer.Save) - { - remembered = WithSecret(remembered, kind, answer.Secret); - } - } + throw new InvalidOperationException("Only a connected workspace gives up a tab."); } - } - private static ConnectionSecrets WithSecret(ConnectionSecrets secrets, SecretKind kind, string value) => kind switch - { - SecretKind.SshPassword => secrets with { SshPassword = value }, - SecretKind.SshPassphrase => secrets with { SshPassphrase = value }, - _ => secrets with { DatabasePassword = value }, - }; - - private async Task SaveSecretAsync(Guid id, ConnectionSecrets secrets) - { - try - { - var snapshot = await _workbench.Library.GetSnapshotAsync().ConfigureAwait(true); - if (snapshot.Connections.FirstOrDefault(connection => connection.Id == id) is { } saved) - { - await _workbench.Library.SaveAsync(saved, secrets).ConfigureAwait(true); - } - } - catch (TableProException) - { - // The connect worked; a password that could not be saved is asked for again next time. - } + var adopted = new OpenConnection(_workbench, Origin with { Tabs = [], SelectedTab = 0 }); + adopted.Mark(Origin.EngineId, Color); + adopted._life.Adopt(_life); + return adopted; } - // A reconnect keeps the tabs, their text and the tabs closed before, to open again on the next session; only - // what their own connections held ends with this one. - public async Task DisconnectAsync(bool keepTabs = false) - { - CancelConnect(); - _keepOnCancel = keepTabs; - if (keepTabs && State == ConnectionState.Connected && Snapshot() is { Tabs.Count: > 0 } tabs) - { - _restore = tabs; - } - - var share = _share; - _share = null; - await View.CloseTabsAsync(keepClosed: keepTabs).ConfigureAwait(true); - if (share is not null) - { - await share.ReleaseAsync().ConfigureAwait(true); - } - - SetState(ConnectionState.NotConnected); - } + public Task DisconnectAsync(bool keepTabs = false) => _life.DisconnectAsync(keepTabs); - public SessionConnection Snapshot() => View.Snapshot(_restore ?? Origin); + public SessionConnection Snapshot() => _life.Snapshot(); - private void SetState(ConnectionState state) + void IConnectionView.ShowState(ConnectionState state) { - State = state; RailItem.InfoBadge = state switch { ConnectionState.Connecting => new InfoBadge { Style = Badge("AttentionDotInfoBadgeStyle") }, @@ -288,6 +124,51 @@ private void SetState(ConnectionState state) StateChanged?.Invoke(this, EventArgs.Empty); } + void IConnectionView.ShowConnecting() => View.ShowConnecting(); + + // A session that names another engine than the one saved marks the rail with it. + void IConnectionView.ShowConnected( + SessionShare share, SessionConnection? restore, bool adopted) + { + if (!adopted && Origin.EngineId != share.Session.EngineId) + { + Mark(share.Session.EngineId, Color); + } + + View.ShowConnected(share, restore, adopted); + if (!adopted && ConnectionId is not null) + { + _workbench.NotifyLibraryChanged(); + } + } + + void IConnectionView.ShowFailed(CoreError failure) => + View.ShowFailed(Strings.Error(failure), Details(failure)); + + void IConnectionView.ShowCancelledKeepsTabs() + { + var message = Strings.Get("ConnectCancelledKeepsTabs"); + View.ShowFailed(message, message); + } + + Task IConnectionView.AskSecretAsync( + SecretKind kind, CancellationToken cancellationToken) => View.AskSecretAsync(kind, cancellationToken); + + async Task IConnectionView.RecoverHostKeyAsync( + Guid id, HostKeyFailure failure, CancellationToken cancellationToken) + { + var snapshot = await _workbench.Library.GetSnapshotAsync().ConfigureAwait(true); + var saved = snapshot.Connections.FirstOrDefault(connection => connection.Id == id); + return saved is not null && await View.CredentialPrompter.RecoverHostKeyAsync( + _workbench.Core, saved, failure, cancellationToken).ConfigureAwait(true); + } + + void IConnectionView.CancelRecovery() => View.CancelRecovery(); + + Task IConnectionView.CloseTabsAsync(bool keepClosed) => View.CloseTabsAsync(keepClosed); + + SessionConnection IConnectionView.Snapshot(SessionConnection origin) => View.Snapshot(origin); + private static Style Badge(string key) => (Style)Application.Current.Resources[key]; private static string Details(CoreError error) diff --git a/windows/src/TablePro.App/Views/QueryTabView.xaml.cs b/windows/src/TablePro.App/Views/QueryTabView.xaml.cs index b6a1388c03..5a85d39aee 100644 --- a/windows/src/TablePro.App/Views/QueryTabView.xaml.cs +++ b/windows/src/TablePro.App/Views/QueryTabView.xaml.cs @@ -5,42 +5,36 @@ using TablePro.App.Model; using TablePro.App.Services; using TablePro.DataGrid; -using TablePro.DataGrid.Model; using TablePro.Editor; using TablePro.Interop; namespace TablePro.App.Views; -// One editor connection for the tab, so a transaction holds from one run to the next. -public sealed partial class QueryTabView : UserControl, ITabContent +// 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 { - private readonly Workbench _workbench; - private readonly SessionShare _share; - private readonly DatabaseSession _session; - private readonly TabWork _work = new(); - private QueryEditor? _editor; - private Task? _closing; - private QueryRun? _run; - private string? _statement; - private GridSort _sort = GridSort.None; - private bool _sorting; - private bool _confirming; + private readonly QueryTab _model; private EditTarget _target; - internal QueryTabView(Workbench workbench, SessionShare share, string title, string? sql) + internal QueryTabView(Workbench workbench, SessionShare share, string title, string? sql) { - _workbench = workbench; - _share = share.Hold(); - _session = share.Session; - Title = title; + var engineId = share.Session.EngineId; InitializeComponent(); SqlText.Text = sql ?? string.Empty; - SqlText.Lexer = new CoreSqlLexer(Grammars.For(_session.EngineId)); + SqlText.Lexer = new CoreSqlLexer(Grammars.For(engineId)); SqlText.EditorFontSize = (float)workbench.Settings.EditorFontSize; AutomationProperties.SetName(SqlText, Strings.Format("EditorName", title)); + _model = new QueryTab( + title, + new CoreTabSession(share), + this, + Results, + workbench.Engine(engineId)?.DataModel ?? DataModel.Relational, + () => workbench.Settings); + _model.StateChanged += (_, _) => StateChanged?.Invoke(this, EventArgs.Empty); Results.StatusChanged += (_, status) => StatusText.Text = status; - Results.SortRequested += OnSortRequested; - Results.ResultPicked += (_, _) => _sort = GridSort.None; + Results.SortRequested += async (_, sort) => await _model.SortAsync(sort).ConfigureAwait(true); + Results.ResultPicked += (_, _) => _model.ResultPicked(); SqlText.GotFocus += (_, _) => _target = EditTarget.Editor; Results.GridView.GotFocus += (_, _) => _target = EditTarget.Grid; Results.MessagesBox.GotFocus += (_, _) => _target = EditTarget.Messages; @@ -48,11 +42,15 @@ internal QueryTabView(Workbench workbench, SessionShare share, string title, str public event EventHandler? StateChanged; - public string Title { get; } + public string Title => _model.Title; - public bool IsRunning { get; private set; } + public TabKind Kind => _model.Kind; - public TransactionState Transaction { get; private set; } = TransactionState.Idle; + public bool IsRunning => _model.IsRunning; + + public TransactionState Transaction => _model.Transaction; + + public bool HasUnsavedChanges => _model.HasUnsavedChanges; public SqlEditor? Editor => SqlText; @@ -63,125 +61,75 @@ internal QueryTabView(Workbench workbench, SessionShare share, string title, str public TextBox? MessagesTarget => _target == EditTarget.Messages && Results.MessagesBox.Visibility == Visibility.Visible ? Results.MessagesBox : null; - public async void Run() => await RunAsync().ConfigureAwait(true); + string IQueryTabView.SelectedText => SqlText.Model.GetSelectedText(); - public async void RunStatement() => await RunStatementAsync().ConfigureAwait(true); + string IQueryTabView.WholeText => SqlText.Text; - public void Stop() => _run?.Cancel(); + string IQueryTabView.DocumentText => SqlText.Document.Snapshot(); - public void FocusContent() => SqlText.Focus(FocusState.Programmatic); + int IQueryTabView.Caret => SqlText.Model.Primary.Active; - public SessionTab Snapshot() => new() { Kind = TabKind.Query, Title = Title, Sql = SqlText.Text }; + public async void Run() => await _model.RunAsync().ConfigureAwait(true); - // Once only, however often it is asked for: the tab lets go of its session exactly once. - public Task CloseAsync() => _closing ??= CloseOnceAsync(); + public async void RunStatement() => await _model.RunStatementAsync().ConfigureAwait(true); - // The run in flight stops and ends before the run, the editor and the session it uses are let go. - private async Task CloseOnceAsync() - { - _run?.Cancel(); - await _work.CloseAsync().ConfigureAwait(true); - _run?.Dispose(); - _run = null; - Results.Clear(); - if (_editor is not null) - { - await _editor.DisposeAsync().ConfigureAwait(true); - _editor = null; - } + public void Stop() => _model.Stop(); - SqlText.Dispose(); - await _share.ReleaseAsync().ConfigureAwait(true); - } + public void FocusContent() => SqlText.Focus(FocusState.Programmatic); - private async Task RunAsync() - { - if (IsRunning || _confirming || _work.IsClosed) - { - return; - } + public SessionTab Snapshot() => _model.Snapshot(); - var sql = SqlText.Model.GetSelectedText(); - if (string.IsNullOrWhiteSpace(sql)) - { - sql = SqlText.Text; - } + public Task ConfirmCloseAsync(bool offerSave) => _model.ConfirmCloseAsync(offerSave); - await RunTypedAsync(sql).ConfigureAwait(true); - } + public Task CloseAsync() => _model.CloseAsync(); - // The statement is selected first so the tab shows which of its statements ran, as the Linux app does. - private async Task RunStatementAsync() + void IQueryTabView.SelectStatement(int start, int length) { - if (IsRunning || _confirming || _work.IsClosed) - { - return; - } - - var text = SqlText.Document.Snapshot(); - if (_session.StatementAt(text, SqlText.Model.Primary.Active) is not { } statement) - { - StatusText.Text = Strings.Get("StatusNoStatement"); - return; - } - - var (start, length) = statement.GetOffsetAndLength(text.Length); SqlText.Model.SetSelection(start + length, start); SqlText.EnsureCaretVisible(); - await RunTypedAsync(text[statement]).ConfigureAwait(true); } - // Safe Mode judges the text that is sent, whichever part of the editor it is. - private async Task RunTypedAsync(string sql) - { - if (string.IsNullOrWhiteSpace(sql)) - { - return; - } + void IQueryTabView.ShowNoStatement() => StatusText.Text = Strings.Get("StatusNoStatement"); - if (!await SafeModeAllowsAsync(sql).ConfigureAwait(true) || IsRunning || _work.IsClosed) - { - return; - } + void IQueryTabView.ShowRefused() => Results.ShowError(Strings.Get("Error_driver_read_only")); - _statement = sql; - _sort = GridSort.None; - await RunSqlAsync(sql).ConfigureAwait(true); - } + void IQueryTabView.ShowTransactionLost() => Results.ShowError(Strings.Get("TransactionLost")); + + void IQueryTabView.ShowSortedHeld(long rows) => StatusText.Text = Strings.Format("StatusSortedHeld", rows); - // Typed SQL only: Commit and Roll back end a transaction at every level, and a sort runs again only a read. - private async Task SafeModeAllowsAsync(string sql) + void IQueryTabView.ShowTransaction(TransactionState state, bool changed, bool canCommit) { - var gate = _session.GateRun(sql); - if (gate.Refused) + if (!WorkspaceNotices.Holds(state)) { - Results.ShowError(Strings.Get("Error_driver_read_only")); - return false; + TransactionBar.IsOpen = false; + return; } - if (gate.Confirm.Count == 0) + TransactionBar.Severity = state == TransactionState.Failed ? InfoBarSeverity.Error : InfoBarSeverity.Warning; + TransactionBar.Title = Strings.Get(state == TransactionState.Failed ? "TransactionFailedTitle" : "TransactionOpenTitle"); + TransactionBar.Message = Strings.Get(state == TransactionState.Failed ? "TransactionFailedMessage" : "TransactionOpenMessage"); + CommitButton.Visibility = canCommit ? Visibility.Visible : Visibility.Collapsed; + if (changed || !TransactionBar.IsOpen) { - return true; + // Narrator reads an InfoBar when it opens, not when its text changes. + TransactionBar.IsOpen = false; + TransactionBar.IsOpen = true; } + } - _confirming = true; - try - { - return await ConfirmWritesAsync(gate).ConfigureAwait(true); - } - finally - { - _confirming = false; - } + void IQueryTabView.ShowRunning(bool running) + { + RunButton.IsEnabled = !running; + StopButton.IsEnabled = running; } // Cancel is the answer Enter gives, and every statement shows in full, as the Linux app asks. - private async Task ConfirmWritesAsync(RunGate gate) + async Task IQueryTabView.ConfirmWritesAsync(RunGate gate, string connection) { var count = gate.Confirm.Count; var message = gate.Destructive - ? Strings.Format(count == 1 ? "ConfirmRunDestructiveOne" : "ConfirmRunDestructiveMany", _session.Name) - : Strings.Format(count == 1 ? "ConfirmRunWriteOne" : "ConfirmRunWriteMany", _session.Name); + ? Strings.Format(count == 1 ? "ConfirmRunDestructiveOne" : "ConfirmRunDestructiveMany", connection) + : Strings.Format(count == 1 ? "ConfirmRunWriteOne" : "ConfirmRunWriteMany", connection); var content = new StackPanel { Spacing = 12 }; content.Children.Add(new TextBlock { Text = message, TextWrapping = TextWrapping.Wrap }); var statements = new TextBlock @@ -203,112 +151,10 @@ private async Task ConfirmWritesAsync(RunGate gate) CloseButtonText = Strings.Get("Cancel"), DefaultButton = ContentDialogButton.Close, }; - return await WindowDialogs.ShowAsync(dialog, this) == ContentDialogResult.Primary; - } - - private Task RunSqlAsync(string sql) => _work.RunAsync(token => RunOnEditorAsync(sql, token)); - - private async Task RunOnEditorAsync(string sql, CancellationToken cancellationToken) - { - SetRunning(true); - try - { - var held = WorkspaceNotices.Holds(Transaction); - if ((await ReleaseLostEditorAsync().ConfigureAwait(true) && held) || _work.IsClosed) - { - return; - } - - // An editor that opens as the tab closes stays in _editor, which the close disposes. - _editor ??= await _session.OpenEditorAsync(cancellationToken).ConfigureAwait(true); - if (_work.IsClosed) - { - return; - } - - _run?.Dispose(); - var settings = _workbench.Settings; - _run = _editor.Run( - sql, - new QueryOptions( - settings.RowLimit, - settings.QueryTimeoutSeconds > 0 ? TimeSpan.FromSeconds(settings.QueryTimeoutSeconds) : null), - cancellationToken); - await Results.ShowRunAsync(_run, _sort, cancellationToken: cancellationToken).ConfigureAwait(true); - if (!_work.IsClosed) - { - await AfterRunAsync().ConfigureAwait(true); - } - } - catch (TableProException exception) - { - if (!_work.IsClosed) - { - Results.ShowError(Strings.Error(exception.Error)); - } - } - finally - { - SetRunning(false); - } - } - - private async Task AfterRunAsync() - { - if (await ReleaseLostEditorAsync().ConfigureAwait(true)) - { - return; - } - - var state = Results.Transaction == TransactionState.Unknown ? Transaction : Results.Transaction; - ShowTransaction(WorkspaceNotices.Holds(state) ? state : TransactionState.Idle); + return await WindowDialogs.ShowAsync(dialog, this).ConfigureAwait(true) == ContentDialogResult.Primary; } - // A new user run may open an idle editor, but must never continue a transaction whose connection was lost. - private async Task ReleaseLostEditorAsync() - { - if (_editor is not { IsLost: true } lost) - { - return false; - } - - _editor = null; - await lost.DisposeAsync().ConfigureAwait(true); - if (WorkspaceNotices.Holds(Transaction)) - { - Results.ShowError(Strings.Get("TransactionLost")); - } - - ShowTransaction(TransactionState.Idle); - return true; - } - - private void ShowTransaction(TransactionState state) - { - var changed = state != Transaction; - Transaction = state; - if (!WorkspaceNotices.Holds(state)) - { - TransactionBar.IsOpen = false; - return; - } - - TransactionBar.Severity = state == TransactionState.Failed ? InfoBarSeverity.Error : InfoBarSeverity.Warning; - TransactionBar.Title = Strings.Get(state == TransactionState.Failed ? "TransactionFailedTitle" : "TransactionOpenTitle"); - TransactionBar.Message = Strings.Get(state == TransactionState.Failed ? "TransactionFailedMessage" : "TransactionOpenMessage"); - // Rolling back keeps nothing, so it is the way out at every safe mode; a read-only connection commits nothing. - CommitButton.Visibility = state == TransactionState.Failed || _session.IsReadOnly ? Visibility.Collapsed : Visibility.Visible; - if (changed || !TransactionBar.IsOpen) - { - // Narrator reads an InfoBar when it opens, not when its text changes. - TransactionBar.IsOpen = false; - TransactionBar.IsOpen = true; - } - } - - private async void OnCommit(object sender, RoutedEventArgs e) => await EndTransactionAsync(commit: true).ConfigureAwait(true); - - private async void OnRollBack(object sender, RoutedEventArgs e) + async Task IQueryTabView.ConfirmRollBackAsync() { var dialog = new ContentDialog { @@ -320,94 +166,14 @@ private async void OnRollBack(object sender, RoutedEventArgs e) CloseButtonText = Strings.Get("Cancel"), DefaultButton = ContentDialogButton.Close, }; - if (await WindowDialogs.ShowAsync(dialog, this) == ContentDialogResult.Primary) - { - await EndTransactionAsync(commit: false).ConfigureAwait(true); - } - } - - // Run as typed SQL is, so the results and the bar follow it, as the Linux app ends one. - private async Task EndTransactionAsync(bool commit) - { - if (IsRunning || _editor is null) - { - return; - } - - var model = _workbench.Engine(_session.EngineId)?.DataModel ?? DataModel.Relational; - _statement = null; - await RunSqlAsync(WorkspaceNotices.EndTransaction(model, commit)).ConfigureAwait(true); + return await WindowDialogs.ShowAsync(dialog, this).ConfigureAwait(true) == ContentDialogResult.Primary; } - private void SetRunning(bool running) - { - IsRunning = running; - RunButton.IsEnabled = !running; - StopButton.IsEnabled = running; - StateChanged?.Invoke(this, EventArgs.Empty); - } + void IQueryTabView.CloseEditor() => SqlText.Dispose(); - // Only one query that reads runs again: running a script or a write again would repeat it. - private async void OnSortRequested(object? sender, GridSort sort) - { - if (IsRunning || _sorting) - { - Results.Sort = _sort; - return; - } - - var columns = Results.Columns.Select(column => column.Name).ToList(); - var sorted = _statement is null || Results.ResultSetCount != 1 || sort.Column >= columns.Count - ? null - : SortedQuery(_statement, columns, sort.Column, sort.Direction == SortDirection.Ascending); - if (sorted is null) - { - // The close waits for it, since it clears the sets the sort reads. - await _work.RunAsync(_ => SortHeldRowsAsync(sort)).ConfigureAwait(true); - return; - } + private async void OnCommit(object sender, RoutedEventArgs e) => await _model.CommitAsync().ConfigureAwait(true); - _sort = sort; - await RunSqlAsync(sorted).ConfigureAwait(true); - } - - private async Task SortHeldRowsAsync(GridSort sort) - { - _sorting = true; - try - { - if (await Results.SortHeldRowsAsync(sort).ConfigureAwait(true)) - { - _sort = sort; - StatusText.Text = Strings.Format("StatusSortedHeld", Results.ShownRows); - } - else - { - Results.Sort = _sort; - } - } - catch (TableProException exception) - { - Results.Sort = _sort; - Results.ShowError(Strings.Error(exception.Error)); - } - finally - { - _sorting = false; - } - } - - private string? SortedQuery(string sql, IReadOnlyList columns, int column, bool ascending) - { - try - { - return _session.SortedQuery(sql, columns, column, ascending); - } - catch (TableProException) - { - return null; - } - } + private async void OnRollBack(object sender, RoutedEventArgs e) => await _model.RollBackAsync().ConfigureAwait(true); private void OnRun(object sender, RoutedEventArgs e) => Run(); diff --git a/windows/src/TablePro.App/Views/ResultsPane.xaml.cs b/windows/src/TablePro.App/Views/ResultsPane.xaml.cs index 8a98a6e8ed..2a16024cda 100644 --- a/windows/src/TablePro.App/Views/ResultsPane.xaml.cs +++ b/windows/src/TablePro.App/Views/ResultsPane.xaml.cs @@ -9,12 +9,13 @@ namespace TablePro.App.Views; // A sort of the rows held shows a sorted copy, so the run's own sets keep arrival order for the next sort. -public sealed partial class ResultsPane : UserControl +public sealed partial class ResultsPane : UserControl, IResultsView { private readonly RunMessages _messages = new(Strings.Get("MessagesCutShort")); private List _held = []; private HeldSet? _picked; private ResultSet? _sorted; + private ResultSet? _shown; private long? _milliseconds; private bool _picking; private ResultsView _view; @@ -39,6 +40,8 @@ public ResultsPane() // The grid shows another set of the run, unsorted. public event EventHandler? ResultPicked; + public event EventHandler? ShownSetChanged; + public DataGridView GridView => ResultGrid; public TextBox MessagesBox => MessagesText; @@ -54,6 +57,9 @@ public ResultsPane() // A table tab words its own page of rows from the count, the milliseconds and whether the limit cut it. internal Func? RowsStatus { get; set; } + // A table tab lays its edits over each set, so the grid gets them without being given its data again. + internal bool ShowsEdits { get; set; } + public TransactionState Transaction { get; private set; } = TransactionState.Idle; public GridSort Sort @@ -62,10 +68,11 @@ public GridSort Sort set => ResultGrid.Sort = value; } - public long ShownRows => (_sorted ?? _picked?.Set)?.RowCount ?? 0; + public ResultSet? ShownSet => _sorted ?? _picked?.Set; - // False when no set is shown, or a run or a pick replaced it while the rows were being sorted. - internal async Task SortHeldRowsAsync(GridSort sort) + public long ShownRowCount => ShownSet?.RowCount ?? 0; + + public async Task SortHeldRowsAsync(GridSort sort) { var picked = _picked; if (picked is null || sort.Column < 0 || sort.Column >= Columns.Count) @@ -83,12 +90,15 @@ internal async Task SortHeldRowsAsync(GridSort sort) var previous = _sorted; _sorted = sorted; - ResultGrid.SetData(new ResultSetData(sorted, Columns)); + ResultGrid.SetData(GridData(sorted, Columns)); ResultGrid.Sort = sort; previous?.Dispose(); + ShownMayHaveChanged(); return true; } + public void ShowError(CoreError failure) => ShowError(Strings.Error(failure)); + public void ShowError(string message) { ErrorBar.Message = message; @@ -108,11 +118,7 @@ public void Clear() } // The sets shown stay until the new run's first set has rows or ends, so a sort or a refresh never blanks the grid. - internal async Task ShowRunAsync( - QueryRun run, - GridSort sort, - int visibleColumns = int.MaxValue, - CancellationToken cancellationToken = default) + public async Task ShowRunAsync(ITabRun run, GridSort sort, int visibleColumns, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(run); ErrorBar.IsOpen = false; @@ -229,13 +235,14 @@ private void ShowRun(List incoming, GridSort sort) _picked = first; _sorted = null; Columns = first.Result.Columns; - ResultGrid.SetData(new ResultSetData(first.Set, first.Result.Columns)); + ResultGrid.SetData(GridData(first.Set, first.Result.Columns)); ResultGrid.Sort = sort; ResultGrid.Visibility = Visibility.Visible; Placeholder.Visibility = Visibility.Collapsed; // The grid disposed the old set's cursor in SetData. DisposeSets(held, sorted); ListAllInPicker(); + ShownMayHaveChanged(); } private void Pick(HeldSet held) @@ -244,9 +251,10 @@ private void Pick(HeldSet held) _picked = held; _sorted = null; Columns = held.Result.Columns; - ResultGrid.SetData(new ResultSetData(held.Set, held.Result.Columns)); + ResultGrid.SetData(GridData(held.Set, held.Result.Columns)); ResultGrid.Sort = GridSort.None; sorted?.Dispose(); + ShownMayHaveChanged(); if (_milliseconds is { } milliseconds) { Status(RowsText(held.Result, milliseconds)); @@ -267,6 +275,28 @@ private void Release() Columns = []; DisposeSets(held, sorted); ListAllInPicker(); + ShownMayHaveChanged(); + } + + // Said once per new set and after the grid shows it, so a table tab's edits follow the rows they were made on. + private void ShownMayHaveChanged() + { + if (!ReferenceEquals(_shown, ShownSet)) + { + _shown = ShownSet; + ShownSetChanged?.Invoke(this, EventArgs.Empty); + } + } + + private IGridData GridData(ResultSet set, IReadOnlyList columns) + { + var data = new ResultSetData(set, columns); + if (ShowsEdits) + { + return new EditedGridData(data, GridEdits.None); + } + + return data; } private static void DisposeSets(List held, ResultSet? sorted) diff --git a/windows/src/TablePro.App/Views/RowEditDialogs.cs b/windows/src/TablePro.App/Views/RowEditDialogs.cs new file mode 100644 index 0000000000..b91dd90c32 --- /dev/null +++ b/windows/src/TablePro.App/Views/RowEditDialogs.cs @@ -0,0 +1,184 @@ +using System.Runtime.InteropServices; +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Automation; +using Microsoft.UI.Xaml.Controls; +using Microsoft.UI.Xaml.Media; +using TablePro.App.Model; +using TablePro.App.Services; +using TablePro.Interop; +using Windows.ApplicationModel.DataTransfer; + +namespace TablePro.App.Views; + +// A table tab's questions about its pending changes, as macOS words them; Enter cancels all but the close question. +internal static class RowEditDialogs +{ + public static async Task ConfirmDiscardAsync(FrameworkElement owner) => + await ShowAsync(owner, new ContentDialog + { + Title = Strings.Get("DiscardChangesTitle"), + Content = Strings.Get("DiscardChangesMessage"), + PrimaryButtonText = Strings.Get("DiscardChangesAction"), + CloseButtonText = Strings.Get("Cancel"), + DefaultButton = ContentDialogButton.Close, + }) == ContentDialogResult.Primary; + + public static async Task ConfirmReloadAsync(FrameworkElement owner, string message) => + await ShowAsync(owner, new ContentDialog + { + Title = Strings.Get("ReloadDiscardTitle"), + Content = message, + PrimaryButtonText = Strings.Get("ReloadDiscardAction"), + CloseButtonText = Strings.Get("Cancel"), + DefaultButton = ContentDialogButton.Close, + }) == ContentDialogResult.Primary; + + // Enter saves, as macOS asks; with no Save to offer, Enter cancels. + public static async Task AskSaveBeforeCloseAsync(FrameworkElement owner, string tab, bool offerSave) + { + var result = await ShowAsync(owner, new ContentDialog + { + Title = Strings.Format("SaveBeforeCloseTab", tab), + Content = Strings.Get("SaveBeforeCloseMessage"), + PrimaryButtonText = offerSave ? Strings.Get("SaveBeforeCloseSave") : string.Empty, + SecondaryButtonText = Strings.Get("SaveBeforeCloseDontSave"), + CloseButtonText = Strings.Get("Cancel"), + DefaultButton = offerSave ? ContentDialogButton.Primary : ContentDialogButton.Close, + }); + return result switch + { + ContentDialogResult.Primary => SaveBeforeClose.Save, + ContentDialogResult.Secondary => SaveBeforeClose.DontSave, + _ => SaveBeforeClose.Cancel, + }; + } + + // Asked before every save that deletes rows, at every Safe Mode level, as macOS asks. + public static async Task ConfirmDeleteAsync(FrameworkElement owner, string table, int rows) => + await ShowAsync(owner, new ContentDialog + { + Title = rows == 1 ? Strings.Format("DeleteRowsTitleOne", table) : Strings.Format("DeleteRowsTitleMany", rows, table), + Content = Strings.Get("DeleteRowsMessage"), + PrimaryButtonText = Strings.Get("DeleteRowsAction"), + CloseButtonText = Strings.Get("Cancel"), + DefaultButton = ContentDialogButton.Close, + }) == ContentDialogResult.Primary; + + // Safe Mode's question before a save: every statement in full with the values it binds. + public static async Task ConfirmSaveAsync(FrameworkElement owner, string connection, IReadOnlyList statements) + { + var content = new StackPanel { Spacing = 12 }; + content.Children.Add(new TextBlock + { + Text = Strings.Format("SaveReviewRunsOn", connection), + TextWrapping = TextWrapping.Wrap, + }); + content.Children.Add(StatementsBlock(statements, "SaveReviewStatements")); + content.Children.Add(CopyAllButton(statements)); + return await ShowAsync(owner, new ContentDialog + { + Title = Title("SaveReviewTitle", statements.Count), + Content = new ScrollViewer { Content = content, MaxHeight = 480 }, + PrimaryButtonText = Strings.Get("SaveReviewAction"), + CloseButtonText = Strings.Get("Cancel"), + DefaultButton = ContentDialogButton.Close, + }) == ContentDialogResult.Primary; + } + + // `error` takes the place of the statements when the edits cannot be planned. + public static async Task ShowPreviewAsync(FrameworkElement owner, IReadOnlyList statements, string? error) + { + var content = new StackPanel { Spacing = 12 }; + if (error is not null) + { + content.Children.Add(new TextBlock { Text = error, TextWrapping = TextWrapping.Wrap, IsTextSelectionEnabled = true }); + } + else if (statements.Count == 0) + { + content.Children.Add(new TextBlock { Text = Strings.Get("PreviewSqlEmpty") }); + } + else + { + content.Children.Add(StatementsBlock(statements, "PreviewSqlStatements")); + content.Children.Add(CopyAllButton(statements)); + } + + await ShowAsync(owner, new ContentDialog + { + Title = error is null && statements.Count > 0 ? Title("PreviewSqlTitle", statements.Count) : Strings.Get("PreviewSqlTitle"), + Content = new ScrollViewer { Content = content, MaxHeight = 480 }, + CloseButtonText = Strings.Get("PreviewSqlDone"), + DefaultButton = ContentDialogButton.Close, + }); + } + + public static async Task ShowSaveFailedAsync(FrameworkElement owner, string message, bool incomplete) + { + var content = new StackPanel { Spacing = 12 }; + content.Children.Add(new TextBlock { Text = message, TextWrapping = TextWrapping.Wrap, IsTextSelectionEnabled = true }); + content.Children.Add(new TextBlock + { + Text = Strings.Get(incomplete ? "SaveUnknownMessage" : "SaveFailedPending"), + TextWrapping = TextWrapping.Wrap, + }); + await ShowAsync(owner, new ContentDialog + { + Title = Strings.Get(incomplete ? "SaveIncompleteTitle" : "SaveFailedTitle"), + Content = content, + CloseButtonText = Strings.Get("PreviewSqlDone"), + DefaultButton = ContentDialogButton.Close, + }); + } + + // A save binds its values, so each statement is followed by the values it sends, as the Linux app shows them. + public static string Text(IReadOnlyList statements) + { + ArgumentNullException.ThrowIfNull(statements); + return string.Join("\n\n", statements.Select(statement => statement.Values.Count == 0 + ? statement.Sql + ";" + : $"{statement.Sql};\n-- {Strings.Format("PreviewSqlValues", string.Join(", ", statement.Values))}")); + } + + private static string Title(string name, int statements) => + $"{Strings.Get(name)} ({(statements == 1 ? Strings.Get("StatementCountOne") : Strings.Format("StatementCountMany", statements))})"; + + private static TextBlock StatementsBlock(IReadOnlyList statements, string automationId) + { + var block = new TextBlock + { + Text = Text(statements), + FontFamily = new FontFamily("Cascadia Mono, Consolas, Courier New"), + TextWrapping = TextWrapping.Wrap, + IsTextSelectionEnabled = true, + }; + AutomationProperties.SetAutomationId(block, automationId); + return block; + } + + private static Button CopyAllButton(IReadOnlyList statements) + { + var button = new Button { Content = Strings.Get("CopyAllButton") }; + AutomationProperties.SetAutomationId(button, "CopyAllStatements"); + button.Click += (_, _) => + { + var package = new DataPackage(); + package.SetText(Text(statements)); + try + { + Clipboard.SetContent(package); + Clipboard.Flush(); + } + catch (COMException) + { + // Another program holds the clipboard open; pressing the button again copies once it lets go. + } + }; + return button; + } + + private static Task ShowAsync(FrameworkElement owner, ContentDialog dialog) + { + dialog.RequestedTheme = owner.ActualTheme; + return WindowDialogs.ShowAsync(dialog, owner); + } +} diff --git a/windows/src/TablePro.App/Views/TableTabView.xaml b/windows/src/TablePro.App/Views/TableTabView.xaml index 6d03102606..1bc19b5ea1 100644 --- a/windows/src/TablePro.App/Views/TableTabView.xaml +++ b/windows/src/TablePro.App/Views/TableTabView.xaml @@ -46,6 +46,14 @@ + + + + + + + + diff --git a/windows/src/TablePro.App/Views/TableTabView.xaml.cs b/windows/src/TablePro.App/Views/TableTabView.xaml.cs index b2f38e391c..8cc8016924 100644 --- a/windows/src/TablePro.App/Views/TableTabView.xaml.cs +++ b/windows/src/TablePro.App/Views/TableTabView.xaml.cs @@ -1,6 +1,7 @@ using Microsoft.UI.Xaml; using Microsoft.UI.Xaml.Controls; using Microsoft.UI.Xaml.Controls.Primitives; +using Microsoft.UI.Xaml.Input; using TablePro.App.Model; using TablePro.App.Services; using TablePro.DataGrid; @@ -10,60 +11,68 @@ namespace TablePro.App.Views; -// A sort is an ORDER BY in the page's statement, so it orders the whole table, not the rows already read. -public sealed partial class TableTabView : UserControl, ITabContent +// The pager and the edits over a table's rows; the page, its count, every reload and every save are TableTab's. +public sealed partial class TableTabView : UserControl, ITabContent, ITableTabView { - private readonly Workbench _workbench; - private readonly SessionShare _share; - private readonly DatabaseSession _session; - private readonly string? _schema; - private readonly string _table; - private readonly TabWork _work = new(); - private QueryEditor? _editor; - private Task? _closing; - private QueryRun? _run; - private GridSort _sort = GridSort.None; - private GridSort _shownSort = GridSort.None; - private TablePage _page; - - // The size this tab was given, as macOS keeps one per table tab; without one, Settings decides. - private int? _chosenSize; + private readonly TableTab _model; private bool _messagesIsTarget; - private (long Milliseconds, bool Truncated)? _finished; - private CancellationTokenSource? _counting; - internal TableTabView(Workbench workbench, SessionShare share, string? schema, string table, SessionTab? restore = null) + internal TableTabView( + Workbench workbench, + SessionShare share, + string? schema, + string table, + SessionTab? restore = null) { - _workbench = workbench; - _share = share.Hold(); - _session = share.Session; - _schema = schema; - _table = table; - _chosenSize = restore?.PageSize is { } size ? Math.Clamp(size, 1, TablePage.LargestSize) : null; - var first = TablePage.First(PageSize); - _page = first.At((restore?.Offset ?? 0) / first.Size * first.Size); InitializeComponent(); + Results.ShowsEdits = true; + var grid = Results.GridView; + grid.DefaultText = Strings.Get("GridDefaultText"); + grid.EditedStatus = Strings.Get("GridEditedStatus"); + grid.NewRowStatus = Strings.Get("GridNewRowStatus"); + grid.DeletedStatus = Strings.Get("GridDeletedStatus"); + _model = new TableTab( + new CoreTabSession(share), + this, + Results, + new TableName(schema, table), + () => workbench.Settings, + restore); + _model.StateChanged += (_, _) => StateChanged?.Invoke(this, EventArgs.Empty); Results.StatusChanged += (_, status) => StatusText.Text = status; Results.RowsStatus = (rows, milliseconds, truncated) => { - _finished = (milliseconds, truncated); - _page = _page with { Rows = rows }; + _model.PageRead(rows, milliseconds, truncated); return RowsStatus()!; }; - Results.SortRequested += OnSortRequested; - Results.GridView.GotFocus += (_, _) => _messagesIsTarget = false; + Results.SortRequested += async (_, sort) => await _model.SortAsync(sort).ConfigureAwait(true); + grid.GotFocus += (_, _) => + { + _messagesIsTarget = false; + EditStateMayHaveChanged(); + }; + // The editor takes focus as it opens and gives it back as it closes, so Save and the closes follow it. + grid.LostFocus += (_, _) => EditStateMayHaveChanged(); Results.MessagesBox.GotFocus += (_, _) => _messagesIsTarget = true; + grid.CellEditStarting += OnCellEditStarting; + grid.CellEditCommitting += OnCellEditCommitting; + grid.DeleteRequested += (_, _) => DeleteRows(); + grid.ContextRequested += OnGridContextRequested; UpdatePager(); + UpdateEditing(); } public event EventHandler? StateChanged; - public string Title => _table; + public string Title => _model.Title; + + public TabKind Kind => _model.Kind; - public bool IsRunning { get; private set; } + public bool IsRunning => _model.IsRunning; - // A table tab only reads. - public TransactionState Transaction => TransactionState.Idle; + public TransactionState Transaction => _model.Transaction; + + public bool HasUnsavedChanges => _model.HasUnsavedChanges; public SqlEditor? Editor => null; @@ -74,178 +83,202 @@ internal TableTabView(Workbench workbench, SessionShare share, string? schema, s public TextBox? MessagesTarget => _messagesIsTarget && Results.MessagesBox.Visibility == Visibility.Visible ? Results.MessagesBox : null; - private int PageSize => _chosenSize ?? _workbench.Settings.PageSize; + public bool CanSave => _model.CanSave; + + public bool CanDiscard => _model.CanDiscard; + + public bool CanPreview => _model.CanPreview; + + public bool CanAddRow => _model.CanEdit; + + // Duplicate and Delete act on the rows the selection touches. + public bool CanChangeRows => _model.CanEdit && Results.GridView.RowCount > 0; + + // The workspace that holds the tab, always in the tree while its window shows it, so a close can ask from it. + internal FrameworkElement? DialogOwner { get; set; } + + bool ITableTabView.HasOpenEdit => Results.GridView.IsEditing; + + private FrameworkElement Owner => DialogOwner ?? this; - public bool Shows(string? schema, string table) => - string.Equals(_table, table, StringComparison.Ordinal) && string.Equals(_schema, schema, StringComparison.Ordinal); + public bool Shows(string? schema, string table) => _model.Shows(schema, table); - public async void Run() => await LoadAsync(_page.Offset).ConfigureAwait(true); + public async void Run() => await _model.RunAsync().ConfigureAwait(true); - public void Stop() => _run?.Cancel(); + public void Stop() => _model.Stop(); public void FocusContent() => Results.GridView.Focus(FocusState.Programmatic); - public SessionTab Snapshot() => new() - { - Kind = TabKind.Table, - Title = Title, - Schema = _schema, - Table = _table, - PageSize = _chosenSize, - Offset = _page.Offset > 0 ? _page.Offset : null, - }; + public SessionTab Snapshot() => _model.Snapshot(); + + public Task ConfirmCloseAsync(bool offerSave) => _model.ConfirmCloseAsync(offerSave); + + public Task CloseAsync() => _model.CloseAsync(); + + public Task SaveAsync() => _model.SaveAsync(); - // Once only, however often it is asked for: the tab lets go of its session exactly once. - public Task CloseAsync() => _closing ??= CloseOnceAsync(); + public Task DiscardAsync() => _model.DiscardAsync(); - // The page in flight and its count stop and end before the run, the editor and the session they use are let go. - private async Task CloseOnceAsync() + public Task PreviewAsync() => _model.PreviewAsync(); + + // The open edit is kept first, and the new row's editor opens on the first column the server does not fill. + public void AddRow() { - _run?.Cancel(); - await _work.CloseAsync().ConfigureAwait(true); - _run?.Dispose(); - _run = null; - Results.Clear(); - if (_editor is not null) + var grid = Results.GridView; + if (!grid.CommitEdit()) { - await _editor.DisposeAsync().ConfigureAwait(true); - _editor = null; + return; } - await _share.ReleaseAsync().ConfigureAwait(true); - } - - private async Task LoadAsync(long offset) - { - if (!IsRunning) + if (_model.AddRow(out var row) is { } refusal) { - await _work.RunAsync(token => LoadPageAsync(offset, token)).ConfigureAwait(true); + ShowRefusal(refusal); + return; } + + grid.FocusCell(row, _model.FirstColumnToFill); + grid.BeginEdit(); } - private async Task LoadPageAsync(long offset, CancellationToken cancellationToken) + public void DuplicateRows() { - _finished = null; - SetRunning(true); - try + var grid = Results.GridView; + if (!grid.CommitEdit()) { - if (_editor is { IsLost: true } lost) - { - _editor = null; - await lost.DisposeAsync().ConfigureAwait(true); - } - - // An editor that opens as the tab closes stays in _editor, which the close disposes. - _editor ??= await _session.OpenEditorAsync(cancellationToken).ConfigureAwait(true); - var page = _page.At(offset); - // A default changed in Settings applies from the page holding the first row shown. - if (_chosenSize is null && page.Size != PageSize) - { - page = page.Resized(PageSize); - } - - var sort = _sort.Direction == SortDirection.None - ? null - : new ColumnSort(_sort.Column, _sort.Direction == SortDirection.Ascending); - var query = await _session.GetTableQueryAsync( - new TableName(_schema, _table), sort, page.Size, page.Offset, cancellationToken) - .ConfigureAwait(true); - if (_work.IsClosed) - { - return; - } - - _run?.Dispose(); - _page = page with { CanSeek = query.CanSeek }; - // The statement holds the page; a run limit one past it keeps a full page from reading as cut short. - _run = _editor.Run(query.Sql, new QueryOptions(page.Size + 1), cancellationToken); - await Results.ShowRunAsync(_run, _sort, query.VisibleColumns, cancellationToken).ConfigureAwait(true); - if (_work.IsClosed) - { - return; - } - - _shownSort = _sort; - _page = _page with { Rows = Results.RowCount }; - CountIfNeeded(); + return; } - catch (TableProException exception) + + if (_model.DuplicateRows(SelectedRows(), out var last) is { } refusal) { - if (!_work.IsClosed) - { - // An engine that reads a table only in its own order refuses the sort; the rows shown keep theirs. - _sort = _shownSort; - Results.Sort = _shownSort; - Results.ShowError(Strings.Error(exception.Error)); - } + ShowRefusal(refusal); + return; } - finally + + if (last >= 0) { - SetRunning(false); + var column = Math.Max(0, grid.FocusedColumn); + grid.FocusCell(last, column); + grid.ScrollIntoView(last, column); } } - private async void CountIfNeeded() => await _work.RunAsync(CountAsync).ConfigureAwait(true); - - // A first page that is not full holds the whole table; otherwise the server counts it, in the background. - private async Task CountAsync(CancellationToken closing) + public void DeleteRows() { - if (_page.Total is not null || !_page.CanSeek) + if (Results.GridView.CommitEdit()) { - UpdatePager(); - return; + ShowRefusal(_model.DeleteRows(SelectedRows())); } + } - if (_page.Offset == 0 && _page.Rows < _page.Size) + void ITableTabView.ShowRunning(bool running) + { + RefreshButton.IsEnabled = !running && !_model.IsSaving; + StopButton.IsEnabled = running; + UpdatePager(); + UpdateEditing(); + } + + void ITableTabView.UpdatePager() => UpdatePager(); + + // Asked first, as macOS asks: a large table on one page takes a lot of memory. + async Task ITableTabView.ConfirmAllRowsAsync(long total) + { + if (XamlRoot is null) { - _page = _page with { Total = _page.Rows }; - UpdatePager(); - return; + return false; } - UpdatePager(); - _counting?.Cancel(); - using var counting = CancellationTokenSource.CreateLinkedTokenSource(closing); - _counting = counting; - try + var dialog = new ContentDialog { - var total = await _session.CountRowsAsync(new TableName(_schema, _table), counting.Token).ConfigureAwait(true); - _page = _page with { Total = total }; - UpdatePager(); - } - catch (Exception exception) when (exception is TableProException or OperationCanceledException) + XamlRoot = XamlRoot, + RequestedTheme = ActualTheme, + Title = Strings.Get("AllRowsTitle"), + Content = Strings.Format("AllRowsMessage", total), + PrimaryButtonText = Strings.Get("AllRowsButton"), + CloseButtonText = Strings.Get("Cancel"), + DefaultButton = ContentDialogButton.Close, + }; + return await WindowDialogs.ShowAsync(dialog, this).ConfigureAwait(true) == ContentDialogResult.Primary; + } + + void ITableTabView.ShowEdits() => UpdateEditing(); + + void ITableTabView.ShowSaving(bool saving) + { + RefreshButton.IsEnabled = !saving && !_model.IsRunning; + if (saving) { - // Without a count the pager still pages forward while pages come back full. + StatusText.Text = Strings.Get("StatusSaving"); } - finally + else if (RowsStatus() is { } status) { - if (ReferenceEquals(_counting, counting)) - { - _counting = null; - } + StatusText.Text = status; } + + UpdatePager(); } + void ITableTabView.ShowEditRefusal(EditRefusal refusal) => ShowRefusal(refusal); + + void ITableTabView.ShowSaveCancelled() => StatusText.Text = Strings.Get("SaveCancelled"); + + bool ITableTabView.CommitOpenEdit() => Results.GridView.CommitEdit(); + + void ITableTabView.FocusRow(int row) + { + var grid = Results.GridView; + var column = Math.Max(0, grid.FocusedColumn); + grid.FocusCell(row, column); + grid.ScrollIntoView(row, column); + } + + Task ITableTabView.ConfirmDiscardForReloadAsync(ReloadReason reason) => + RowEditDialogs.ConfirmReloadAsync(Owner, Strings.Get(reason switch + { + ReloadReason.Refresh => "ReloadDiscardRefresh", + ReloadReason.Sort => "ReloadDiscardSort", + _ => "ReloadDiscardPage", + })); + + Task ITableTabView.ConfirmDiscardAsync() => RowEditDialogs.ConfirmDiscardAsync(Owner); + + Task ITableTabView.AskSaveBeforeCloseAsync(string tab, bool offerSave) => + RowEditDialogs.AskSaveBeforeCloseAsync(Owner, tab, offerSave); + + Task ITableTabView.ConfirmDeleteAsync(string table, int rows) => + RowEditDialogs.ConfirmDeleteAsync(Owner, table, rows); + + Task ITableTabView.ConfirmSaveAsync(string connection, IReadOnlyList statements) => + RowEditDialogs.ConfirmSaveAsync(Owner, connection, statements); + + Task ITableTabView.ShowPreviewAsync(IReadOnlyList statements, CoreError? failure) => + RowEditDialogs.ShowPreviewAsync(Owner, statements, failure is null ? null : Strings.Error(failure)); + + Task ITableTabView.ShowSaveFailedAsync(CoreError failure, bool incomplete) => + RowEditDialogs.ShowSaveFailedAsync(Owner, Strings.Error(failure), incomplete); + private void UpdatePager() { - var shown = _page.IsPaged ? Visibility.Visible : Visibility.Collapsed; + var page = _model.Page; + var busy = _model.IsRunning || _model.IsSaving; + var shown = page.IsPaged ? Visibility.Visible : Visibility.Collapsed; foreach (var element in new UIElement[] { FirstPageButton, PreviousPageButton, GoToPageButton, NextPageButton, LastPageButton }) { element.Visibility = shown; } - FirstPageButton.IsEnabled = !IsRunning && _page.HasPrevious; - PreviousPageButton.IsEnabled = !IsRunning && _page.HasPrevious; - NextPageButton.IsEnabled = !IsRunning && _page.HasNext; - LastPageButton.IsEnabled = !IsRunning && _page.HasLast; - PageSizeButton.Label = Strings.Format("PageSizeLabel", _page.Size); - PageSizeButton.IsEnabled = !IsRunning; + FirstPageButton.IsEnabled = !busy && page.HasPrevious; + PreviousPageButton.IsEnabled = !busy && page.HasPrevious; + NextPageButton.IsEnabled = !busy && page.HasNext; + LastPageButton.IsEnabled = !busy && page.HasLast; + PageSizeButton.Label = Strings.Format("PageSizeLabel", page.Size); + PageSizeButton.IsEnabled = !busy; // Going to a page needs the count, as on macOS; until it lands the button names the page alone. - GoToPageButton.Label = _page.Count is { } count - ? Strings.Format("PageOf", _page.Number, count) - : Strings.Format("PageNumber", _page.Number); - GoToPageButton.IsEnabled = !IsRunning && _page.Count is > 1; - if (RowsStatus() is { } status) + GoToPageButton.Label = page.Count is { } count + ? Strings.Format("PageOf", page.Number, count) + : Strings.Format("PageNumber", page.Number); + GoToPageButton.IsEnabled = !busy && page.Count is > 1; + if (!_model.IsSaving && RowsStatus() is { } status) { StatusText.Text = status; } @@ -254,50 +287,163 @@ private void UpdatePager() // Null until a run has read the page; a count that arrives later adds the total, as on macOS. private string? RowsStatus() { - if (_finished is not { } run) + if (_model.Finished is not { } run) { return null; } - if (!_page.IsPaged) + var page = _model.Page; + if (!page.IsPaged) { - return Strings.Format(run.Truncated ? "StatusRowsLimited" : "StatusRows", _page.Rows, run.Milliseconds); + return Strings.Format(run.Truncated ? "StatusRowsLimited" : "StatusRows", page.Rows, run.Milliseconds); } - return _page.Total is { } total - ? Strings.Format("StatusPageOf", _page.FirstRow, _page.LastRow, total, run.Milliseconds) - : Strings.Format("StatusPage", _page.FirstRow, _page.LastRow, run.Milliseconds); + return page.Total is { } total + ? Strings.Format("StatusPageOf", page.FirstRow, page.LastRow, total, run.Milliseconds) + : Strings.Format("StatusPage", page.FirstRow, page.LastRow, run.Milliseconds); } - private void SetRunning(bool running) + // An editor opening or closing counts as a change for Save and the menus. + private void EditStateMayHaveChanged() { - IsRunning = running; - RefreshButton.IsEnabled = !running; - StopButton.IsEnabled = running; - UpdatePager(); + UpdateEditing(); StateChanged?.Invoke(this, EventArgs.Empty); } - private void Resize(TablePage page, int chosen) + // The grid swaps its edits only when they moved, since EditsChanged reads every cell again. + private void UpdateEditing() { - if (IsRunning) + var grid = Results.GridView; + if (grid.Data is EditedGridData edited) { + var edits = _model.Edits?.Snapshot() ?? GridEdits.None; + if (!ReferenceEquals(edited.Edits, edits)) + { + edited.Edits = edits; + grid.EditsChanged(); + } + } + + grid.IsEditable = _model.AcceptsEdits; + AddRowButton.IsEnabled = CanAddRow; + DuplicateRowButton.IsEnabled = CanChangeRows; + DeleteRowsButton.IsEnabled = CanChangeRows; + SaveChangesButton.IsEnabled = CanSave; + DiscardChangesButton.IsEnabled = CanDiscard; + PreviewSqlButton.IsEnabled = CanPreview; + } + + private void OnCellEditStarting(object? sender, GridEditStartingEventArgs e) + { + if (_model.StartEdit(e.Row, e.Column, out var text) is { } refusal) + { + e.Cancel = true; + ShowRefusal(refusal); return; } - _chosenSize = chosen; - if (page.Size != _page.Size || page.Offset != _page.Offset) + e.Text = text; + } + + // A refusal keeps the editor open with the reason on it; on a focus loss the editor closes, so the status says it too. + private void OnCellEditCommitting(object? sender, GridEditCommittingEventArgs e) + { + if (_model.CommitEdit(e.Row, e.Column, e.Text) is { } refusal) + { + var text = RefusalText(refusal) ?? Strings.Get("EditCellReadOnly"); + e.Error = text; + StatusText.Text = text; + } + } + + // The status is a polite live region, so a refusal is read out where the user is. + private void ShowRefusal(EditRefusal? refusal) + { + if (refusal is not null && RefusalText(refusal) is { } text) + { + StatusText.Text = text; + } + } + + private string? RefusalText(EditRefusal refusal) => refusal switch + { + EditRefusal.TableLocked { Lock: EditLock.ReadOnlyConnection } => Strings.Get("EditLockReadOnly"), + EditRefusal.TableLocked { Lock: EditLock.NoPrimaryKey } => Strings.Format("EditLockNoPrimaryKey", _model.Title), + EditRefusal.TableLocked { Lock: EditLock.KeyUnreadable } => Strings.Format("EditLockKeyUnreadable", _model.Title), + EditRefusal.TableLocked => Strings.Get("EditLockColumnsChanged"), + EditRefusal.CellLocked => Strings.Get("EditCellReadOnly"), + EditRefusal.SaveBlocked => Strings.Get("SaveUnknownBlocked"), + EditRefusal.Invalid invalid => Strings.Error(invalid.Failure), + _ => null, + }; + + private List SelectedRows() + { + var range = Results.GridView.SelectionRange; + return range.IsEmpty ? [] : [.. Enumerable.Range(range.FirstRow, range.RowCount)]; + } + + // Built when asked for, since a menu keeps the window it first opened in and a tab can move to another. + private void OnGridContextRequested(UIElement sender, ContextRequestedEventArgs args) + { + var grid = Results.GridView; + // The editor's TextBox shows its own menu; a right-click on another cell keeps the edit first. + if (grid.IsEditing && (grid.IsInEditor(args.OriginalSource) || !grid.CommitEdit())) + { + return; + } + + args.Handled = true; + var (row, column) = (grid.FocusedRow, grid.FocusedColumn); + var menu = new MenuFlyout(); + // A row marked for delete offers only to keep it, as macOS does. + if (grid.RowCount > 0 && _model.IsDeleted(row)) + { + menu.Items.Add(MenuItem("GridMenuUndoDelete", _model.CanEdit, () => ShowRefusal(_model.RestoreRows(SelectedRows())))); + } + else + { + var setValue = new MenuFlyoutSubItem { Text = Strings.Get("GridMenuSetValue"), IsEnabled = _model.CanEdit }; + setValue.Items.Add(ValueItem("GridMenuEmpty", row, column, CellValueKind.Empty)); + setValue.Items.Add(ValueItem("GridMenuNull", row, column, CellValueKind.Null)); + setValue.Items.Add(ValueItem("GridMenuDefault", row, column, CellValueKind.Default)); + menu.Items.Add(setValue); + menu.Items.Add(new MenuFlyoutSeparator()); + menu.Items.Add(MenuItem("GridMenuAddRow", CanAddRow, AddRow)); + menu.Items.Add(MenuItem("GridMenuDuplicate", CanChangeRows, DuplicateRows)); + menu.Items.Add(MenuItem("GridMenuDelete", CanChangeRows, DeleteRows)); + } + + 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); + if (args.TryGetPosition(grid, out var point)) + { + menu.ShowAt(grid, new FlyoutShowOptions { Position = point }); + } + else { - _page = page; - Run(); + menu.ShowAt(grid); } } + private MenuFlyoutItem ValueItem(string text, int row, int column, CellValueKind kind) => + MenuItem(text, _model.CanSetValue(row, column, kind), () => ShowRefusal(_model.SetValue(row, column, kind))); + + private static MenuFlyoutItem MenuItem(string text, bool enabled, Action invoke) + { + var item = new MenuFlyoutItem { Text = Strings.Get(text), IsEnabled = enabled }; + item.Click += (_, _) => invoke(); + return item; + } + // A command in the bar's overflow has no place of its own on screen, so its flyout opens at the bar. private FrameworkElement Anchor(AppBarButton button) => button.IsInOverflow ? Commands : button; private void OnPageSize(object sender, RoutedEventArgs e) { + var page = _model.Page; var menu = new MenuFlyout { Placement = FlyoutPlacementMode.BottomEdgeAlignedLeft }; foreach (var size in TablePage.Presets) { @@ -305,17 +451,17 @@ private void OnPageSize(object sender, RoutedEventArgs e) { Text = Strings.Format("PageSizeOption", size), GroupName = "PageSize", - IsChecked = size == _page.Size, + IsChecked = size == page.Size, }; - item.Click += (_, _) => Resize(_page.Resized(size), size); + item.Click += async (_, _) => await _model.ResizeAsync(size).ConfigureAwait(true); menu.Items.Add(item); } menu.Items.Add(new MenuFlyoutSeparator()); - if (_page.CanSeek) + if (page.CanSeek) { - var all = new MenuFlyoutItem { Text = Strings.Get("PageSizeAll"), IsEnabled = _page.Total is > 0 }; - all.Click += async (_, _) => await ShowAllRowsAsync().ConfigureAwait(true); + var all = new MenuFlyoutItem { Text = Strings.Get("PageSizeAll"), IsEnabled = page.Total is > 0 }; + all.Click += async (_, _) => await _model.ShowAllRowsAsync().ConfigureAwait(true); menu.Items.Add(all); } @@ -329,93 +475,57 @@ private void AskPageSize() { var request = new NumberRequest( Strings.Get("PageSizeCaption"), - _page.Size, + _model.Page.Size, TablePage.MaximumSize, Strings.Get("PageSizeApply"), "PageSizeBox", "PageSizeApplyButton"); - NumberFlyout.Create(request, size => Resize(_page.Resized((int)size), (int)size)) + NumberFlyout.Create(request, async size => await _model.ResizeAsync((int)size).ConfigureAwait(true)) .ShowAt(Anchor(PageSizeButton)); } - // Asked first, as macOS asks: a large table on one page takes a lot of memory. - private async Task ShowAllRowsAsync() - { - if (_page.Total is not { } total || XamlRoot is null) - { - return; - } - - var dialog = new ContentDialog - { - XamlRoot = XamlRoot, - RequestedTheme = ActualTheme, - Title = Strings.Get("AllRowsTitle"), - Content = Strings.Format("AllRowsMessage", total), - PrimaryButtonText = Strings.Get("AllRowsButton"), - CloseButtonText = Strings.Get("Cancel"), - DefaultButton = ContentDialogButton.Close, - }; - if (await WindowDialogs.ShowAsync(dialog, this) == ContentDialogResult.Primary) - { - var all = _page.AllRows(); - Resize(all, all.Size); - } - } - private void OnGoToPage(object sender, RoutedEventArgs e) { - if (_page.Count is not { } count) + var page = _model.Page; + if (page.Count is not { } count) { return; } var request = new NumberRequest( Strings.Get("GoToPageCaption"), - _page.Number, + page.Number, count, Strings.Get("GoToPageAction"), "GoToPageBox", "GoToPageGo"); - NumberFlyout.Create(request, number => - { - if (_page.Accepts(number) && number != _page.Number) - { - Run(_page.OffsetOf(number)); - } - }) + NumberFlyout.Create(request, async number => await _model.GoToPageAsync(number).ConfigureAwait(true)) .ShowAt(Anchor(GoToPageButton)); } - private async void Run(long offset) => await LoadAsync(offset).ConfigureAwait(true); + private async void OnFirstPage(object sender, RoutedEventArgs e) => await _model.FirstPageAsync().ConfigureAwait(true); - private void OnFirstPage(object sender, RoutedEventArgs e) => Run(0); + private async void OnPreviousPage(object sender, RoutedEventArgs e) => + await _model.PreviousPageAsync().ConfigureAwait(true); - private void OnPreviousPage(object sender, RoutedEventArgs e) => Run(_page.PreviousOffset); + private async void OnNextPage(object sender, RoutedEventArgs e) => await _model.NextPageAsync().ConfigureAwait(true); - private void OnNextPage(object sender, RoutedEventArgs e) => Run(_page.NextOffset); + private async void OnLastPage(object sender, RoutedEventArgs e) => await _model.LastPageAsync().ConfigureAwait(true); - private void OnLastPage(object sender, RoutedEventArgs e) => Run(_page.LastOffset); + private async void OnRefresh(object sender, RoutedEventArgs e) => await _model.RefreshAsync().ConfigureAwait(true); - private void OnSortRequested(object? sender, GridSort sort) - { - if (IsRunning) - { - Results.Sort = _sort; - return; - } + private void OnStop(object sender, RoutedEventArgs e) => Stop(); - _sort = sort; - _page = _page.At(0); - Run(); - } + private void OnAddRow(object sender, RoutedEventArgs e) => AddRow(); - // A refresh counts the table again. - private void OnRefresh(object sender, RoutedEventArgs e) - { - _page = _page with { Total = null }; - Run(); - } + private void OnDuplicateRow(object sender, RoutedEventArgs e) => DuplicateRows(); - private void OnStop(object sender, RoutedEventArgs e) => Stop(); + private void OnDeleteRows(object sender, RoutedEventArgs e) => DeleteRows(); + + private async void OnSaveChanges(object sender, RoutedEventArgs e) => await _model.SaveAsync().ConfigureAwait(true); + + private async void OnDiscardChanges(object sender, RoutedEventArgs e) => + await _model.DiscardAsync().ConfigureAwait(true); + + private async void OnPreviewSql(object sender, RoutedEventArgs e) => await _model.PreviewAsync().ConfigureAwait(true); } diff --git a/windows/src/TablePro.App/Views/WorkspaceView.xaml.cs b/windows/src/TablePro.App/Views/WorkspaceView.xaml.cs index 0d27b2b496..4f3a54b4fc 100644 --- a/windows/src/TablePro.App/Views/WorkspaceView.xaml.cs +++ b/windows/src/TablePro.App/Views/WorkspaceView.xaml.cs @@ -14,13 +14,13 @@ namespace TablePro.App.Views; -internal sealed record SecretAnswer(string Secret, bool Save); - -public sealed partial class WorkspaceView : UserControl +// The closing and reopening of tabs is WorkspaceTabs'; the tree, the bars and the strip's moves are drawn here. +public sealed partial class WorkspaceView : UserControl, IWorkspaceTabsView { private readonly Workbench _workbench; private readonly OpenConnection _connection; - private SessionShare? _share; + private readonly WorkspaceTabs _tabs; + private SessionShare? _share; private DatabaseSession? _session; private IReadOnlyList? _everyObject; private bool _singleSchema; @@ -29,11 +29,9 @@ public sealed partial class WorkspaceView : UserControl // Schemas a refresh reads again, the next time each one opens. private readonly HashSet _stale = []; - private readonly ClosedTabs _closed = new(); // What each query tab's text read at its document's version, since the session is written every few seconds. private readonly Dictionary _snapshots = []; - private readonly HashSet _closingTabs = []; private CancellationTokenSource? _watching; private Windows.Foundation.Point _stripOrigin; private WindowId _tearOutWindow; @@ -44,6 +42,8 @@ internal WorkspaceView(Workbench workbench, OpenConnection connection) { _workbench = workbench; _connection = connection; + _tabs = new WorkspaceTabs(this); + _tabs.Emptied += (_, _) => Emptied?.Invoke(this, EventArgs.Empty); InitializeComponent(); ObjectList.ContainerContentChanging += OnObjectContainerChanging; for (var number = 1; number <= 9; number++) @@ -90,7 +90,7 @@ internal WorkspaceView(Workbench workbench, OpenConnection connection) public bool ObjectsVisible => ObjectsPane.Visibility == Visibility.Visible; - public bool CanReopenTab => _session is not null && _closed.Count > 0; + public bool CanReopenTab => _session is not null && _tabs.ClosedCount > 0; internal ITabContent? ActiveTab => (Tabs.SelectedItem as TabViewItem)?.Content as ITabContent; @@ -154,7 +154,7 @@ public void ShowFailed(string message, string details) } // A workspace a tab is moved into starts with none, and reads its tree once the tab is there (Start). - internal void ShowConnected(SessionShare share, SessionConnection? restore, bool adopted = false) + internal void ShowConnected(SessionShare share, SessionConnection? restore, bool adopted = false) { _share = share; _session = share.Session; @@ -245,47 +245,21 @@ private SessionTab SnapshotOf(ITabContent content) return tab; } - internal bool HasUnconfirmedTransactions(ISet confirmed) => Tabs.TabItems.OfType() - .Any(item => item.Content is ITabContent content && WorkspaceNotices.Holds(content.Transaction) && !confirmed.Contains(content)); + // A held transaction or unsaved changes the close has not been answered about. + internal bool HasUnconfirmed(ISet confirmed) => _tabs.HasUnconfirmed(confirmed); - // A table tab loading a page is not work the user started, so only a query tab's run is asked about. - internal List RunningQueries() => [.. Tabs.TabItems.OfType() - .Select(item => item.Content) - .OfType() - .Where(view => view.IsRunning)]; + internal IReadOnlyList RunningQueries() => _tabs.RunningQueries(); - // The tabs of a window that closed, so Reopen closed tab brings them back here in their order. internal void KeepClosed(IReadOnlyList tabs) { - ArgumentNullException.ThrowIfNull(tabs); - for (var index = tabs.Count - 1; index >= 0; index--) - { - _closed.Push(tabs[index], int.MaxValue); - } - + _tabs.KeepClosed(tabs); CommandsChanged?.Invoke(this, EventArgs.Empty); } - internal async Task ConfirmCloseAsync(ISet confirmed) - { - foreach (var item in Tabs.TabItems.OfType().ToList()) - { - if (item.Content is ITabContent content && WorkspaceNotices.Holds(content.Transaction) && !confirmed.Contains(content)) - { - Tabs.SelectedItem = item; - if (!await ConfirmCloseHeldAsync(content).ConfigureAwait(true)) - { - return false; - } - - confirmed.Add(content); - } - } - - return true; - } + // Without Save when the connection is being made read only. + internal Task ConfirmCloseAsync(ISet confirmed, bool offerSave = true) => + _tabs.ConfirmCloseAsync(confirmed, offerSave); - // A reconnect keeps the closed tabs, which hold only their text or table, to reopen on the next session. public async Task CloseTabsAsync(bool keepClosed = false) { CancelRecovery(); @@ -299,16 +273,7 @@ public async Task CloseTabsAsync(bool keepClosed = false) HealthBar.IsOpen = false; ElsewhereBar.IsOpen = false; HideChangesOnConnect(); - if (!keepClosed) - { - _closed.Clear(); - } - - foreach (var content in Tabs.TabItems.OfType().Select(item => item.Content).OfType().ToList()) - { - await content.CloseAsync().ConfigureAwait(true); - } - + await _tabs.CloseAllAsync(keepClosed).ConfigureAwait(true); Tabs.TabItems.Clear(); _snapshots.Clear(); Objects.Clear(); @@ -379,7 +344,7 @@ public void ToggleObjects() public void ReopenClosedTab() { - if (_share is null || _closed.Pop() is not { } closed) + if (_share is null || _tabs.TakeClosed() is not { } closed) { return; } @@ -471,6 +436,12 @@ private void AddTab(ITabContent content, Symbol icon, int? index = null) internal void Take(TabViewItem item, int? index = null) { item.Tag = this; + // A tab that is not shown is out of the tree, so its questions are asked from here, as a held transaction's are. + if (item.Content is TableTabView table) + { + table.DialogOwner = this; + } + item.ContextRequested += OnTabContextRequested; if (item.Content is ITabContent content) { @@ -670,41 +641,19 @@ private void OnExternalTornOutTabsDropped(TabView sender, TabViewExternalTornOut } } - // Closing a tab ends its own connection, and its transaction with it, so a held one is asked about first. - // A second request while the first is closing the tab, or asking about its transaction, does nothing. - private async Task CloseTabAsync(TabViewItem item) - { - if (!_closingTabs.Add(item)) - { - return; - } + private Task CloseTabAsync(TabViewItem item) => _tabs.CloseAsync(item); - try - { - if (item.Content is ITabContent content) - { - if (WorkspaceNotices.Holds(content.Transaction) && !await ConfirmCloseHeldAsync(content).ConfigureAwait(true)) - { - return; - } + IReadOnlyList IWorkspaceTabsView.Items => [.. Tabs.TabItems.OfType()]; - _closed.Push(content.Snapshot(), Tabs.TabItems.IndexOf(item)); - await content.CloseAsync().ConfigureAwait(true); - } - } - finally - { - _closingTabs.Remove(item); - } + IWorkspaceTab? IWorkspaceTabsView.ContentOf(TabViewItem item) => item.Content as ITabContent; - Release(item); - if (Tabs.TabItems.Count == 0) - { - Emptied?.Invoke(this, EventArgs.Empty); - } - } + void IWorkspaceTabsView.SelectTab(TabViewItem item) => Tabs.SelectedItem = item; + + Task IWorkspaceTabsView.ConfirmCloseHeldAsync(IWorkspaceTab tab) => ConfirmCloseHeldAsync(tab); + + void IWorkspaceTabsView.Remove(TabViewItem item) => Release(item); - private async Task ConfirmCloseHeldAsync(ITabContent content) + private async Task ConfirmCloseHeldAsync(IWorkspaceTab content) { var dialog = new ContentDialog { diff --git a/windows/src/TablePro.DataGrid.Model/CellBlock.cs b/windows/src/TablePro.DataGrid.Model/CellBlock.cs index 056db54fe1..7e7dc84293 100644 --- a/windows/src/TablePro.DataGrid.Model/CellBlock.cs +++ b/windows/src/TablePro.DataGrid.Model/CellBlock.cs @@ -3,7 +3,7 @@ namespace TablePro.DataGrid.Model; [Flags] -public enum CellState : byte +public enum CellState : ushort { None = 0, Null = 1, @@ -18,6 +18,18 @@ public enum CellState : byte // The core shows control characters as spaces, so a copy reads text with a space whole. Lossy = 16, + + // A cell of a data row the user changed. + Modified = 32, + + // Any cell of a new row. + Inserted = 64, + + // Any cell of a row marked for delete; it keeps the data's text. + Deleted = 128, + + // The server's value, with no text: the grid draws its DefaultText. + Default = 256, } public readonly ref struct CellText(ReadOnlySpan text, CellState state) @@ -28,6 +40,8 @@ public readonly ref struct CellText(ReadOnlySpan text, CellState state) public bool IsNull => (State & CellState.Null) != 0; + public bool IsDefault => (State & CellState.Default) != 0; + public bool IsTruncated => (State & CellState.Truncated) != 0; public bool IsRightToLeft => (State & CellState.RightToLeft) != 0; @@ -77,7 +91,9 @@ public void Reset(int firstRow, int rowCount, int firstColumn, int columnCount, _starts[0] = 0; } - public void AddNull() => Close(CellState.Null); + public void AddNull(CellState marks = CellState.None) => Close(CellState.Null | marks); + + public void AddDefault(CellState marks = CellState.None) => Close(CellState.Default | marks); // Grows the buffer once for a window's text, where adding cell by cell would grow it several times. public void EnsureCapacity(int characters) => Reserve(characters - _length, exact: true); @@ -87,16 +103,16 @@ public void Add(ReadOnlySpan utf8, bool truncated, bool lossy = false) Reserve(Encoding.UTF8.GetMaxCharCount(utf8.Length) + 1); var start = _length; _length += Encoding.UTF8.GetChars(utf8, _chars.AsSpan(_length)); - Finish(start, truncated, lossy); + Finish(start, truncated, lossy, CellState.None); } - // A cell another block already read, copied as it is. - public void Add(CellText cell) + // A cell another block already read, copied as it is, with the marks added. + public void Add(CellText cell, CellState marks = CellState.None) { Reserve(cell.Text.Length); cell.Text.CopyTo(_chars.AsSpan(_length)); _length += cell.Text.Length; - Close(cell.State); + Close(cell.State | marks); } public void Add(ReadOnlySpan text, bool truncated, bool lossy = false) @@ -105,7 +121,28 @@ public void Add(ReadOnlySpan text, bool truncated, bool lossy = false) var start = _length; text.CopyTo(_chars.AsSpan(_length)); _length += text.Length; - Finish(start, truncated, lossy); + Finish(start, truncated, lossy, CellState.None); + } + + // Text the user typed, shown as the core shows a value: cut at the block's cap, control characters as spaces. + public void AddTyped(ReadOnlySpan text, CellState marks) + { + var cut = MaxCharacters > 0 && text.Length > MaxCharacters; + if (cut) + { + var end = char.IsHighSurrogate(text[MaxCharacters - 1]) ? MaxCharacters - 1 : MaxCharacters; + text = text[..end]; + } + Reserve(text.Length + 1); + var start = _length; + var lossy = false; + foreach (var character in text) + { + var control = char.IsControl(character); + lossy |= control; + _chars[_length++] = control ? ' ' : character; + } + Finish(start, cut, lossy, marks); } // The span stays valid until the block is refilled. @@ -120,9 +157,13 @@ public CellText Get(int row, int column) return new CellText(_chars.AsSpan(start, _starts[cell + 1] - start), _flags[cell]); } - private void Finish(int start, bool truncated, bool lossy) + private void Finish(int start, bool truncated, bool lossy, CellState marks) { - var flags = TextDirection.IsRightToLeft(_chars.AsSpan(start, _length - start)) ? CellState.RightToLeft : CellState.None; + var flags = marks; + if (TextDirection.IsRightToLeft(_chars.AsSpan(start, _length - start))) + { + flags |= CellState.RightToLeft; + } if (lossy) { flags |= CellState.Lossy; diff --git a/windows/src/TablePro.DataGrid.Model/CellCache.cs b/windows/src/TablePro.DataGrid.Model/CellCache.cs index 47fd897b17..db7215d81c 100644 --- a/windows/src/TablePro.DataGrid.Model/CellCache.cs +++ b/windows/src/TablePro.DataGrid.Model/CellCache.cs @@ -39,6 +39,8 @@ public CellText Get(int row, int column, int maxCharacters) return block.Get(row, column); } + public string? ReadWhole(int row, int column) => _reader.ReadWhole(row, column); + public void Clear() { _blocks.Clear(); diff --git a/windows/src/TablePro.DataGrid.Model/EditedGridData.cs b/windows/src/TablePro.DataGrid.Model/EditedGridData.cs new file mode 100644 index 0000000000..55f40d2050 --- /dev/null +++ b/windows/src/TablePro.DataGrid.Model/EditedGridData.cs @@ -0,0 +1,181 @@ +namespace TablePro.DataGrid.Model; + +// The data with the edits laid over it. Grid rows are the data's rows, then the new rows. +public sealed class EditedGridData : IGridData +{ + private GridEdits _edits; + + public EditedGridData(IGridData data, GridEdits edits) + { + ArgumentNullException.ThrowIfNull(data); + ArgumentNullException.ThrowIfNull(edits); + Data = data; + _edits = edits; + } + + public IGridData Data { get; } + + // The host swaps it on the UI thread and calls the grid's EditsChanged; a copy reads it from a pool thread. + public GridEdits Edits + { + get => Volatile.Read(ref _edits); + set + { + ArgumentNullException.ThrowIfNull(value); + Volatile.Write(ref _edits, value); + } + } + + public int RowCount => Data.RowCount + Edits.AddedRows; + + public int ColumnCount => Data.ColumnCount; + + public string GetColumnName(int column) => Data.GetColumnName(column); + + public RowMark GetRowMark(int row) + { + var edits = Edits; + var dataRows = Data.RowCount; + if (row < 0) + { + return RowMark.None; + } + if (row >= dataRows) + { + return row - dataRows < edits.AddedRows ? RowMark.Inserted : RowMark.None; + } + return edits.IsDeleted(row) ? RowMark.Deleted : edits.IsModified(row) ? RowMark.Modified : RowMark.None; + } + + // The reader keeps the edits as they are now, so it never sees half a change. + public IGridReader OpenReader() => OpenReader(Edits); + + // A copy takes the edits on the UI thread and opens its reader on a pool thread. + public IGridReader OpenReader(GridEdits edits) + { + ArgumentNullException.ThrowIfNull(edits); + return new Reader(Data, Data.OpenReader(), edits); + } + + private sealed class Reader(IGridData data, IGridReader inner, GridEdits edits) : IGridReader + { + private readonly CellBlock _scratch = new(); + + // The data's rows come from its own reader into a scratch block; new rows are never asked of the data. + public void Read(int firstRow, int rowCount, int firstColumn, int columnCount, int maxCharacters, CellBlock block) + { + ArgumentNullException.ThrowIfNull(block); + var dataRows = data.RowCount; + var columns = Math.Clamp(data.ColumnCount - firstColumn, 0, Math.Max(0, columnCount)); + var wanted = Math.Clamp(dataRows - firstRow, 0, Math.Max(0, rowCount)); + var read = wanted; + if (wanted > 0 && columns > 0) + { + inner.Read(firstRow, wanted, firstColumn, columns, maxCharacters, _scratch); + read = Math.Min(wanted, _scratch.RowCount); + } + var added = 0; + var firstAdded = 0; + // New rows follow the data's last row, so a data read that stopped short leaves them out. + if (read == wanted) + { + var start = Math.Max(firstRow, dataRows); + var end = (int)Math.Min((long)firstRow + rowCount, (long)dataRows + edits.AddedRows); + added = Math.Max(0, end - start); + firstAdded = start - dataRows; + } + block.Reset(firstRow, read + added, firstColumn, columns, maxCharacters); + block.EnsureCapacity(Characters(firstRow, read, firstColumn, columns, firstAdded, added, maxCharacters)); + for (var column = firstColumn; column < firstColumn + columns; column++) + { + for (var row = firstRow; row < firstRow + read; row++) + { + if (edits.IsDeleted(row)) + { + block.Add(_scratch.Get(row, column), CellState.Deleted); + } + else if (edits.TryGetCell(row, column, out var pending)) + { + Add(block, pending, CellState.Modified); + } + else + { + block.Add(_scratch.Get(row, column)); + } + } + for (var index = firstAdded; index < firstAdded + added; index++) + { + Add(block, edits.GetAddedCell(index, column), CellState.Inserted); + } + } + } + + // The pending text, null for NULL and "" for DEFAULT; a deleted row keeps the data's value. + public string? ReadWhole(int row, int column) + { + var dataRows = data.RowCount; + if (row >= dataRows) + { + return row - dataRows < edits.AddedRows ? Whole(edits.GetAddedCell(row - dataRows, column)) : null; + } + return !edits.IsDeleted(row) && edits.TryGetCell(row, column, out var pending) + ? Whole(pending) + : inner.ReadWhole(row, column); + } + + public void Dispose() => inner.Dispose(); + + private static void Add(CellBlock block, PendingCell pending, CellState marks) + { + switch (pending.Kind) + { + case PendingKind.Null: + block.AddNull(marks); + break; + case PendingKind.Default: + block.AddDefault(marks); + break; + default: + block.AddTyped(pending.Text, marks); + break; + } + } + + private static string? Whole(PendingCell pending) => pending.Kind switch + { + PendingKind.Null => null, + PendingKind.Default => string.Empty, + _ => pending.Text ?? string.Empty, + }; + + // One more per typed cell for a cut mark. + private int Characters(int firstRow, int read, int firstColumn, int columns, int firstAdded, int added, + int maxCharacters) + { + var characters = 0; + for (var column = firstColumn; column < firstColumn + columns; column++) + { + for (var row = firstRow; row < firstRow + read; row++) + { + characters += !edits.IsDeleted(row) && edits.TryGetCell(row, column, out var pending) + ? Typed(pending, maxCharacters) + : _scratch.Get(row, column).Text.Length; + } + for (var index = firstAdded; index < firstAdded + added; index++) + { + characters += Typed(edits.GetAddedCell(index, column), maxCharacters); + } + } + return characters; + } + + private static int Typed(PendingCell pending, int maxCharacters) + { + if (pending.Kind != PendingKind.Value || pending.Text is null) + { + return 0; + } + return (maxCharacters > 0 ? Math.Min(pending.Text.Length, maxCharacters) : pending.Text.Length) + 1; + } + } +} diff --git a/windows/src/TablePro.DataGrid.Model/GridEdits.cs b/windows/src/TablePro.DataGrid.Model/GridEdits.cs new file mode 100644 index 0000000000..b90a09d8b2 --- /dev/null +++ b/windows/src/TablePro.DataGrid.Model/GridEdits.cs @@ -0,0 +1,63 @@ +namespace TablePro.DataGrid.Model; + +public enum RowMark : byte +{ + None, + Modified, + Inserted, + Deleted, +} + +public enum PendingKind : byte +{ + Value, + Null, + Default, +} + +// Text is "" unless Kind is Value. +public readonly record struct PendingCell(PendingKind Kind, string Text); + +// Immutable, so readers on any thread see one state. Data rows count from the data, new rows from the first new row. +public sealed class GridEdits +{ + private readonly Dictionary<(int Row, int Column), PendingCell> _cells; + private readonly HashSet _deleted; + private readonly HashSet _modified; + private readonly PendingCell[][] _added; + + public GridEdits( + IReadOnlyDictionary<(int Row, int Column), PendingCell> cells, + IReadOnlySet deleted, + IReadOnlyList> added) + { + ArgumentNullException.ThrowIfNull(cells); + ArgumentNullException.ThrowIfNull(deleted); + ArgumentNullException.ThrowIfNull(added); + _cells = new Dictionary<(int Row, int Column), PendingCell>(cells); + _deleted = [.. deleted]; + _modified = [.. _cells.Keys.Select(key => key.Row)]; + _added = [.. added.Select(row => row.ToArray())]; + } + + public static GridEdits None { get; } = + new(new Dictionary<(int Row, int Column), PendingCell>(), new HashSet(), []); + + public int AddedRows => _added.Length; + + public bool HasChanges => _cells.Count > 0 || _deleted.Count > 0 || _added.Length > 0; + + public bool IsDeleted(int dataRow) => _deleted.Contains(dataRow); + + public bool IsModified(int dataRow) => _modified.Contains(dataRow); + + public bool TryGetCell(int dataRow, int column, out PendingCell cell) => + _cells.TryGetValue((dataRow, column), out cell); + + // A new row shorter than the columns reads NULL past its end, so a host's slip cannot fail a draw. + public PendingCell GetAddedCell(int addedRow, int column) + { + var row = _added[addedRow]; + return column >= 0 && column < row.Length ? row[column] : new PendingCell(PendingKind.Null, string.Empty); + } +} diff --git a/windows/src/TablePro.DataGrid/Automation/DataGridAutomationPeer.cs b/windows/src/TablePro.DataGrid/Automation/DataGridAutomationPeer.cs index b593c787a5..bfade0cd28 100644 --- a/windows/src/TablePro.DataGrid/Automation/DataGridAutomationPeer.cs +++ b/windows/src/TablePro.DataGrid/Automation/DataGridAutomationPeer.cs @@ -44,6 +44,15 @@ public CellAutomationPeer Cell(int row, int column) public IRawElementProviderSimple Provider(AutomationPeer peer) => ProviderFromPeer(peer); + // After the edits or the data changed; each held cell whose ItemStatus moved raises the change. + public void RefreshStatuses(bool raise) + { + foreach (var cell in _cells.Values) + { + cell.RefreshStatus(raise); + } + } + // Any cell, on screen or not. ScrollItem on the cell brings it into view. public IRawElementProviderSimple? GetItem(int row, int column) => row < 0 || row >= RowCount || column < 0 || column >= ColumnCount ? null : ProviderFromPeer(Cell(row, column)); @@ -131,6 +140,8 @@ private void Prune() internal sealed partial class CellAutomationPeer(DataGridView grid, DataGridAutomationPeer gridPeer, int row, int column) : AutomationPeer, IGridItemProvider, ITableItemProvider, ISelectionItemProvider, IScrollItemProvider { + private string _status = grid.CellStatus(row, column); + public int Row => row; public int Column => column; @@ -183,12 +194,30 @@ public void ScrollIntoView() } } + public void RefreshStatus(bool raise) + { + var status = grid.CellStatus(row, column); + if (string.Equals(status, _status, StringComparison.Ordinal)) + { + return; + } + var previous = _status; + _status = status; + if (raise) + { + RaisePropertyChangedEvent(AutomationElementIdentifiers.ItemStatusProperty, previous, status); + } + } + protected override string GetClassNameCore() => "DataGridCell"; protected override AutomationControlType GetAutomationControlTypeCore() => AutomationControlType.DataItem; protected override string GetNameCore() => grid.CellName(row, column); + // The pending change, as the macOS grid's VoiceOver suffixes; the name stays the value. + protected override string GetItemStatusCore() => _status = grid.CellStatus(row, column); + protected override bool IsContentElementCore() => true; protected override bool IsControlElementCore() => true; @@ -288,8 +317,11 @@ internal sealed partial class PaneAutomationPeer(PaneContent owner, DataGridView protected override bool IsContentElementCore() => false; - // The grid's peer lists the cells. - protected override IList? GetChildrenCore() => null; + // The grid's peer lists the cells; a pane holds only an open editor. + protected override IList? GetChildrenCore() => + grid.EditorIn(owner.IsFrozen) is { } editor && CreatePeerForElement(editor) is { } peer + ? new List { peer } + : null; // XAML passes physical pixels from the window's client area here (ElementProviderFromPointImpl, UIAWindow.cpp). protected override object? GetElementFromPointCore(Windows.Foundation.Point pointInWindowCoordinates) => diff --git a/windows/src/TablePro.DataGrid/CellPainter.cs b/windows/src/TablePro.DataGrid/CellPainter.cs index 3ce8d51cee..ecbd077967 100644 --- a/windows/src/TablePro.DataGrid/CellPainter.cs +++ b/windows/src/TablePro.DataGrid/CellPainter.cs @@ -26,6 +26,8 @@ internal enum CellInk : byte Text, Placeholder, RowNumber, + Default, + Deleted, } // Matches a TextBlock cell: XAML's font and content size times the text scale, one line cut with an ellipsis. @@ -41,8 +43,10 @@ internal sealed unsafe class CellPainter : IDisposable private IDWriteTextFormat* _text; private IDWriteTextFormat* _null; private IDWriteTextFormat* _number; + private IDWriteTextFormat* _default; private IDWriteInlineObject* _ellipsis; private IDWriteInlineObject* _nullEllipsis; + private IDWriteInlineObject* _defaultEllipsis; private ID2D1SolidColorBrush* _textBrush; private ID2D1SolidColorBrush* _placeholderBrush; private ID2D1SolidColorBrush* _cutMarkBrush; @@ -51,8 +55,15 @@ internal sealed unsafe class CellPainter : IDisposable private ID2D1SolidColorBrush* _frozenEdgeBrush; private ID2D1SolidColorBrush* _headerBrush; private ID2D1SolidColorBrush* _selectedTextBrush; + private ID2D1SolidColorBrush* _defaultBrush; + private ID2D1SolidColorBrush* _deletedBrush; + private ID2D1SolidColorBrush* _modifiedFill; + private ID2D1SolidColorBrush* _insertedFill; + private ID2D1SolidColorBrush* _deletedFill; + private ID2D1SolidColorBrush* _selectionBrush; private int _brushGeneration = -1; private GridColors _colors; + private string _defaultText = "DEFAULT"; public CellPainter(SurfaceDevice device, float fontSize, GridColors colors) { @@ -66,6 +77,20 @@ public CellPainter(SurfaceDevice device, float fontSize, GridColors colors) public float FontSize { get; private set; } + // What a cell the server fills shows. + public string DefaultText + { + get => _defaultText; + set + { + if (!string.Equals(_defaultText, value, StringComparison.Ordinal)) + { + _defaultText = value; + Version++; + } + } + } + // Bumped by every change that makes drawn rows stale: fonts, colors, the device. public int Version { get; private set; } @@ -86,8 +111,10 @@ public void Configure(float fontSize, GridColors colors) _text = CreateFormat(DWRITE_FONT_STYLE_NORMAL, DWRITE_TEXT_ALIGNMENT_LEADING); _null = CreateFormat(DWRITE_FONT_STYLE_ITALIC, DWRITE_TEXT_ALIGNMENT_LEADING); _number = CreateFormat(DWRITE_FONT_STYLE_NORMAL, DWRITE_TEXT_ALIGNMENT_TRAILING); + _default = CreateFormat(DWRITE_FONT_STYLE_NORMAL, DWRITE_TEXT_ALIGNMENT_LEADING, DWRITE_FONT_WEIGHT_SEMI_BOLD); _ellipsis = Trim(_text); _nullEllipsis = Trim(_null); + _defaultEllipsis = Trim(_default); _brushGeneration = -1; Version++; } @@ -109,6 +136,12 @@ public void EnsureBrushes() _frozenEdgeBrush = Brush(context, _colors.FrozenEdge); _headerBrush = Brush(context, _colors.HeaderBackground); _selectedTextBrush = Brush(context, _colors.SelectedText); + _defaultBrush = Brush(context, _colors.DefaultValue); + _deletedBrush = Brush(context, _colors.DeletedText); + _modifiedFill = Brush(context, _colors.ModifiedFill); + _insertedFill = Brush(context, _colors.InsertedFill); + _deletedFill = Brush(context, _colors.DeletedFill); + _selectionBrush = Brush(context, _colors.Selection); _brushGeneration = _device.Generation; Version++; } @@ -117,9 +150,29 @@ public void EnsureBrushes() { CellInk.Placeholder => (ID2D1Brush*)_placeholderBrush, CellInk.RowNumber => (ID2D1Brush*)(selected ? _textBrush : _rowNumberBrush), + CellInk.Default => (ID2D1Brush*)(selected && _colors.HighContrast ? _selectedTextBrush : _defaultBrush), + CellInk.Deleted => (ID2D1Brush*)(selected && _colors.HighContrast ? _selectedTextBrush : _deletedBrush), _ => (ID2D1Brush*)(selected && _colors.HighContrast ? _selectedTextBrush : _textBrush), }; + // The wash behind a pending change, or null where none is drawn. + public ID2D1Brush* FillBrush(CellState marks) + { + if (_colors.HighContrast) + { + return null; + } + if ((marks & CellState.Deleted) != 0) + { + return (ID2D1Brush*)_deletedFill; + } + if ((marks & CellState.Inserted) != 0) + { + return (ID2D1Brush*)_insertedFill; + } + return (marks & CellState.Modified) != 0 ? (ID2D1Brush*)_modifiedFill : null; + } + public ID2D1Brush* DividerBrush => (ID2D1Brush*)_dividerBrush; public ID2D1Brush* FrozenEdgeBrush => (ID2D1Brush*)_frozenEdgeBrush; @@ -128,37 +181,78 @@ public void EnsureBrushes() public ID2D1Brush* SelectedTextBrush => (ID2D1Brush*)_selectedTextBrush; + // The selection's tint, for a washed cell that hides the selection box beneath the row. + public ID2D1Brush* SelectionBrush => (ID2D1Brush*)_selectionBrush; + // A layout for one cell's text, or null when nothing shows. The caller releases it. public IDWriteTextLayout* CreateLayout(ReadOnlySpan text, CellState state, float width, float height, out CellInk ink) { - ink = CellInk.Text; + var deleted = (state & CellState.Deleted) != 0; + ink = deleted ? CellInk.Deleted : CellInk.Text; if (width <= 0 || (state & CellState.Missing) != 0) { return null; } + IDWriteTextLayout* layout; + int length; if ((state & CellState.Null) != 0) { - ink = CellInk.Placeholder; - return Create(NullText, _null, width, height); + ink = deleted ? CellInk.Deleted : CellInk.Placeholder; + layout = Create(NullText, _null, width, height); + length = NullText.Length; } - if (text.IsEmpty) + else if ((state & CellState.Default) != 0) { - return null; + if (_defaultText.Length == 0) + { + return null; + } + ink = deleted ? CellInk.Deleted : CellInk.Default; + layout = Create(_defaultText, _default, width, height); + length = _defaultText.Length; } - var layout = Create(text, _text, width, height); - if ((state & CellState.RightToLeft) != 0) + else { - layout->SetReadingDirection(DWRITE_READING_DIRECTION_RIGHT_TO_LEFT); + if (text.IsEmpty) + { + return null; + } + layout = Create(text, _text, width, height); + length = text.Length; + if ((state & CellState.RightToLeft) != 0) + { + layout->SetReadingDirection(DWRITE_READING_DIRECTION_RIGHT_TO_LEFT); + } + if ((state & CellState.Truncated) != 0) + { + layout->SetDrawingEffect((IUnknown*)_cutMarkBrush, new DWRITE_TEXT_RANGE { startPosition = (uint)(text.Length - 1), length = 1 }); + } } - if ((state & CellState.Truncated) != 0) + var range = new DWRITE_TEXT_RANGE { startPosition = 0, length = (uint)length }; + if (deleted) { - layout->SetDrawingEffect((IUnknown*)_cutMarkBrush, new DWRITE_TEXT_RANGE { startPosition = (uint)(text.Length - 1), length = 1 }); + layout->SetStrikethrough(BOOL.TRUE, range); + } + else if ((state & (CellState.Modified | CellState.Inserted)) != 0) + { + layout->SetUnderline(BOOL.TRUE, range); } return layout; } - public IDWriteTextLayout* CreateRowNumber(ReadOnlySpan digits, float width, float height) => - width <= 0 || digits.IsEmpty ? null : Create(digits, _number, width, height); + public IDWriteTextLayout* CreateRowNumber(ReadOnlySpan digits, float width, float height, bool deleted) + { + if (width <= 0 || digits.IsEmpty) + { + return null; + } + var layout = Create(digits, _number, width, height); + if (deleted) + { + layout->SetStrikethrough(BOOL.TRUE, new DWRITE_TEXT_RANGE { startPosition = 0, length = (uint)digits.Length }); + } + return layout; + } // The width text takes on one line, for fitting a column to its content. public float Measure(ReadOnlySpan text, bool placeholder = false) @@ -167,13 +261,11 @@ public float Measure(ReadOnlySpan text, bool placeholder = false) { return 0; } - var layout = Create(text, placeholder ? _null : _text, 100_000, 100); - DWRITE_TEXT_METRICS metrics; - layout->GetMetrics(&metrics); - layout->Release(); - return metrics.widthIncludingTrailingWhitespace; + return Measure(text, placeholder ? _null : _text); } + public float MeasureDefault() => _defaultText.Length == 0 ? 0 : Measure(_defaultText, _default); + // Lays out and draws sample cells of every common script as the rows do, on the rows' device from a pool thread. public Task WarmAsync(float width, float height) { @@ -278,6 +370,15 @@ private static void DrawSamples(IDWriteFactory* factory, ID2D1Device* device, ID } } + private float Measure(ReadOnlySpan text, IDWriteTextFormat* format) + { + var layout = Create(text, format, 100_000, 100); + DWRITE_TEXT_METRICS metrics; + layout->GetMetrics(&metrics); + layout->Release(); + return metrics.widthIncludingTrailingWhitespace; + } + private IDWriteTextLayout* Create(ReadOnlySpan text, IDWriteTextFormat* format, float width, float height) { IDWriteTextLayout* layout; @@ -289,7 +390,8 @@ private static void DrawSamples(IDWriteFactory* factory, ID2D1Device* device, ID return layout; } - private IDWriteTextFormat* CreateFormat(DWRITE_FONT_STYLE style, DWRITE_TEXT_ALIGNMENT alignment) + private IDWriteTextFormat* CreateFormat(DWRITE_FONT_STYLE style, DWRITE_TEXT_ALIGNMENT alignment, + DWRITE_FONT_WEIGHT weight = DWRITE_FONT_WEIGHT_NORMAL) { IDWriteTextFormat* format; // The user's language picks glyph variants, such as Han forms, as XAML text does. @@ -297,7 +399,7 @@ private static void DrawSamples(IDWriteFactory* factory, ID2D1Device* device, ID fixed (char* family = FamilyName) fixed (char* localeName = locale.Length == 0 ? "en-us" : locale) { - NativeCom.Check(_device.DWrite->CreateTextFormat(family, null, DWRITE_FONT_WEIGHT_NORMAL, style, + NativeCom.Check(_device.DWrite->CreateTextFormat(family, null, weight, style, DWRITE_FONT_STRETCH_NORMAL, FontSize, localeName, &format)); } format->SetWordWrapping(DWRITE_WORD_WRAPPING_NO_WRAP); @@ -359,14 +461,22 @@ private void ReleaseBrushes() NativeCom.Release(ref _frozenEdgeBrush); NativeCom.Release(ref _headerBrush); NativeCom.Release(ref _selectedTextBrush); + NativeCom.Release(ref _defaultBrush); + NativeCom.Release(ref _deletedBrush); + NativeCom.Release(ref _modifiedFill); + NativeCom.Release(ref _insertedFill); + NativeCom.Release(ref _deletedFill); + NativeCom.Release(ref _selectionBrush); } private void ReleaseFormats() { NativeCom.Release(ref _ellipsis); NativeCom.Release(ref _nullEllipsis); + NativeCom.Release(ref _defaultEllipsis); NativeCom.Release(ref _text); NativeCom.Release(ref _null); NativeCom.Release(ref _number); + NativeCom.Release(ref _default); } } diff --git a/windows/src/TablePro.DataGrid/DataGridView.Editing.cs b/windows/src/TablePro.DataGrid/DataGridView.Editing.cs new file mode 100644 index 0000000000..bf78b600d0 --- /dev/null +++ b/windows/src/TablePro.DataGrid/DataGridView.Editing.cs @@ -0,0 +1,514 @@ +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Automation; +using Microsoft.UI.Xaml.Automation.Peers; +using Microsoft.UI.Xaml.Controls; +using Microsoft.UI.Xaml.Input; +using Microsoft.UI.Xaml.Media; +using TablePro.DataGrid.Automation; +using TablePro.DataGrid.Model; +using Windows.System; + +namespace TablePro.DataGrid; + +// The grid opens the editor and shows the pending changes; the host checks, keeps and saves them. +public sealed partial class DataGridView +{ + private const int EditorMaxRows = 4; + + private TextBox? _editor; + private ToolTip? _editorTip; + private (int Row, int Column)? _edit; + private string _editText = string.Empty; + private string _newline = "\r"; + private int _editSession; + private bool _committing; + private bool _isEditable; + private string _defaultText = "DEFAULT"; + + public bool IsEditable + { + get => _isEditable; + set + { + _isEditable = value; + if (!value) + { + CancelEdit(); + } + } + } + + public bool IsEditing => _edit is not null; + + public string DefaultText + { + get => _defaultText; + set + { + ArgumentNullException.ThrowIfNull(value); + if (string.Equals(_defaultText, value, StringComparison.Ordinal)) + { + return; + } + _defaultText = value; + if (_painter is not null) + { + _painter.DefaultText = value; + InvalidateRows(); + } + } + } + + public string EditedStatus { get; set; } = "edited"; + + public string NewRowStatus { get; set; } = "new row"; + + public string DeletedStatus { get; set; } = "marked for deletion"; + + public event EventHandler? CellEditStarting; + + public event EventHandler? CellEditCommitting; + + public event EventHandler? DeleteRequested; + + internal TextBox? Editor => _editor; + + private bool EditorFocused => _editor is not null && _editor.FocusState != FocusState.Unfocused; + + public void BeginEdit() + { + if (!IsEditable || (IsEditing && !Commit(EditorFocused))) + { + return; + } + var (row, column) = (FocusedRow, FocusedColumn); + if (_cache is null || !Contains(row, column)) + { + return; + } + var args = new GridEditStartingEventArgs(row, column, _cache.ReadWhole(row, column) ?? string.Empty); + CellEditStarting?.Invoke(this, args); + // A TextBox cannot hold NUL, so such a value would come back changed. + if (args.Cancel || args.Text.Contains('\0', StringComparison.Ordinal) || IsEditing || !Contains(row, column)) + { + return; + } + ScrollIntoView(row, column); + OpenEditor(row, column, args.Text); + } + + // True when no editor is open or the host took the text; false keeps the editor open with the host's Error. + public bool CommitEdit() => Commit(EditorFocused); + + public void CancelEdit() => Cancel(EditorFocused); + + public void FocusCell(int row, int column) => SelectCell(row, column, extend: false); + + public void EditsChanged() + { + if (_data is null) + { + return; + } + if (_edit is { } open && !_committing && _data.RowCount != RowCount) + { + // The host's new rows have moved already, so a new row's index may name another one now. + if (_edited is null || open.Row < _edited.Data.RowCount) + { + CommitOrCancel(EditorFocused); + } + else + { + Cancel(EditorFocused); + } + } + _cache?.Dispose(); + _cache = new CellCache(_data.OpenReader()); + var count = _data.RowCount; + if (count != RowCount) + { + var focus = (_selection.FocusRow, _selection.FocusColumn); + if (count < RowCount) + { + // IndexList only grows. A new source, as SetData gives, takes the rows that went (trap 5). + _rowsLayout.Forget(); + _frozenRowsLayout.Forget(); + _items = new IndexList(count); + _rows.ItemsSource = _items; + _frozenRows.ItemsSource = _items; + } + else + { + _items.Grow(count); + } + RowCount = count; + _selection.Clamp(count, ColumnCount); + _selectionVersion++; + UpdateRowNumberWidth(); + UpdateExtent(); + // ScrollTo clamps to the ScrollViewer's extent, which follows the new height only after a layout pass. + _scroller.UpdateLayout(); + UpdateSelectionBoxes(); + UpdateFocusBox(); + if (focus != (_selection.FocusRow, _selection.FocusColumn)) + { + RaiseFocusChanged(); + } + } + if (_edit is { } edit && !Contains(edit.Row, edit.Column)) + { + Cancel(EditorFocused); + } + _layoutVersion++; + InvalidateRows(); + Follow(_viewX, _viewY); + RaiseStatusChanges(); + } + + internal bool HandleEditorKey(VirtualKey key, bool control, bool shift) + { + if (_editor is null || _edit is not { } edit) + { + return false; + } + switch (key) + { + case VirtualKey.Escape: + Cancel(refocus: true); + return true; + case VirtualKey.Enter when control || !_editor.AcceptsReturn: + Commit(refocus: true); + return true; + case VirtualKey.Tab: + // As NSTableView moves a field editor on: the next cell in the row is edited. + var next = edit.Column + (shift ? -1 : 1); + if (Commit(refocus: true) && Contains(edit.Row, next)) + { + SelectCell(edit.Row, next, extend: false); + BeginEditAfterKey(); + } + return true; + default: + return false; + } + } + + // The key's character goes to whatever has focus once KeyDown returns, so the editor opens after it. + private void BeginEditAfterKey() + { + var data = _data; + var cell = (FocusedRow, FocusedColumn); + DispatcherQueue.TryEnqueue(() => + { + if (!IsEditing && ReferenceEquals(data, _data) && cell == (FocusedRow, FocusedColumn)) + { + BeginEdit(); + } + }); + } + + internal RowMark MarkOf(int row) => _edited?.GetRowMark(row) ?? RowMark.None; + + // Read from the edits, not the cells, so a peer off screen fetches nothing. + internal string CellStatus(int row, int column) + { + if (_edited is null || !Contains(row, column)) + { + return string.Empty; + } + return _edited.GetRowMark(row) switch + { + RowMark.Deleted => DeletedStatus, + RowMark.Inserted => NewRowStatus, + RowMark.Modified when _edited.Edits.TryGetCell(row, column, out _) => EditedStatus, + _ => string.Empty, + }; + } + + // The TextBox shows its own menu for a request from inside it, which starts on a part of its template. + public bool IsInEditor(object? source) + { + if (_editor is null) + { + return false; + } + for (var element = source as DependencyObject; element is not null; element = VisualTreeHelper.GetParent(element)) + { + if (ReferenceEquals(element, _editor)) + { + return true; + } + } + return false; + } + + internal UIElement? EditorIn(bool frozen) => + IsEditing && _editor is not null && ReferenceEquals(_editor.Parent, frozen ? _frozenWindow : _window) + ? _editor + : null; + + private void RaiseStatusChanges() + { + if (FrameworkElementAutomationPeer.FromElement(this) is DataGridAutomationPeer peer) + { + peer.RefreshStatuses(AutomationPeer.ListenerExists(AutomationEvents.PropertyChanged)); + } + } + + private bool Commit(bool refocus) + { + if (_editor is null || _edit is not { } edit) + { + return true; + } + if (_committing) + { + return false; + } + var text = EditorText(_editor); + // Text the editor opened with is no change: a NULL cell stays NULL. + if (string.Equals(text, _editText, StringComparison.Ordinal)) + { + CloseEditor(refocus); + return true; + } + var session = _editSession; + var args = new GridEditCommittingEventArgs(edit.Row, edit.Column, text); + _committing = true; + try + { + CellEditCommitting?.Invoke(this, args); + } + finally + { + _committing = false; + } + if (session != _editSession || !IsEditing) + { + return true; + } + if (!string.IsNullOrEmpty(args.Error)) + { + ShowEditError(args.Error); + return false; + } + CloseEditor(refocus); + return true; + } + + private void Cancel(bool refocus) + { + if (IsEditing) + { + CloseEditor(refocus); + } + } + + // The editor closes either way, its ToolTip with it, so the host shows a refused commit's Error itself. + private void CommitOrCancel(bool refocus) + { + if (!Commit(refocus)) + { + Cancel(refocus); + } + } + + private void OpenEditor(int row, int column, string text) + { + var editor = _editor ??= CreateEditor(); + var window = column < _columns.FrozenCount ? _frozenWindow : _window; + if (!ReferenceEquals(editor.Parent, window)) + { + (editor.Parent as Panel)?.Children.Remove(editor); + window.Children.Add(editor); + } + _editSession++; + _edit = (row, column); + ClearEditError(); + // Before the text: a TextBox that takes no returns keeps only the first line. + editor.AcceptsReturn = text.AsSpan().IndexOfAny('\r', '\n') >= 0; + _newline = text.Contains("\r\n", StringComparison.Ordinal) ? "\r\n" + : text.Contains('\n', StringComparison.Ordinal) ? "\n" + : "\r"; + editor.Text = text; + // What the TextBox holds, so a value with mixed line breaks opened and left is no change. + _editText = EditorText(editor); + AutomationProperties.SetName(editor, _names[column]); + editor.Visibility = Visibility.Visible; + PlaceEditor(); + if (editor.IsLoaded) + { + FocusEditor(editor); + } + else + { + editor.Loaded -= OnEditorLoaded; + editor.Loaded += OnEditorLoaded; + } + } + + // A new editor, or one moved to the other pane, takes focus once it is in the tree. + private void OnEditorLoaded(object sender, RoutedEventArgs e) + { + var editor = (TextBox)sender; + editor.Loaded -= OnEditorLoaded; + if (IsEditing) + { + FocusEditor(editor); + } + } + + private static void FocusEditor(TextBox editor) + { + editor.Focus(FocusState.Programmatic); + editor.SelectAll(); + } + + // In the window the rows sit in, so it scrolls with them; called wherever the focus box moves. + private void PlaceEditor() + { + if (_editor is null || _edit is not { } edit || !Contains(edit.Row, edit.Column)) + { + return; + } + Canvas.SetLeft(_editor, _columns.PaneX(edit.Column)); + Canvas.SetTop(_editor, (edit.Row * _rowHeight) - _originY); + _editor.Width = _columns.Width(edit.Column); + if (_editor.AcceptsReturn) + { + _editor.Height = double.NaN; + _editor.MinHeight = _rowHeight; + _editor.MaxHeight = _rowHeight * EditorMaxRows; + } + else + { + _editor.Height = _rowHeight; + _editor.MinHeight = 0; + _editor.MaxHeight = double.PositiveInfinity; + } + } + + private void CloseEditor(bool refocus) + { + _edit = null; + if (_editor is null) + { + return; + } + ClearEditError(); + // Before the editor hides, so the focus stays in the grid rather than moving on. + if (refocus) + { + Focus(FocusState.Programmatic); + } + _editor.Visibility = Visibility.Collapsed; + UpdateFocusBox(); + } + + // TextBox keeps a line break as CR; the value gets back the line break style it opened with. + private string EditorText(TextBox editor) + { + var text = editor.Text; + if (!editor.AcceptsReturn) + { + return text; + } + return text.Replace("\r\n", "\r", StringComparison.Ordinal).Replace('\n', '\r') + .Replace("\r", _newline, StringComparison.Ordinal); + } + + private TextBox CreateEditor() + { + var editor = new TextBox + { + FontFamily = new FontFamily(Painter.FamilyName), + // TextBox scales its text with the text scale factor, as the painter's size already is. + FontSize = BaseFontSize, + MinWidth = 0, + MinHeight = 0, + TextWrapping = TextWrapping.NoWrap, + Visibility = Visibility.Collapsed, + }; + editor.PreviewKeyDown += OnEditorKeyDown; + // Arrows and paging the TextBox leaves would reach the ScrollViewer around it and scroll the grid. + editor.KeyDown += (_, e) => e.Handled |= e.Key is VirtualKey.Up or VirtualKey.Down or VirtualKey.Left + or VirtualKey.Right or VirtualKey.PageUp or VirtualKey.PageDown or VirtualKey.Home or VirtualKey.End; + editor.LostFocus += OnEditorLostFocus; + // The grid has put the cell in view; for an editor in the frozen header the ScrollViewer would move too. + editor.BringIntoViewRequested += (_, e) => e.Handled = true; + return editor; + } + + private void OnEditorKeyDown(object sender, KeyRoutedEventArgs e) + { + if (HandleEditorKey(e.Key, IsDown(VirtualKey.Control), IsDown(VirtualKey.Shift))) + { + e.Handled = true; + } + } + + // Focus moving to the editor's own menus comes back. + private void OnEditorLostFocus(object sender, RoutedEventArgs e) + { + if (_editor is null || !IsEditing || EditorFocused + || _editor.ContextFlyout is { IsOpen: true } || _editor.SelectionFlyout is { IsOpen: true }) + { + return; + } + CommitOrCancel(refocus: false); + } + + private void ShowEditError(string error) + { + if (_editor is null) + { + return; + } + var tip = _editorTip ??= new ToolTip(); + tip.Content = error; + ToolTipService.SetToolTip(_editor, tip); + tip.IsOpen = true; + AutomationProperties.SetFullDescription(_editor, error); + // The focus stays in the editor, so a screen reader hears the error only from this. + FrameworkElementAutomationPeer.FromElement(_editor)?.RaiseNotificationEvent(AutomationNotificationKind.ActionAborted, + AutomationNotificationProcessing.ImportantMostRecent, error, "TablePro.DataGrid.EditRefused"); + } + + private void ClearEditError() + { + if (_editor is null) + { + return; + } + if (_editorTip is not null) + { + _editorTip.IsOpen = false; + } + ToolTipService.SetToolTip(_editor, null); + AutomationProperties.SetFullDescription(_editor, string.Empty); + } +} + +public sealed class GridEditStartingEventArgs(int row, int column, string text) : EventArgs +{ + public int Row { get; } = row; + + public int Column { get; } = column; + + // The editor's text: the cell's whole value until the host sets it. + public string Text { get; set; } = text; + + public bool Cancel { get; set; } +} + +public sealed class GridEditCommittingEventArgs(int row, int column, string text) : EventArgs +{ + public int Row { get; } = row; + + public int Column { get; } = column; + + public string Text { get; } = text; + + // Set to refuse the text: the editor stays open and shows it. + public string? Error { get; set; } +} diff --git a/windows/src/TablePro.DataGrid/DataGridView.Interaction.cs b/windows/src/TablePro.DataGrid/DataGridView.Interaction.cs index 65a3a66aaa..8e04ed6edb 100644 --- a/windows/src/TablePro.DataGrid/DataGridView.Interaction.cs +++ b/windows/src/TablePro.DataGrid/DataGridView.Interaction.cs @@ -20,10 +20,10 @@ public sealed partial class DataGridView public int Copies { get; private set; } - // Moves the focused cell for a key, as OnKeyDown does; false when the key is not the grid's. + // Moves the focused cell for a key, as OnKeyDown does; false when the key is not the grid's or an editor is open. public bool HandleKey(VirtualKey key, bool control, bool shift) { - if (_data is null || RowCount == 0 || ColumnCount == 0) + if (_data is null || RowCount == 0 || ColumnCount == 0 || IsEditing) { return false; } @@ -61,6 +61,22 @@ public bool HandleKey(VirtualKey key, bool control, bool shift) case VirtualKey.Insert when control: _ = CopySelectionAsync(); return true; + // Typing does not start an edit, as on macOS. + case VirtualKey.F2 when !control && !shift: + case VirtualKey.Enter when !control && !shift: + if (!IsEditable) + { + return false; + } + BeginEditAfterKey(); + return true; + case VirtualKey.Delete when !control && !shift: + if (!IsEditable) + { + return false; + } + DeleteRequested?.Invoke(this, EventArgs.Empty); + return true; default: return false; } @@ -157,11 +173,14 @@ public async Task CopySelectionAsync() using var cancel = new CancellationTokenSource(); _copy = cancel; var data = _data; + var edited = _edited; + // Taken with the range, so a later swap of the edits cannot move the rows it names. + var edits = edited?.Edits ?? GridEdits.None; try { var text = await Task.Run(() => { - using var reader = data.OpenReader(); + using var reader = edited is null ? data.OpenReader() : edited.OpenReader(edits); return GridCopy.Tsv(reader, range, cancel.Token); }, cancel.Token).ConfigureAwait(true); if (cancel.IsCancellationRequested || !ClipboardText.TrySet(text)) @@ -240,7 +259,7 @@ private double ContentWidth(int column, int firstRow, int lastRow, int maxCharac var cell = Cell(row, column); widest = Math.Max(widest, cell.IsNull ? painter.Measure(CellPainter.NullText, placeholder: true) - : painter.Measure(Head(cell.Text, maxCharacters))); + : cell.IsDefault ? painter.MeasureDefault() : painter.Measure(Head(cell.Text, maxCharacters))); } return Math.Ceiling(widest + (CellPainter.Padding * 2) + 2); } @@ -327,6 +346,12 @@ internal Rect CellBoundsPhysical(int row, int column) protected override void OnKeyDown(KeyRoutedEventArgs e) { ArgumentNullException.ThrowIfNull(e); + // The editor's keys bubble here, the Enter that committed it among them. + if (e.Handled || (_editor is not null && ReferenceEquals(e.OriginalSource, _editor))) + { + base.OnKeyDown(e); + return; + } if (HandleKey(e.Key, IsDown(VirtualKey.Control), IsDown(VirtualKey.Shift))) { e.Handled = true; @@ -345,6 +370,60 @@ private void InitializeInput() _frozenContent.PointerReleased += (_, _) => _dragging = false; _content.PointerCaptureLost += (_, _) => _dragging = false; _frozenContent.PointerCaptureLost += (_, _) => _dragging = false; + _content.DoubleTapped += (_, e) => OnPaneDoubleTapped(e, frozen: false); + _frozenContent.DoubleTapped += (_, e) => OnPaneDoubleTapped(e, frozen: true); + _content.ContextRequested += (_, e) => OnPaneContextRequested(e, frozen: false); + _frozenContent.ContextRequested += (_, e) => OnPaneContextRequested(e, frozen: true); + } + + // The panes see the request before the host's handler on the grid; a key's request has no position. + private void OnPaneContextRequested(ContextRequestedEventArgs e, bool frozen) + { + if (e.Handled || IsInEditor(e.OriginalSource)) + { + return; + } + var pane = frozen ? (UIElement)_frozenContent : _content; + Point? point = e.TryGetPosition(pane, out var at) ? at : null; + HandleContextRequest(frozen, point); + } + + // As File Explorer and Excel: a right-click outside the selection selects the cell first. Also how the tests right-click. + internal void HandleContextRequest(bool frozen, Point? point) + { + if (point is not { } at || HitTest(frozen, at) is not { } hit) + { + return; + } + Focus(FocusState.Pointer); + var range = SelectionRange; + var inside = hit.Column >= 0 + ? range.Contains(hit.Row, hit.Column) + : range.Contains(hit.Row, 0) && range.LastColumn == ColumnCount - 1; + if (inside) + { + return; + } + if (hit.Column < 0) + { + SelectRows(hit.Row, extend: false); + } + else + { + SelectCell(hit.Row, hit.Column, extend: false); + } + } + + private void OnPaneDoubleTapped(DoubleTappedRoutedEventArgs e, bool frozen) + { + var pane = frozen ? (UIElement)_frozenContent : _content; + if (!IsEditable || HitTest(frozen, e.GetPosition(pane)) is not { Column: >= 0 } hit) + { + return; + } + SelectCell(hit.Row, hit.Column, extend: false); + BeginEdit(); + e.Handled = true; } // A press picks a cell, or a row on the row numbers; Shift extends from the anchor. Dragging extends too. @@ -449,11 +528,16 @@ private void SelectionChanged() { ((DrawnRow)row).Invalidate(); } - if (Painter.Colors.HighContrast) + var highContrast = Painter.Colors.HighContrast; + if (highContrast || _edited is not null) { foreach (var (_, row) in _rowsLayout.Realized) { - ((DrawnRow)row).Invalidate(); + var drawn = (DrawnRow)row; + if (highContrast || drawn.IsWashed) + { + drawn.Invalidate(); + } } } if (AutomationPeer.ListenerExists(AutomationEvents.SelectionItemPatternOnElementSelected) @@ -510,6 +594,7 @@ private void PlaceSelection(Microsoft.UI.Xaml.Shapes.Rectangle box, int firstCol private void UpdateFocusBox() { + PlaceEditor(); var row = _selection.FocusRow; var column = _selection.FocusColumn; var show = FocusState != FocusState.Unfocused && column < ColumnCount && row < RowCount diff --git a/windows/src/TablePro.DataGrid/DataGridView.cs b/windows/src/TablePro.DataGrid/DataGridView.cs index 79e7db0fc5..24252921f3 100644 --- a/windows/src/TablePro.DataGrid/DataGridView.cs +++ b/windows/src/TablePro.DataGrid/DataGridView.cs @@ -60,6 +60,7 @@ public sealed partial class DataGridView : UserControl, IGridWindow private readonly UISettings _settings = new(); private IGridData? _data; + private EditedGridData? _edited; private CellCache? _cache; private IndexList _items = new(0); private IndexList _columnItems = new(0); @@ -220,6 +221,8 @@ public int FrozenColumnCount get => _columns.FrozenCount; set { + // The editor sits in its column's pane, which this may change. + CommitOrCancel(EditorFocused); _columns.FrozenCount = value; ColumnsChanged(); } @@ -312,8 +315,18 @@ public GridSort Sort // Fonts, colors, widths, the device or the data changed: every drawn row lays out again. internal int LayoutVersion => unchecked((_layoutVersion * 397) ^ Painter.Version); - // Selected cells are drawn in other colors only in high contrast; the row numbers always mark selected rows. - internal int InkVersion(bool frozen) => frozen || Painter.Colors.HighContrast ? _selectionVersion : 0; + // Selected cells look different only in high contrast and on a wash; row numbers always mark selected rows. + internal int InkVersion(bool drawsSelection) => drawsSelection || Painter.Colors.HighContrast ? _selectionVersion : 0; + + // The selection box is drawn for more than the focused cell alone. + internal bool SelectionBoxShown + { + get + { + var range = SelectionRange; + return !range.IsEmpty && !(range.RowCount == 1 && range.ColumnCount == 1 && _selection.Kind == SelectionKind.Cells); + } + } public double PaneWidth(bool frozen) => frozen ? _columns.FrozenWidth : _columns.ScrollWidth; @@ -337,11 +350,13 @@ 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) { + 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(); _cache?.Dispose(); _cache = null; _data = data; + _edited = data as EditedGridData; if (data is not null) { _cache = new CellCache(data.OpenReader()); @@ -381,6 +396,7 @@ public void SetData(IGridData? data) ColumnsChanged(); _scroller.ChangeView(0, 0, null, true); Follow(0, 0); + RaiseStatusChanges(); } // The data's RowCount grew, as rows of a running query arrived. @@ -396,7 +412,17 @@ public void RowsChanged() return; } RowCount = count; - _cache?.RowsChanged(); + // New rows follow the data's last row, so they move down as the data grows. + if (_edited is { Edits.AddedRows: > 0 }) + { + _cache?.Clear(); + _layoutVersion++; + InvalidateRows(); + } + else + { + _cache?.RowsChanged(); + } _items.Grow(count); UpdateRowNumberWidth(); UpdateExtent(); @@ -422,7 +448,7 @@ internal CellText Cell(int row, int column) => internal string CellName(int row, int column) { var cell = Cell(row, column); - return cell.IsNull ? CellPainter.NullText : cell.Text.ToString(); + return cell.IsNull ? CellPainter.NullText : cell.IsDefault ? DefaultText : cell.Text.ToString(); } internal void OnDeviceLost() @@ -498,7 +524,10 @@ private unsafe CellPainter CreatePainter() s_device ??= new SurfaceDevice(ElementCompositionPreview.GetElementVisual(this).Compositor, PreferSoftwareRendering); _textScale = _settings.TextScaleFactor; _rowHeight = Math.Ceiling(BaseRowHeight * _textScale); - var painter = new CellPainter(s_device, (float)(BaseFontSize * _textScale), GridColors.Resolve(ActualTheme)); + var painter = new CellPainter(s_device, (float)(BaseFontSize * _textScale), GridColors.Resolve(ActualTheme)) + { + DefaultText = _defaultText, + }; FontWarmupTask = Task.WhenAll( FontWarmup.Start(s_device.DWrite, painter.FamilyName, BaseFontSize, PreferSoftwareRendering), painter.WarmAsync((float)(DefaultColumnWidth - (CellPainter.Padding * 2)), (float)_rowHeight)); @@ -527,6 +556,8 @@ private void OnLoaded(object sender, RoutedEventArgs e) private void OnUnloaded(object sender, RoutedEventArgs e) { + // 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 }) { foreach (var row in rows) diff --git a/windows/src/TablePro.DataGrid/DrawnRow.cs b/windows/src/TablePro.DataGrid/DrawnRow.cs index 036e89dd7d..fd914a90a9 100644 --- a/windows/src/TablePro.DataGrid/DrawnRow.cs +++ b/windows/src/TablePro.DataGrid/DrawnRow.cs @@ -3,6 +3,7 @@ using System.Numerics; using Microsoft.UI.Composition; using Microsoft.UI.Xaml.Hosting; +using TablePro.DataGrid.Model; using TablePro.Graphics; using TerraFX.Interop.DirectX; using Windows.Foundation; @@ -26,6 +27,8 @@ internal sealed unsafe partial class DrawnRow : Microsoft.UI.Xaml.Controls.Grid private int _cellCount; private nint _numberLayout; private int _numberRow = -1; + private bool _numberDeleted; + private bool _washed; private int _layoutVersion = -1; private int _inkVersion = -1; private int _generation = -1; @@ -64,6 +67,9 @@ public DrawnRow(DataGridView grid, bool frozen) public int CellCount => _cellCount; + // A wash covers the selection box beneath the row, so the row draws the selection's tint and follows it. + public bool IsWashed => _washed; + public void SetRow(int row) { if (row != Row) @@ -123,12 +129,14 @@ private void Draw() var device = painter.Device; painter.EnsureBrushes(); var layoutVersion = _grid.LayoutVersion; - var inkVersion = _grid.InkVersion(_frozen); + var inkVersion = _grid.InkVersion(_frozen || _washed); if (Row == DrawnRowIndex && first == DrawnFirst && last == DrawnLast && layoutVersion == _layoutVersion && inkVersion == _inkVersion && _generation == device.Generation) { return; } + var mark = _grid.MarkOf(Row); + _washed = mark != RowMark.None && !painter.Colors.HighContrast; var started = Stopwatch.GetTimestamp(); if (layoutVersion != _layoutVersion || DrawnRowIndex != Row) { @@ -185,18 +193,29 @@ private void Draw() context->SetTextAntialiasMode(D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE); var selection = _grid.SelectionRange; var rowSelected = Row >= selection.FirstRow && Row <= selection.LastRow; + var tinted = _washed && _grid.SelectionBoxShown; if (_frozen) { - DrawRowNumber(context, painter, rowHeight, rowSelected && selection.FirstColumn == 0 && selection.LastColumn == columns.Count - 1); + DrawRowNumber(context, painter, rowHeight, mark, rowSelected && selection.FirstColumn == 0 && selection.LastColumn == columns.Count - 1); } for (var i = 0; i < _cellCount; i++) { ref var cell = ref _cells[i]; var x = (float)(columns.PaneX(cell.Column) - x0); var w = (float)columns.Width(cell.Column); + var selected = rowSelected && cell.Column >= selection.FirstColumn && cell.Column <= selection.LastColumn; + var fill = _washed ? painter.FillBrush(cell.Marks) : null; + if (fill != null) + { + var area = new D2D_RECT_F(x, 0, x + w, rowHeight); + context->FillRectangle(&area, fill); + if (selected && tinted) + { + context->FillRectangle(&area, painter.SelectionBrush); + } + } if (cell.Layout != 0) { - var selected = rowSelected && cell.Column >= selection.FirstColumn && cell.Column <= selection.LastColumn; context->DrawTextLayout(new D2D_POINT_2F(x + CellPainter.Padding, 0), (IDWriteTextLayout*)cell.Layout, painter.InkBrush(cell.Ink, selected), D2D1_DRAW_TEXT_OPTIONS_ENABLE_COLOR_FONT); } @@ -222,28 +241,32 @@ private void Draw() DrawnRowIndex = Row; DrawnFirst = first; DrawnLast = last; - _inkVersion = inkVersion; + _inkVersion = _grid.InkVersion(_frozen || _washed); _generation = device.Generation; _grid.Counters.RowsDrawn++; _grid.Counters.DrawMilliseconds += Stopwatch.GetElapsedTime(started).TotalMilliseconds; } - private void DrawRowNumber(ID2D1DeviceContext* context, CellPainter painter, float rowHeight, bool selected) + private void DrawRowNumber(ID2D1DeviceContext* context, CellPainter painter, float rowHeight, RowMark mark, bool selected) { var width = (float)_grid.Columns.RowHeaderWidth; var back = new D2D_RECT_F(0, 0, width, rowHeight); - context->FillRectangle(&back, painter.HeaderBrush); - if (_numberRow != Row || _numberLayout == 0) + var deleted = mark == RowMark.Deleted; + var fill = painter.FillBrush(deleted ? CellState.Deleted : mark == RowMark.Inserted ? CellState.Inserted : CellState.None); + context->FillRectangle(&back, fill != null ? fill : painter.HeaderBrush); + if (_numberRow != Row || _numberLayout == 0 || _numberDeleted != deleted) { ReleaseNumber(); (Row + 1).TryFormat(_number, out var length, provider: CultureInfo.CurrentCulture); - _numberLayout = (nint)painter.CreateRowNumber(_number.AsSpan(0, length), width - CellPainter.RowNumberPadding * 2, rowHeight); + _numberLayout = (nint)painter.CreateRowNumber(_number.AsSpan(0, length), width - CellPainter.RowNumberPadding * 2, rowHeight, + deleted); _numberRow = Row; + _numberDeleted = deleted; } if (_numberLayout != 0) { context->DrawTextLayout(new D2D_POINT_2F(CellPainter.RowNumberPadding, 0), (IDWriteTextLayout*)_numberLayout, - painter.InkBrush(CellInk.RowNumber, selected), D2D1_DRAW_TEXT_OPTIONS_NONE); + painter.InkBrush(deleted ? CellInk.Deleted : CellInk.RowNumber, selected), D2D1_DRAW_TEXT_OPTIONS_NONE); } var edge = new D2D_RECT_F(width - 1, 0, width, rowHeight); context->FillRectangle(&edge, painter.DividerBrush); @@ -263,6 +286,7 @@ private void AddCell(int column, CellPainter painter, float rowHeight) Column = column, Layout = (nint)layout, Ink = ink, + Marks = cell.State & (CellState.Modified | CellState.Inserted | CellState.Deleted), Hash = string.GetHashCode(cell.Text), Length = cell.Text.Length, }; @@ -332,6 +356,7 @@ private struct CellSlot public int Column; public nint Layout; public CellInk Ink; + public CellState Marks; public int Hash; public int Length; } diff --git a/windows/src/TablePro.DataGrid/GridColors.cs b/windows/src/TablePro.DataGrid/GridColors.cs index 79b9a1388e..d893098947 100644 --- a/windows/src/TablePro.DataGrid/GridColors.cs +++ b/windows/src/TablePro.DataGrid/GridColors.cs @@ -12,10 +12,8 @@ internal sealed record GridColors public Color Text { get; init; } - // NULL cells. public Color Placeholder { get; init; } - // The mark after a value the core cut. public Color CutMark { get; init; } public Color RowNumber { get; init; } @@ -38,6 +36,16 @@ internal sealed record GridColors public Color Focus { get; init; } + public Color DefaultValue { get; init; } + + public Color DeletedText { get; init; } + + public Color ModifiedFill { get; init; } + + public Color InsertedFill { get; init; } + + public Color DeletedFill { get; init; } + public bool HighContrast { get; init; } public static GridColors Resolve(ElementTheme theme) @@ -65,6 +73,8 @@ public static GridColors Resolve(ElementTheme theme) Selection = highlight, SelectedText = ThemeColors.System("SystemColorHighlightTextColor", ThemeColors.FromArgb(0xFF000000u)), Focus = windowText, + DefaultValue = windowText, + DeletedText = windowText, }; } var dark = theme == ElementTheme.Dark; @@ -90,6 +100,14 @@ public static GridColors Resolve(ElementTheme theme) Selection = Color.FromArgb(dark ? (byte)0x55 : (byte)0x3A, accent.R, accent.G, accent.B), SelectedText = text, Focus = Themed("AccentFillColorDefault", 0xFF005FB8u, 0xFF60CDFFu), + // The accent shade AccentTextFillColorPrimary takes, should the key be missing. + DefaultValue = ThemeColors.Theme("AccentTextFillColorPrimary", theme, + ThemeColors.Theme(dark ? "SystemAccentColorLight3" : "SystemAccentColorDark2", theme, + ThemeColors.FromArgb(dark ? 0xFF99EBFFu : 0xFF003E92u))), + DeletedText = Themed("SystemFillColorCritical", 0xFFC42B1Cu, 0xFFFF99A4u), + ModifiedFill = Themed("SystemFillColorCautionBackground", 0xFFFFF4CEu, 0xFF433519u), + InsertedFill = Themed("SystemFillColorSuccessBackground", 0xFFDFF6DDu, 0xFF393D1Bu), + DeletedFill = Themed("SystemFillColorCriticalBackground", 0xFFFDE7E9u, 0xFF442726u), }; } } diff --git a/windows/src/TablePro.Interop/DatabaseSession.cs b/windows/src/TablePro.Interop/DatabaseSession.cs index d0e29f8b9c..0241eba507 100644 --- a/windows/src/TablePro.Interop/DatabaseSession.cs +++ b/windows/src/TablePro.Interop/DatabaseSession.cs @@ -146,6 +146,20 @@ public RunGate GateRun(string sql) // new connection can do; the session keeps its level until then. public bool SetSafeMode(SafeMode level) => _session.SetSafeMode(Mapping.Level(level)); + // A table's rows as a save sees them. Refresh reads the catalog again, as a tab's Refresh does. + public async Task OpenTableEditorAsync( + TableName table, + bool refresh, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(table); + var editor = await CoreCall.RunAsync( + token => _session.TableEditor(Mapping.Table(table), refresh, token), + cancellationToken) + .ConfigureAwait(false); + return new TableEditor(editor); + } + // 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 0eab50fb97..89842843ec 100644 --- a/windows/src/TablePro.Interop/Generated/tablepro_ffi.cs +++ b/windows/src/TablePro.Interop/Generated/tablepro_ffi.cs @@ -1003,6 +1003,32 @@ public struct UniffiVTableCallbackInterfaceRunListener + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -1583,6 +1609,160 @@ public static extern ulong uniffi_tablepro_ffi_fn_method_resultset_sorted(ulong @ptr,uint @column,sbyte @ascending,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 + ulong uniffi_tablepro_ffi_fn_clone_rowsave(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_rowsave(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_rowsave_gate(ulong @ptr,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 + sbyte uniffi_tablepro_ffi_fn_method_rowsave_is_empty(ulong @ptr,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 + ulong uniffi_tablepro_ffi_fn_method_rowsave_run(ulong @ptr,sbyte @confirmed,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 + RustBuffer uniffi_tablepro_ffi_fn_method_rowsave_statements(ulong @ptr,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 + ulong uniffi_tablepro_ffi_fn_clone_tableeditor(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_tableeditor(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_method_tableeditor_check(ulong @ptr,uint @column,RustBuffer @edit,sbyte @newRow,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_tableeditor_columns(ulong @ptr,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_tableeditor_edit_start(ulong @ptr,ulong @rows,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_tableeditor_lock(ulong @ptr,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_tableeditor_lock_for(ulong @ptr,ulong @rows,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 + ulong uniffi_tablepro_ffi_fn_method_tableeditor_plan(ulong @ptr,ulong @rows,RustBuffer @edits,ref UniffiRustCallStatus _uniffi_out_err + ); + #if NET8_0_OR_GREATER [LibraryImport("tablepro_ffi")] [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] @@ -1858,6 +2038,17 @@ public static extern RustBuffer uniffi_tablepro_ffi_fn_method_databasesession_statement_at(ulong @ptr,RustBuffer @sql,uint @caret,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 + ulong uniffi_tablepro_ffi_fn_method_databasesession_table_editor(ulong @ptr,RustBuffer @table,sbyte @refresh,RustBuffer @cancel + ); + #if NET8_0_OR_GREATER [LibraryImport("tablepro_ffi")] [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] @@ -2922,7 +3113,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_queryrun_cancel( + ushort uniffi_tablepro_ffi_checksum_method_rowsave_gate( ); #if NET8_0_OR_GREATER @@ -2933,7 +3124,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_queryrun_drain_events( + ushort uniffi_tablepro_ffi_checksum_method_rowsave_is_empty( ); #if NET8_0_OR_GREATER @@ -2944,7 +3135,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_queryrun_outcome( + ushort uniffi_tablepro_ffi_checksum_method_rowsave_run( ); #if NET8_0_OR_GREATER @@ -2955,7 +3146,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_queryrun_result_set( + ushort uniffi_tablepro_ffi_checksum_method_rowsave_statements( ); #if NET8_0_OR_GREATER @@ -2966,7 +3157,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_close( + ushort uniffi_tablepro_ffi_checksum_method_tableeditor_check( ); #if NET8_0_OR_GREATER @@ -2977,7 +3168,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_columns( + ushort uniffi_tablepro_ffi_checksum_method_tableeditor_columns( ); #if NET8_0_OR_GREATER @@ -2988,7 +3179,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_driver_id( + ushort uniffi_tablepro_ffi_checksum_method_tableeditor_edit_start( ); #if NET8_0_OR_GREATER @@ -2999,7 +3190,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_gate_run( + ushort uniffi_tablepro_ffi_checksum_method_tableeditor_lock( ); #if NET8_0_OR_GREATER @@ -3010,7 +3201,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_health( + ushort uniffi_tablepro_ffi_checksum_method_tableeditor_lock_for( ); #if NET8_0_OR_GREATER @@ -3021,7 +3212,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_health_change( + ushort uniffi_tablepro_ffi_checksum_method_tableeditor_plan( ); #if NET8_0_OR_GREATER @@ -3032,7 +3223,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_id( + ushort uniffi_tablepro_ffi_checksum_method_queryrun_cancel( ); #if NET8_0_OR_GREATER @@ -3043,7 +3234,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_name( + ushort uniffi_tablepro_ffi_checksum_method_queryrun_drain_events( ); #if NET8_0_OR_GREATER @@ -3054,7 +3245,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_objects( + ushort uniffi_tablepro_ffi_checksum_method_queryrun_outcome( ); #if NET8_0_OR_GREATER @@ -3065,7 +3256,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_open_editor( + ushort uniffi_tablepro_ffi_checksum_method_queryrun_result_set( ); #if NET8_0_OR_GREATER @@ -3076,7 +3267,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_read_only( + ushort uniffi_tablepro_ffi_checksum_method_databasesession_close( ); #if NET8_0_OR_GREATER @@ -3087,7 +3278,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_reconnect( + ushort uniffi_tablepro_ffi_checksum_method_databasesession_columns( ); #if NET8_0_OR_GREATER @@ -3098,7 +3289,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_refresh_objects( + ushort uniffi_tablepro_ffi_checksum_method_databasesession_driver_id( ); #if NET8_0_OR_GREATER @@ -3109,7 +3300,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_schemas( + ushort uniffi_tablepro_ffi_checksum_method_databasesession_gate_run( ); #if NET8_0_OR_GREATER @@ -3120,7 +3311,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_set_safe_mode( + ushort uniffi_tablepro_ffi_checksum_method_databasesession_health( ); #if NET8_0_OR_GREATER @@ -3131,7 +3322,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_sorted_query( + ushort uniffi_tablepro_ffi_checksum_method_databasesession_health_change( ); #if NET8_0_OR_GREATER @@ -3142,7 +3333,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_statement_at( + ushort uniffi_tablepro_ffi_checksum_method_databasesession_id( ); #if NET8_0_OR_GREATER @@ -3153,7 +3344,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_table_query( + ushort uniffi_tablepro_ffi_checksum_method_databasesession_name( ); #if NET8_0_OR_GREATER @@ -3164,7 +3355,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_table_row_count( + ushort uniffi_tablepro_ffi_checksum_method_databasesession_objects( ); #if NET8_0_OR_GREATER @@ -3175,7 +3366,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_constructor_canceltoken_new( + ushort uniffi_tablepro_ffi_checksum_method_databasesession_open_editor( ); #if NET8_0_OR_GREATER @@ -3186,7 +3377,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_constructor_core_new( + ushort uniffi_tablepro_ffi_checksum_method_databasesession_read_only( ); #if NET8_0_OR_GREATER @@ -3197,7 +3388,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_constructor_core_with_system_secrets( + ushort uniffi_tablepro_ffi_checksum_method_databasesession_reconnect( ); #if NET8_0_OR_GREATER @@ -3208,7 +3399,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_hostsecrets_load( + ushort uniffi_tablepro_ffi_checksum_method_databasesession_refresh_objects( ); #if NET8_0_OR_GREATER @@ -3219,7 +3410,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_hostsecrets_store( + ushort uniffi_tablepro_ffi_checksum_method_databasesession_schemas( ); #if NET8_0_OR_GREATER @@ -3230,7 +3421,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_hostsecrets_relabel( + ushort uniffi_tablepro_ffi_checksum_method_databasesession_set_safe_mode( ); #if NET8_0_OR_GREATER @@ -3241,7 +3432,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_hostsecrets_delete( + ushort uniffi_tablepro_ffi_checksum_method_databasesession_sorted_query( ); #if NET8_0_OR_GREATER @@ -3252,7 +3443,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_hostsecrets_delete_connection( + ushort uniffi_tablepro_ffi_checksum_method_databasesession_statement_at( ); #if NET8_0_OR_GREATER @@ -3263,7 +3454,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_hostsecrets_load_item( + ushort uniffi_tablepro_ffi_checksum_method_databasesession_table_editor( ); #if NET8_0_OR_GREATER @@ -3274,7 +3465,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_hostsecrets_store_item( + ushort uniffi_tablepro_ffi_checksum_method_databasesession_table_query( ); #if NET8_0_OR_GREATER @@ -3285,7 +3476,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_hostsecrets_delete_item( + ushort uniffi_tablepro_ffi_checksum_method_databasesession_table_row_count( ); #if NET8_0_OR_GREATER @@ -3296,7 +3487,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_hostprompter_prompt( + ushort uniffi_tablepro_ffi_checksum_constructor_canceltoken_new( ); #if NET8_0_OR_GREATER @@ -3307,7 +3498,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_runlistener_events_pending( + ushort uniffi_tablepro_ffi_checksum_constructor_core_new( ); #if NET8_0_OR_GREATER @@ -3318,17 +3509,138 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - uint ffi_tablepro_ffi_uniffi_contract_version( + ushort uniffi_tablepro_ffi_checksum_constructor_core_with_system_secrets( ); - + #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_hostsecrets_load( + ); - static void uniffiCheckContractApiVersion() { - var scaffolding_contract_version = _UniFFILib.ffi_tablepro_ffi_uniffi_contract_version(); - if (30 != scaffolding_contract_version) { - throw new UniffiContractVersionException($"TablePro.Interop.Native: uniffi bindings expected version `30`, library returned `{scaffolding_contract_version}`"); - } - } + #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_hostsecrets_store( + ); + + #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_hostsecrets_relabel( + ); + + #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_hostsecrets_delete( + ); + + #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_hostsecrets_delete_connection( + ); + + #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_hostsecrets_load_item( + ); + + #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_hostsecrets_store_item( + ); + + #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_hostsecrets_delete_item( + ); + + #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_hostprompter_prompt( + ); + + #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_runlistener_events_pending( + ); + + #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 + uint ffi_tablepro_ffi_uniffi_contract_version( + ); + + + + static void uniffiCheckContractApiVersion() { + var scaffolding_contract_version = _UniFFILib.ffi_tablepro_ffi_uniffi_contract_version(); + if (30 != scaffolding_contract_version) { + throw new UniffiContractVersionException($"TablePro.Interop.Native: uniffi bindings expected version `30`, library returned `{scaffolding_contract_version}`"); + } + } static void uniffiCheckApiChecksums() { { var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_func_parse_connection_url(); @@ -3558,6 +3870,66 @@ static void uniffiCheckApiChecksums() { throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_resultset_sorted` checksum `38864`, library returned `{checksum}`"); } } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_rowsave_gate(); + if (checksum != 38215) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_rowsave_gate` checksum `38215`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_rowsave_is_empty(); + if (checksum != 11321) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_rowsave_is_empty` checksum `11321`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_rowsave_run(); + if (checksum != 30258) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_rowsave_run` checksum `30258`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_rowsave_statements(); + if (checksum != 596) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_rowsave_statements` checksum `596`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_tableeditor_check(); + if (checksum != 19847) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_tableeditor_check` checksum `19847`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_tableeditor_columns(); + if (checksum != 6588) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_tableeditor_columns` checksum `6588`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_tableeditor_edit_start(); + if (checksum != 21277) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_tableeditor_edit_start` checksum `21277`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_tableeditor_lock(); + if (checksum != 43387) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_tableeditor_lock` checksum `43387`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_tableeditor_lock_for(); + if (checksum != 43908) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_tableeditor_lock_for` checksum `43908`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_tableeditor_plan(); + if (checksum != 7349) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_tableeditor_plan` checksum `7349`, library returned `{checksum}`"); + } + } { var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_queryrun_cancel(); if (checksum != 58442) { @@ -3684,6 +4056,12 @@ static void uniffiCheckApiChecksums() { throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_databasesession_statement_at` checksum `63657`, library returned `{checksum}`"); } } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_databasesession_table_editor(); + if (checksum != 1990) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_databasesession_table_editor` checksum `1990`, library returned `{checksum}`"); + } + } { var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_databasesession_table_query(); if (checksum != 23159) { @@ -4933,6 +5311,8 @@ internal interface IDatabaseSession { string? SortedQuery(string @sql, string[] @columns, uint @column, bool @ascending); StatementSpan? StatementAt(string @sql, uint @caret); /// + Task TableEditor(TableName @table, bool @refresh, CancelToken? @cancel); + /// Task TableQuery(TableName @table, ColumnSort? @sort, ulong @limit, ulong @offset, CancelToken? @cancel); /// Task TableRowCount(TableName @table, CancelToken? @cancel); @@ -5258,6 +5638,28 @@ public bool SetSafeMode(SafeModeTag @level) { } + /// + public async Task TableEditor(TableName @table, bool @refresh, CancelToken? @cancel) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_table_editor(thisPtr, FfiConverterTypeTableName.INSTANCE.Lower(@table), FfiConverterBoolean.INSTANCE.Lower(@refresh), 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) => FfiConverterTypeTableEditor.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + /// public async Task TableQuery(TableName @table, ColumnSort? @sort, ulong @limit, ulong @offset, CancelToken? @cancel) { return await _UniFFIAsync.UniffiRustCallAsync( @@ -5914,62 +6316,446 @@ public override void Write(ResultSet value, BigEndianStream stream) { -internal record CloudConnectionFields ( - string ConnectionId, - string? Name, - string? GroupId, - long? SortOrder, - long? IsFavorite -) { +internal interface IRowSave { + SaveGate Gate(); + bool IsEmpty(); + /// + Task Run(bool @confirmed, CancelToken? @cancel); + PlannedStatement[] Statements(); } +internal class RowSave : IRowSave, IDisposable { + protected ulong pointer; + private int _wasDestroyed = 0; + private long _callCounter = 1; -class FfiConverterTypeCloudConnectionFields: FfiConverterRustBuffer { - public static FfiConverterTypeCloudConnectionFields INSTANCE = new FfiConverterTypeCloudConnectionFields(); + public RowSave(ulong pointer) { + this.pointer = pointer; + } - public override CloudConnectionFields Read(BigEndianStream stream) { - return new CloudConnectionFields( - ConnectionId: FfiConverterString.INSTANCE.Read(stream), - Name: FfiConverterOptionalString.INSTANCE.Read(stream), - GroupId: FfiConverterOptionalString.INSTANCE.Read(stream), - SortOrder: FfiConverterOptionalInt64.INSTANCE.Read(stream), - IsFavorite: FfiConverterOptionalInt64.INSTANCE.Read(stream) - ); + ~RowSave() { + Destroy(); } - public override int AllocationSize(CloudConnectionFields value) { - return 0 - + FfiConverterString.INSTANCE.AllocationSize(value.ConnectionId) - + FfiConverterOptionalString.INSTANCE.AllocationSize(value.Name) - + FfiConverterOptionalString.INSTANCE.AllocationSize(value.GroupId) - + FfiConverterOptionalInt64.INSTANCE.AllocationSize(value.SortOrder) - + FfiConverterOptionalInt64.INSTANCE.AllocationSize(value.IsFavorite); + protected void FreeRustArcPtr() { + _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { + _UniFFILib.uniffi_tablepro_ffi_fn_free_rowsave(this.pointer, ref status); + }); } - public override void Write(CloudConnectionFields value, BigEndianStream stream) { - FfiConverterString.INSTANCE.Write(value.ConnectionId, stream); - FfiConverterOptionalString.INSTANCE.Write(value.Name, stream); - FfiConverterOptionalString.INSTANCE.Write(value.GroupId, stream); - FfiConverterOptionalInt64.INSTANCE.Write(value.SortOrder, stream); - FfiConverterOptionalInt64.INSTANCE.Write(value.IsFavorite, stream); + protected ulong CloneRustArcPtr() { + return _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { + return _UniFFILib.uniffi_tablepro_ffi_fn_clone_rowsave(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. + } -internal record CloudGroupFields ( - string GroupId, - string? Name, - string? Color, - string? IconName, - string? ParentId, - long? SortOrder -) { -} + 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)); -class FfiConverterTypeCloudGroupFields: FfiConverterRustBuffer { - public static FfiConverterTypeCloudGroupFields INSTANCE = new FfiConverterTypeCloudGroupFields(); + } while (Interlocked.CompareExchange(ref _callCounter, count + 1, count) != count); + } - public override CloudGroupFields Read(BigEndianStream stream) { + 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 SaveGate Gate() { + return CallWithPointer(thisPtr => FfiConverterTypeSaveGate.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_rowsave_gate(thisPtr, ref _status) +))); + } + + + public bool IsEmpty() { + return CallWithPointer(thisPtr => FfiConverterBoolean.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_rowsave_is_empty(thisPtr, ref _status) +))); + } + + + /// + public async Task Run(bool @confirmed, CancelToken? @cancel) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_rowsave_run(thisPtr, FfiConverterBoolean.INSTANCE.Lower(@confirmed), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + // Lift + (result) => FfiConverterTypeRowSaveOutcome.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + public PlannedStatement[] Statements() { + return CallWithPointer(thisPtr => FfiConverterSequenceTypePlannedStatement.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_rowsave_statements(thisPtr, ref _status) +))); + } + + + + +} +class FfiConverterTypeRowSave: FfiConverter { + public static FfiConverterTypeRowSave INSTANCE = new FfiConverterTypeRowSave(); + + + public override ulong Lower(RowSave value) { + return value.CallWithPointer(thisPtr => thisPtr); + } + + public override RowSave Lift(ulong value) { + return new RowSave(value); + } + + public override RowSave Read(BigEndianStream stream) { + return Lift(stream.ReadULong()); + } + + public override int AllocationSize(RowSave value) { + return 8; + } + + public override void Write(RowSave value, BigEndianStream stream) { + stream.WriteULong(Lower(value)); + } +} + + + +internal interface ITableEditor { + /// + void Check(uint @column, CellEdit @edit, bool @newRow); + EditColumnInfo[] Columns(); + /// + EditStart EditStart(ResultSet @rows, ulong @row, uint @column); + EditLock? Lock(); + EditLock? LockFor(ResultSet @rows); + /// + RowSave Plan(ResultSet @rows, RowEdit[] @edits); +} +internal class TableEditor : ITableEditor, IDisposable { + protected ulong pointer; + private int _wasDestroyed = 0; + private long _callCounter = 1; + + public TableEditor(ulong pointer) { + this.pointer = pointer; + } + + ~TableEditor() { + Destroy(); + } + + protected void FreeRustArcPtr() { + _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { + _UniFFILib.uniffi_tablepro_ffi_fn_free_tableeditor(this.pointer, ref status); + }); + } + + protected ulong CloneRustArcPtr() { + return _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { + return _UniFFILib.uniffi_tablepro_ffi_fn_clone_tableeditor(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 void Check(uint @column, CellEdit @edit, bool @newRow) { + CallWithPointer(thisPtr => + _UniffiHelpers.RustCallWithError(FfiConverterTypeCoreError.INSTANCE, (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_tableeditor_check(thisPtr, FfiConverterUInt32.INSTANCE.Lower(@column), FfiConverterTypeCellEdit.INSTANCE.Lower(@edit), FfiConverterBoolean.INSTANCE.Lower(@newRow), ref _status) +)); + } + + + + public EditColumnInfo[] Columns() { + return CallWithPointer(thisPtr => FfiConverterSequenceTypeEditColumnInfo.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_tableeditor_columns(thisPtr, ref _status) +))); + } + + + /// + public EditStart EditStart(ResultSet @rows, ulong @row, uint @column) { + return CallWithPointer(thisPtr => FfiConverterTypeEditStart.INSTANCE.Lift( + _UniffiHelpers.RustCallWithError(FfiConverterTypeCoreError.INSTANCE, (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_tableeditor_edit_start(thisPtr, FfiConverterTypeResultSet.INSTANCE.Lower(@rows), FfiConverterUInt64.INSTANCE.Lower(@row), FfiConverterUInt32.INSTANCE.Lower(@column), ref _status) +))); + } + + + public EditLock? Lock() { + return CallWithPointer(thisPtr => FfiConverterOptionalTypeEditLock.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_tableeditor_lock(thisPtr, ref _status) +))); + } + + + public EditLock? LockFor(ResultSet @rows) { + return CallWithPointer(thisPtr => FfiConverterOptionalTypeEditLock.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_tableeditor_lock_for(thisPtr, FfiConverterTypeResultSet.INSTANCE.Lower(@rows), ref _status) +))); + } + + + /// + 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 record CellChange ( + uint Column, + CellEdit Edit +) { +} + +class FfiConverterTypeCellChange: FfiConverterRustBuffer { + public static FfiConverterTypeCellChange INSTANCE = new FfiConverterTypeCellChange(); + + public override CellChange Read(BigEndianStream stream) { + return new CellChange( + Column: FfiConverterUInt32.INSTANCE.Read(stream), + Edit: FfiConverterTypeCellEdit.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(CellChange value) { + return 0 + + FfiConverterUInt32.INSTANCE.AllocationSize(value.Column) + + FfiConverterTypeCellEdit.INSTANCE.AllocationSize(value.Edit); + } + + public override void Write(CellChange value, BigEndianStream stream) { + FfiConverterUInt32.INSTANCE.Write(value.Column, stream); + FfiConverterTypeCellEdit.INSTANCE.Write(value.Edit, stream); + } +} + + + +internal record CloudConnectionFields ( + string ConnectionId, + string? Name, + string? GroupId, + long? SortOrder, + long? IsFavorite +) { +} + +class FfiConverterTypeCloudConnectionFields: FfiConverterRustBuffer { + public static FfiConverterTypeCloudConnectionFields INSTANCE = new FfiConverterTypeCloudConnectionFields(); + + public override CloudConnectionFields Read(BigEndianStream stream) { + return new CloudConnectionFields( + ConnectionId: FfiConverterString.INSTANCE.Read(stream), + Name: FfiConverterOptionalString.INSTANCE.Read(stream), + GroupId: FfiConverterOptionalString.INSTANCE.Read(stream), + SortOrder: FfiConverterOptionalInt64.INSTANCE.Read(stream), + IsFavorite: FfiConverterOptionalInt64.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(CloudConnectionFields value) { + return 0 + + FfiConverterString.INSTANCE.AllocationSize(value.ConnectionId) + + FfiConverterOptionalString.INSTANCE.AllocationSize(value.Name) + + FfiConverterOptionalString.INSTANCE.AllocationSize(value.GroupId) + + FfiConverterOptionalInt64.INSTANCE.AllocationSize(value.SortOrder) + + FfiConverterOptionalInt64.INSTANCE.AllocationSize(value.IsFavorite); + } + + public override void Write(CloudConnectionFields value, BigEndianStream stream) { + FfiConverterString.INSTANCE.Write(value.ConnectionId, stream); + FfiConverterOptionalString.INSTANCE.Write(value.Name, stream); + FfiConverterOptionalString.INSTANCE.Write(value.GroupId, stream); + FfiConverterOptionalInt64.INSTANCE.Write(value.SortOrder, stream); + FfiConverterOptionalInt64.INSTANCE.Write(value.IsFavorite, stream); + } +} + + + +internal record CloudGroupFields ( + string GroupId, + string? Name, + string? Color, + string? IconName, + string? ParentId, + long? SortOrder +) { +} + +class FfiConverterTypeCloudGroupFields: FfiConverterRustBuffer { + public static FfiConverterTypeCloudGroupFields INSTANCE = new FfiConverterTypeCloudGroupFields(); + + public override CloudGroupFields Read(BigEndianStream stream) { return new CloudGroupFields( GroupId: FfiConverterString.INSTANCE.Read(stream), Name: FfiConverterOptionalString.INSTANCE.Read(stream), @@ -6361,6 +7147,60 @@ public override void Write(DriverInfo value, BigEndianStream stream) { +internal record EditColumnInfo ( + string Name, + bool Editable, + bool EditableInNewRow, + CellEdit NewRow, + bool Nullable, + bool PrimaryKey, + bool TakesEmpty, + bool TakesDefault +) { +} + +class FfiConverterTypeEditColumnInfo: FfiConverterRustBuffer { + public static FfiConverterTypeEditColumnInfo INSTANCE = new FfiConverterTypeEditColumnInfo(); + + public override EditColumnInfo Read(BigEndianStream stream) { + return new EditColumnInfo( + Name: FfiConverterString.INSTANCE.Read(stream), + Editable: FfiConverterBoolean.INSTANCE.Read(stream), + EditableInNewRow: FfiConverterBoolean.INSTANCE.Read(stream), + NewRow: FfiConverterTypeCellEdit.INSTANCE.Read(stream), + Nullable: FfiConverterBoolean.INSTANCE.Read(stream), + PrimaryKey: FfiConverterBoolean.INSTANCE.Read(stream), + TakesEmpty: FfiConverterBoolean.INSTANCE.Read(stream), + TakesDefault: FfiConverterBoolean.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(EditColumnInfo value) { + return 0 + + FfiConverterString.INSTANCE.AllocationSize(value.Name) + + FfiConverterBoolean.INSTANCE.AllocationSize(value.Editable) + + FfiConverterBoolean.INSTANCE.AllocationSize(value.EditableInNewRow) + + FfiConverterTypeCellEdit.INSTANCE.AllocationSize(value.NewRow) + + FfiConverterBoolean.INSTANCE.AllocationSize(value.Nullable) + + FfiConverterBoolean.INSTANCE.AllocationSize(value.PrimaryKey) + + FfiConverterBoolean.INSTANCE.AllocationSize(value.TakesEmpty) + + FfiConverterBoolean.INSTANCE.AllocationSize(value.TakesDefault); + } + + public override void Write(EditColumnInfo value, BigEndianStream stream) { + FfiConverterString.INSTANCE.Write(value.Name, stream); + FfiConverterBoolean.INSTANCE.Write(value.Editable, stream); + FfiConverterBoolean.INSTANCE.Write(value.EditableInNewRow, stream); + FfiConverterTypeCellEdit.INSTANCE.Write(value.NewRow, stream); + FfiConverterBoolean.INSTANCE.Write(value.Nullable, stream); + FfiConverterBoolean.INSTANCE.Write(value.PrimaryKey, stream); + FfiConverterBoolean.INSTANCE.Write(value.TakesEmpty, stream); + FfiConverterBoolean.INSTANCE.Write(value.TakesDefault, stream); + } +} + + + /// /// An error as the app words it: by `code`, the innermost of `codes`, /// which run from the outermost error in. `message` is English for the @@ -6810,6 +7650,36 @@ public override void Write(ParsedConnectionUrl value, BigEndianStream stream) { +internal record PlannedStatement ( + string Sql, + string[] Values +) { +} + +class FfiConverterTypePlannedStatement: FfiConverterRustBuffer { + public static FfiConverterTypePlannedStatement INSTANCE = new FfiConverterTypePlannedStatement(); + + public override PlannedStatement Read(BigEndianStream stream) { + return new PlannedStatement( + Sql: FfiConverterString.INSTANCE.Read(stream), + Values: FfiConverterSequenceString.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(PlannedStatement value) { + return 0 + + FfiConverterString.INSTANCE.AllocationSize(value.Sql) + + FfiConverterSequenceString.INSTANCE.AllocationSize(value.Values); + } + + public override void Write(PlannedStatement value, BigEndianStream stream) { + FfiConverterString.INSTANCE.Write(value.Sql, stream); + FfiConverterSequenceString.INSTANCE.Write(value.Values, stream); + } +} + + + internal record PromptFieldInfo ( string Label, bool Secret @@ -7256,21 +8126,94 @@ public override TlsSettings Read(BigEndianStream stream) { ); } - public override int AllocationSize(TlsSettings value) { - return 0 - + FfiConverterTypeTlsModeTag.INSTANCE.AllocationSize(value.Mode) - + FfiConverterOptionalString.INSTANCE.AllocationSize(value.CaFile) - + FfiConverterOptionalString.INSTANCE.AllocationSize(value.ClientCertificate) - + FfiConverterOptionalString.INSTANCE.AllocationSize(value.ClientKey) - + FfiConverterOptionalString.INSTANCE.AllocationSize(value.ServerName); + public override int AllocationSize(TlsSettings value) { + return 0 + + FfiConverterTypeTlsModeTag.INSTANCE.AllocationSize(value.Mode) + + FfiConverterOptionalString.INSTANCE.AllocationSize(value.CaFile) + + FfiConverterOptionalString.INSTANCE.AllocationSize(value.ClientCertificate) + + FfiConverterOptionalString.INSTANCE.AllocationSize(value.ClientKey) + + FfiConverterOptionalString.INSTANCE.AllocationSize(value.ServerName); + } + + public override void Write(TlsSettings value, BigEndianStream stream) { + FfiConverterTypeTlsModeTag.INSTANCE.Write(value.Mode, stream); + FfiConverterOptionalString.INSTANCE.Write(value.CaFile, stream); + FfiConverterOptionalString.INSTANCE.Write(value.ClientCertificate, stream); + FfiConverterOptionalString.INSTANCE.Write(value.ClientKey, stream); + FfiConverterOptionalString.INSTANCE.Write(value.ServerName, stream); + } +} + + + + + +internal record CellEdit { + + public record Text ( + string TextValue + ) : CellEdit {} + + public record Null: CellEdit {} + + + public record Default: CellEdit {} + + + + +} + +class FfiConverterTypeCellEdit : FfiConverterRustBuffer{ + public static FfiConverterRustBuffer INSTANCE = new FfiConverterTypeCellEdit(); + + public override CellEdit Read(BigEndianStream stream) { + var value = stream.ReadInt(); + switch (value) { + case 1: + return new CellEdit.Text( + FfiConverterString.INSTANCE.Read(stream) + ); + case 2: + return new CellEdit.Null( + ); + case 3: + return new CellEdit.Default( + ); + default: + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeCellEdit.Read()", value)); + } + } + + public override int AllocationSize(CellEdit value) { + switch (value) { + case CellEdit.Text variant_value: + return 4 + + FfiConverterString.INSTANCE.AllocationSize(variant_value.TextValue); + case CellEdit.Null variant_value: + return 4; + case CellEdit.Default variant_value: + return 4; + default: + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeCellEdit.AllocationSize()", value)); + } } - public override void Write(TlsSettings value, BigEndianStream stream) { - FfiConverterTypeTlsModeTag.INSTANCE.Write(value.Mode, stream); - FfiConverterOptionalString.INSTANCE.Write(value.CaFile, stream); - FfiConverterOptionalString.INSTANCE.Write(value.ClientCertificate, stream); - FfiConverterOptionalString.INSTANCE.Write(value.ClientKey, stream); - FfiConverterOptionalString.INSTANCE.Write(value.ServerName, stream); + public override void Write(CellEdit value, BigEndianStream stream) { + switch (value) { + case CellEdit.Text variant_value: + stream.WriteInt(1); + FfiConverterString.INSTANCE.Write(variant_value.TextValue, stream); + break; + case CellEdit.Null variant_value: + stream.WriteInt(2); + break; + case CellEdit.Default variant_value: + stream.WriteInt(3); + break; + default: + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeCellEdit.Write()", value)); + } } } @@ -7278,6 +8221,8 @@ public override void Write(TlsSettings value, BigEndianStream stream) { + + /// /// Why a call produced no value. A cancel is its own variant, so a /// binding can turn it into its language's cancellation. @@ -7399,6 +8344,160 @@ public override void Write(DataModelTag value, BigEndianStream stream) { +internal record EditLock { + + public record ReadOnlyConnection: EditLock {} + + + public record NoPrimaryKey: EditLock {} + + + public record KeyUnreadable ( + string Column + ) : EditLock {} + + public record ColumnsChanged: EditLock {} + + + + +} + +class FfiConverterTypeEditLock : FfiConverterRustBuffer{ + public static FfiConverterRustBuffer INSTANCE = new FfiConverterTypeEditLock(); + + public override EditLock Read(BigEndianStream stream) { + var value = stream.ReadInt(); + switch (value) { + case 1: + return new EditLock.ReadOnlyConnection( + ); + case 2: + return new EditLock.NoPrimaryKey( + ); + case 3: + return new EditLock.KeyUnreadable( + FfiConverterString.INSTANCE.Read(stream) + ); + case 4: + return new EditLock.ColumnsChanged( + ); + default: + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeEditLock.Read()", value)); + } + } + + public override int AllocationSize(EditLock value) { + switch (value) { + case EditLock.ReadOnlyConnection variant_value: + return 4; + case EditLock.NoPrimaryKey variant_value: + return 4; + case EditLock.KeyUnreadable variant_value: + return 4 + + FfiConverterString.INSTANCE.AllocationSize(variant_value.Column); + case EditLock.ColumnsChanged variant_value: + return 4; + default: + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeEditLock.AllocationSize()", value)); + } + } + + public override void Write(EditLock value, BigEndianStream stream) { + switch (value) { + case EditLock.ReadOnlyConnection variant_value: + stream.WriteInt(1); + break; + case EditLock.NoPrimaryKey variant_value: + stream.WriteInt(2); + break; + case EditLock.KeyUnreadable variant_value: + stream.WriteInt(3); + FfiConverterString.INSTANCE.Write(variant_value.Column, stream); + break; + case EditLock.ColumnsChanged variant_value: + stream.WriteInt(4); + break; + default: + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeEditLock.Write()", value)); + } + } +} + + + + + + + +internal record EditStart { + + public record Editable ( + string Text, + bool IsNull + ) : EditStart {} + + public record ReadOnly: EditStart {} + + + + +} + +class FfiConverterTypeEditStart : FfiConverterRustBuffer{ + public static FfiConverterRustBuffer INSTANCE = new FfiConverterTypeEditStart(); + + public override EditStart Read(BigEndianStream stream) { + var value = stream.ReadInt(); + switch (value) { + case 1: + return new EditStart.Editable( + FfiConverterString.INSTANCE.Read(stream), + FfiConverterBoolean.INSTANCE.Read(stream) + ); + case 2: + return new EditStart.ReadOnly( + ); + default: + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeEditStart.Read()", value)); + } + } + + public override int AllocationSize(EditStart value) { + switch (value) { + case EditStart.Editable variant_value: + return 4 + + FfiConverterString.INSTANCE.AllocationSize(variant_value.Text) + + FfiConverterBoolean.INSTANCE.AllocationSize(variant_value.IsNull); + case EditStart.ReadOnly variant_value: + return 4; + default: + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeEditStart.AllocationSize()", value)); + } + } + + public override void Write(EditStart value, BigEndianStream stream) { + switch (value) { + case EditStart.Editable variant_value: + stream.WriteInt(1); + FfiConverterString.INSTANCE.Write(variant_value.Text, stream); + FfiConverterBoolean.INSTANCE.Write(variant_value.IsNull, stream); + break; + case EditStart.ReadOnly variant_value: + stream.WriteInt(2); + break; + default: + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeEditStart.Write()", value)); + } + } +} + + + + + + + internal record EndpointInfo { public record Network ( @@ -8072,47 +9171,225 @@ public override PromptReasonTag Read(BigEndianStream stream) { return new PromptReasonTag.KeyringUnavailable( FfiConverterString.INSTANCE.Read(stream) ); - case 4: - return new PromptReasonTag.Rejected( + case 4: + return new PromptReasonTag.Rejected( + ); + default: + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypePromptReasonTag.Read()", value)); + } + } + + public override int AllocationSize(PromptReasonTag value) { + switch (value) { + case PromptReasonTag.NotStored variant_value: + return 4; + case PromptReasonTag.KeyringLocked variant_value: + return 4; + case PromptReasonTag.KeyringUnavailable variant_value: + return 4 + + FfiConverterString.INSTANCE.AllocationSize(variant_value.Detail); + case PromptReasonTag.Rejected variant_value: + return 4; + default: + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypePromptReasonTag.AllocationSize()", value)); + } + } + + public override void Write(PromptReasonTag value, BigEndianStream stream) { + switch (value) { + case PromptReasonTag.NotStored variant_value: + stream.WriteInt(1); + break; + case PromptReasonTag.KeyringLocked variant_value: + stream.WriteInt(2); + break; + case PromptReasonTag.KeyringUnavailable variant_value: + stream.WriteInt(3); + FfiConverterString.INSTANCE.Write(variant_value.Detail, stream); + break; + case PromptReasonTag.Rejected variant_value: + stream.WriteInt(4); + break; + default: + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypePromptReasonTag.Write()", value)); + } + } +} + + + + + + + +internal record RowEdit { + + public record Update ( + ulong Row, + CellChange[] Cells + ) : RowEdit {} + + public record Insert ( + CellEdit[] Cells + ) : RowEdit {} + + public record Delete ( + ulong Row + ) : RowEdit {} + + + +} + +class FfiConverterTypeRowEdit : FfiConverterRustBuffer{ + public static FfiConverterRustBuffer INSTANCE = new FfiConverterTypeRowEdit(); + + public override RowEdit Read(BigEndianStream stream) { + var value = stream.ReadInt(); + switch (value) { + case 1: + return new RowEdit.Update( + FfiConverterUInt64.INSTANCE.Read(stream), + FfiConverterSequenceTypeCellChange.INSTANCE.Read(stream) + ); + case 2: + return new RowEdit.Insert( + FfiConverterSequenceTypeCellEdit.INSTANCE.Read(stream) + ); + case 3: + return new RowEdit.Delete( + FfiConverterUInt64.INSTANCE.Read(stream) + ); + default: + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeRowEdit.Read()", value)); + } + } + + public override int AllocationSize(RowEdit value) { + switch (value) { + case RowEdit.Update variant_value: + return 4 + + FfiConverterUInt64.INSTANCE.AllocationSize(variant_value.Row) + + FfiConverterSequenceTypeCellChange.INSTANCE.AllocationSize(variant_value.Cells); + case RowEdit.Insert variant_value: + return 4 + + FfiConverterSequenceTypeCellEdit.INSTANCE.AllocationSize(variant_value.Cells); + case RowEdit.Delete variant_value: + return 4 + + FfiConverterUInt64.INSTANCE.AllocationSize(variant_value.Row); + default: + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeRowEdit.AllocationSize()", value)); + } + } + + public override void Write(RowEdit value, BigEndianStream stream) { + switch (value) { + case RowEdit.Update variant_value: + stream.WriteInt(1); + FfiConverterUInt64.INSTANCE.Write(variant_value.Row, stream); + FfiConverterSequenceTypeCellChange.INSTANCE.Write(variant_value.Cells, stream); + break; + case RowEdit.Insert variant_value: + stream.WriteInt(2); + FfiConverterSequenceTypeCellEdit.INSTANCE.Write(variant_value.Cells, stream); + break; + case RowEdit.Delete variant_value: + stream.WriteInt(3); + FfiConverterUInt64.INSTANCE.Write(variant_value.Row, stream); + break; + default: + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeRowEdit.Write()", value)); + } + } +} + + + + + + + +internal record RowSaveOutcome { + + public record Saved ( + ulong? Rows + ) : RowSaveOutcome {} + + public record RolledBack ( + BoxedErrorInfo Error, + uint? Edit + ) : RowSaveOutcome {} + + public record Unknown ( + BoxedErrorInfo Error, + uint? Edit + ) : RowSaveOutcome {} + + + +} + +class FfiConverterTypeRowSaveOutcome : FfiConverterRustBuffer{ + public static FfiConverterRustBuffer INSTANCE = new FfiConverterTypeRowSaveOutcome(); + + public override RowSaveOutcome Read(BigEndianStream stream) { + var value = stream.ReadInt(); + switch (value) { + case 1: + return new RowSaveOutcome.Saved( + FfiConverterOptionalUInt64.INSTANCE.Read(stream) + ); + case 2: + return new RowSaveOutcome.RolledBack( + FfiConverterTypeBoxedErrorInfo.INSTANCE.Read(stream), + FfiConverterOptionalUInt32.INSTANCE.Read(stream) + ); + case 3: + return new RowSaveOutcome.Unknown( + FfiConverterTypeBoxedErrorInfo.INSTANCE.Read(stream), + FfiConverterOptionalUInt32.INSTANCE.Read(stream) ); default: - throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypePromptReasonTag.Read()", value)); + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeRowSaveOutcome.Read()", value)); } } - public override int AllocationSize(PromptReasonTag value) { + public override int AllocationSize(RowSaveOutcome value) { switch (value) { - case PromptReasonTag.NotStored variant_value: - return 4; - case PromptReasonTag.KeyringLocked variant_value: - return 4; - case PromptReasonTag.KeyringUnavailable variant_value: + case RowSaveOutcome.Saved variant_value: return 4 - + FfiConverterString.INSTANCE.AllocationSize(variant_value.Detail); - case PromptReasonTag.Rejected variant_value: - return 4; + + FfiConverterOptionalUInt64.INSTANCE.AllocationSize(variant_value.Rows); + case RowSaveOutcome.RolledBack variant_value: + return 4 + + FfiConverterTypeBoxedErrorInfo.INSTANCE.AllocationSize(variant_value.Error) + + FfiConverterOptionalUInt32.INSTANCE.AllocationSize(variant_value.Edit); + case RowSaveOutcome.Unknown variant_value: + return 4 + + FfiConverterTypeBoxedErrorInfo.INSTANCE.AllocationSize(variant_value.Error) + + FfiConverterOptionalUInt32.INSTANCE.AllocationSize(variant_value.Edit); default: - throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypePromptReasonTag.AllocationSize()", value)); + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeRowSaveOutcome.AllocationSize()", value)); } } - public override void Write(PromptReasonTag value, BigEndianStream stream) { + public override void Write(RowSaveOutcome value, BigEndianStream stream) { switch (value) { - case PromptReasonTag.NotStored variant_value: + case RowSaveOutcome.Saved variant_value: stream.WriteInt(1); + FfiConverterOptionalUInt64.INSTANCE.Write(variant_value.Rows, stream); break; - case PromptReasonTag.KeyringLocked variant_value: + case RowSaveOutcome.RolledBack variant_value: stream.WriteInt(2); + FfiConverterTypeBoxedErrorInfo.INSTANCE.Write(variant_value.Error, stream); + FfiConverterOptionalUInt32.INSTANCE.Write(variant_value.Edit, stream); break; - case PromptReasonTag.KeyringUnavailable variant_value: + case RowSaveOutcome.Unknown variant_value: stream.WriteInt(3); - FfiConverterString.INSTANCE.Write(variant_value.Detail, stream); - break; - case PromptReasonTag.Rejected variant_value: - stream.WriteInt(4); + FfiConverterTypeBoxedErrorInfo.INSTANCE.Write(variant_value.Error, stream); + FfiConverterOptionalUInt32.INSTANCE.Write(variant_value.Edit, stream); break; default: - throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypePromptReasonTag.Write()", value)); + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeRowSaveOutcome.Write()", value)); } } } @@ -8493,6 +9770,45 @@ public override void Write(SafeModeTag value, BigEndianStream stream) { +internal enum SaveGate: int { + Run, + Confirm, + Refuse +} + +class FfiConverterTypeSaveGate: FfiConverterRustBuffer { + public static FfiConverterTypeSaveGate INSTANCE = new FfiConverterTypeSaveGate(); + + public override SaveGate Read(BigEndianStream stream) { + var value = stream.ReadInt(); + switch (value) { + case 1: return SaveGate.Run; + case 2: return SaveGate.Confirm; + case 3: return SaveGate.Refuse; + default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeSaveGate.Read()", value)); + } + } + + public override int AllocationSize(SaveGate value) { + return 4; + } + + public override void Write(SaveGate value, BigEndianStream stream) { + switch (value) { + case SaveGate.Run: stream.WriteInt(1); break; + case SaveGate.Confirm: stream.WriteInt(2); break; + case SaveGate.Refuse: stream.WriteInt(3); break; + default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeSaveGate.Write()", value)); + } + } +} + + + + + + + internal enum SecretItemTag: int { McpToken, AnthropicKey, @@ -10134,6 +11450,37 @@ public override void Write(StatementSpan? value, BigEndianStream stream) { +class FfiConverterOptionalTypeEditLock: FfiConverterRustBuffer { + public static FfiConverterOptionalTypeEditLock INSTANCE = new FfiConverterOptionalTypeEditLock(); + + public override EditLock? Read(BigEndianStream stream) { + if (stream.ReadByte() == 0) { + return null; + } + return FfiConverterTypeEditLock.INSTANCE.Read(stream); + } + + public override int AllocationSize(EditLock? value) { + if (value == null) { + return 1; + } else { + return 1 + FfiConverterTypeEditLock.INSTANCE.AllocationSize((EditLock)value); + } + } + + public override void Write(EditLock? value, BigEndianStream stream) { + if (value == null) { + stream.WriteByte(0); + } else { + stream.WriteByte(1); + FfiConverterTypeEditLock.INSTANCE.Write((EditLock)value, stream); + } + } +} + + + + class FfiConverterOptionalTypeSecretKindTag: FfiConverterRustBuffer { public static FfiConverterOptionalTypeSecretKindTag INSTANCE = new FfiConverterOptionalTypeSecretKindTag(); @@ -10412,6 +11759,52 @@ public override void Write(string[] value, BigEndianStream stream) { +class FfiConverterSequenceTypeCellChange: FfiConverterRustBuffer { + public static FfiConverterSequenceTypeCellChange INSTANCE = new FfiConverterSequenceTypeCellChange(); + + public override CellChange[] Read(BigEndianStream stream) { + var length = stream.ReadInt(); + if (length == 0) { + return []; + } + + var result = new CellChange[length]; + var readFn = FfiConverterTypeCellChange.INSTANCE.Read; + for (int i = 0; i < length; i++) { + result[i] = readFn(stream); + } + return result; + } + + public override int AllocationSize(CellChange[] value) { + var sizeForLength = 4; + + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + return sizeForLength; + } + + var allocationSizeFn = FfiConverterTypeCellChange.INSTANCE.AllocationSize; + var sizeForItems = value.Sum(item => allocationSizeFn(item)); + return sizeForLength + sizeForItems; + } + + public override void Write(CellChange[] 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 = FfiConverterTypeCellChange.INSTANCE.Write; + value.ForEach(item => writerFn(item, stream)); + } +} + + + + class FfiConverterSequenceTypeCloudConnectionFields: FfiConverterRustBuffer { public static FfiConverterSequenceTypeCloudConnectionFields INSTANCE = new FfiConverterSequenceTypeCloudConnectionFields(); @@ -10642,6 +12035,52 @@ public override void Write(DriverInfo[] value, BigEndianStream stream) { +class FfiConverterSequenceTypeEditColumnInfo: FfiConverterRustBuffer { + public static FfiConverterSequenceTypeEditColumnInfo INSTANCE = new FfiConverterSequenceTypeEditColumnInfo(); + + public override EditColumnInfo[] Read(BigEndianStream stream) { + var length = stream.ReadInt(); + if (length == 0) { + return []; + } + + var result = new EditColumnInfo[length]; + var readFn = FfiConverterTypeEditColumnInfo.INSTANCE.Read; + for (int i = 0; i < length; i++) { + result[i] = readFn(stream); + } + return result; + } + + public override int AllocationSize(EditColumnInfo[] value) { + var sizeForLength = 4; + + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + return sizeForLength; + } + + var allocationSizeFn = FfiConverterTypeEditColumnInfo.INSTANCE.AllocationSize; + var sizeForItems = value.Sum(item => allocationSizeFn(item)); + return sizeForLength + sizeForItems; + } + + public override void Write(EditColumnInfo[] 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 = FfiConverterTypeEditColumnInfo.INSTANCE.Write; + value.ForEach(item => writerFn(item, stream)); + } +} + + + + class FfiConverterSequenceTypeGroupRecord: FfiConverterRustBuffer { public static FfiConverterSequenceTypeGroupRecord INSTANCE = new FfiConverterSequenceTypeGroupRecord(); @@ -10734,6 +12173,52 @@ public override void Write(ObjectEntry[] value, BigEndianStream stream) { +class FfiConverterSequenceTypePlannedStatement: FfiConverterRustBuffer { + public static FfiConverterSequenceTypePlannedStatement INSTANCE = new FfiConverterSequenceTypePlannedStatement(); + + public override PlannedStatement[] Read(BigEndianStream stream) { + var length = stream.ReadInt(); + if (length == 0) { + return []; + } + + var result = new PlannedStatement[length]; + var readFn = FfiConverterTypePlannedStatement.INSTANCE.Read; + for (int i = 0; i < length; i++) { + result[i] = readFn(stream); + } + return result; + } + + public override int AllocationSize(PlannedStatement[] value) { + var sizeForLength = 4; + + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + return sizeForLength; + } + + var allocationSizeFn = FfiConverterTypePlannedStatement.INSTANCE.AllocationSize; + var sizeForItems = value.Sum(item => allocationSizeFn(item)); + return sizeForLength + sizeForItems; + } + + public override void Write(PlannedStatement[] 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 = FfiConverterTypePlannedStatement.INSTANCE.Write; + value.ForEach(item => writerFn(item, stream)); + } +} + + + + class FfiConverterSequenceTypePromptFieldInfo: FfiConverterRustBuffer { public static FfiConverterSequenceTypePromptFieldInfo INSTANCE = new FfiConverterSequenceTypePromptFieldInfo(); @@ -10918,6 +12403,98 @@ public override void Write(TagRecord[] value, BigEndianStream stream) { +class FfiConverterSequenceTypeCellEdit: FfiConverterRustBuffer { + public static FfiConverterSequenceTypeCellEdit INSTANCE = new FfiConverterSequenceTypeCellEdit(); + + public override CellEdit[] Read(BigEndianStream stream) { + var length = stream.ReadInt(); + if (length == 0) { + return []; + } + + var result = new CellEdit[length]; + var readFn = FfiConverterTypeCellEdit.INSTANCE.Read; + for (int i = 0; i < length; i++) { + result[i] = readFn(stream); + } + return result; + } + + public override int AllocationSize(CellEdit[] value) { + var sizeForLength = 4; + + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + return sizeForLength; + } + + var allocationSizeFn = FfiConverterTypeCellEdit.INSTANCE.AllocationSize; + var sizeForItems = value.Sum(item => allocationSizeFn(item)); + return sizeForLength + sizeForItems; + } + + public override void Write(CellEdit[] 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 = FfiConverterTypeCellEdit.INSTANCE.Write; + value.ForEach(item => writerFn(item, stream)); + } +} + + + + +class FfiConverterSequenceTypeRowEdit: FfiConverterRustBuffer { + public static FfiConverterSequenceTypeRowEdit INSTANCE = new FfiConverterSequenceTypeRowEdit(); + + public override RowEdit[] Read(BigEndianStream stream) { + var length = stream.ReadInt(); + if (length == 0) { + return []; + } + + var result = new RowEdit[length]; + var readFn = FfiConverterTypeRowEdit.INSTANCE.Read; + for (int i = 0; i < length; i++) { + result[i] = readFn(stream); + } + return result; + } + + public override int AllocationSize(RowEdit[] value) { + var sizeForLength = 4; + + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + return sizeForLength; + } + + var allocationSizeFn = FfiConverterTypeRowEdit.INSTANCE.AllocationSize; + var sizeForItems = value.Sum(item => allocationSizeFn(item)); + return sizeForLength + sizeForItems; + } + + public override void Write(RowEdit[] 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 = FfiConverterTypeRowEdit.INSTANCE.Write; + value.ForEach(item => writerFn(item, stream)); + } +} + + + + class FfiConverterSequenceTypeRunEvent: FfiConverterRustBuffer { public static FfiConverterSequenceTypeRunEvent INSTANCE = new FfiConverterSequenceTypeRunEvent(); diff --git a/windows/src/TablePro.Interop/Mapping.cs b/windows/src/TablePro.Interop/Mapping.cs index 6faa25d78d..2559e81df2 100644 --- a/windows/src/TablePro.Interop/Mapping.cs +++ b/windows/src/TablePro.Interop/Mapping.cs @@ -414,4 +414,43 @@ private static List Columns(Native.ResultColumnInfo[] columns) => Native.ObjectKindTag.Key => Interop.ObjectKind.Key, _ => Interop.ObjectKind.Other, }; + + public static Native.CellEdit Edit(CellEdit edit) => edit switch + { + CellEdit.Text text => new Native.CellEdit.Text(text.Value), + CellEdit.Null => new Native.CellEdit.Null(), + _ => new Native.CellEdit.Default(), + }; + + public static CellEdit Edit(Native.CellEdit edit) => edit switch + { + Native.CellEdit.Text text => new CellEdit.Text(text.TextValue), + Native.CellEdit.Null => CellEdit.Null.Instance, + _ => CellEdit.ServerDefault.Instance, + }; + + public static Native.RowEdit Edit(RowEdit edit) => edit switch + { + RowEdit.Update update => new Native.RowEdit.Update( + checked((ulong)update.Row), + [.. update.Cells.Select(cell => new Native.CellChange(checked((uint)cell.Column), Edit(cell.Edit)))]), + RowEdit.Insert insert => new Native.RowEdit.Insert([.. insert.Cells.Select(Edit)]), + RowEdit.Delete delete => new Native.RowEdit.Delete(checked((ulong)delete.Row)), + _ => throw new ArgumentException("A row edit of a kind the core does not know.", nameof(edit)), + }; + + public static EditLock Lock(Native.EditLock locked) => locked switch + { + Native.EditLock.ReadOnlyConnection => EditLock.ReadOnlyConnection, + Native.EditLock.NoPrimaryKey => EditLock.NoPrimaryKey, + Native.EditLock.KeyUnreadable => EditLock.KeyUnreadable, + _ => EditLock.ColumnsChanged, + }; + + public static SaveGate Gate(Native.SaveGate gate) => gate switch + { + Native.SaveGate.Run => SaveGate.Run, + Native.SaveGate.Confirm => SaveGate.Confirm, + _ => SaveGate.Refuse, + }; } diff --git a/windows/src/TablePro.Interop/ResultSet.cs b/windows/src/TablePro.Interop/ResultSet.cs index 7988cba879..ee42a98540 100644 --- a/windows/src/TablePro.Interop/ResultSet.cs +++ b/windows/src/TablePro.Interop/ResultSet.cs @@ -15,6 +15,8 @@ internal ResultSet(Native.ResultSet set, int index) public int Index { get; } + internal Native.ResultSet Handle => _set; + public long RowCount => Mapping.Count(_set.RowCount()); public bool IsFinished => _set.IsFinished(); diff --git a/windows/src/TablePro.Interop/RowEdits.cs b/windows/src/TablePro.Interop/RowEdits.cs new file mode 100644 index 0000000000..13b660bb40 --- /dev/null +++ b/windows/src/TablePro.Interop/RowEdits.cs @@ -0,0 +1,100 @@ +namespace TablePro.Interop; + +// Why no row of a table, or of a page, can be changed. +public enum EditLock +{ + ReadOnlyConnection, + NoPrimaryKey, + KeyUnreadable, + ColumnsChanged, +} + +// An empty text means what the core's parse says for the column: the empty string, the server's default, or NULL. +public abstract record CellEdit +{ + private CellEdit() + { + } + + public sealed record Text(string Value) : CellEdit; + + public sealed record Null : CellEdit + { + public static Null Instance { get; } = new(); + } + + // The server's value: an insert leaves the column out, an update sets it to DEFAULT. + public sealed record ServerDefault : CellEdit + { + public static ServerDefault Instance { get; } = new(); + } +} + +public sealed record CellChange(int Column, CellEdit Edit); + +// A row of the page, by its place in the result set the page was read into. +public abstract record RowEdit +{ + private RowEdit() + { + } + + public sealed record Update(long Row, IReadOnlyList Cells) : RowEdit; + + // One cell per column, in the table's order. + public sealed record Insert(IReadOnlyList Cells) : RowEdit; + + public sealed record Delete(long Row) : RowEdit; +} + +// A saved row's key and a column the server fills are locked; TakesDefault offers DEFAULT in a saved row. +public sealed record EditColumn( + string Name, + bool Editable, + bool EditableInNewRow, + CellEdit NewRow, + bool Nullable, + bool PrimaryKey, + bool TakesEmpty, + bool TakesDefault); + +public abstract record EditStart +{ + private EditStart() + { + } + + // The whole value, which the grid shows cut; empty for NULL. + public sealed record Editable(string Text, bool IsNull) : EditStart; + + public sealed record Locked : EditStart + { + public static Locked Instance { get; } = new(); + } +} + +// One statement of a save, with the values it binds as they would be written. +public sealed record PlannedStatement(string Sql, IReadOnlyList Values); + +// Row changes are writes: Off saves, Confirm writes shows the statements first, Read only refuses. +public enum SaveGate +{ + Run, + Confirm, + Refuse, +} + +public abstract record RowSaveOutcome +{ + private RowSaveOutcome() + { + } + + public sealed record Saved(long? Rows) : RowSaveOutcome; + + // Nothing was written. Edit is the place in the edits of the change the save stopped at, when the engine said. + public sealed record RolledBack(CoreError Error, int? Edit) : RowSaveOutcome; + + // The save may have landed in part or in full, so saving again could write it twice. + public sealed record Unknown(CoreError Error, int? Edit) : RowSaveOutcome; +} diff --git a/windows/src/TablePro.Interop/TableEditor.cs b/windows/src/TablePro.Interop/TableEditor.cs new file mode 100644 index 0000000000..e13b486caf --- /dev/null +++ b/windows/src/TablePro.Interop/TableEditor.cs @@ -0,0 +1,117 @@ +using Native = TablePro.Interop.Native; + +namespace TablePro.Interop; + +// A table tab's rows as a save sees them: the catalog's columns, keyed by the primary key. +public sealed class TableEditor : IDisposable +{ + private readonly Native.TableEditor _editor; + + internal TableEditor(Native.TableEditor editor) + { + _editor = editor; + Columns = [.. editor.Columns().Select(column => new EditColumn( + column.Name, + column.Editable, + column.EditableInNewRow, + Mapping.Edit(column.NewRow), + column.Nullable, + column.PrimaryKey, + column.TakesEmpty, + column.TakesDefault))]; + } + + // Read again on each call, since a reconnect can make the connection read-only. + public EditLock? Lock => _editor.Lock() is { } locked ? Mapping.Lock(locked) : null; + + // The page's own locks as well: a key the page holds that cannot be named exactly, or columns that changed. + public EditLock? LockFor(ResultSet rows) + { + ArgumentNullException.ThrowIfNull(rows); + return _editor.LockFor(rows.Handle) is { } locked ? Mapping.Lock(locked) : null; + } + + public IReadOnlyList Columns { get; } + + public EditStart GetEditStart(ResultSet rows, long row, int column) + { + ArgumentNullException.ThrowIfNull(rows); + ArgumentOutOfRangeException.ThrowIfNegative(row); + ArgumentOutOfRangeException.ThrowIfNegative(column); + return CoreCall.Run(() => _editor.EditStart(rows.Handle, checked((ulong)row), checked((uint)column))) switch + { + Native.EditStart.Editable editable => new EditStart.Editable(editable.Text, editable.IsNull), + _ => EditStart.Locked.Instance, + }; + } + + // Null when the cell saves as typed; otherwise why not, with an edit.* code. + public CoreError? Check(int column, CellEdit edit, bool newRow) + { + ArgumentOutOfRangeException.ThrowIfNegative(column); + ArgumentNullException.ThrowIfNull(edit); + try + { + CoreCall.Run(() => + { + _editor.Check(checked((uint)column), Mapping.Edit(edit), newRow); + return true; + }); + return null; + } + catch (TableProException exception) + { + return exception.Error; + } + } + + // At the connection's Safe Mode level now; a cell edited back to its value is left out, so the save can be empty. + public RowSave Plan(ResultSet rows, IReadOnlyList edits) + { + ArgumentNullException.ThrowIfNull(rows); + ArgumentNullException.ThrowIfNull(edits); + var native = edits.Select(Mapping.Edit).ToArray(); + return new RowSave(CoreCall.Run(() => _editor.Plan(rows.Handle, native))); + } + + public void Dispose() => _editor.Dispose(); +} + +// One save, which runs only the statements it was planned with. +public sealed class RowSave : IDisposable +{ + private readonly Native.RowSave _save; + + internal RowSave(Native.RowSave save) + { + _save = save; + Statements = [.. save.Statements().Select(statement => new PlannedStatement(statement.Sql, [.. statement.Values]))]; + IsEmpty = save.IsEmpty(); + Gate = Mapping.Gate(save.Gate()); + } + + public IReadOnlyList Statements { get; } + + public bool IsEmpty { get; } + + public SaveGate Gate { get; } + + // Confirmed says Safe Mode's question was answered; nothing is sent when the level or the plan moved since. + public async Task RunAsync(bool confirmed, CancellationToken cancellationToken = default) + { + var outcome = await CoreCall.RunAsync(token => _save.Run(confirmed, token), cancellationToken).ConfigureAwait(false); + return outcome switch + { + Native.RowSaveOutcome.Saved saved => new RowSaveOutcome.Saved(saved.Rows is { } rows ? Mapping.Count(rows) : null), + Native.RowSaveOutcome.RolledBack rolledBack => new RowSaveOutcome.RolledBack( + Mapping.Error(rolledBack.Error), + rolledBack.Edit is { } edit ? checked((int)edit) : null), + Native.RowSaveOutcome.Unknown unknown => new RowSaveOutcome.Unknown( + Mapping.Error(unknown.Error), + unknown.Edit is { } edit ? checked((int)edit) : null), + _ => throw new InvalidOperationException("The core reported a save outcome this build does not know."), + }; + } + + public void Dispose() => _save.Dispose(); +} diff --git a/windows/tests/TablePro.App.Model.Tests/ConnectionFakes.cs b/windows/tests/TablePro.App.Model.Tests/ConnectionFakes.cs new file mode 100644 index 0000000000..3aff80c551 --- /dev/null +++ b/windows/tests/TablePro.App.Model.Tests/ConnectionFakes.cs @@ -0,0 +1,122 @@ +using TablePro.Interop; + +namespace TablePro.App.Model.Tests; + +internal sealed class FakeDatabase : IAsyncDisposable +{ + public int Disposals { get; private set; } + + public ValueTask DisposeAsync() + { + Disposals++; + return ValueTask.CompletedTask; + } +} + +internal sealed class FakeConnector : IConnector +{ + public List Opened { get; } = []; + + public List Attempts { get; } = []; + + public List Saved { get; } = []; + + // Each connect takes the next failure, until none is left. + public Queue Failures { get; } = new(); + + public Gate? Connecting { get; set; } + + public async Task ConnectSavedAsync( + Guid id, + ConnectionSecrets secrets, + CancellationToken cancellationToken) + { + Attempts.Add(secrets); + return await OpenAsync(cancellationToken); + } + + public Task OpenFileAsync(string path, string? engineId, CancellationToken cancellationToken) => + OpenAsync(cancellationToken); + + public Task SaveSecretsAsync(Guid id, ConnectionSecrets secrets) + { + Saved.Add(secrets); + return Task.CompletedTask; + } + + private async Task OpenAsync(CancellationToken cancellationToken) + { + if (Connecting is { } connecting) + { + await connecting.PassAsync(cancellationToken); + } + + if (Failures.TryDequeue(out var failure)) + { + throw new TableProException(failure); + } + + var database = new FakeDatabase(); + Opened.Add(database); + return database; + } +} + +// The workspace a connection shows: its strip is the truth once connected, as WorkspaceView.Snapshot says. +internal sealed class FakeConnectionView : IConnectionView +{ + public List Shown { get; } = []; + + public List Restores { get; } = []; + + public List Closes { get; } = []; + + public SessionShare? Share { get; private set; } + + public IReadOnlyList Strip { get; set; } = []; + + public Func Answer { get; set; } = _ => null; + + public bool ForgetsHostKey { get; set; } + + public int RecoveriesCancelled { get; private set; } + + public void ShowState(ConnectionState state) => Shown.Add($"state {state}"); + + public void ShowConnecting() => Shown.Add("connecting"); + + public void ShowConnected(SessionShare share, SessionConnection? restore, bool adopted) + { + Share = share; + Restores.Add(restore); + Shown.Add(adopted ? "adopted" : "connected"); + } + + public void ShowFailed(CoreError failure) => Shown.Add("failed " + failure.Code); + + public void ShowCancelledKeepsTabs() => Shown.Add("cancelled, tabs kept"); + + public Task AskSecretAsync(SecretKind kind, CancellationToken cancellationToken) + { + Shown.Add($"asked {kind}"); + return Task.FromResult(Answer(kind)); + } + + public Task RecoverHostKeyAsync(Guid id, HostKeyFailure failure, CancellationToken cancellationToken) + { + Shown.Add("host key " + failure.Host); + return Task.FromResult(ForgetsHostKey); + } + + public void CancelRecovery() => RecoveriesCancelled++; + + public Task CloseTabsAsync(bool keepClosed) + { + Closes.Add(keepClosed); + Share = null; + return Task.CompletedTask; + } + + public SessionConnection Snapshot(SessionConnection origin) => + Share is null ? origin : origin with { Tabs = Strip }; +} diff --git a/windows/tests/TablePro.App.Model.Tests/ConnectionLifeTests.cs b/windows/tests/TablePro.App.Model.Tests/ConnectionLifeTests.cs new file mode 100644 index 0000000000..829bf46d2f --- /dev/null +++ b/windows/tests/TablePro.App.Model.Tests/ConnectionLifeTests.cs @@ -0,0 +1,233 @@ +using TablePro.Interop; + +namespace TablePro.App.Model.Tests; + +public sealed class ConnectionLifeTests +{ + private static readonly Guid SavedId = Guid.NewGuid(); + private readonly FakeConnectionView _view = new(); + private readonly FakeConnector _connector = new(); + + [Fact] + public async Task AConnectionSavedWithTabsShowsThemOnItsFirstSession() + { + var origin = new SessionConnection + { + ConnectionId = SavedId, + Name = "Chinook", + Tabs = [new SessionTab { Kind = TabKind.Query, Title = "Query 1", Sql = "select 1" }], + }; + var life = New(origin); + + await life.ConnectAsync(); + + Assert.Equal(ConnectionState.Connected, life.State); + Assert.Same(origin, Assert.Single(_view.Restores)); + Assert.Same(Assert.Single(_connector.Opened), life.Session); + Assert.Equal( + ["state Connecting", "connecting", "state Connected", "connected"], + _view.Shown); + } + + [Fact] + public async Task AReconnectKeepsTheTabsAndShowsThemOnTheNextSession() + { + var life = New(); + await life.ConnectAsync(); + var first = Assert.Single(_connector.Opened); + _view.Strip = [new SessionTab { Kind = TabKind.Table, Title = "Artist", Table = "Artist" }]; + + await life.DisconnectAsync(keepTabs: true); + + Assert.Equal(ConnectionState.NotConnected, life.State); + Assert.Equal(1, first.Disposals); + Assert.Equal([true], _view.Closes); + Assert.Equal(_view.Strip, life.Snapshot().Tabs); + + await life.ConnectAsync(); + + Assert.Equal(2, _connector.Opened.Count); + Assert.Null(_view.Restores[0]); + Assert.Equal(_view.Strip, _view.Restores[^1]?.Tabs); + } + + [Fact] + public async Task ACancelledReconnectKeepsTheConnectionAndItsTabsToRetry() + { + var life = New(); + var cancelled = 0; + life.Cancelled += (_, _) => cancelled++; + await life.ConnectAsync(); + _view.Strip = [new SessionTab { Kind = TabKind.Query, Title = "Query 1", Sql = "select 1" }]; + await life.DisconnectAsync(keepTabs: true); + var connecting = new Gate(); + _connector.Connecting = connecting; + + var reconnect = life.ConnectAsync(); + await connecting.Reached; + life.CancelConnect(); + await reconnect; + + Assert.Equal(ConnectionState.NotConnected, life.State); + Assert.Equal(0, cancelled); + Assert.Contains("cancelled, tabs kept", _view.Shown); + + _connector.Connecting = null; + await life.ConnectAsync(); + + Assert.Equal(ConnectionState.Connected, life.State); + Assert.Equal(_view.Strip, _view.Restores[^1]?.Tabs); + } + + [Fact] + public async Task ACancelledFirstConnectTakesTheConnectionAway() + { + var life = New(); + var cancelled = 0; + life.Cancelled += (_, _) => cancelled++; + var connecting = new Gate(); + _connector.Connecting = connecting; + + var connect = life.ConnectAsync(); + await connecting.Reached; + life.CancelConnect(); + await connect; + + Assert.Equal(1, cancelled); + Assert.Equal(ConnectionState.NotConnected, life.State); + Assert.DoesNotContain("cancelled, tabs kept", _view.Shown); + Assert.Empty(_connector.Opened); + } + + [Fact] + public async Task DisconnectingTwiceLetsTheSessionGoOnce() + { + var life = New(); + await life.ConnectAsync(); + var database = Assert.Single(_connector.Opened); + + await life.DisconnectAsync(); + await life.DisconnectAsync(); + + Assert.Equal(1, database.Disposals); + Assert.Null(life.Session); + Assert.Equal([false, false], _view.Closes); + Assert.Empty(life.Snapshot().Tabs); + } + + [Fact] + public async Task AWindowThatAdoptsTheSessionHoldsItUntilBothLetGo() + { + var life = New(); + await life.ConnectAsync(); + var database = Assert.Single(_connector.Opened); + var other = new FakeConnectionView(); + var adopted = new ConnectionLife(life.Origin with { Tabs = [] }, other, _connector); + + adopted.Adopt(life); + + Assert.Equal(ConnectionState.Connected, adopted.State); + Assert.Same(life.Share, other.Share); + Assert.Equal(2, life.Share?.Holders); + Assert.Contains("adopted", other.Shown); + Assert.Single(_connector.Opened); + + await life.DisconnectAsync(); + + Assert.Equal(0, database.Disposals); + + await adopted.DisconnectAsync(); + + Assert.Equal(1, database.Disposals); + } + + [Fact] + public void OnlyAConnectedConnectionGivesUpItsSession() + { + var adopted = New(); + + Assert.Throws(() => adopted.Adopt(New())); + } + + [Fact] + public async Task ASecretWithNoneSavedIsAskedForAndSavedOnceTheConnectWorks() + { + _connector.Failures.Enqueue(Errors.Of("keyring.secret_not_stored", SecretKind.SshPassword)); + _view.Answer = _ => new SecretAnswer("typed", Save: true); + var life = New(); + + await life.ConnectAsync(); + + Assert.Equal(ConnectionState.Connected, life.State); + Assert.Equal( + [ConnectionSecrets.None, new ConnectionSecrets(SshPassword: "typed")], + _connector.Attempts); + Assert.Equal(new ConnectionSecrets(SshPassword: "typed"), Assert.Single(_connector.Saved)); + Assert.Contains("asked SshPassword", _view.Shown); + } + + [Fact] + public async Task ASecretRefusedAgainFailsAndAClosedQuestionCancelsTheConnect() + { + _connector.Failures.Enqueue(Errors.Of("keyring.secret_not_stored", SecretKind.DatabasePassword)); + _connector.Failures.Enqueue(Errors.Of("keyring.secret_not_stored", SecretKind.DatabasePassword)); + _view.Answer = _ => new SecretAnswer("wrong", Save: true); + var life = New(); + var cancelled = 0; + life.Cancelled += (_, _) => cancelled++; + + await life.ConnectAsync(); + + Assert.Equal(ConnectionState.Failed, life.State); + Assert.Contains("failed keyring.secret_not_stored", _view.Shown); + Assert.Empty(_connector.Saved); + + _view.Answer = _ => null; + _connector.Failures.Enqueue(Errors.Of("keyring.secret_not_stored")); + await life.ConnectAsync(); + + Assert.Equal(1, cancelled); + Assert.Equal(ConnectionState.NotConnected, life.State); + } + + [Fact] + public async Task AChangedHostKeyIsForgottenOnceAskedAndTheConnectTriedAgain() + { + var key = new HostKeyFailure("db.example.com", "ssh-ed25519", "SHA256:abc", "known_hosts", 3, TrustAllowed: true); + _connector.Failures.Enqueue(Errors.Of("ssh.host_key_changed", hostKey: key)); + _view.ForgetsHostKey = true; + var life = New(); + + await life.ConnectAsync(); + + Assert.Equal(ConnectionState.Connected, life.State); + Assert.Equal(2, _connector.Attempts.Count); + Assert.Contains("host key db.example.com", _view.Shown); + + _view.ForgetsHostKey = false; + await life.DisconnectAsync(); + _connector.Failures.Enqueue(Errors.Of("ssh.host_key_changed", hostKey: key)); + await life.ConnectAsync(); + + Assert.Equal(ConnectionState.Failed, life.State); + Assert.Contains("failed ssh.host_key_changed", _view.Shown); + } + + [Fact] + public async Task AFileOpensByItsPathAndMatchesItWhateverTheCase() + { + var life = New(new SessionConnection { FilePath = @"C:\Data\Chinook.sqlite", Name = "Chinook.sqlite" }); + + await life.ConnectAsync(); + + Assert.Equal(ConnectionState.Connected, life.State); + Assert.Empty(_connector.Attempts); + Assert.True(life.Matches(null, @"c:\data\chinook.sqlite")); + Assert.False(life.Matches(SavedId, null)); + } + + private ConnectionLife New(SessionConnection? origin = null) => new( + origin ?? new SessionConnection { ConnectionId = SavedId, Name = "Chinook", EngineId = "sqlite" }, + _view, + _connector); +} diff --git a/windows/tests/TablePro.App.Model.Tests/QueryTabTests.cs b/windows/tests/TablePro.App.Model.Tests/QueryTabTests.cs new file mode 100644 index 0000000000..f49eba94cb --- /dev/null +++ b/windows/tests/TablePro.App.Model.Tests/QueryTabTests.cs @@ -0,0 +1,351 @@ +using TablePro.DataGrid.Model; +using TablePro.Interop; + +namespace TablePro.App.Model.Tests; + +public sealed class QueryTabTests +{ + private readonly FakeSession _session = new(); + private readonly FakeQueryView _view = new(); + private readonly FakeResults _results = new(); + private readonly QueryTab _tab; + + public QueryTabTests() + { + _tab = new QueryTab("Query 1", _session, _view, _results, DataModel.Relational, () => new AppSettings()); + } + + [Fact] + public async Task ATabClosedWhileItsEditorOpensOpensNoneAndLetsItsSessionGoOnce() + { + var opening = new Gate(); + _session.Opening = opening; + + var running = _tab.RunAsync(); + await opening.Reached; + await _tab.CloseAsync(); + await running; + + Assert.Empty(_session.Editors); + Assert.Equal(1, _session.Releases); + Assert.Equal(["clear"], _results.Shown); + Assert.Equal(["running", "idle", "editor closed"], _view.Shown); + } + + [Fact] + public async Task AnEditorThatOpensAsTheTabClosesIsDisposedOnceAndRunsNothing() + { + var opening = new Gate(honorsCancel: false); + _session.Opening = opening; + + var running = _tab.RunAsync(); + await opening.Reached; + var closing = _tab.CloseAsync(); + var waited = !closing.IsCompleted; + opening.Open(); + await closing; + await running; + + Assert.True(waited); + var editor = Assert.Single(_session.Editors); + Assert.Equal(1, editor.Disposals); + Assert.Empty(editor.Runs); + Assert.Equal(1, _session.Releases); + Assert.Equal(["clear"], _results.Shown); + Assert.Equal(["running", "idle", "editor closed"], _view.Shown); + } + + [Fact] + public async Task ATabClosedWhileItsRunIsReadStopsTheRunAndLetsGoOfEachPieceOnce() + { + var reading = new Gate(); + var run = FakeRun.Rows(5); + run.Reading = reading; + _session.Script = _ => run; + + var running = _tab.RunAsync(); + await reading.Reached; + await _tab.CloseAsync(); + await running; + + var editor = Assert.Single(_session.Editors); + Assert.Equal(1, run.Cancels); + Assert.Equal(1, run.Disposals); + Assert.Equal(1, editor.Disposals); + Assert.Equal(1, _session.Releases); + Assert.Equal(["run", "clear"], _results.Shown); + Assert.Equal(["running", "idle", "editor closed"], _view.Shown); + } + + [Fact] + public async Task ATabClosedAfterItsRunWhileItLetsGoOfALostEditorSaysNothingMore() + { + _session.Script = _ => FakeRun.Rows(1, TransactionState.InTransaction); + await _tab.RunAsync(); + var editor = Assert.Single(_session.Editors); + var reading = new Gate(); + var run = FakeRun.Rows(1, TransactionState.InTransaction); + run.Reading = reading; + _session.Script = _ => run; + var running = _tab.RunAsync(); + await reading.Reached; + var disposing = new Gate(); + editor.Disposing = disposing; + editor.IsLost = true; + + reading.Open(); + await disposing.Reached; + var closing = _tab.CloseAsync(); + disposing.Open(); + await closing; + await running; + + Assert.Equal(1, editor.Disposals); + Assert.Equal(1, _session.Releases); + Assert.Equal(TransactionState.Idle, _tab.Transaction); + Assert.DoesNotContain("transaction lost", _view.Shown); + Assert.Equal("clear", _results.Shown[^1]); + } + + [Fact] + public async Task ATabClosedAfterItsRunLetsGoOfEachPieceOnce() + { + await _tab.RunAsync(); + + await Task.WhenAll(_tab.CloseAsync(), _tab.CloseAsync()); + await _tab.RunAsync(); + + var editor = Assert.Single(_session.Editors); + Assert.Equal(1, editor.Disposals); + Assert.Single(editor.Runs); + Assert.Equal(1, Assert.Single(editor.Started).Disposals); + Assert.Equal(1, _session.Releases); + } + + [Fact] + public async Task ARunOnALostEditorThatHeldATransactionSaysSoAndRunsNothing() + { + _session.Script = _ => FakeRun.Rows(1, TransactionState.InTransaction); + await _tab.RunAsync(); + var lost = Assert.Single(_session.Editors); + lost.IsLost = true; + + await _tab.RunAsync(); + + Assert.Single(lost.Runs); + Assert.Equal(1, lost.Disposals); + Assert.Single(_session.Editors); + Assert.Contains("transaction lost", _view.Shown); + Assert.Equal(TransactionState.Idle, _tab.Transaction); + + await _tab.RunAsync(); + + Assert.Equal(2, _session.Editors.Count); + Assert.Single(_session.Editors[1].Runs); + } + + [Fact] + public async Task ALostEditorWithNoTransactionIsReplacedAndTheRunGoesOn() + { + await _tab.RunAsync(); + var lost = Assert.Single(_session.Editors); + lost.IsLost = true; + + await _tab.RunAsync(); + + Assert.Equal(1, lost.Disposals); + Assert.Equal(2, _session.Editors.Count); + Assert.Single(_session.Editors[1].Runs); + Assert.DoesNotContain("transaction lost", _view.Shown); + } + + [Fact] + public async Task ARunReadOnlyRefusesNeverStarts() + { + _session.Verdict = new RunGate(true, [], false); + + await _tab.RunAsync(); + + Assert.Empty(_session.Editors); + Assert.Contains("refused", _view.Shown); + Assert.False(_tab.IsRunning); + } + + [Fact] + public async Task AWriteDeclinedAtTheQuestionNeverRuns() + { + _session.Verdict = new RunGate(false, ["delete from Artist"], true); + _view.Confirm = _ => Task.FromResult(false); + + await _tab.RunAsync(); + + Assert.Empty(_session.Editors); + Assert.Contains("asked Chinook", _view.Shown); + } + + [Fact] + public async Task AWriteConfirmedAtTheQuestionRuns() + { + _session.Verdict = new RunGate(false, ["delete from Artist"], true); + _view.WholeText = "delete from Artist"; + + await _tab.RunAsync(); + + Assert.Equal(["delete from Artist"], Assert.Single(_session.Editors).Runs); + } + + [Fact] + public async Task ATabClosedWhileItsQuestionIsOpenNeverRuns() + { + _session.Verdict = new RunGate(false, ["delete from Artist"], false); + var answer = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + _view.Confirm = _ => answer.Task; + + var running = _tab.RunAsync(); + await _tab.RunAsync(); + await _tab.CloseAsync(); + answer.SetResult(true); + await running; + + Assert.Equal(1, _session.GateRuns); + Assert.Empty(_session.Editors); + Assert.Equal(1, _session.Releases); + } + + [Fact] + public async Task CommitAndRollBackEndTheTransactionWithoutSafeModeAsking() + { + _session.Script = _ => FakeRun.Rows(0, TransactionState.InTransaction); + await _tab.RunAsync(); + Assert.Equal(TransactionState.InTransaction, _tab.Transaction); + Assert.True(_view.CanCommit); + _session.Verdict = new RunGate(true, [], false); + + await _tab.CommitAsync(); + await _tab.RollBackAsync(); + + Assert.Equal(["select * from Artist", "COMMIT", "ROLLBACK"], Assert.Single(_session.Editors).Runs); + Assert.Equal(1, _session.GateRuns); + Assert.DoesNotContain("refused", _view.Shown); + } + + [Fact] + public async Task ARollBackDeclinedSendsNothingAndAKeyValueEngineEndsWithItsOwnCommands() + { + var tab = new QueryTab("Query 1", _session, _view, _results, DataModel.KeyValue, () => new AppSettings()); + _session.Script = _ => FakeRun.Rows(0, TransactionState.InTransaction); + await tab.RunAsync(); + _view.RollsBack = false; + + await tab.RollBackAsync(); + await tab.CommitAsync(); + _view.RollsBack = true; + await tab.RollBackAsync(); + + Assert.Equal(["select * from Artist", "EXEC", "DISCARD"], Assert.Single(_session.Editors).Runs); + } + + [Fact] + public async Task AFailedTransactionOrAReadOnlyConnectionOffersOnlyRollBack() + { + _session.IsReadOnly = true; + _session.Script = _ => FakeRun.Rows(0, TransactionState.InTransaction); + await _tab.RunAsync(); + Assert.False(_view.CanCommit); + + _session.IsReadOnly = false; + _session.Script = _ => FakeRun.Rows(0, TransactionState.Failed); + await _tab.RunAsync(); + + Assert.False(_view.CanCommit); + Assert.Equal(TransactionState.Failed, _tab.Transaction); + } + + [Fact] + public async Task ASortRunsTheStatementAgainWithoutSafeModeAsking() + { + _session.Sorted = (sql, columns, column, _) => $"{sql} order by {columns[column]}"; + await _tab.RunAsync(); + _session.Verdict = new RunGate(true, [], false); + var sort = new GridSort(1, SortDirection.Ascending); + + await _tab.SortAsync(sort); + + Assert.Equal("select * from Artist order by name", Assert.Single(_session.Editors).Runs[^1]); + Assert.Equal(sort, _results.RunSort); + Assert.Equal(1, _session.GateRuns); + } + + [Fact] + public async Task ASortThatCannotRunAgainSortsTheRowsHeld() + { + _session.Script = _ => FakeRun.Rows(7); + await _tab.RunAsync(); + var sort = new GridSort(0, SortDirection.Descending); + + await _tab.SortAsync(sort); + + Assert.Single(Assert.Single(_session.Editors).Runs); + Assert.Contains("sort held", _results.Shown); + Assert.Contains("sorted held 7", _view.Shown); + Assert.Equal(sort, _results.Sort); + } + + [Fact] + public async Task AScriptIsNeverRunAgainToSortAndARefusedHeldSortKeepsTheShownOne() + { + var asked = 0; + _session.Sorted = (sql, _, _, _) => + { + asked++; + return sql; + }; + _session.Script = _ => FakeRun.Script(); + await _tab.RunAsync(); + _results.SortsHeldRows = false; + + await _tab.SortAsync(new GridSort(0, SortDirection.Ascending)); + + Assert.Equal(0, asked); + Assert.Single(Assert.Single(_session.Editors).Runs); + Assert.Equal(GridSort.None, _results.Sort); + } + + [Fact] + public async Task RunStatementSelectsTheStatementAtTheCaretAndRunsOnlyIt() + { + _view.WholeText = "select 1; select 2"; + _view.Caret = 12; + _session.Statement = (_, caret) => caret >= 10 ? new Range(10, 18) : new Range(0, 8); + + await _tab.RunStatementAsync(); + + Assert.Contains("selected 10 8", _view.Shown); + Assert.Equal(["select 2"], Assert.Single(_session.Editors).Runs); + } + + [Fact] + public async Task RunStatementWithNoStatementAtTheCaretSaysSoAndRunsNothing() + { + await _tab.RunStatementAsync(); + + Assert.Contains("no statement", _view.Shown); + Assert.Empty(_session.Editors); + Assert.Equal(0, _session.GateRuns); + } + + [Fact] + public async Task ARunSendsTheSelectionOrTheWholeTextWhenNothingIsSelected() + { + _view.SelectedText = "select 2"; + await _tab.RunAsync(); + _view.SelectedText = " "; + await _tab.RunAsync(); + + Assert.Equal(["select 2", "select * from Artist"], Assert.Single(_session.Editors).Runs); + Assert.Equal( + new SessionTab { Kind = TabKind.Query, Title = "Query 1", Sql = "select * from Artist" }, + _tab.Snapshot()); + Assert.False(_tab.HasUnsavedChanges); + } +} diff --git a/windows/tests/TablePro.App.Model.Tests/SessionShareTests.cs b/windows/tests/TablePro.App.Model.Tests/SessionShareTests.cs new file mode 100644 index 0000000000..9617e67f52 --- /dev/null +++ b/windows/tests/TablePro.App.Model.Tests/SessionShareTests.cs @@ -0,0 +1,24 @@ +namespace TablePro.App.Model.Tests; + +public sealed class SessionShareTests +{ + [Fact] + public async Task TheLastHolderToLetGoDisposesTheSessionOnce() + { + var database = new FakeDatabase(); + var share = new SessionShare(database); + + Assert.Same(share, share.Hold()); + share.Hold(); + await share.ReleaseAsync(); + await share.ReleaseAsync(); + + Assert.Equal(0, database.Disposals); + Assert.Equal(1, share.Holders); + + await share.ReleaseAsync(); + + Assert.Equal(1, database.Disposals); + Assert.Equal(0, share.Holders); + } +} diff --git a/windows/tests/TablePro.App.Model.Tests/TabFakes.cs b/windows/tests/TablePro.App.Model.Tests/TabFakes.cs new file mode 100644 index 0000000000..742cbcc0c0 --- /dev/null +++ b/windows/tests/TablePro.App.Model.Tests/TabFakes.cs @@ -0,0 +1,620 @@ +using System.Globalization; +using System.Runtime.CompilerServices; +using TablePro.DataGrid.Model; +using TablePro.Interop; + +namespace TablePro.App.Model.Tests; + +// A point the code under test waits at until the test opens it; a cancel ends the wait as the core's calls end. +internal sealed class Gate(bool honorsCancel = true) +{ + private readonly TaskCompletionSource _reached = new(TaskCreationOptions.RunContinuationsAsynchronously); + private readonly TaskCompletionSource _opened = new(TaskCreationOptions.RunContinuationsAsynchronously); + + public Task Reached => _reached.Task; + + public void Open() => _opened.TrySetResult(); + + public async Task PassAsync(CancellationToken cancellationToken) + { + _reached.TrySetResult(); + try + { + await _opened.Task.WaitAsync(honorsCancel ? cancellationToken : CancellationToken.None); + } + catch (OperationCanceledException) + { + // The UI thread runs a continuation after the cancel returns, not inside it. + await Task.Yield(); + throw; + } + } +} + +internal sealed class FakeSession : ITabSession +{ + public List Editors { get; } = []; + + public List<(ColumnSort? Sort, long Limit, long Offset)> Queries { get; } = []; + + public Gate? Opening { get; set; } + + public Gate? Querying { get; set; } + + public Gate? Counting { get; set; } + + // Waited at by the run of each page a table query writes. + public Gate? PageReading { get; set; } + + public RunGate Verdict { get; set; } = new(false, [], false); + + public Func Statement { get; set; } = (_, _) => null; + + public Func, int, bool, string?> Sorted { get; set; } = (_, _, _, _) => null; + + // The events a run of the SQL gives; the default is one empty set that completes. + public Func Script { get; set; } = _ => FakeRun.Rows(0); + + public long TableRows { get; set; } + + public bool RefusesSort { get; set; } + + // Every open gives this one, so a test sets it up before the page loads. + public FakeTableEditor TableEditor { get; } = new(); + + public CoreError? TableEditorFailure { get; set; } + + public Gate? OpeningTableEditor { get; set; } + + public int TableEditorOpens { get; private set; } + + public List TableEditorRefreshes { get; } = []; + + // A page query that fails, as a server that went away does. + public CoreError? QueryFailure { get; set; } + + public int GateRuns { get; private set; } + + public int Counts { get; private set; } + + public int Releases { get; private set; } + + public string Name => "Chinook"; + + public string EngineId => "sqlite"; + + public bool IsReadOnly { get; set; } + + public async Task OpenEditorAsync(CancellationToken cancellationToken) + { + if (Opening is { } opening) + { + await opening.PassAsync(cancellationToken); + } + + var editor = new FakeEditor(this); + Editors.Add(editor); + return editor; + } + + public async Task GetTableQueryAsync( + TableName table, + ColumnSort? sort, + long limit, + long offset, + CancellationToken cancellationToken) + { + Queries.Add((sort, limit, offset)); + if (Querying is { } querying) + { + await querying.PassAsync(cancellationToken); + } + + if (sort is not null && RefusesSort) + { + throw new TableProException(Errors.Of("ffi.sort_unsupported")); + } + + if (QueryFailure is { } failure) + { + throw new TableProException(failure); + } + + var rows = Math.Clamp(TableRows - offset, 0, limit); + var page = FakeRun.Rows(rows); + page.Reading = PageReading; + Script = _ => page; + return new TableQuery($"select * from {table.Name} limit {limit} offset {offset}", 2); + } + + public async Task CountRowsAsync(TableName table, CancellationToken cancellationToken) + { + Counts++; + if (Counting is { } counting) + { + await counting.PassAsync(cancellationToken); + } + + return TableRows; + } + + public RunGate GateRun(string sql) + { + GateRuns++; + return Verdict; + } + + public Range? StatementAt(string sql, int caret) => Statement(sql, caret); + + public string? SortedQuery(string sql, IReadOnlyList columns, int column, bool ascending) => + Sorted(sql, columns, column, ascending); + + public async Task OpenTableEditorAsync( + TableName table, + bool refresh, + CancellationToken cancellationToken) + { + TableEditorOpens++; + TableEditorRefreshes.Add(refresh); + if (OpeningTableEditor is { } opening) + { + await opening.PassAsync(cancellationToken); + } + + return TableEditorFailure is { } failure ? throw new TableProException(failure) : TableEditor; + } + + public ValueTask ReleaseAsync() + { + Releases++; + return ValueTask.CompletedTask; + } +} + +internal sealed class FakeEditor(FakeSession session) : ITabEditor +{ + public List Runs { get; } = []; + + public List Started { get; } = []; + + public bool IsLost { get; set; } + + public Gate? Disposing { get; set; } + + public int Disposals { get; private set; } + + public ITabRun Run(string sql, QueryOptions options, CancellationToken cancellationToken) + { + Runs.Add(sql); + var run = session.Script(sql); + Started.Add(run); + return run; + } + + public async ValueTask DisposeAsync() + { + Disposals++; + if (Disposing is { } disposing) + { + await disposing.PassAsync(CancellationToken.None); + } + } +} + +internal sealed class FakeRun(IReadOnlyList events) : ITabRun +{ + private static readonly ResultColumn[] Columns = + [ + new("id", "INTEGER", ValueKind.Integer), + new("name", "TEXT", ValueKind.Text), + ]; + + // Waited at before the last event, as a run waits for the server. + public Gate? Reading { get; set; } + + public int Cancels { get; private set; } + + public int Disposals { get; private set; } + + public static FakeRun Rows(long rows, TransactionState transaction = TransactionState.Idle) => new( + [ + new QueryEvent.ResultSetStarted(0, Columns), + new QueryEvent.ResultSetFinished(0, rows, null, Truncation.Complete), + new QueryEvent.Finished(new QueryOutcome.Completed(TimeSpan.FromMilliseconds(12)), transaction), + ]); + + public static FakeRun Script() => new( + [ + new QueryEvent.ResultSetStarted(0, Columns), + new QueryEvent.ResultSetFinished(0, 3, null, Truncation.Complete), + new QueryEvent.ResultSetStarted(1, Columns), + new QueryEvent.ResultSetFinished(1, 4, null, Truncation.Complete), + new QueryEvent.Finished(new QueryOutcome.Completed(TimeSpan.FromMilliseconds(12)), TransactionState.Idle), + ]); + + public async IAsyncEnumerable ReadEventsAsync( + [EnumeratorCancellation] CancellationToken cancellationToken) + { + for (var index = 0; index < events.Count; index++) + { + if (index == events.Count - 1 && Reading is { } reading) + { + await reading.PassAsync(cancellationToken); + } + + yield return events[index]; + } + } + + // A fake run's sets live in no core. + public ResultSet? GetResultSet(int index) => null; + + public void Cancel() => Cancels++; + + public void Dispose() => Disposals++; +} + +// Reads a run as the results pane does, and keeps what it was asked to show. +internal sealed class FakeResults : IResultsView +{ + public List Shown { get; } = []; + + public GridSort Sort { get; set; } = GridSort.None; + + public GridSort RunSort { get; private set; } = GridSort.None; + + public IReadOnlyList Columns { get; private set; } = []; + + public int ResultSetCount { get; private set; } + + public long RowCount { get; private set; } + + public long ShownRowCount => RowCount; + + public TransactionState Transaction { get; private set; } + + public ResultSet? ShownSet => null; + + public bool SortsHeldRows { get; set; } = true; + + public event EventHandler? ShownSetChanged; + + public async Task ShowRunAsync(ITabRun run, GridSort sort, int visibleColumns, CancellationToken cancellationToken) + { + Shown.Add("run"); + RunSort = sort; + ResultSetCount = 0; + long? rows = null; + await foreach (var queryEvent in run.ReadEventsAsync(cancellationToken)) + { + switch (queryEvent) + { + case QueryEvent.ResultSetStarted started: + ResultSetCount++; + Columns = started.Columns; + break; + case QueryEvent.ResultSetFinished ended: + rows ??= ended.RowCount; + break; + case QueryEvent.Finished finished: + Transaction = finished.Transaction; + RowCount = rows ?? 0; + break; + default: + break; + } + } + } + + public Task SortHeldRowsAsync(GridSort sort) + { + Shown.Add("sort held"); + if (SortsHeldRows) + { + Sort = sort; + } + + return Task.FromResult(SortsHeldRows); + } + + public void ShowError(CoreError failure) => Shown.Add("error " + failure.Code); + + public void Clear() + { + Shown.Add("clear"); + ShownSetChanged?.Invoke(this, EventArgs.Empty); + } +} + +internal sealed class FakeQueryView : IQueryTabView +{ + public List Shown { get; } = []; + + public string SelectedText { get; set; } = string.Empty; + + public string WholeText { get; set; } = "select * from Artist"; + + public string DocumentText => WholeText; + + public int Caret { get; set; } + + public Func> Confirm { get; set; } = _ => Task.FromResult(true); + + public bool RollsBack { get; set; } = true; + + public bool CanCommit { get; private set; } + + public void SelectStatement(int start, int length) => Shown.Add($"selected {start} {length}"); + + public void ShowNoStatement() => Shown.Add("no statement"); + + public void ShowRefused() => Shown.Add("refused"); + + public void ShowTransactionLost() => Shown.Add("transaction lost"); + + public void ShowSortedHeld(long rows) => Shown.Add($"sorted held {rows}"); + + public void ShowTransaction(TransactionState state, bool changed, bool canCommit) + { + CanCommit = canCommit; + Shown.Add($"transaction {state}"); + } + + public void ShowRunning(bool running) => Shown.Add(running ? "running" : "idle"); + + public Task ConfirmWritesAsync(RunGate gate, string connection) + { + Shown.Add("asked " + connection); + return Confirm(gate); + } + + public Task ConfirmRollBackAsync() => Task.FromResult(RollsBack); + + public void CloseEditor() => Shown.Add("editor closed"); +} + +internal sealed class FakeTableView : ITableTabView +{ + public TableTab? Tab { get; set; } + + // The page each pager update drew. + public List Pagers { get; } = []; + + public List Shown { get; } = []; + + public List ReloadsAsked { get; } = []; + + public List<(string Table, int Rows)> DeletesAsked { get; } = []; + + public List> SavesAsked { get; } = []; + + public List<(IReadOnlyList Statements, CoreError? Failure)> Previews { get; } = []; + + public List<(CoreError Failure, bool Incomplete)> Failures { get; } = []; + + public List Refusals { get; } = []; + + public List Focused { get; } = []; + + public bool ShowsAllRows { get; set; } = true; + + public bool CommitsOpenEdit { get; set; } = true; + + public bool HasOpenEdit { get; set; } + + // What keeping the open editor's text does, as the grid raises CellEditCommitting. + public Action? OnCommit { get; set; } + + public bool? OffersSave { get; private set; } + + public bool DiscardsForReload { get; set; } = true; + + public bool Discards { get; set; } = true; + + public SaveBeforeClose CloseAnswer { get; set; } = SaveBeforeClose.Save; + + public bool ConfirmsDelete { get; set; } = true; + + public bool ConfirmsSave { get; set; } = true; + + public int EditsShown { get; private set; } + + public int ClosesAsked { get; private set; } + + public int SavesCancelled { get; private set; } + + public void ShowRunning(bool running) => UpdatePager(); + + public void UpdatePager() + { + if (Tab is { } tab) + { + Pagers.Add(tab.Page); + } + } + + public Task ConfirmAllRowsAsync(long total) => Task.FromResult(ShowsAllRows); + + public void ShowEdits() => EditsShown++; + + public void ShowSaving(bool saving) => Shown.Add(saving ? "saving" : "saved"); + + public void ShowEditRefusal(EditRefusal refusal) => Refusals.Add(refusal); + + public void ShowSaveCancelled() => SavesCancelled++; + + public bool CommitOpenEdit() + { + if (!CommitsOpenEdit || !HasOpenEdit) + { + return CommitsOpenEdit; + } + + HasOpenEdit = false; + OnCommit?.Invoke(); + return true; + } + + public void FocusRow(int row) => Focused.Add(row); + + public Task ConfirmDiscardForReloadAsync(ReloadReason reason) + { + ReloadsAsked.Add(reason); + return Task.FromResult(DiscardsForReload); + } + + public Task ConfirmDiscardAsync() => Task.FromResult(Discards); + + public Task AskSaveBeforeCloseAsync(string tab, bool offerSave) + { + ClosesAsked++; + OffersSave = offerSave; + return Task.FromResult(CloseAnswer); + } + + public Task ConfirmDeleteAsync(string table, int rows) + { + DeletesAsked.Add((table, rows)); + return Task.FromResult(ConfirmsDelete); + } + + public Task ConfirmSaveAsync(string connection, IReadOnlyList statements) + { + SavesAsked.Add(statements); + return Task.FromResult(ConfirmsSave); + } + + public Task ShowPreviewAsync(IReadOnlyList statements, CoreError? failure) + { + Previews.Add((statements, failure)); + return Task.CompletedTask; + } + + public Task ShowSaveFailedAsync(CoreError failure, bool incomplete) + { + Failures.Add((failure, incomplete)); + return Task.CompletedTask; + } +} + +// A stored cell reads "r{row}c{column}", and each change plans one statement named for its kind. +internal sealed class FakeTableEditor : ITableEditor +{ + public EditLock? Lock { get; set; } + + public EditLock? PageLock { get; set; } + + // Artist's key is filled by the server, so a new row leaves it as Default, and its name takes any text. + public IReadOnlyList Columns { get; set; } = + [ + new( + "ArtistId", + Editable: false, + EditableInNewRow: false, + CellEdit.ServerDefault.Instance, + Nullable: false, + PrimaryKey: true, + TakesEmpty: false, + TakesDefault: false), + new( + "Name", + Editable: true, + EditableInNewRow: true, + CellEdit.Null.Instance, + Nullable: true, + PrimaryKey: false, + TakesEmpty: true, + TakesDefault: false), + ]; + + public Func Start { get; set; } = (row, column) => new EditStart.Editable(Stored(row, column), IsNull: false); + + public Func Checker { get; set; } = (_, _, _) => null; + + public SaveGate Verdict { get; set; } = SaveGate.Run; + + public Func Outcome { get; set; } = () => new RowSaveOutcome.Saved(1); + + public Gate? Saving { get; set; } + + public CoreError? PlanFailure { get; set; } + + // The core leaves out cells edited back to their value, so a plan can be empty with changes pending. + public bool PlansNothing { get; set; } + + public List> Plans { get; } = []; + + public List Saves { get; } = []; + + public int Disposals { get; private set; } + + public static string Stored(long row, int column) => string.Create(CultureInfo.InvariantCulture, $"r{row}c{column}"); + + public EditLock? LockFor(ResultSet? rows) => PageLock; + + public EditStart GetEditStart(ResultSet? rows, long row, int column) => Start(row, column); + + public CoreError? Check(int column, CellEdit edit, bool newRow) => Checker(column, edit, newRow); + + public IRowSave Plan(ResultSet? rows, IReadOnlyList edits) + { + Plans.Add(edits); + if (PlanFailure is { } failure) + { + throw new TableProException(failure); + } + + var statements = PlansNothing ? new List() : edits.Select(Statement).ToList(); + var save = new FakeRowSave(statements, Verdict, Outcome, Saving); + Saves.Add(save); + return save; + } + + public void Dispose() => Disposals++; + + private static PlannedStatement Statement(RowEdit edit) => edit switch + { + RowEdit.Delete => new PlannedStatement("DELETE", []), + RowEdit.Update => new PlannedStatement("UPDATE", []), + _ => new PlannedStatement("INSERT", []), + }; +} + +internal sealed class FakeRowSave( + List statements, + SaveGate verdict, + Func outcome, + Gate? saving) : IRowSave +{ + public IReadOnlyList Statements => statements; + + public bool IsEmpty => statements.Count == 0; + + public SaveGate Gate => verdict; + + public int Runs { get; private set; } + + public int Disposals { get; private set; } + + public bool Confirmed { get; private set; } + + public async Task RunAsync(bool confirmed, CancellationToken cancellationToken) + { + Runs++; + Confirmed = confirmed; + if (saving is { } wait) + { + await wait.PassAsync(cancellationToken); + } + + return outcome(); + } + + public void Dispose() => Disposals++; +} + +internal static class Errors +{ + public static CoreError Of(string code, SecretKind? secret = null, HostKeyFailure? hostKey = null) => + new(code, [code], code, null, null, secret, hostKey); +} diff --git a/windows/tests/TablePro.App.Model.Tests/TableEditsTests.cs b/windows/tests/TablePro.App.Model.Tests/TableEditsTests.cs new file mode 100644 index 0000000000..b7f9df42b8 --- /dev/null +++ b/windows/tests/TablePro.App.Model.Tests/TableEditsTests.cs @@ -0,0 +1,272 @@ +using TablePro.DataGrid.Model; +using TablePro.Interop; + +namespace TablePro.App.Model.Tests; + +public sealed class TableEditsTests +{ + private static readonly IReadOnlyList Columns = + [ + Column("id", editable: false, CellEdit.ServerDefault.Instance, nullable: false, primaryKey: true), + Column("name", editable: true, CellEdit.Null.Instance, nullable: false), + Column("total", editable: false, CellEdit.ServerDefault.Instance, nullable: true), + ]; + + // A child row naming its parent by key: the order the save sends them in decides whether the key holds. + private static readonly IReadOnlyList Children = + [ + Column("id", editable: false, CellEdit.ServerDefault.Instance, nullable: false, primaryKey: true), + Column("name", editable: true, CellEdit.Null.Instance, nullable: true), + Column("parent", editable: true, CellEdit.Null.Instance, nullable: true), + ]; + + [Fact] + public void ACellEditedBackToItsStoredValueIsNoChange() + { + var edits = new TableEdits(Columns, dataRows: 3); + + edits.SetCell(1, 1, new CellEdit.Text("Grace Hopper"), stored: "Grace"); + var changed = edits.HasChanges; + edits.SetCell(1, 1, new CellEdit.Text("Grace"), stored: "Grace"); + + Assert.True(changed); + Assert.False(edits.HasChanges); + Assert.Null(edits.GetCell(1, 1)); + } + + [Fact] + public void NullOnAStoredNullIsNoChangeAndOnAValueIsOne() + { + var edits = new TableEdits(Columns, dataRows: 2); + + edits.SetCell(0, 2, CellEdit.Null.Instance, stored: null); + var onNull = edits.HasChanges; + edits.SetCell(1, 2, CellEdit.Null.Instance, stored: "10"); + + Assert.False(onNull); + Assert.Equal(CellEdit.Null.Instance, edits.GetCell(1, 2)); + } + + [Fact] + public void ANewRowStartsWithTheServersValuesAndFollowsTheDataRows() + { + var edits = new TableEdits(Columns, dataRows: 2); + + var row = edits.AddRow(); + edits.SetCell(row, 1, new CellEdit.Text("Edsger"), stored: null); + + Assert.Equal(2, row); + Assert.True(edits.IsAdded(row)); + Assert.Equal(3, edits.RowCount); + Assert.Equal(CellEdit.ServerDefault.Instance, edits.GetCell(row, 0)); + Assert.Equal(new CellEdit.Text("Edsger"), edits.GetCell(row, 1)); + } + + [Fact] + public void ADuplicateCopiesValuesButStartsTheKeyAndComputedColumnsAsANewRow() + { + var edits = new TableEdits(Columns, dataRows: 2); + edits.SetCell(0, 1, new CellEdit.Text("Ada Lovelace"), stored: "Ada"); + + var copy = edits.DuplicateRow(0, column => new CellEdit.Text("stored " + column)); + + Assert.Equal(CellEdit.ServerDefault.Instance, edits.GetCell(copy, 0)); + Assert.Equal(new CellEdit.Text("Ada Lovelace"), edits.GetCell(copy, 1)); + Assert.Equal(CellEdit.ServerDefault.Instance, edits.GetCell(copy, 2)); + } + + [Fact] + public void DeletingANewRowRemovesItAndADataRowIsMarkedWithoutItsEdits() + { + var edits = new TableEdits(Columns, dataRows: 2); + edits.SetCell(1, 1, new CellEdit.Text("changed"), stored: "Grace"); + var first = edits.AddRow(); + var second = edits.AddRow(); + edits.SetCell(second, 1, new CellEdit.Text("kept"), stored: null); + + edits.DeleteRows([1, first]); + + Assert.True(edits.IsDeleted(1)); + Assert.Null(edits.GetCell(1, 1)); + Assert.Equal(1, edits.AddedRows); + Assert.Equal(new CellEdit.Text("kept"), edits.GetCell(2, 1)); + } + + [Fact] + public void ARestoredRowIsNoLongerDeletedAndDiscardForgetsEverything() + { + var edits = new TableEdits(Columns, dataRows: 2); + edits.DeleteRows([0]); + + edits.RestoreRows([0]); + var restored = edits.HasChanges; + edits.AddRow(); + edits.Discard(); + + Assert.False(restored); + Assert.False(edits.HasChanges); + Assert.Equal(2, edits.RowCount); + } + + [Fact] + public void TheRowEditsNameTheGridRowEachCameFromWithEachRowAtItsLatestChange() + { + var edits = new TableEdits(Columns, dataRows: 3); + edits.SetCell(2, 1, new CellEdit.Text("third"), stored: "Linus"); + edits.DeleteRows([0]); + var added = edits.AddRow(); + edits.SetCell(2, 1, new CellEdit.Text("third again"), stored: "Linus"); + + var planned = edits.ToRowEdits(); + + Assert.Equal( + [ + new RowEdit.Delete(0), + new RowEdit.Insert([CellEdit.ServerDefault.Instance, CellEdit.Null.Instance, CellEdit.ServerDefault.Instance]), + new RowEdit.Update(2, [new CellChange(1, new CellEdit.Text("third again"))]), + ], + planned.Edits, + RowEditComparer.Instance); + Assert.Equal([0, added, 2], planned.Rows); + } + + [Fact] + public void ANewParentRowSavesBeforeTheChildPointedAtIt() + { + var edits = new TableEdits(Children, dataRows: 2); + + var parent = edits.AddRow(); + edits.SetCell(1, 2, new CellEdit.Text("new parent"), stored: "0"); + + Assert.Equal( + [ + new RowEdit.Insert([CellEdit.ServerDefault.Instance, CellEdit.Null.Instance, CellEdit.Null.Instance]), + new RowEdit.Update(1, [new CellChange(2, new CellEdit.Text("new parent"))]), + ], + edits.ToRowEdits().Edits, + RowEditComparer.Instance); + Assert.Equal([parent, 1], edits.ToRowEdits().Rows); + } + + [Fact] + public void AChildEditedBeforeItsNewParentWasAddedSavesAfterThatParentOnceItPointsAtIt() + { + var edits = new TableEdits(Children, dataRows: 2); + + edits.SetCell(1, 1, new CellEdit.Text("renamed child"), stored: "child"); + edits.AddRow(); + edits.SetCell(1, 2, new CellEdit.Text("new parent"), stored: "0"); + + Assert.Equal( + [ + new RowEdit.Insert([CellEdit.ServerDefault.Instance, CellEdit.Null.Instance, CellEdit.Null.Instance]), + new RowEdit.Update( + 1, + [ + new CellChange(1, new CellEdit.Text("renamed child")), + new CellChange(2, new CellEdit.Text("new parent")), + ]), + ], + edits.ToRowEdits().Edits, + RowEditComparer.Instance); + } + + [Fact] + public void ChildrenPointedAwaySaveBeforeTheirParentIsDeleted() + { + var edits = new TableEdits(Children, dataRows: 3); + + edits.SetCell(1, 2, new CellEdit.Text("2"), stored: "0"); + edits.SetCell(2, 2, CellEdit.Null.Instance, stored: "0"); + edits.DeleteRows([0]); + + Assert.Equal( + [ + new RowEdit.Update(1, [new CellChange(2, new CellEdit.Text("2"))]), + new RowEdit.Update(2, [new CellChange(2, CellEdit.Null.Instance)]), + new RowEdit.Delete(0), + ], + edits.ToRowEdits().Edits, + RowEditComparer.Instance); + } + + [Fact] + public void ARowWhoseChangesAreUndoneLeavesTheOrderAndComesBackAtItsNextChange() + { + var edits = new TableEdits(Children, dataRows: 3); + edits.SetCell(1, 2, new CellEdit.Text("changed"), stored: "0"); + edits.DeleteRows([2]); + + edits.SetCell(1, 2, new CellEdit.Text("0"), stored: "0"); + edits.RestoreRows([2]); + edits.DeleteRows([2]); + edits.SetCell(1, 2, new CellEdit.Text("later"), stored: "0"); + + Assert.Equal([2, 1], edits.ToRowEdits().Rows); + } + + [Fact] + public void DeletingEveryRowOfALargePageTakesOnePass() + { + var edits = new TableEdits(Children, dataRows: 100_000); + for (var row = 0; row < 100_000; row += 2) + { + edits.SetCell(row, 1, new CellEdit.Text("edited"), stored: "stored"); + } + + edits.DeleteRows(Enumerable.Range(0, 100_000)); + var planned = edits.ToRowEdits(); + + Assert.Equal(100_000, planned.Edits.Count); + Assert.All(planned.Edits, edit => Assert.IsType(edit)); + Assert.Null(edits.GetCell(0, 1)); + } + + [Fact] + public void TheSnapshotShowsEachChangeAndStaysTheSameUntilTheNext() + { + var edits = new TableEdits(Columns, dataRows: 2); + edits.SetCell(0, 1, new CellEdit.Text("Ada Lovelace"), stored: "Ada"); + edits.DeleteRows([1]); + edits.AddRow(); + + var snapshot = edits.Snapshot(); + + Assert.Same(snapshot, edits.Snapshot()); + Assert.True(snapshot.IsModified(0)); + Assert.True(snapshot.TryGetCell(0, 1, out var cell)); + Assert.Equal(new PendingCell(PendingKind.Value, "Ada Lovelace"), cell); + Assert.True(snapshot.IsDeleted(1)); + Assert.Equal(1, snapshot.AddedRows); + Assert.Equal(PendingKind.Default, snapshot.GetAddedCell(0, 0).Kind); + edits.AddRow(); + Assert.NotSame(snapshot, edits.Snapshot()); + } + + // A saved row edits where `editable` says; a new row takes a value wherever the server does not fill it. + private static EditColumn Column(string name, bool editable, CellEdit newRow, bool nullable, bool primaryKey = false) => + new( + name, + editable, + EditableInNewRow: newRow is not CellEdit.ServerDefault, + newRow, + nullable, + primaryKey, + TakesEmpty: editable, + TakesDefault: false); + + // Records holding lists compare the lists by reference. + private sealed class RowEditComparer : IEqualityComparer + { + public static RowEditComparer Instance { get; } = new(); + + public bool Equals(RowEdit? x, RowEdit? y) => (x, y) switch + { + (RowEdit.Update a, RowEdit.Update b) => a.Row == b.Row && a.Cells.SequenceEqual(b.Cells), + (RowEdit.Insert a, RowEdit.Insert b) => a.Cells.SequenceEqual(b.Cells), + _ => object.Equals(x, y), + }; + + public int GetHashCode(RowEdit obj) => 0; + } +} diff --git a/windows/tests/TablePro.App.Model.Tests/TableTabEditingTests.cs b/windows/tests/TablePro.App.Model.Tests/TableTabEditingTests.cs new file mode 100644 index 0000000000..8b9292cb00 --- /dev/null +++ b/windows/tests/TablePro.App.Model.Tests/TableTabEditingTests.cs @@ -0,0 +1,558 @@ +using TablePro.DataGrid.Model; +using TablePro.Interop; + +namespace TablePro.App.Model.Tests; + +public sealed class TableTabEditingTests +{ + private readonly FakeSession _session = new() { TableRows = 3 }; + private readonly FakeTableView _view = new(); + private readonly FakeResults _results = new(); + private readonly TableTab _tab; + + public TableTabEditingTests() + { + _tab = new TableTab(_session, _view, _results, new TableName(null, "Artist"), () => new AppSettings()); + _view.Tab = _tab; + } + + private FakeTableEditor Editor => _session.TableEditor; + + [Fact] + public async Task APageReadMakesEditsForItsRowsAndAKeptEditStaysPending() + { + await _tab.RunAsync(); + + var edits = Assert.IsType(_tab.Edits); + Assert.Equal(3, edits.DataRows); + Assert.True(_tab.CanEdit); + Assert.Null(_tab.StartEdit(1, 1, out var stored)); + Assert.Equal("r1c1", stored); + Assert.Null(_tab.CommitEdit(1, 1, "Accept II")); + Assert.True(_tab.HasUnsavedChanges); + Assert.Null(_tab.StartEdit(1, 1, out var pending)); + Assert.Equal("Accept II", pending); + Assert.Null(_tab.CommitEdit(1, 1, "r1c1")); + Assert.False(_tab.HasUnsavedChanges); + Assert.True(_view.EditsShown > 0); + } + + [Fact] + public async Task AnEditTheCoreRefusesIsNotKeptAndSaysWhy() + { + var failure = Errors.Of("edit.invalid_integer"); + Editor.Checker = (_, _, _) => failure; + await _tab.RunAsync(); + + var refusal = Assert.IsType(_tab.CommitEdit(0, 1, "x")); + + Assert.Same(failure, refusal.Failure); + Assert.False(_tab.HasUnsavedChanges); + } + + [Fact] + public async Task AValueWithNoTextToEditARowMarkedForDeleteAndACellPastThePageDoNotOpen() + { + Editor.Start = (_, column) => + column == 1 ? (EditStart)EditStart.Locked.Instance : new EditStart.Editable("1", IsNull: false); + await _tab.RunAsync(); + + Assert.IsType(_tab.StartEdit(0, 1, out _)); + Assert.Null(_tab.DeleteRows([2])); + Assert.IsType(_tab.StartEdit(2, 0, out _)); + Assert.IsType(_tab.StartEdit(9, 0, out _)); + Assert.IsType(_tab.CommitEdit(0, 1, "x")); + } + + [Fact] + public async Task AReadOnlyConnectionLocksEveryEditAndSaysWhy() + { + Editor.Lock = EditLock.ReadOnlyConnection; + await _tab.RunAsync(); + + Assert.True(_tab.AcceptsEdits); + Assert.False(_tab.CanEdit); + Assert.Equal(new EditRefusal.TableLocked(EditLock.ReadOnlyConnection), _tab.StartEdit(0, 1, out _)); + Assert.IsType(_tab.AddRow(out _)); + Assert.IsType(_tab.DeleteRows([0])); + Assert.False(_tab.CanSetValue(0, 1, CellValueKind.Null)); + Assert.False(_tab.HasUnsavedChanges); + } + + [Fact] + public async Task ATableEditorThatCannotOpenLeavesThePageShownAndReadOnly() + { + _session.TableEditorFailure = Errors.Of("catalog.columns_unavailable"); + + await _tab.RunAsync(); + + Assert.Single(_session.Queries); + Assert.Null(_tab.Edits); + Assert.False(_tab.AcceptsEdits); + Assert.IsType(_tab.StartEdit(0, 1, out _)); + } + + [Fact] + public async Task TheTableEditorOpensWithThePageAndAgainOnRefresh() + { + await _tab.RunAsync(); + await _tab.FirstPageAsync(); + + Assert.Equal(1, _session.TableEditorOpens); + + await _tab.RefreshAsync(); + + Assert.Equal(2, _session.TableEditorOpens); + Assert.Equal([false, true], _session.TableEditorRefreshes); + } + + [Fact] + public async Task SetValueOffersWhatTheColumnTakesAndDefaultInANewRowWhereTheServerFillsIt() + { + Editor.Columns = + [ + Editor.Columns[0], + Editor.Columns[1], + new( + "Country", + Editable: true, + EditableInNewRow: true, + CellEdit.ServerDefault.Instance, + Nullable: false, + PrimaryKey: false, + TakesEmpty: false, + TakesDefault: true), + ]; + await _tab.RunAsync(); + var edits = Assert.IsType(_tab.Edits); + + Assert.False(_tab.CanSetValue(0, 0, CellValueKind.Null)); + Assert.True(_tab.CanSetValue(0, 1, CellValueKind.Null)); + Assert.True(_tab.CanSetValue(0, 1, CellValueKind.Empty)); + Assert.False(_tab.CanSetValue(0, 2, CellValueKind.Empty)); + Assert.False(_tab.CanSetValue(0, 1, CellValueKind.Default)); + Assert.True(_tab.CanSetValue(0, 2, CellValueKind.Default)); + Assert.Null(_tab.AddRow(out var row)); + Assert.False(_tab.CanSetValue(row, 0, CellValueKind.Default)); + Assert.False(_tab.CanSetValue(row, 1, CellValueKind.Default)); + Assert.True(_tab.CanSetValue(row, 2, CellValueKind.Default)); + Assert.Null(_tab.SetValue(0, 1, CellValueKind.Null)); + Assert.Null(_tab.SetValue(1, 1, CellValueKind.Empty)); + Assert.Null(_tab.SetValue(2, 2, CellValueKind.Default)); + Assert.IsType(_tab.SetValue(0, 0, CellValueKind.Null)); + + Assert.Equal(CellEdit.Null.Instance, edits.GetCell(0, 1)); + Assert.Equal(new CellEdit.Text(string.Empty), edits.GetCell(1, 1)); + Assert.Equal(CellEdit.ServerDefault.Instance, edits.GetCell(2, 2)); + } + + [Fact] + public async Task APageWhoseKeysCannotBeReadBackExactlyIsReadOnly() + { + Editor.PageLock = EditLock.KeyUnreadable; + + await _tab.RunAsync(); + + Assert.Equal(EditLock.KeyUnreadable, _tab.Lock); + Assert.False(_tab.CanEdit); + Assert.Equal(new EditRefusal.TableLocked(EditLock.KeyUnreadable), _tab.StartEdit(0, 1, out _)); + } + + [Fact] + public async Task AnOpenEditTheGridCannotKeepHoldsBackAReloadAndAClose() + { + await _tab.RunAsync(); + _view.CommitsOpenEdit = false; + + await _tab.RefreshAsync(); + + Assert.Single(_session.Queries); + Assert.False(await _tab.ConfirmCloseAsync(offerSave: true)); + Assert.Equal(0, _view.ClosesAsked); + } + + [Fact] + public async Task AddDuplicateDeleteAndRestoreChangeThePendingRows() + { + await _tab.RunAsync(); + var edits = Assert.IsType(_tab.Edits); + + Assert.Null(_tab.AddRow(out var added)); + Assert.Equal(3, added); + Assert.Equal(1, _tab.FirstColumnToFill); + Assert.Null(_tab.DuplicateRows([1, 0], out var last)); + Assert.Equal(5, last); + Assert.Equal(new CellEdit.Text("r0c1"), edits.GetCell(4, 1)); + Assert.Equal(CellEdit.ServerDefault.Instance, edits.GetCell(4, 0)); + Assert.Null(_tab.DeleteRows([0, added])); + Assert.True(edits.IsDeleted(0)); + Assert.Equal(2, edits.AddedRows); + Assert.Null(_tab.RestoreRows([0])); + Assert.False(edits.IsDeleted(0)); + } + + [Fact] + public async Task EveryReloadAsksWhileChangesArePendingAndANoKeepsThem() + { + await _tab.RunAsync(); + _tab.CommitEdit(0, 1, "changed"); + _view.DiscardsForReload = false; + + await _tab.RefreshAsync(); + await _tab.SortAsync(new GridSort(1, SortDirection.Ascending)); + await _tab.ResizeAsync(500); + await _tab.FirstPageAsync(); + + Assert.Equal( + [ReloadReason.Refresh, ReloadReason.Sort, ReloadReason.PageSize, ReloadReason.Page], + _view.ReloadsAsked); + Assert.Single(_session.Queries); + Assert.True(_tab.HasUnsavedChanges); + Assert.False(await _tab.MayReloadAsync(ReloadReason.Refresh)); + + _view.DiscardsForReload = true; + await _tab.RefreshAsync(); + + Assert.Equal(2, _session.Queries.Count); + Assert.False(_tab.HasUnsavedChanges); + Assert.NotNull(_tab.Edits); + } + + [Fact] + public async Task DiscardAsksFirstAndForgetsEveryChange() + { + await _tab.RunAsync(); + _tab.AddRow(out _); + _view.Discards = false; + + await _tab.DiscardAsync(); + + Assert.True(_tab.HasUnsavedChanges); + + _view.Discards = true; + await _tab.DiscardAsync(); + + Assert.False(_tab.HasUnsavedChanges); + Assert.Single(_session.Queries); + } + + [Fact] + public async Task PreviewShowsThePlannedStatementsOrWhyThereAreNone() + { + await _tab.RunAsync(); + _tab.CommitEdit(0, 1, "changed"); + _tab.DeleteRows([1]); + _tab.AddRow(out _); + + await _tab.PreviewAsync(); + + var (statements, failure) = Assert.Single(_view.Previews); + Assert.Null(failure); + Assert.Equal(["UPDATE", "DELETE", "INSERT"], statements.Select(statement => statement.Sql)); + + Editor.PlanFailure = Errors.Of("build.no_insert_values"); + await _tab.PreviewAsync(); + + Assert.Equal("build.no_insert_values", _view.Previews[^1].Failure?.Code); + Assert.DoesNotContain(Editor.Saves, save => save.Runs > 0); + Assert.True(_tab.HasUnsavedChanges); + } + + [Fact] + public async Task ASaveThatWritesClearsTheChangesAndReadsThePageAgainWithoutAsking() + { + await _tab.RunAsync(); + _tab.CommitEdit(0, 1, "changed"); + + Assert.True(await _tab.SaveAsync()); + + Assert.False(_tab.HasUnsavedChanges); + Assert.Equal(2, _session.Queries.Count); + Assert.Empty(_view.ReloadsAsked); + Assert.Empty(_view.DeletesAsked); + Assert.Empty(_view.SavesAsked); + var save = Assert.Single(Editor.Saves); + Assert.Equal(1, save.Runs); + Assert.True(save.Confirmed); + Assert.Equal(1, save.Disposals); + Assert.Equal(["saving", "saved"], _view.Shown); + Assert.False(_tab.IsSaving); + } + + [Fact] + public async Task EveryDeleteIsAskedAboutAndANoSavesNothing() + { + await _tab.RunAsync(); + _tab.DeleteRows([0, 2]); + _view.ConfirmsDelete = false; + + Assert.False(await _tab.SaveAsync()); + + Assert.Equal(("Artist", 2), Assert.Single(_view.DeletesAsked)); + Assert.Equal(0, Assert.Single(Editor.Saves).Runs); + Assert.True(_tab.HasUnsavedChanges); + } + + [Fact] + public async Task ConfirmWritesShowsTheStatementsAfterTheDeleteQuestionAndCancelSavesNothing() + { + Editor.Verdict = SaveGate.Confirm; + await _tab.RunAsync(); + _tab.DeleteRows([1]); + _view.ConfirmsSave = false; + + Assert.False(await _tab.SaveAsync()); + + Assert.Single(_view.DeletesAsked); + Assert.Equal("DELETE", Assert.Single(Assert.Single(_view.SavesAsked)).Sql); + Assert.Equal(1, _view.SavesCancelled); + Assert.Equal(0, Assert.Single(Editor.Saves).Runs); + + _view.ConfirmsSave = true; + + Assert.True(await _tab.SaveAsync()); + Assert.Equal(1, Editor.Saves[^1].Runs); + Assert.True(Editor.Saves[^1].Confirmed); + } + + [Fact] + public async Task AReadOnlyLevelAtSaveTimeRefusesTheSave() + { + Editor.Verdict = SaveGate.Refuse; + await _tab.RunAsync(); + _tab.CommitEdit(0, 1, "changed"); + + Assert.False(await _tab.SaveAsync()); + + Assert.Equal(new EditRefusal.TableLocked(EditLock.ReadOnlyConnection), Assert.Single(_view.Refusals)); + Assert.Equal(0, Assert.Single(Editor.Saves).Runs); + Assert.True(_tab.HasUnsavedChanges); + } + + [Fact] + public async Task APlanWithNothingToWriteDropsTheChanges() + { + Editor.PlansNothing = true; + await _tab.RunAsync(); + _tab.CommitEdit(0, 1, "1.0"); + + Assert.True(await _tab.SaveAsync()); + + Assert.False(_tab.HasUnsavedChanges); + Assert.Equal(0, Assert.Single(Editor.Saves).Runs); + Assert.Single(_session.Queries); + } + + [Fact] + public async Task ARolledBackSaveKeepsEveryChangeAndShowsTheRowItStoppedAt() + { + Editor.Outcome = () => new RowSaveOutcome.RolledBack(Errors.Of("driver.row_guard_failed"), 1); + await _tab.RunAsync(); + _tab.DeleteRows([0]); + _tab.CommitEdit(2, 1, "changed"); + + Assert.False(await _tab.SaveAsync()); + + var (failure, incomplete) = Assert.Single(_view.Failures); + Assert.Equal("driver.row_guard_failed", failure.Code); + Assert.False(incomplete); + Assert.Equal(2, Assert.Single(_view.Focused)); + Assert.True(_tab.HasUnsavedChanges); + Assert.True(_tab.CanSave); + Assert.Single(_session.Queries); + } + + [Fact] + public async Task AnUnknownOutcomeKeepsTheChangesAndRefusesASaveUntilTheRowsAreReadAgain() + { + Editor.Outcome = () => new RowSaveOutcome.Unknown(Errors.Of("driver.commit_outcome_unknown"), 0); + await _tab.RunAsync(); + _tab.CommitEdit(0, 1, "changed"); + + Assert.False(await _tab.SaveAsync()); + + Assert.True(Assert.Single(_view.Failures).Incomplete); + Assert.Equal(0, Assert.Single(_view.Focused)); + Assert.True(_tab.HasUnsavedChanges); + Assert.False(_tab.CanSave); + Assert.False(await _tab.SaveAsync()); + Assert.IsType(Assert.Single(_view.Refusals)); + Assert.Single(Editor.Saves); + + await _tab.RefreshAsync(); + _tab.CommitEdit(0, 1, "again"); + + Assert.True(_tab.CanSave); + } + + [Fact] + public async Task ASaveTheCoreRefusesToRunKeepsTheChanges() + { + Editor.Outcome = () => throw new TableProException(Errors.Of("edit.safe_mode_changed")); + await _tab.RunAsync(); + _tab.CommitEdit(0, 1, "changed"); + + Assert.False(await _tab.SaveAsync()); + + Assert.Equal("edit.safe_mode_changed", Assert.Single(_view.Failures).Failure.Code); + Assert.False(Assert.Single(_view.Failures).Incomplete); + Assert.True(_tab.HasUnsavedChanges); + Assert.True(_tab.CanSave); + Assert.False(_tab.IsSaving); + } + + [Fact] + public async Task AnyOtherFailureOfARunningSaveIsTakenAsMaybeWrittenAndBlocksTheNext() + { + Editor.Outcome = () => throw new TableProException(Errors.Of("ffi.panicked")); + await _tab.RunAsync(); + _tab.CommitEdit(0, 1, "changed"); + + Assert.False(await _tab.SaveAsync()); + + Assert.True(Assert.Single(_view.Failures).Incomplete); + Assert.True(_tab.HasUnsavedChanges); + Assert.False(_tab.CanSave); + } + + [Fact] + public async Task ADiscardingReloadClearsTheSaveBlockEvenWhenTheReloadFails() + { + Editor.Outcome = () => new RowSaveOutcome.Unknown(Errors.Of("driver.commit_outcome_unknown"), null); + await _tab.RunAsync(); + _tab.CommitEdit(0, 1, "changed"); + Assert.False(await _tab.SaveAsync()); + _session.QueryFailure = Errors.Of("ffi.not_connected"); + + await _tab.RefreshAsync(); + _tab.CommitEdit(0, 1, "again"); + + Assert.Equal("error ffi.not_connected", _results.Shown[^1]); + Assert.True(_tab.CanSave); + } + + [Fact] + public async Task AValueStillInTheOpenEditorCountsAsUnsavedAndSaveKeepsItFirst() + { + await _tab.RunAsync(); + _view.HasOpenEdit = true; + _view.OnCommit = () => _tab.CommitEdit(0, 1, "typed"); + + Assert.True(_tab.HasUnsavedChanges); + Assert.True(_tab.CanSave); + Assert.True(await _tab.SaveAsync()); + + Assert.False(_view.HasOpenEdit); + Assert.Equal(1, Assert.Single(Editor.Saves).Runs); + Assert.IsType(Assert.Single(Assert.Single(Editor.Plans))); + } + + [Fact] + public async Task AnOpenEditorWhoseTextIsUnchangedClosesWithoutAQuestion() + { + await _tab.RunAsync(); + _view.HasOpenEdit = true; + + Assert.True(_tab.HasUnsavedChanges); + Assert.True(await _tab.ConfirmCloseAsync(offerSave: true)); + + Assert.Equal(0, _view.ClosesAsked); + } + + [Fact] + public async Task ACloseWhileASaveRunsWaitsForItAndAsksNothingOnceItSaved() + { + var saving = new Gate(); + Editor.Saving = saving; + await _tab.RunAsync(); + _tab.CommitEdit(0, 1, "changed"); + + var save = _tab.SaveAsync(); + await saving.Reached; + var closing = _tab.ConfirmCloseAsync(offerSave: true); + var waited = !closing.IsCompleted; + saving.Open(); + + Assert.True(await closing); + Assert.True(await save); + Assert.True(waited); + Assert.Equal(0, _view.ClosesAsked); + } + + [Fact] + public async Task MakingTheConnectionReadOnlyOffersOnlyDontSaveAndCancel() + { + await _tab.RunAsync(); + _tab.CommitEdit(0, 1, "changed"); + _view.CloseAnswer = SaveBeforeClose.Save; + + Assert.False(await _tab.ConfirmCloseAsync(offerSave: false)); + + Assert.False(_view.OffersSave); + Assert.Empty(Editor.Plans); + + _view.CloseAnswer = SaveBeforeClose.DontSave; + + Assert.True(await _tab.ConfirmCloseAsync(offerSave: false)); + } + + [Fact] + public async Task AnOpenEditTheGridCannotKeepStopsTheSave() + { + await _tab.RunAsync(); + _tab.CommitEdit(0, 1, "changed"); + _view.CommitsOpenEdit = false; + + Assert.False(await _tab.SaveAsync()); + + Assert.Empty(Editor.Plans); + } + + [Fact] + public async Task ClosingDuringASaveWaitsForItAndReadsNothingAfter() + { + var saving = new Gate(); + Editor.Saving = saving; + await _tab.RunAsync(); + _tab.CommitEdit(0, 1, "changed"); + + var save = _tab.SaveAsync(); + await saving.Reached; + var closing = _tab.CloseAsync(); + var waited = !closing.IsCompleted; + saving.Open(); + + Assert.True(await save); + await closing; + Assert.True(waited); + Assert.Single(_session.Queries); + Assert.Equal(1, Editor.Disposals); + Assert.Equal(1, _session.Releases); + } + + [Fact] + public async Task ACloseAsksAboutPendingChangesAndClosesOnlyOnceTheyAreSavedOrLeft() + { + await _tab.RunAsync(); + + Assert.True(await _tab.ConfirmCloseAsync(offerSave: true)); + Assert.Equal(0, _view.ClosesAsked); + + _tab.CommitEdit(0, 1, "changed"); + _view.CloseAnswer = SaveBeforeClose.Cancel; + Assert.False(await _tab.ConfirmCloseAsync(offerSave: true)); + _view.CloseAnswer = SaveBeforeClose.DontSave; + Assert.True(await _tab.ConfirmCloseAsync(offerSave: true)); + Assert.True(_tab.HasUnsavedChanges); + + _view.CloseAnswer = SaveBeforeClose.Save; + Editor.Outcome = () => new RowSaveOutcome.RolledBack(Errors.Of("driver.rolled_back"), null); + Assert.False(await _tab.ConfirmCloseAsync(offerSave: true)); + Editor.Outcome = () => new RowSaveOutcome.Saved(1); + Assert.True(await _tab.ConfirmCloseAsync(offerSave: true)); + + Assert.False(_tab.HasUnsavedChanges); + Assert.Equal(4, _view.ClosesAsked); + Assert.Single(_session.Queries); + } +} diff --git a/windows/tests/TablePro.App.Model.Tests/TableTabTests.cs b/windows/tests/TablePro.App.Model.Tests/TableTabTests.cs new file mode 100644 index 0000000000..b599c92ac2 --- /dev/null +++ b/windows/tests/TablePro.App.Model.Tests/TableTabTests.cs @@ -0,0 +1,287 @@ +using TablePro.DataGrid.Model; +using TablePro.Interop; + +namespace TablePro.App.Model.Tests; + +public sealed class TableTabTests +{ + private readonly FakeSession _session = new() { TableRows = 3_503 }; + private readonly FakeTableView _view = new(); + private readonly FakeResults _results = new(); + private readonly TableTab _tab; + private AppSettings _settings = new(); + + public TableTabTests() + { + _tab = New(); + } + + [Fact] + public async Task AFullFirstPageCountsTheTableAndPagesToItsLastAndToAPageInIt() + { + await _tab.RunAsync(); + + Assert.Equal(1_000, _tab.Page.Rows); + Assert.Equal(3_503, _tab.Page.Total); + Assert.Equal(4, _tab.Page.Count); + + await _tab.LastPageAsync(); + + Assert.Equal(3_000, _tab.Page.Offset); + Assert.Equal(503, _tab.Page.Rows); + + await _tab.GoToPageAsync(2); + await _tab.GoToPageAsync(9); + await _tab.PreviousPageAsync(); + await _tab.NextPageAsync(); + await _tab.FirstPageAsync(); + + Assert.Equal([0, 3_000, 1_000, 0, 1_000, 0], _session.Queries.Select(query => query.Offset)); + Assert.Equal(1, _session.Counts); + } + + [Fact] + public async Task AFirstPageThatIsNotFullIsTheWholeTableWithNoCount() + { + _session.TableRows = 347; + + await _tab.RunAsync(); + + Assert.Equal(347, _tab.Page.Total); + Assert.Equal(0, _session.Counts); + Assert.False(_tab.Page.IsPaged); + } + + [Fact] + public async Task ARefreshCountsTheTableAgain() + { + await _tab.RunAsync(); + _session.TableRows = 4_000; + + await _tab.RefreshAsync(); + + Assert.Equal(2, _session.Counts); + Assert.Equal(4_000, _tab.Page.Total); + } + + [Fact] + public async Task ANewPageSizeKeepsThePageHoldingTheFirstRowAndTheSnapshotKeepsBoth() + { + await _tab.RunAsync(); + await _tab.GoToPageAsync(3); + + await _tab.ResizeAsync(500); + + Assert.Equal(500, _tab.Page.Size); + Assert.Equal(2_000, _tab.Page.Offset); + Assert.Equal(500, _session.Queries[^1].Limit); + var snapshot = _tab.Snapshot(); + Assert.Equal(500, snapshot.PageSize); + Assert.Equal(2_000, snapshot.Offset); + var restored = New(snapshot); + Assert.Equal(500, restored.Page.Size); + Assert.Equal(2_000, restored.Page.Offset); + } + + [Fact] + public async Task ADefaultPageSizeChangedInSettingsAppliesFromThePageShown() + { + await _tab.RunAsync(); + await _tab.GoToPageAsync(2); + _settings = new AppSettings { PageSize = 500 }; + + await _tab.RefreshAsync(); + + Assert.Equal(500, _tab.Page.Size); + Assert.Equal(1_000, _tab.Page.Offset); + Assert.Null(_tab.Snapshot().PageSize); + } + + [Fact] + public async Task AllRowsAsksFirstAndShowsTheCountedTableOnOnePage() + { + await _tab.RunAsync(); + _view.ShowsAllRows = false; + + await _tab.ShowAllRowsAsync(); + + Assert.Equal(1_000, _tab.Page.Size); + + _view.ShowsAllRows = true; + await _tab.ShowAllRowsAsync(); + + Assert.Equal(3_503, _tab.Page.Size); + Assert.Equal(0, _tab.Page.Offset); + Assert.Equal(3_503, _tab.Snapshot().PageSize); + } + + [Fact] + public void ARestoredTabStartsAtThePageHoldingItsFirstRow() + { + var tab = New(new SessionTab + { + Kind = TabKind.Table, + Title = "Artist", + Table = "Artist", + PageSize = 20, + Offset = 45, + }); + + Assert.Equal(40, tab.Page.Offset); + Assert.Equal(20, tab.Page.Size); + Assert.True(tab.Shows(null, "Artist")); + Assert.False(tab.Shows("main", "Artist")); + } + + [Fact] + public async Task ASortReadsTheFirstPageInOrderAndARefusedOneKeepsTheShownSort() + { + await _tab.RunAsync(); + await _tab.NextPageAsync(); + var sort = new GridSort(1, SortDirection.Descending); + + await _tab.SortAsync(sort); + + var (sorted, _, offset) = _session.Queries[^1]; + Assert.Equal(new ColumnSort(1, false), sorted); + Assert.Equal(0, offset); + Assert.Equal(sort, _results.RunSort); + + _session.RefusesSort = true; + await _tab.SortAsync(new GridSort(0, SortDirection.Ascending)); + + Assert.Equal(sort, _results.Sort); + Assert.Equal("error ffi.sort_unsupported", _results.Shown[^1]); + } + + [Fact] + public async Task EveryReloadMayGoWhileTheTabHasNothingOfItsOwnToLose() + { + Assert.False(_tab.HasUnsavedChanges); + Assert.Equal(TransactionState.Idle, _tab.Transaction); + foreach (var reason in Enum.GetValues()) + { + Assert.True(await _tab.MayReloadAsync(reason)); + } + } + + [Fact] + public async Task ATableTabClosedWhileItsEditorOpensLetsItsSessionGoOnceAndShowsNothing() + { + var opening = new Gate(); + _session.Opening = opening; + + var loading = _tab.RunAsync(); + await opening.Reached; + await _tab.CloseAsync(); + await loading; + + Assert.Empty(_session.Editors); + Assert.Empty(_session.Queries); + Assert.Equal(1, _session.Releases); + Assert.Equal(["clear"], _results.Shown); + } + + [Fact] + public async Task ATableTabClosedWhileItsPageIsWrittenDisposesItsEditorOnceAndRunsNothing() + { + var querying = new Gate(honorsCancel: false); + _session.Querying = querying; + + var loading = _tab.RunAsync(); + await querying.Reached; + var closing = _tab.CloseAsync(); + var waited = !closing.IsCompleted; + querying.Open(); + await closing; + await loading; + + Assert.True(waited); + var editor = Assert.Single(_session.Editors); + Assert.Equal(1, editor.Disposals); + Assert.Empty(editor.Runs); + Assert.Equal(1, _session.TableEditor.Disposals); + Assert.Equal(1, _session.Releases); + Assert.Equal(["clear"], _results.Shown); + } + + [Fact] + public async Task ATableTabClosedWhileItsPageIsReadStopsTheRunAndCountsNothing() + { + var reading = new Gate(); + _session.PageReading = reading; + + var loading = _tab.RunAsync(); + await reading.Reached; + await _tab.CloseAsync(); + await loading; + + var editor = Assert.Single(_session.Editors); + var run = Assert.Single(editor.Started); + Assert.Equal(1, run.Cancels); + Assert.Equal(1, run.Disposals); + Assert.Equal(1, editor.Disposals); + Assert.Equal(1, _session.Releases); + Assert.Equal(0, _session.Counts); + Assert.Equal(["run", "clear"], _results.Shown); + } + + [Fact] + public async Task ATableTabClosedWhileItCountsStopsTheCountAndLetsGoOnce() + { + var counting = new Gate(); + _session.Counting = counting; + await _tab.RunAsync(); + await counting.Reached; + var pagers = _view.Pagers.Count; + + await _tab.CloseAsync(); + + Assert.Equal(1, Assert.Single(_session.Editors).Disposals); + Assert.Equal(1, _session.Releases); + Assert.Null(_tab.Page.Total); + Assert.Equal(pagers, _view.Pagers.Count); + } + + [Fact] + public async Task ACountThatLandsAsTheTabClosesIsNotShown() + { + var counting = new Gate(honorsCancel: false); + _session.Counting = counting; + await _tab.RunAsync(); + var pagers = _view.Pagers.Count; + + var closing = _tab.CloseAsync(); + var waited = !closing.IsCompleted; + counting.Open(); + await closing; + + Assert.True(waited); + Assert.Null(_tab.Page.Total); + Assert.Equal(pagers, _view.Pagers.Count); + Assert.Equal(1, _session.Releases); + Assert.Equal(1, Assert.Single(_session.Editors).Disposals); + } + + [Fact] + public async Task TheRowsShownGoWithTheClose() + { + var changes = 0; + _tab.ShownRowsChanged += (_, _) => changes++; + await _tab.RunAsync(); + + await _tab.CloseAsync(); + await _tab.RunAsync(); + + Assert.Equal(1, changes); + Assert.Null(_tab.ShownRows); + Assert.Single(_session.Queries); + } + + private TableTab New(SessionTab? restore = null) + { + var tab = new TableTab(_session, _view, _results, new TableName(null, "Artist"), () => _settings, restore); + _view.Tab = tab; + return tab; + } +} diff --git a/windows/tests/TablePro.App.Model.Tests/WorkspaceTabsTests.cs b/windows/tests/TablePro.App.Model.Tests/WorkspaceTabsTests.cs new file mode 100644 index 0000000000..f551b6488b --- /dev/null +++ b/windows/tests/TablePro.App.Model.Tests/WorkspaceTabsTests.cs @@ -0,0 +1,260 @@ +using TablePro.Interop; + +namespace TablePro.App.Model.Tests; + +public sealed class WorkspaceTabsTests +{ + private readonly FakeStrip _strip = new(); + private readonly WorkspaceTabs _tabs; + + public WorkspaceTabsTests() + { + _tabs = new WorkspaceTabs(_strip); + } + + [Fact] + public async Task ATabHoldingATransactionAsksFirstAndStaysWhenTheAnswerIsNo() + { + var held = new FakeTab("Query 1") { Transaction = TransactionState.InTransaction }; + _strip.Tabs.Add(held); + _strip.Answer = _ => false; + + await _tabs.CloseAsync(held); + + Assert.Equal(["Query 1"], _strip.Asked); + Assert.Equal(0, held.Closes); + Assert.Single(_strip.Tabs); + Assert.Equal(0, _tabs.ClosedCount); + } + + [Fact] + public async Task AClosedTabIsKeptAtItsPlaceToReopenAndTheLastOneEmptiesTheStrip() + { + var first = new FakeTab("Query 1"); + var second = new FakeTab("Artist", TabKind.Table) { Transaction = TransactionState.Failed }; + _strip.Tabs.AddRange([first, second]); + var emptied = 0; + _tabs.Emptied += (_, _) => emptied++; + + await _tabs.CloseAsync(second); + + Assert.Equal(1, second.Closes); + Assert.Equal(["Artist"], _strip.Asked); + Assert.Equal(0, emptied); + + await _tabs.CloseAsync(first); + + Assert.Empty(_strip.Tabs); + Assert.Equal(1, emptied); + Assert.Equal(new ClosedTab(first.Snapshot(), 0), _tabs.TakeClosed()); + Assert.Equal(new ClosedTab(second.Snapshot(), 1), _tabs.TakeClosed()); + Assert.Null(_tabs.TakeClosed()); + } + + [Fact] + public async Task ASecondCloseWhileTheFirstIsClosingTheTabDoesNothing() + { + var closing = new Gate(); + var tab = new FakeTab("Query 1") { Closing = closing }; + _strip.Tabs.Add(tab); + + var first = _tabs.CloseAsync(tab); + await _tabs.CloseAsync(tab); + var waited = !first.IsCompleted; + closing.Open(); + await first; + + Assert.True(waited); + Assert.Equal(1, tab.Closes); + Assert.Empty(_strip.Tabs); + Assert.Equal(1, _tabs.ClosedCount); + } + + [Fact] + public async Task ConfirmingAWindowsCloseShowsEachHeldTabAndStopsAtTheFirstNo() + { + var idle = new FakeTab("Query 1"); + var held = new FakeTab("Query 2") { Transaction = TransactionState.InTransaction }; + var failed = new FakeTab("Query 3") { Transaction = TransactionState.Failed }; + _strip.Tabs.AddRange([idle, held, failed]); + _strip.Answer = tab => ReferenceEquals(tab, held); + var confirmed = new HashSet(); + + Assert.True(_tabs.HasUnconfirmed(confirmed)); + Assert.False(await _tabs.ConfirmCloseAsync(confirmed)); + + Assert.Equal([held, failed], _strip.Selected); + Assert.Same(held, Assert.Single(confirmed)); + + _strip.Answer = _ => true; + + Assert.True(await _tabs.ConfirmCloseAsync(confirmed)); + Assert.False(_tabs.HasUnconfirmed(confirmed)); + Assert.Equal(0, idle.Closes); + } + + [Fact] + public async Task ATabWithUnsavedChangesShowsAndAsksBeforeItClosesAndStaysOnANo() + { + var other = new FakeTab("Query 1"); + var edited = new FakeTab("Artist", TabKind.Table) { HasUnsavedChanges = true, ClosesUnsaved = false }; + _strip.Tabs.AddRange([other, edited]); + + await _tabs.CloseAsync(edited); + + Assert.Same(edited, Assert.Single(_strip.Selected)); + Assert.Equal(1, edited.CloseQuestions); + Assert.Equal(0, edited.Closes); + Assert.Equal(2, _strip.Tabs.Count); + Assert.Empty(_strip.Asked); + + edited.ClosesUnsaved = true; + await _tabs.CloseAsync(edited); + + Assert.Equal(1, edited.Closes); + Assert.Same(other, Assert.Single(_strip.Tabs)); + } + + [Fact] + public async Task ConfirmingAWindowsCloseAsksAboutUnsavedChangesTooAndAnsweredTabsAreNotAskedAgain() + { + var edited = new FakeTab("Artist", TabKind.Table) { HasUnsavedChanges = true }; + var held = new FakeTab("Query 1") { Transaction = TransactionState.InTransaction }; + _strip.Tabs.AddRange([edited, held]); + var confirmed = new HashSet(); + + Assert.True(_tabs.HasUnconfirmed(confirmed)); + Assert.True(await _tabs.ConfirmCloseAsync(confirmed)); + + Assert.Equal([edited, held], _strip.Selected); + Assert.Equal(1, edited.CloseQuestions); + Assert.Equal(["Query 1"], _strip.Asked); + Assert.False(_tabs.HasUnconfirmed(confirmed)); + + edited.ClosesUnsaved = false; + Assert.True(await _tabs.ConfirmCloseAsync(confirmed)); + Assert.Equal(1, edited.CloseQuestions); + } + + [Fact] + public async Task MakingTheConnectionReadOnlyAsksWithoutSaveAndAClosedTabAsksWithIt() + { + var edited = new FakeTab("Artist", TabKind.Table) { HasUnsavedChanges = true }; + _strip.Tabs.Add(edited); + + Assert.True(await _tabs.ConfirmCloseAsync(new HashSet(), offerSave: false)); + Assert.False(edited.OfferedSave); + + await _tabs.CloseAsync(edited); + Assert.True(edited.OfferedSave); + } + + [Fact] + public async Task AFailedSaveBeforeAWindowsCloseKeepsEveryTab() + { + var edited = new FakeTab("Artist", TabKind.Table) { HasUnsavedChanges = true, ClosesUnsaved = false }; + var held = new FakeTab("Query 1") { Transaction = TransactionState.InTransaction }; + _strip.Tabs.AddRange([edited, held]); + + Assert.False(await _tabs.ConfirmCloseAsync(new HashSet())); + + Assert.Empty(_strip.Asked); + Assert.Equal(0, edited.Closes); + } + + [Fact] + public void OnlyARunningQueryTabIsAskedAboutBeforeAClose() + { + var running = new FakeTab("Query 1") { IsRunning = true }; + var loading = new FakeTab("Artist", TabKind.Table) { IsRunning = true }; + _strip.Tabs.AddRange([running, loading, new FakeTab("Query 2")]); + + Assert.Same(running, Assert.Single(_tabs.RunningQueries())); + } + + [Fact] + public async Task AClosedWindowsTabsReopenInTheirOrderAndOnlyADisconnectForgetsThem() + { + _tabs.KeepClosed([new SessionTab { Title = "Query 1" }, new SessionTab { Title = "Query 2" }]); + + Assert.Equal("Query 1", _tabs.TakeClosed()?.Tab.Title); + + var open = new FakeTab("Query 3"); + _strip.Tabs.Add(open); + await _tabs.CloseAllAsync(keepClosed: true); + + Assert.Equal(1, open.Closes); + Assert.Equal(1, _tabs.ClosedCount); + + await _tabs.CloseAllAsync(keepClosed: false); + + Assert.Equal(0, _tabs.ClosedCount); + } +} + +internal sealed class FakeTab(string title, TabKind kind = TabKind.Query) : IWorkspaceTab +{ + public string Title { get; } = title; + + public TabKind Kind { get; } = kind; + + public bool IsRunning { get; set; } + + public TransactionState Transaction { get; set; } + + public bool HasUnsavedChanges { get; set; } + + // The answer its own question gives: Save that saved, or Don't save, against Cancel or a failed save. + public bool ClosesUnsaved { get; set; } = true; + + public Gate? Closing { get; set; } + + public int Closes { get; private set; } + + public int CloseQuestions { get; private set; } + + public bool? OfferedSave { get; private set; } + + public Task ConfirmCloseAsync(bool offerSave) + { + CloseQuestions++; + OfferedSave = offerSave; + return Task.FromResult(ClosesUnsaved); + } + + public SessionTab Snapshot() => new() { Kind = Kind, Title = Title }; + + public async Task CloseAsync() + { + Closes++; + if (Closing is { } closing) + { + await closing.PassAsync(CancellationToken.None); + } + } +} + +internal sealed class FakeStrip : IWorkspaceTabsView +{ + public List Tabs { get; } = []; + + public List Selected { get; } = []; + + public List Asked { get; } = []; + + public Func Answer { get; set; } = _ => true; + + public IReadOnlyList Items => [.. Tabs]; + + public IWorkspaceTab? ContentOf(FakeTab item) => item; + + public void SelectTab(FakeTab item) => Selected.Add(item); + + public Task ConfirmCloseHeldAsync(IWorkspaceTab tab) + { + Asked.Add(tab.Title); + return Task.FromResult(Answer(tab)); + } + + public void Remove(FakeTab item) => Tabs.Remove(item); +} diff --git a/windows/tests/TablePro.App.UITests/TableEditingTests.cs b/windows/tests/TablePro.App.UITests/TableEditingTests.cs new file mode 100644 index 0000000000..9ebdccf91c --- /dev/null +++ b/windows/tests/TablePro.App.UITests/TableEditingTests.cs @@ -0,0 +1,88 @@ +using FlaUI.Core.AutomationElements; +using FlaUI.Core.Definitions; +using FlaUI.Core.Input; +using FlaUI.Core.Tools; +using FlaUI.Core.WindowsAPI; + +namespace TablePro.App.UITests; + +public sealed partial class ShellTests +{ + [Theory] + [MemberData(nameof(Themes))] + public void ATableTabKeepsEditsPendingPreviewsTheirSqlAndSavesThem(string theme) + { + const string Renamed = "AC/DC (edited)"; + const string Added = "TablePro Test Artist"; + using var app = AppSession.Launch(theme); + + app.Click(app.Find("SampleCard"), () => app.TryFind("Rail_Chinook (Sample)") is not null); + app.Click(app.FindByName("Artist", app.Find("ObjectTree")), () => app.TryFind("TableStatus") is not null); + AppSession.WaitForText(app.Find("TableStatus"), value => value.StartsWith("Rows: 275", StringComparison.Ordinal)); + var grid = app.Find("ResultsGrid"); + + // F2 opens the cell with its whole value selected, and Enter keeps what was typed, pending. + app.Click(CellOf(grid, 0, 1)); + app.Chord(() => GridEditor(grid) is not null, VirtualKeyShort.F2); + Keyboard.Type(Renamed); + app.Chord(() => GridEditor(grid) is null, VirtualKeyShort.RETURN); + Assert.Equal(Renamed, app.WaitForCell(grid, 0, 1, value => value == Renamed)); + Assert.Equal("edited", ItemStatusOf(grid, 0, 1)); + + // Artists 1 to 24 have albums, which a foreign key keeps; the 25th, grid row 24, has none. + Keyboard.Type(Enumerable.Repeat(VirtualKeyShort.DOWN, 24).ToArray()); + var deleted = app.WaitForCell(grid, 24, 1, value => value.Length > 0); + app.Chord(() => ItemStatusOf(grid, 24, 1) == "marked for deletion", VirtualKeyShort.DELETE); + app.Screenshot("44-table-edits-pending"); + + // A new row follows the page's rows and opens on the first column the server does not fill. + app.Chord(() => GridEditor(grid) is not null, VirtualKeyShort.CONTROL, VirtualKeyShort.SHIFT, VirtualKeyShort.KEY_N); + Keyboard.Type(Added); + app.Chord(() => GridEditor(grid) is null, VirtualKeyShort.RETURN); + Assert.Equal(Added, app.WaitForCell(grid, 275, 1, value => value == Added)); + Assert.Equal("new row", ItemStatusOf(grid, 275, 1)); + app.Screenshot("45-table-new-row"); + + app.Chord( + () => app.TryFind("PreviewSqlStatements") is not null, + VirtualKeyShort.CONTROL, + VirtualKeyShort.SHIFT, + VirtualKeyShort.KEY_P); + var preview = app.Find("PreviewSqlStatements").Name; + Assert.Contains("UPDATE", preview, StringComparison.Ordinal); + Assert.Contains("INSERT", preview, StringComparison.Ordinal); + Assert.Contains("DELETE", preview, StringComparison.Ordinal); + app.Screenshot("46-table-preview-sql"); + app.CloseDialog(); + Assert.True(Retry.WhileTrue(() => app.TryFind("PreviewSqlStatements") is not null, AppSession.Wait, throwOnTimeout: false).Success); + + // A save that deletes rows asks first at every Safe Mode level; the page is read again once it wrote. + app.Chord(() => app.TryFind("PrimaryButton") is not null, VirtualKeyShort.CONTROL, VirtualKeyShort.KEY_S); + app.PressDialogButton(); + if (Retry.WhileNull(() => app.TryFind("SaveReviewStatements"), TimeSpan.FromSeconds(3), throwOnTimeout: false).Result is not null) + { + app.PressDialogButton(); + } + + Assert.Equal(Renamed, app.WaitForCell(grid, 0, 1, value => value == Renamed && ItemStatusOf(grid, 0, 1).Length == 0)); + + // The table holds what was saved: the new name and the new row, and not the deleted one. + app.Chord(() => app.TryFind("SqlEditor") is { IsOffscreen: false }, VirtualKeyShort.CONTROL, VirtualKeyShort.KEY_1); + var names = string.Join(", ", new[] { Renamed, Added, deleted }.Select(name => "'" + name.Replace("'", "''", StringComparison.Ordinal) + "'")); + app.TypeInto("Query 1", $"SELECT COUNT(*) FROM Artist WHERE Name IN ({names});"); + app.Chord(() => app.Find("QueryStatus").Name.StartsWith("Rows: 1", StringComparison.Ordinal), + VirtualKeyShort.CONTROL, VirtualKeyShort.ENTER); + Assert.Equal("2", app.WaitForCell(app.Find("ResultsGrid"), 0, 0, value => value == "2")); + } + + private static AutomationElement CellOf(AutomationElement grid, int row, int column) => + Retry.WhileNull(() => grid.Patterns.Grid.Pattern.GetItem(row, column), AppSession.Wait, throwOnTimeout: false).Result + ?? throw new InvalidOperationException($"No cell ({row}, {column}) appeared."); + + // The grid lists its open editor, a TextBox, as its pane's one child. + private static AutomationElement? GridEditor(AutomationElement grid) => + grid.FindFirstDescendant(condition => condition.ByControlType(ControlType.Edit)); + + private static string ItemStatusOf(AutomationElement grid, int row, int column) => + grid.Patterns.Grid.Pattern.GetItem(row, column)?.Properties.ItemStatus.ValueOrDefault ?? string.Empty; +} diff --git a/windows/tests/TablePro.DataGrid.Model.Tests/EditedGridDataTests.cs b/windows/tests/TablePro.DataGrid.Model.Tests/EditedGridDataTests.cs new file mode 100644 index 0000000000..c65a86058b --- /dev/null +++ b/windows/tests/TablePro.DataGrid.Model.Tests/EditedGridDataTests.cs @@ -0,0 +1,307 @@ +using System.Globalization; + +namespace TablePro.DataGrid.Model.Tests; + +public sealed class EditedGridDataTests +{ + private static readonly string?[][] Rows = + [ + ["a", "b"], + ["c", null], + ["e", "f"], + ]; + + [Fact] + public void TheRowsAreTheDataRowsThenTheNewRows() + { + var data = new TableData(Rows); + var edited = new EditedGridData(data, Edits(added: [[Value("n"), Null()], [Default(), Value("m")]])); + + Assert.Same(data, edited.Data); + Assert.Equal(5, edited.RowCount); + Assert.Equal(2, edited.ColumnCount); + Assert.Equal("c1", edited.GetColumnName(1)); + edited.Edits = GridEdits.None; + Assert.Equal(3, edited.RowCount); + Assert.False(edited.Edits.HasChanges); + } + + [Fact] + public void EachRowIsMarkedByItsEdits() + { + var edits = Edits(cells: [((0, 1), Value("x"))], deleted: [1], added: [[Value("n"), Null()]]); + var edited = new EditedGridData(new TableData(Rows), edits); + + Assert.Equal(RowMark.Modified, edited.GetRowMark(0)); + Assert.Equal(RowMark.Deleted, edited.GetRowMark(1)); + Assert.Equal(RowMark.None, edited.GetRowMark(2)); + Assert.Equal(RowMark.Inserted, edited.GetRowMark(3)); + Assert.Equal(RowMark.None, edited.GetRowMark(4)); + Assert.Equal(RowMark.None, edited.GetRowMark(-1)); + Assert.True(edits.IsModified(0)); + Assert.False(edits.IsModified(2)); + Assert.True(edits.HasChanges); + } + + [Fact] + public void APendingValueIsReadInPlaceOfTheDataWithItsMark() + { + var edited = new EditedGridData(new TableData(Rows), Edits(cells: [((0, 1), Value("new"))])); + var block = Read(edited, 0, 32, 0, 2); + + var changed = block.Get(0, 1); + Assert.Equal("new", changed.Text.ToString()); + Assert.Equal(CellState.Modified, changed.State); + Assert.Equal("a", block.Get(0, 0).Text.ToString()); + Assert.Equal(CellState.None, block.Get(0, 0).State); + Assert.True(block.Get(1, 1).IsNull); + Assert.Equal("f", block.Get(2, 1).Text.ToString()); + } + + [Fact] + public void NullAndDefaultCellsHaveNoText() + { + var edited = new EditedGridData(new TableData(Rows), Edits(cells: [((0, 0), Null()), ((2, 0), Default())])); + var block = Read(edited, 0, 32, 0, 2); + + var nothing = block.Get(0, 0); + Assert.True(nothing.IsNull); + Assert.False(nothing.IsDefault); + Assert.Equal(CellState.Null | CellState.Modified, nothing.State); + Assert.True(nothing.Text.IsEmpty); + var server = block.Get(2, 0); + Assert.True(server.IsDefault); + Assert.False(server.IsNull); + Assert.Equal(CellState.Default | CellState.Modified, server.State); + Assert.True(server.Text.IsEmpty); + } + + [Fact] + public void EveryCellOfADeletedRowKeepsTheDataAndIsMarked() + { + var edits = Edits(cells: [((1, 0), Value("ignored"))], deleted: [1]); + var block = Read(new EditedGridData(new TableData(Rows), edits), 0, 32, 0, 2); + + Assert.Equal("c", block.Get(1, 0).Text.ToString()); + Assert.Equal(CellState.Deleted, block.Get(1, 0).State); + Assert.Equal(CellState.Null | CellState.Deleted, block.Get(1, 1).State); + Assert.Equal(CellState.None, block.Get(0, 0).State); + } + + [Fact] + public void NewRowsComeFromTheEditsAndAreNeverAskedOfTheData() + { + var data = new TableData(Rows); + var edited = new EditedGridData(data, Edits(added: [[Value("n"), Null()], [Default(), Value("m")]])); + + var block = Read(edited, 0, 32, 0, 2); + Assert.Equal(5, block.RowCount); + Assert.All(data.Reads, read => Assert.True(read.First + read.Count <= 3, $"read {read}")); + Assert.Equal("n", block.Get(3, 0).Text.ToString()); + Assert.Equal(CellState.Inserted, block.Get(3, 0).State); + Assert.Equal(CellState.Null | CellState.Inserted, block.Get(3, 1).State); + Assert.Equal(CellState.Default | CellState.Inserted, block.Get(4, 0).State); + Assert.Equal("m", block.Get(4, 1).Text.ToString()); + Assert.Equal(CellState.Missing, block.Get(5, 0).State); + + var reads = data.Reads.Count; + var past = Read(edited, 4, 32, 0, 2); + Assert.Equal(reads, data.Reads.Count); + Assert.Equal(1, past.RowCount); + Assert.Equal("m", past.Get(4, 1).Text.ToString()); + } + + [Fact] + public void ReadWholeGivesThePendingTextNullForNullAndEmptyForDefault() + { + var whole = new string('x', 5_000); + var edits = Edits( + cells: [((0, 0), Value(whole)), ((0, 1), Null()), ((2, 0), Default())], + deleted: [1], + added: [[Value("n"), Default()]]); + using var reader = new EditedGridData(new TableData(Rows), edits).OpenReader(); + + Assert.Equal(whole, reader.ReadWhole(0, 0)); + Assert.Null(reader.ReadWhole(0, 1)); + Assert.Equal("", reader.ReadWhole(2, 0)); + Assert.Equal("f", reader.ReadWhole(2, 1)); + Assert.Equal("c", reader.ReadWhole(1, 0)); + Assert.Null(reader.ReadWhole(1, 1)); + Assert.Equal("n", reader.ReadWhole(3, 0)); + Assert.Equal("", reader.ReadWhole(3, 1)); + Assert.Null(reader.ReadWhole(4, 0)); + } + + // As the core shows a value: cut at the cap with the cut mark, control characters as spaces. + [Fact] + public void ALongOrMultiLineValueIsShownAsTheCoreShowsIt() + { + var edits = Edits(cells: [((0, 0), Value(new string('x', 300))), ((0, 1), Value("one\ntwo")), ((2, 0), Value("مرحبا"))]); + var block = Read(new EditedGridData(new TableData(Rows), edits), 0, 32, 0, 2, maxCharacters: 32); + + var cut = block.Get(0, 0); + Assert.True(cut.IsTruncated); + Assert.Equal(33, cut.Text.Length); + Assert.Equal(CellBlock.Ellipsis, cut.Text[^1]); + var lines = block.Get(0, 1); + Assert.Equal("one two", lines.Text.ToString()); + Assert.Equal(CellState.Lossy | CellState.Modified, lines.State); + Assert.True(block.Get(2, 0).IsRightToLeft); + } + + [Fact] + public void AReaderKeepsTheEditsItOpenedWith() + { + var edited = new EditedGridData(new TableData(Rows), Edits(cells: [((0, 0), Value("first"))])); + using var before = edited.OpenReader(); + + edited.Edits = Edits(cells: [((0, 0), Value("second"))], added: [[Value("n"), Value("o")]]); + using var after = edited.OpenReader(); + + var old = new CellBlock(); + before.Read(0, 32, 0, 2, 256, old); + Assert.Equal("first", old.Get(0, 0).Text.ToString()); + Assert.Equal(3, old.RowCount); + Assert.Equal("first", before.ReadWhole(0, 0)); + var now = new CellBlock(); + after.Read(0, 32, 0, 2, 256, now); + Assert.Equal("second", now.Get(0, 0).Text.ToString()); + Assert.Equal(4, now.RowCount); + } + + [Fact] + public void AReaderOpensOverTheEditsItIsGiven() + { + var taken = Edits(cells: [((0, 0), Value("taken"))], added: [[Value("n"), Value("o")]]); + var edited = new EditedGridData(new TableData(Rows), taken); + edited.Edits = GridEdits.None; + + using var reader = edited.OpenReader(taken); + var block = new CellBlock(); + reader.Read(0, 32, 0, 2, 256, block); + + Assert.Equal("taken", reader.ReadWhole(0, 0)); + Assert.Equal(4, block.RowCount); + Assert.Equal("n", block.Get(3, 0).Text.ToString()); + } + + // A copy reads with a reader of its own, so it takes the pending text, whole. + [Fact] + public void ACopyOverEditsTakesThePendingText() + { + var edits = Edits( + cells: [((0, 1), Value("x\ty")), ((2, 0), Null())], + deleted: [1], + added: [[Value("n"), Default()]]); + using var reader = new EditedGridData(new TableData(Rows), edits).OpenReader(); + + var tsv = GridCopy.Tsv(reader, new CellRange(0, 0, 3, 1), TestContext.Current.CancellationToken); + + Assert.Equal("a\t\"x\ty\"\r\nc\t\r\n\tf\r\nn\t\r\n", tsv); + } + + // The data's last tile holds new rows too; the grid makes a new cache when the edits change. + [Fact] + public void ACacheReadsNewRowsInTheDataTilesAndPastThem() + { + var rows = Enumerable.Range(0, 30) + .Select(row => new[] { string.Create(CultureInfo.InvariantCulture, $"r{row}") }) + .ToArray(); + var added = Enumerable.Range(0, 4) + .Select(row => (IReadOnlyList)new[] { Value(string.Create(CultureInfo.InvariantCulture, $"new {row}")) }) + .ToList(); + var edited = new EditedGridData(new TableData(rows), new GridEdits(Cells(), new HashSet(), added)); + using var cache = new CellCache(edited.OpenReader()); + + Assert.Equal(34, edited.RowCount); + Assert.Equal("r29", cache.Get(29, 0, 64).Text.ToString()); + Assert.Equal("new 1", cache.Get(31, 0, 64).Text.ToString()); + Assert.Equal("new 3", cache.Get(33, 0, 64).Text.ToString()); + Assert.Equal(CellState.Inserted, cache.Get(33, 0, 64).State); + Assert.Equal(CellState.Missing, cache.Get(34, 0, 64).State); + Assert.Equal("new 2", cache.ReadWhole(32, 0)); + } + + // The grid's plain path is unchanged: no marks on a result with no edits. + [Fact] + public void DataWithNoEditsReadsAsTheDataDoes() + { + var block = Read(new EditedGridData(new TableData(Rows), GridEdits.None), 0, 32, 0, 2); + + Assert.Equal(3, block.RowCount); + Assert.Equal("a", block.Get(0, 0).Text.ToString()); + Assert.Equal(CellState.Null, block.Get(1, 1).State); + Assert.Equal(CellState.None, block.Get(2, 1).State); + } + + private static PendingCell Value(string text) => new(PendingKind.Value, text); + + private static PendingCell Null() => new(PendingKind.Null, ""); + + private static PendingCell Default() => new(PendingKind.Default, ""); + + private static Dictionary<(int Row, int Column), PendingCell> Cells(params ((int Row, int Column) Cell, PendingCell Pending)[] cells) => + cells.ToDictionary(cell => cell.Cell, cell => cell.Pending); + + private static GridEdits Edits( + ((int Row, int Column) Cell, PendingCell Pending)[]? cells = null, + int[]? deleted = null, + PendingCell[][]? added = null) => + new(Cells(cells ?? []), new HashSet(deleted ?? []), [.. (added ?? []).Select(row => (IReadOnlyList)row)]); + + private static CellBlock Read(EditedGridData data, int firstRow, int rowCount, int firstColumn, int columnCount, + int maxCharacters = 256) + { + using var reader = data.OpenReader(); + var block = new CellBlock(); + reader.Read(firstRow, rowCount, firstColumn, columnCount, maxCharacters, block); + return block; + } +} + +// Fixed values that record each window asked of them, cut at the cap as the core cuts. +internal sealed class TableData(string?[][] rows) : IGridData +{ + public int RowCount => rows.Length; + + public int ColumnCount => rows.Length == 0 ? 0 : rows[0].Length; + + public List<(int First, int Count)> Reads { get; } = []; + + public string GetColumnName(int column) => string.Create(CultureInfo.InvariantCulture, $"c{column}"); + + public IGridReader OpenReader() => new Reader(this, rows); + + private sealed class Reader(TableData data, string?[][] rows) : IGridReader + { + public void Read(int firstRow, int rowCount, int firstColumn, int columnCount, int maxCharacters, CellBlock block) + { + data.Reads.Add((firstRow, rowCount)); + var count = Math.Max(0, Math.Min(rowCount, data.RowCount - firstRow)); + var columns = Math.Max(0, Math.Min(columnCount, data.ColumnCount - firstColumn)); + block.Reset(firstRow, count, firstColumn, columns, maxCharacters); + for (var column = firstColumn; column < firstColumn + columns; column++) + { + for (var row = firstRow; row < firstRow + count; row++) + { + var value = rows[row][column]; + if (value is null) + { + block.AddNull(); + } + else + { + var cut = value.Length > maxCharacters; + block.Add(cut ? value.AsSpan(0, maxCharacters) : value, cut); + } + } + } + } + + public string? ReadWhole(int row, int column) => rows[row][column]; + + public void Dispose() + { + } + } +} diff --git a/windows/tests/TablePro.DataGrid.Tests/EditingTests.cs b/windows/tests/TablePro.DataGrid.Tests/EditingTests.cs new file mode 100644 index 0000000000..2ad9ee911c --- /dev/null +++ b/windows/tests/TablePro.DataGrid.Tests/EditingTests.cs @@ -0,0 +1,388 @@ +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Automation; +using Microsoft.UI.Xaml.Automation.Peers; +using Microsoft.UI.Xaml.Controls; +using TablePro.DataGrid.Automation; +using TablePro.DataGrid.Model; +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; +using Windows.System; + +namespace TablePro.DataGrid.Tests; + +// The in-place editor and the marks of pending changes. The host's checks and saves are the app's. +public sealed class EditingTests +{ + [Fact] + public Task F2OpensATextBoxOverTheCellWithTheHostsText() => WinUiHost.RunAsync(async () => + { + var grid = await ShowEditableAsync(new SyntheticData()); + var starts = new List<(int Row, int Column)>(); + grid.CellEditStarting += (_, e) => + { + starts.Add((e.Row, e.Column)); + Assert.Equal("r2c3", e.Text); + e.Text = "host text"; + }; + grid.SelectCell(2, 3, extend: false); + + Assert.True(grid.HandleKey(VirtualKey.F2, control: false, shift: false)); + Assert.False(grid.IsEditing); + await SettleAsync(grid); + + var editor = Assert.IsType(grid.Editor); + Assert.True(grid.IsEditing); + Assert.Equal((2, 3), Assert.Single(starts)); + Assert.Equal("host text", editor.Text); + Assert.Equal("host text", editor.SelectedText); + Assert.Equal(grid.Painter.FamilyName, editor.FontFamily.Source); + Assert.Equal(grid.Columns.Width(3), editor.ActualWidth, 1); + var at = editor.TransformToVisual(grid.ScrollingPane).TransformPoint(default); + Assert.Equal(grid.Columns.PaneX(3), at.X, 1); + Assert.Equal(2 * grid.RowHeight, at.Y, 1); + grid.CancelEdit(); + }); + + [Fact] + public Task AnEditorInAFrozenColumnSitsInTheFrozenPane() => WinUiHost.RunAsync(async () => + { + var grid = await ShowEditableAsync(new SyntheticData(), frozen: 1); + grid.SelectCell(5, 0, extend: false); + + grid.BeginEdit(); + await SettleAsync(grid); + + var editor = grid.Editor!; + Assert.Equal("r5c0", editor.Text); + var at = editor.TransformToVisual(grid.FrozenPane).TransformPoint(default); + Assert.Equal(grid.Columns.PaneX(0), at.X, 1); + Assert.Equal(5 * grid.RowHeight, at.Y, 1); + grid.CancelEdit(); + }); + + [Fact] + public Task EnterRaisesCellEditCommittingWithTheTypedText() => WinUiHost.RunAsync(async () => + { + var grid = await ShowEditableAsync(new SyntheticData()); + var commits = new List<(int Row, int Column, string Text)>(); + grid.CellEditCommitting += (_, e) => commits.Add((e.Row, e.Column, e.Text)); + grid.SelectCell(4, 1, extend: false); + grid.BeginEdit(); + await SettleAsync(grid); + + var editor = grid.Editor!; + editor.Text = "typed"; + Assert.True(grid.HandleEditorKey(VirtualKey.Enter, control: false, shift: false)); + + Assert.Equal((4, 1, "typed"), Assert.Single(commits)); + Assert.False(grid.IsEditing); + Assert.Equal(Visibility.Collapsed, editor.Visibility); + Assert.Equal((4, 1), (grid.FocusedRow, grid.FocusedColumn)); + }); + + // A NULL cell opened and left as it was stays NULL: the text it opened with is no change. + [Fact] + public Task EnterOnUnchangedTextRaisesNothing() => WinUiHost.RunAsync(async () => + { + var grid = await ShowEditableAsync(new SyntheticData()); + var commits = 0; + grid.CellEditCommitting += (_, _) => commits++; + grid.SelectCell(0, 3, extend: false); + grid.BeginEdit(); + await SettleAsync(grid); + + Assert.Equal("", grid.Editor!.Text); + Assert.True(grid.HandleEditorKey(VirtualKey.Enter, control: false, shift: false)); + + Assert.Equal(0, commits); + Assert.False(grid.IsEditing); + }); + + [Fact] + public Task EscapeCancelsWithoutAnEvent() => WinUiHost.RunAsync(async () => + { + var grid = await ShowEditableAsync(new SyntheticData()); + var commits = 0; + grid.CellEditCommitting += (_, _) => commits++; + grid.SelectCell(4, 1, extend: false); + grid.BeginEdit(); + await SettleAsync(grid); + + grid.Editor!.Text = "typed"; + Assert.True(grid.HandleEditorKey(VirtualKey.Escape, control: false, shift: false)); + + Assert.Equal(0, commits); + Assert.False(grid.IsEditing); + Assert.True(grid.CommitEdit()); + Assert.Equal(0, commits); + }); + + [Fact] + public Task AnErrorFromTheHostKeepsTheEditorOpenAndShowsIt() => WinUiHost.RunAsync(async () => + { + var grid = await ShowEditableAsync(new SyntheticData()); + grid.CellEditCommitting += (_, e) => e.Error = "Not a number"; + grid.SelectCell(1, 2, extend: false); + grid.BeginEdit(); + await SettleAsync(grid); + + var editor = grid.Editor!; + editor.Text = "abc"; + Assert.True(grid.HandleEditorKey(VirtualKey.Enter, control: false, shift: false)); + + Assert.True(grid.IsEditing); + Assert.Equal(Visibility.Visible, editor.Visibility); + Assert.Equal("abc", editor.Text); + Assert.Equal("Not a number", AutomationProperties.GetFullDescription(editor)); + Assert.Equal("Not a number", Assert.IsType(ToolTipService.GetToolTip(editor)).Content); + Assert.False(grid.CommitEdit()); + Assert.True(grid.IsEditing); + + grid.CancelEdit(); + Assert.False(grid.IsEditing); + Assert.Equal("", AutomationProperties.GetFullDescription(editor)); + Assert.Null(ToolTipService.GetToolTip(editor)); + }); + + [Fact] + public Task TabCommitsAndEditsTheNextCell() => WinUiHost.RunAsync(async () => + { + var grid = await ShowEditableAsync(new SyntheticData()); + var commits = new List<(int Row, int Column, string Text)>(); + grid.CellEditCommitting += (_, e) => commits.Add((e.Row, e.Column, e.Text)); + grid.SelectCell(3, 4, extend: false); + grid.BeginEdit(); + await SettleAsync(grid); + + var editor = grid.Editor!; + editor.Text = "four"; + Assert.True(grid.HandleEditorKey(VirtualKey.Tab, control: false, shift: false)); + await SettleAsync(grid); + + Assert.Equal((3, 4, "four"), Assert.Single(commits)); + Assert.True(grid.IsEditing); + Assert.Equal((3, 5), (grid.FocusedRow, grid.FocusedColumn)); + Assert.Equal(SyntheticData.Value(3, 5), editor.Text); + Assert.True(grid.HandleEditorKey(VirtualKey.Tab, control: false, shift: true)); + Assert.Equal((3, 4), (grid.FocusedRow, grid.FocusedColumn)); + Assert.False(grid.IsEditing); + await SettleAsync(grid); + + Assert.True(grid.IsEditing); + Assert.Equal("r3c4", editor.Text); + Assert.Single(commits); + grid.CancelEdit(); + }); + + [Fact] + public Task AValueWithNulOpensNothing() => WinUiHost.RunAsync(async () => + { + var grid = await ShowEditableAsync(new SyntheticData()); + grid.CellEditStarting += (_, e) => e.Text = "a\0b"; + + grid.BeginEdit(); + await SettleAsync(grid); + + Assert.False(grid.IsEditing); + }); + + [Fact] + public Task AValueWithMixedLineBreaksOpenedAndLeftRaisesNothing() => WinUiHost.RunAsync(async () => + { + var grid = await ShowEditableAsync(new SyntheticData()); + var commits = new List(); + grid.CellEditStarting += (_, e) => e.Text = "a\nb\r\nc"; + grid.CellEditCommitting += (_, e) => commits.Add(e.Text); + grid.BeginEdit(); + await SettleAsync(grid); + + var editor = grid.Editor!; + Assert.True(editor.AcceptsReturn); + Assert.True(grid.HandleEditorKey(VirtualKey.Enter, control: true, shift: false)); + Assert.Empty(commits); + Assert.False(grid.IsEditing); + + grid.BeginEdit(); + await SettleAsync(grid); + editor.Text = "a\rb"; + Assert.True(grid.HandleEditorKey(VirtualKey.Enter, control: true, shift: false)); + Assert.Equal("a\r\nb", Assert.Single(commits)); + }); + + // The editor's row index outlives the host's change only on a data row. + [Fact] + public Task RowsThatComeOrGoCloseAnOpenEditor() => WinUiHost.RunAsync(async () => + { + var edited = new EditedGridData(new SyntheticData(rows: 100, columns: 10), NewRows(2)); + var grid = await ShowEditableAsync(edited); + var commits = new List<(int Row, int Column, string Text)>(); + grid.CellEditCommitting += (_, e) => commits.Add((e.Row, e.Column, e.Text)); + + grid.SelectCell(101, 0, extend: false); + grid.BeginEdit(); + await SettleAsync(grid); + grid.Editor!.Text = "typed"; + edited.Edits = NewRows(1); + grid.EditsChanged(); + + Assert.False(grid.IsEditing); + Assert.Empty(commits); + Assert.Equal(101, grid.RowCount); + + grid.SelectCell(3, 2, extend: false); + grid.BeginEdit(); + await SettleAsync(grid); + grid.Editor!.Text = "typed"; + edited.Edits = GridEdits.None; + grid.EditsChanged(); + + Assert.False(grid.IsEditing); + Assert.Equal((3, 2, "typed"), Assert.Single(commits)); + Assert.Equal(100, grid.RowCount); + }); + + [Fact] + public Task AGridThatIsNotEditableOpensNothing() => WinUiHost.RunAsync(async () => + { + var grid = await WinUiHost.ShowAsync(new SyntheticData()); + var events = 0; + grid.CellEditStarting += (_, _) => events++; + grid.DeleteRequested += (_, _) => events++; + + Assert.False(grid.IsEditable); + Assert.False(grid.HandleKey(VirtualKey.F2, control: false, shift: false)); + Assert.False(grid.HandleKey(VirtualKey.Enter, control: false, shift: false)); + Assert.False(grid.HandleKey(VirtualKey.Delete, control: false, shift: false)); + grid.BeginEdit(); + + Assert.False(grid.IsEditing); + Assert.Null(grid.Editor); + Assert.Equal(0, events); + }); + + [Fact] + public Task DeleteRaisesDeleteRequestedOnlyWithNoEditorOpen() => WinUiHost.RunAsync(async () => + { + var grid = await ShowEditableAsync(new SyntheticData()); + var deletes = 0; + grid.DeleteRequested += (_, _) => deletes++; + + Assert.True(grid.HandleKey(VirtualKey.Delete, control: false, shift: false)); + Assert.Equal(1, deletes); + + grid.BeginEdit(); + Assert.False(grid.HandleKey(VirtualKey.Delete, control: false, shift: false)); + Assert.Equal(1, deletes); + grid.CancelEdit(); + Assert.False(grid.HandleKey(VirtualKey.Delete, control: true, shift: false)); + Assert.Equal(1, deletes); + }); + + [Fact] + public Task NewDataCancelsAnOpenEditor() => WinUiHost.RunAsync(async () => + { + var grid = await ShowEditableAsync(new SyntheticData()); + var commits = 0; + grid.CellEditCommitting += (_, _) => commits++; + grid.BeginEdit(); + await SettleAsync(grid); + grid.Editor!.Text = "typed"; + + grid.SetData(new SyntheticData(rows: 10, columns: 4)); + + Assert.False(grid.IsEditing); + Assert.Equal(0, commits); + }); + + // The host swaps the edits and calls EditsChanged: rows, marks, names and ItemStatus follow, with no stale cell. + [Fact] + public Task PendingChangesAreDrawnAndReadByUiAutomation() => WinUiHost.RunAsync(async () => + { + var edited = new EditedGridData(new SyntheticData(rows: 100, columns: 10), GridEdits.None); + var grid = await ShowEditableAsync(edited, frozen: 1); + var peer = (DataGridAutomationPeer)FrameworkElementAutomationPeer.CreatePeerForElement(grid); + var changed = peer.Cell(1, 1); + Assert.Equal("", changed.GetItemStatus()); + + edited.Edits = new GridEdits( + new Dictionary<(int Row, int Column), PendingCell> { [(1, 1)] = new(PendingKind.Value, "pending") }, + new HashSet { 2 }, + [new PendingCell[] { new(PendingKind.Value, "new"), new(PendingKind.Default, "") }]); + grid.EditsChanged(); + await SettleAsync(grid); + + Assert.Equal(101, grid.RowCount); + Assert.Equal("pending", changed.GetName()); + Assert.Equal(grid.EditedStatus, changed.GetItemStatus()); + Assert.Equal("", peer.Cell(1, 0).GetItemStatus()); + Assert.Equal(grid.DeletedStatus, peer.Cell(2, 4).GetItemStatus()); + Assert.Equal("r2c4", peer.Cell(2, 4).GetName()); + Assert.Equal(grid.NewRowStatus, peer.Cell(100, 0).GetItemStatus()); + Assert.Equal(grid.DefaultText, peer.Cell(100, 1).GetName()); + var problems = GridChecks.Check(grid, edited); + Assert.True(problems.None, problems.ToString()); + AssertMarks(grid); + + grid.SelectCell(100, 1, extend: false); + edited.Edits = GridEdits.None; + grid.EditsChanged(); + await SettleAsync(grid); + + Assert.Equal(100, grid.RowCount); + Assert.Equal(99, grid.FocusedRow); + Assert.Equal("", changed.GetItemStatus()); + Assert.Equal("r1c1", changed.GetName()); + problems = GridChecks.Check(grid, edited); + Assert.True(problems.None, problems.ToString()); + }); + + private static unsafe void AssertMarks(DataGridView grid) + { + var painter = grid.Painter; + var modified = grid.Cell(1, 1); + var layout = painter.CreateLayout(modified.Text, modified.State, 116, 32, out var ink); + BOOL underline; + layout->GetUnderline(0, &underline, null); + layout->Release(); + Assert.Equal(CellInk.Text, ink); + Assert.Equal(BOOL.TRUE, underline); + + var deleted = grid.Cell(2, 4); + layout = painter.CreateLayout(deleted.Text, deleted.State, 116, 32, out ink); + BOOL strikethrough; + layout->GetStrikethrough(0, &strikethrough, null); + layout->Release(); + Assert.Equal(CellInk.Deleted, ink); + Assert.Equal(BOOL.TRUE, strikethrough); + + var server = grid.Cell(100, 1); + Assert.True(server.IsDefault); + layout = painter.CreateLayout(server.Text, server.State, 116, 32, out ink); + DWRITE_FONT_WEIGHT weight; + layout->GetFontWeight(0, &weight, null); + layout->GetUnderline(0, &underline, null); + layout->Release(); + Assert.Equal(CellInk.Default, ink); + Assert.Equal(DWRITE_FONT_WEIGHT.DWRITE_FONT_WEIGHT_SEMI_BOLD, weight); + Assert.Equal(BOOL.TRUE, underline); + } + + private static GridEdits NewRows(int count) => new( + new Dictionary<(int Row, int Column), PendingCell>(), + new HashSet(), + [.. Enumerable.Range(0, count).Select(_ => (IReadOnlyList)new[] { new PendingCell(PendingKind.Value, "new") })]); + + private static async Task ShowEditableAsync(IGridData data, int frozen = 0) + { + var grid = await WinUiHost.ShowAsync(data, frozen); + grid.IsEditable = true; + return grid; + } + + private static async Task SettleAsync(DataGridView grid) + { + grid.UpdateLayout(); + await WinUiHost.NextFrameAsync(); + await WinUiHost.NextFrameAsync(); + } +} diff --git a/windows/tests/TablePro.DataGrid.Tests/InteractionTests.cs b/windows/tests/TablePro.DataGrid.Tests/InteractionTests.cs index b763784cee..71687ee9c3 100644 --- a/windows/tests/TablePro.DataGrid.Tests/InteractionTests.cs +++ b/windows/tests/TablePro.DataGrid.Tests/InteractionTests.cs @@ -72,6 +72,37 @@ public Task AClickPicksACellShiftClickARangeAndTheRowNumbersPickRows() => WinUiH Assert.Equal(new CellRange(6, 0, 9, 199), grid.SelectionRange); }); + // The host builds its menu on ContextRequested, so the selection must be the cells under the pointer by then. + [Fact] + public Task ARightClickOutsideTheSelectionSelectsTheCellAndOneInsideKeepsIt() => WinUiHost.RunAsync(async () => + { + var grid = await WinUiHost.ShowAsync(new SyntheticData(), frozen: 1); + var rh = grid.RowHeight; + grid.SelectCell(2, 2, extend: false); + grid.SelectCell(4, 4, extend: true); + var range = new CellRange(2, 2, 4, 4); + + grid.HandleContextRequest(frozen: false, new Point(grid.Columns.PaneX(3) + 5, (3 * rh) + 5)); + Assert.Equal(range, grid.SelectionRange); + Assert.Equal((4, 4), (grid.FocusedRow, grid.FocusedColumn)); + grid.HandleContextRequest(frozen: false, null); + Assert.Equal(range, grid.SelectionRange); + + grid.HandleContextRequest(frozen: false, new Point(grid.Columns.PaneX(6) + 5, (8 * rh) + 5)); + Assert.Equal(new CellRange(8, 6, 8, 6), grid.SelectionRange); + Assert.Equal((8, 6), (grid.FocusedRow, grid.FocusedColumn)); + grid.HandleContextRequest(frozen: true, new Point(grid.Columns.PaneX(0) + 5, (1 * rh) + 5)); + Assert.Equal(new CellRange(1, 0, 1, 0), grid.SelectionRange); + + grid.HandleContextRequest(frozen: true, new Point(4, (5 * rh) + 5)); + Assert.Equal(SelectionKind.Rows, grid.SelectionKind); + Assert.Equal(new CellRange(5, 0, 5, 199), grid.SelectionRange); + grid.HandleContextRequest(frozen: false, new Point(grid.Columns.PaneX(6) + 5, (5 * rh) + 5)); + grid.HandleContextRequest(frozen: true, new Point(4, (5 * rh) + 5)); + Assert.Equal(SelectionKind.Rows, grid.SelectionKind); + Assert.Equal(new CellRange(5, 0, 5, 199), grid.SelectionRange); + }); + [Fact] public Task CopyPutsExcelStyleTsvWithWholeValuesOnTheClipboard() => WinUiHost.RunAsync(async () => { diff --git a/windows/tests/TablePro.Interop.Tests/RowEditTests.cs b/windows/tests/TablePro.Interop.Tests/RowEditTests.cs new file mode 100644 index 0000000000..5624d00c78 --- /dev/null +++ b/windows/tests/TablePro.Interop.Tests/RowEditTests.cs @@ -0,0 +1,151 @@ +namespace TablePro.Interop.Tests; + +public sealed class RowEditTests +{ + private static readonly TableName People = new(null, "people"); + + [Fact] + public async Task AnUpdateAnInsertAndADeleteSaveAndTheTableReadsThemBack() + { + var cancellationToken = TestContext.Current.CancellationToken; + await using var database = await SqliteDatabase.CreateAsync(); + using var editor = await database.Session.OpenTableEditorAsync(People, refresh: false, cancellationToken); + using var page = await PageAsync(database, cancellationToken); + + using var save = editor.Plan(page.Rows, + [ + new RowEdit.Update(0, [new CellChange(2, new CellEdit.Text("first"))]), + new RowEdit.Insert([CellEdit.ServerDefault.Instance, new CellEdit.Text("Edsger"), CellEdit.Null.Instance]), + new RowEdit.Delete(1), + ]); + var outcome = await save.RunAsync(confirmed: false, cancellationToken); + var names = await ReadAsync(database, "SELECT name || ':' || coalesce(note, 'NULL') FROM people ORDER BY id", cancellationToken); + + Assert.Equal(SaveGate.Run, save.Gate); + Assert.Equal(3, save.Statements.Count); + Assert.Equal(["'first'", "1"], save.Statements[0].Values); + Assert.StartsWith("INSERT", save.Statements[1].Sql, StringComparison.Ordinal); + Assert.StartsWith("DELETE", save.Statements[2].Sql, StringComparison.Ordinal); + Assert.Equal(["2"], save.Statements[2].Values); + Assert.Equal(new RowSaveOutcome.Saved(3), outcome); + Assert.Equal(["Ada:first", "Zoë 👋:中文", "Edsger:NULL"], names); + } + + [Fact] + public async Task TheEditorStartsFromTheWholeValueAndANewRowFromTheServersValues() + { + var cancellationToken = TestContext.Current.CancellationToken; + await using var database = await SqliteDatabase.CreateAsync(); + using var editor = await database.Session.OpenTableEditorAsync(People, refresh: false, cancellationToken); + using var page = await PageAsync(database, cancellationToken); + + var note = editor.GetEditStart(page.Rows, 1, 2); + var none = editor.GetEditStart(page.Rows, 0, 2); + + Assert.Null(editor.Lock); + Assert.Equal(new EditStart.Editable("line one\nline two", false), note); + Assert.Equal(new EditStart.Editable(string.Empty, true), none); + Assert.Equal([CellEdit.ServerDefault.Instance, CellEdit.Null.Instance, CellEdit.Null.Instance], editor.Columns.Select(column => column.NewRow)); + Assert.True(editor.Columns[0].PrimaryKey); + Assert.False(editor.Columns[0].Editable); + Assert.True(editor.Columns[1].TakesEmpty); + Assert.Null(editor.LockFor(page.Rows)); + } + + [Fact] + public async Task TextTheColumnCannotHoldIsRefusedWithItsCode() + { + var cancellationToken = TestContext.Current.CancellationToken; + await using var database = await SqliteDatabase.CreateAsync(); + await database.ExecuteAsync("ALTER TABLE people ADD COLUMN age INTEGER"); + using var editor = await database.Session.OpenTableEditorAsync(People, refresh: false, cancellationToken); + + var number = editor.Check(3, new CellEdit.Text("one"), newRow: false); + var required = editor.Check(1, CellEdit.Null.Instance, newRow: false); + var key = editor.Check(0, new CellEdit.Text("7"), newRow: false); + var fine = editor.Check(3, new CellEdit.Text("7"), newRow: false); + + Assert.Equal("edit.invalid_integer", number?.Code); + Assert.Equal("edit.required", required?.Code); + Assert.Equal("edit.not_editable", key?.Code); + Assert.Null(fine); + } + + [Fact] + public async Task ACellEditedBackToItsValueSavesNothing() + { + var cancellationToken = TestContext.Current.CancellationToken; + await using var database = await SqliteDatabase.CreateAsync(); + using var editor = await database.Session.OpenTableEditorAsync(People, refresh: false, cancellationToken); + using var page = await PageAsync(database, cancellationToken); + + using var save = editor.Plan(page.Rows, [new RowEdit.Update(2, [new CellChange(1, new CellEdit.Text("Zoë 👋"))])]); + + Assert.True(save.IsEmpty); + Assert.Empty(save.Statements); + } + + [Fact] + public async Task ARowThatChangedUnderTheSaveRollsBackAndNamesItsEdit() + { + var cancellationToken = TestContext.Current.CancellationToken; + await using var database = await SqliteDatabase.CreateAsync(); + using var editor = await database.Session.OpenTableEditorAsync(People, refresh: false, cancellationToken); + using var page = await PageAsync(database, cancellationToken); + await database.ExecuteAsync("DELETE FROM people WHERE id = 3"); + + using var save = editor.Plan(page.Rows, + [ + new RowEdit.Update(0, [new CellChange(2, new CellEdit.Text("kept back"))]), + new RowEdit.Update(2, [new CellChange(2, new CellEdit.Text("gone"))]), + ]); + var outcome = await save.RunAsync(confirmed: false, cancellationToken); + var notes = await ReadAsync(database, "SELECT coalesce(note, 'NULL') FROM people WHERE id = 1", cancellationToken); + + var rolledBack = Assert.IsType(outcome); + Assert.Equal("driver.row_guard_failed", rolledBack.Error.Code); + Assert.Equal(1, rolledBack.Edit); + Assert.Equal(["NULL"], notes); + } + + [Fact] + public async Task AReadOnlyFileLocksEveryRowAndATableWithNoKeyToo() + { + var cancellationToken = TestContext.Current.CancellationToken; + await using var database = await SqliteDatabase.CreateAsync(); + await database.ExecuteAsync("CREATE TABLE notes (body TEXT)"); + using var notes = await database.Session.OpenTableEditorAsync(new TableName(null, "notes"), refresh: false, cancellationToken); + await using var readOnly = await database.Core.OpenFileAsync(new FileOpenOptions(database.Path, ReadOnly: true), cancellationToken); + using var locked = await readOnly.OpenTableEditorAsync(People, refresh: false, cancellationToken); + + Assert.Equal(EditLock.NoPrimaryKey, notes.Lock); + Assert.Equal(EditLock.ReadOnlyConnection, locked.Lock); + } + + private static async Task PageAsync(SqliteDatabase database, CancellationToken cancellationToken) + { + var query = await database.Session.GetTableQueryAsync(People, null, 100, cancellationToken: cancellationToken); + var run = database.Editor.Run(query.Sql, cancellationToken: cancellationToken); + Assert.IsType(await run.Completion); + return new Page(run, run.GetResultSet(0) ?? throw new InvalidOperationException("The page read no set.")); + } + + private static async Task> ReadAsync(SqliteDatabase database, string sql, CancellationToken cancellationToken) + { + using var run = database.Editor.Run(sql, cancellationToken: cancellationToken); + Assert.IsType(await run.Completion); + using var set = run.GetResultSet(0) ?? throw new InvalidOperationException("The read held no set."); + return [.. Enumerable.Range(0, (int)set.RowCount).Select(row => set.GetCellText(row, 0))]; + } + + private sealed class Page(QueryRun run, ResultSet rows) : IDisposable + { + public ResultSet Rows { get; } = rows; + + public void Dispose() + { + Rows.Dispose(); + run.Dispose(); + } + } +}