diff --git a/Cargo.lock b/Cargo.lock index 9d5b164ed6..eac7c32deb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7976,6 +7976,7 @@ dependencies = [ "tablepro-session", "tablepro-ssh", "tablepro-storage", + "tablepro-test-support", "tempfile", "thiserror 2.0.20", "tokio", diff --git a/core/crates/ffi/Cargo.toml b/core/crates/ffi/Cargo.toml index 7963653d29..05f0eb5723 100644 --- a/core/crates/ffi/Cargo.toml +++ b/core/crates/ffi/Cargo.toml @@ -57,6 +57,8 @@ windows-sys.workspace = true [dev-dependencies] tablepro-account = { workspace = true, features = ["fakes"] } +tablepro-session = { workspace = true, features = ["fakes", "in-process-ssh"] } +tablepro-test-support.workspace = true csbindgen.workspace = true russh.workspace = true tempfile.workspace = true diff --git a/core/crates/ffi/src/core_handle.rs b/core/crates/ffi/src/core_handle.rs index 0581165a1c..cd3380585c 100644 --- a/core/crates/ffi/src/core_handle.rs +++ b/core/crates/ffi/src/core_handle.rs @@ -8,7 +8,7 @@ use tablepro_account::{AccountSettings, RefreshTokenVault}; use tablepro_core::credentials::{CredentialInteraction, CredentialPrompter, SecretItems, SecretKind, SecretVault}; use tablepro_core::{ ConnectEnvironment, Credentials, DatabaseDriver, DriverError, DriverRegistry, FileEndpoint, LivenessPolicy, - SafeModeLevel, WorkspaceSettings, + SafeModeLevel, UnsupportedFeature, WorkspaceSettings, }; use tablepro_session::runtime::Tasks; use tablepro_session::{ @@ -177,9 +177,11 @@ impl Core { } // Typed secrets come first, then Credential Manager; `keep` is stored once it logs in; no prompter, no SSH asks. + // `database`, in place of the saved one, opens the connection in another of the server's databases. pub async fn connect_saved( &self, id: String, + database: Option, secrets: ConnectionSecrets, keep: ConnectionSecrets, prompter: Option>, @@ -215,8 +217,17 @@ impl Core { CredentialDemand::default(), ) .await?; + let request = match database.as_deref().filter(|name| !name.is_empty()) { + Some(database) => refreshed + .request + .in_database(database) + .ok_or(DriverError::Unsupported { + feature: UnsupportedFeature::NetworkConnection, + })?, + None => refreshed.request, + }; let pending = connector - .establish(refreshed.request, interaction(prompter.as_ref()), cancel.clone()) + .establish(request, interaction(prompter.as_ref()), cancel.clone()) .await?; if cancel.is_cancelled() { let report = pending.discard().await; @@ -657,7 +668,14 @@ mod tests { }; let connect = core - .connect_saved(stored.id.to_string(), typed(), ConnectionSecrets::default(), None, None) + .connect_saved( + stored.id.to_string(), + None, + typed(), + ConnectionSecrets::default(), + None, + None, + ) .await .unwrap_err(); let test = core diff --git a/core/crates/ffi/src/editor.rs b/core/crates/ffi/src/editor.rs index 7396bc2205..b5504c5db8 100644 --- a/core/crates/ffi/src/editor.rs +++ b/core/crates/ffi/src/editor.rs @@ -71,7 +71,13 @@ impl QueryEditor { self.editor.state() == EditorSessionState::Lost } - // Where a definition names no database of its own, its text has to run in the one it was read from. + // The database an unqualified name resolves to now, as the server last said, a typed USE included. None where + // the engine does not follow it. + pub fn database(&self) -> Option { + self.editor.database().filter(|name| !name.is_empty()) + } + + // Moves the editor's connection, keeping its transaction. An engine that binds the database at connect refuses. pub async fn use_database(&self, database: String, cancel: Option>) -> Result<(), CoreError> { let editor = self.editor.clone(); let cancel = token(cancel); diff --git a/core/crates/ffi/src/history.rs b/core/crates/ffi/src/history.rs index ac7f3eeab2..3c9bbe514d 100644 --- a/core/crates/ffi/src/history.rs +++ b/core/crates/ffi/src/history.rs @@ -136,6 +136,20 @@ impl QueryHistoryStore { .await } + // Drops unpinned entries older than `retention_days` (0 keeps every age), then the oldest past `max_entries` + // (0 keeps the store's own cap). Returns how many went. + pub async fn prune(&self, retention_days: u32, max_entries: u32) -> Result { + let history = self.history.clone(); + on_runtime(&self.tasks, async move { + let report = match max_entries { + 0 => history.prune(retention_days).await?, + kept => history.prune_keeping(retention_days, kept).await?, + }; + Ok(report.total()) + }) + .await + } + pub async fn clear(&self) -> Result<(), CoreError> { let history = self.history.clone(); on_runtime(&self.tasks, async move { diff --git a/core/crates/ffi/src/key_read.rs b/core/crates/ffi/src/key_read.rs new file mode 100644 index 0000000000..2adf89a835 --- /dev/null +++ b/core/crates/ffi/src/key_read.rs @@ -0,0 +1,300 @@ +use std::collections::HashSet; +use std::sync::{Arc, Mutex, PoisonError}; + +use tablepro_core::keyspace::{KeyCursor, KeyPage, KeyTtl, KeyWindow}; +use tablepro_core::meta::KeyKind; +use tablepro_core::{Truncation, Value}; +use tablepro_session::runtime::Tasks; +use tablepro_session::{OperationKind, Session}; + +use crate::cancel_token::{CancelToken, token}; +use crate::error::CoreError; +use crate::results::{ResultSet, ResultStore}; +use crate::runtime::on_runtime; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)] +pub enum KeyKindTag { + String, + Hash, + List, + Set, + SortedSet, + Stream, + // A module's type, such as a JSON document, which the engine names but the reader does not read. + Other, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)] +pub enum KeyTtlTag { + Persistent, + ExpiresIn { seconds: u64 }, + // The login may read the key but not ask when it expires. + Unknown, +} + +// What the key is after the window just read, and what the reader holds of its value. +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct KeyWindowInfo { + pub kind: KeyKindTag, + // The engine's own name for the type, what a tab shows for a type it does not read. + pub type_name: String, + pub ttl: KeyTtlTag, + // Entries, or a string's bytes. + pub length: Option, + // Rows held after this window, an entry a scan returned again left out. + pub rows: u64, + pub has_more: bool, + // A string longer than the window's bytes: the row holds its start. + pub truncated: bool, + // The key changed type since the last window, so the rows started again in a new set. + pub restarted: bool, +} + +// One key's value read a window at a time into one set, which the grid shows while Load More adds to it. +#[derive(uniffi::Object)] +pub struct KeyReader { + session: Arc, + tasks: Tasks, + key: String, + state: Arc>, +} + +#[derive(Default)] +struct ReadState { + kind: Option, + // None once the last window was read. + next: Option, + set: Option>, + store: Option>, + // A scan can return an entry an earlier step already did. + seen: HashSet>, + last: Option, +} + +impl KeyReader { + pub(crate) fn new(session: Arc, tasks: Tasks, key: String) -> Self { + Self { + session, + tasks, + key, + state: Arc::new(Mutex::new(ReadState { + next: Some(KeyCursor::start()), + ..ReadState::default() + })), + } + } +} + +#[uniffi::export] +impl KeyReader { + pub fn key(&self) -> String { + self.key.clone() + } + + // The rows read so far, from the first window on; None before it. + pub fn rows(&self) -> Option> { + self.state.lock().unwrap_or_else(PoisonError::into_inner).set.clone() + } + + // The next window. None when the key does not exist. Past the last window it reads nothing and says so again. + pub async fn read_more(&self, cancel: Option>) -> Result, CoreError> { + let session = self.session.clone(); + let key = self.key.clone(); + let state = self.state.clone(); + let cancel = token(cancel); + on_runtime(&self.tasks, async move { + let cursor = { + let held = state.lock().unwrap_or_else(PoisonError::into_inner); + match &held.next { + Some(cursor) => cursor.clone(), + None => return Ok(held.last.clone()), + } + }; + let window = KeyWindow::after(cursor); + let page = session + .run_cancellable(OperationKind::Page, &cancel, |lease, options| { + let key = key.clone(); + let window = window.clone(); + async move { Ok(lease.read_key(&key, &window, options).await?) } + }) + .await?; + let Some(page) = page else { + return Ok(None); + }; + let mut held = state.lock().unwrap_or_else(PoisonError::into_inner); + Ok(Some(held.take(page))) + }) + .await + } +} + +impl ReadState { + fn take(&mut self, page: KeyPage) -> KeyWindowInfo { + let restarted = self.kind.is_some_and(|kind| kind != page.kind); + if restarted || self.store.is_none() { + let store = Arc::new(ResultStore::new(page.rows.columns.clone())); + self.set = Some(Arc::new(ResultSet::new(0, store.clone()))); + self.store = Some(store); + self.seen.clear(); + } + self.kind = Some(page.kind); + let scanned = matches!(page.kind, KeyKind::Hash | KeyKind::Set); + let rows: Vec> = page + .rows + .rows + .into_iter() + .filter(|row| !scanned || entry_name(row.first()).is_none_or(|name| self.seen.insert(name))) + .collect(); + let has_more = page.next.is_some(); + let held = self.store.as_ref().map_or(0, |store| { + store.append(&rows); + let truncation = if has_more || page.rows.truncated { + Truncation::ReadPastLimit + } else { + Truncation::Complete + }; + store.finish_as(None, truncation); + store.row_count() + }); + self.next = page.next; + let info = KeyWindowInfo { + kind: page.kind.into(), + type_name: page.type_name, + ttl: page.ttl.into(), + length: page.length, + rows: held, + has_more, + truncated: page.rows.truncated, + restarted, + }; + self.last = Some(KeyWindowInfo { + restarted: false, + ..info.clone() + }); + info + } +} + +// A hash's field or a set's member, the part a scan can repeat. +fn entry_name(value: Option<&Value>) -> Option> { + match value? { + Value::Text(text) => Some(text.as_bytes().to_vec()), + Value::Bytes(bytes) => Some(bytes.clone()), + Value::Null => None, + other => Some(format!("{other:?}").into_bytes()), + } +} + +impl From for KeyKindTag { + fn from(kind: KeyKind) -> Self { + match kind { + KeyKind::String => Self::String, + KeyKind::Hash => Self::Hash, + KeyKind::List => Self::List, + KeyKind::Set => Self::Set, + KeyKind::SortedSet => Self::SortedSet, + KeyKind::Stream => Self::Stream, + KeyKind::Other => Self::Other, + } + } +} + +impl From for KeyTtlTag { + fn from(ttl: KeyTtl) -> Self { + match ttl { + KeyTtl::Persistent => Self::Persistent, + KeyTtl::ExpiresIn(left) => Self::ExpiresIn { + seconds: left.as_secs(), + }, + KeyTtl::Unknown => Self::Unknown, + } + } +} + +impl std::fmt::Debug for KeyReader { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("KeyReader").finish_non_exhaustive() + } +} + +#[cfg(test)] +mod tests { + use std::time::Duration; + + use tablepro_core::QueryResult; + use tablepro_core::column::{ColumnType, ResultColumn}; + use tablepro_test_support::{ConnectionScript, FakeReply}; + + use super::*; + use crate::session::DatabaseSession; + use crate::test_session::started; + + fn page(kind: KeyKind, names: &[&str], next: Option<&str>) -> KeyPage { + let columns = vec![ResultColumn::new("member", ColumnType::unknown())]; + let rows = names.iter().map(|name| vec![Value::Text((*name).to_owned())]).collect(); + KeyPage { + kind, + type_name: "set".to_owned(), + ttl: KeyTtl::ExpiresIn(Duration::from_secs(90)), + length: Some(4), + rows: QueryResult::new(columns, rows), + next: next.map(KeyCursor::new), + } + } + + #[tokio::test] + async fn load_more_adds_the_next_window_to_one_set_without_a_scan_s_repeats() { + let mut script = ConnectionScript::default(); + script + .read_key + .once(FakeReply::ok(Some(page(KeyKind::Set, &["a", "b"], Some("7"))))) + .once(FakeReply::ok(Some(page(KeyKind::Set, &["b", "c", "d"], None)))); + let (session, tasks) = started(script); + let reader = DatabaseSession::new(session, tasks).open_key("tags".to_owned()); + + let first = reader.read_more(None).await.unwrap().unwrap(); + let set = reader.rows().unwrap(); + let second = reader.read_more(None).await.unwrap().unwrap(); + let again = reader.read_more(None).await.unwrap().unwrap(); + + assert_eq!(first.kind, KeyKindTag::Set); + assert_eq!(first.ttl, KeyTtlTag::ExpiresIn { seconds: 90 }); + assert_eq!((first.rows, first.has_more, first.length), (2, true, Some(4))); + assert_eq!((second.rows, second.has_more, second.restarted), (4, false, false)); + assert_eq!(set.row_count(), 4, "the second window joined the set the grid holds"); + assert_eq!(again, second, "past the end nothing more is read"); + let members: Vec<_> = (0..4).map(|row| set.cell_text(row, 0).unwrap().unwrap()).collect(); + assert_eq!(members, ["a", "b", "c", "d"]); + } + + #[tokio::test] + async fn a_key_that_is_gone_reads_as_none() { + let mut script = ConnectionScript::default(); + script.read_key.always(FakeReply::ok(None)); + let (session, tasks) = started(script); + let reader = DatabaseSession::new(session, tasks).open_key("gone".to_owned()); + + assert_eq!(reader.read_more(None).await.unwrap(), None); + assert!(reader.rows().is_none()); + } + + #[tokio::test] + async fn a_key_of_another_type_starts_its_rows_again() { + let mut script = ConnectionScript::default(); + script + .read_key + .once(FakeReply::ok(Some(page(KeyKind::Set, &["a"], Some("3"))))) + .once(FakeReply::ok(Some(page(KeyKind::List, &["x"], None)))); + let (session, tasks) = started(script); + let reader = DatabaseSession::new(session, tasks).open_key("k".to_owned()); + + reader.read_more(None).await.unwrap(); + let before = reader.rows().unwrap(); + let after = reader.read_more(None).await.unwrap().unwrap(); + + assert!(after.restarted); + assert_eq!(after.kind, KeyKindTag::List); + assert_eq!(after.rows, 1); + assert!(!Arc::ptr_eq(&before, &reader.rows().unwrap())); + } +} diff --git a/core/crates/ffi/src/lib.rs b/core/crates/ffi/src/lib.rs index 1f58c984e6..114969d31a 100644 --- a/core/crates/ffi/src/lib.rs +++ b/core/crates/ffi/src/lib.rs @@ -19,6 +19,7 @@ mod filter; mod history; mod host; mod host_key; +mod key_read; mod library; mod masking; mod prompter; @@ -32,6 +33,8 @@ mod session; mod statement_at; mod structure; mod syntax; +#[cfg(test)] +mod test_session; pub mod window_abi; pub use account::{ @@ -58,6 +61,7 @@ pub use history::{ HistoryCursorArg, HistoryEntryInfo, HistoryOutcomeTag, HistoryPageInfo, HistoryRun, QueryHistoryStore, }; pub use host::{HostConfig, HostSecretError, HostSecretStore, HostSecrets, SecretItemTag, SecretKindTag}; +pub use key_read::{KeyKindTag, KeyReader, KeyTtlTag, KeyWindowInfo}; pub use library::{ ConnectionLibrary, ConnectionRecord, ConnectionSecrets, GroupRecord, ImportSummary, LibrarySnapshot, SafeModeTag, SshAuthTag, SshSettings, TagRecord, TlsModeTag, TlsSettings, @@ -75,7 +79,10 @@ pub use row_edits::{ }; pub use run::{QueryRun, RunEvent, RunListener, RunOutcome, TransactionStateTag, TruncationTag}; pub use safe_mode_gate::RunGate; -pub use session::{ColumnSort, DatabaseSession, FailureCauseTag, RowEstimate, SessionHealthTag, TablePageRead}; +pub use session::{ + ColumnSort, DatabaseLayoutTag, DatabaseSession, FailureCauseTag, PageResume, RowEstimate, SessionHealthTag, + TablePageRead, +}; pub use statement_at::StatementSpan; pub use structure::{StructureColumn, StructureForeignKey, StructureIndex, TableStructure}; diff --git a/core/crates/ffi/src/session.rs b/core/crates/ffi/src/session.rs index 5362a5eec0..a79be7b982 100644 --- a/core/crates/ffi/src/session.rs +++ b/core/crates/ffi/src/session.rs @@ -1,14 +1,17 @@ -use std::sync::Arc; +use std::sync::{Arc, Mutex, PoisonError}; use std::time::Instant; use tablepro_core::browse::{ ExportFields, ExportRequest, PageRequest, PagingMode, SortKey, build_count, build_page, build_view_sql, paging_mode, read_page, }; +use tablepro_core::dialect::DatabaseLayout; use tablepro_core::filter::FilterSet; use tablepro_core::meta::{ObjectInfo, ObjectScope, PagePosition, RowCountEstimate, RowIdentity, TableRef}; use tablepro_core::sql_syntax::{SortReference, sort_reference, with_order_by}; -use tablepro_core::{ByteLimit, ColumnInfo, EditorSessionOptions, QueryResult, ResultEvent, ResultSink, Truncation}; +use tablepro_core::{ + ByteLimit, CallOptions, ColumnInfo, EditorSessionOptions, QueryResult, ResultEvent, ResultSink, Truncation, +}; use tablepro_session::runtime::{Tasks, catch_panic}; use tablepro_session::{FailureCause, MonitorSignal, OperationError, OperationKind, Session, SessionHealth}; use tokio_util::sync::CancellationToken; @@ -19,6 +22,7 @@ use crate::definition::ObjectSource; use crate::editor::QueryEditor; use crate::error::{BoxedErrorInfo, CoreError}; use crate::filter::{self, FilterChoices, TableFilterArg}; +use crate::key_read::KeyReader; use crate::library::SafeModeTag; use crate::row_edits::TableEditor; use crate::run::{QueryRun, RunListener, RunOutcome, RunSink, RunState, TransactionStateTag}; @@ -33,13 +37,15 @@ pub struct ColumnSort { pub ascending: bool, } -// Row-address columns may follow the visible ones. An engine that pages on the server cannot seek past page one. +// Row-address columns may follow the visible ones. An engine that pages on the server reads a page by an offset only +// through the rows before it, so it says it cannot seek, and its next page resumes from where this one stopped. #[derive(uniffi::Object)] pub struct TablePageRead { run: Arc, visible_columns: u32, can_seek: bool, view_sql: Option, + next: Arc>>, } #[uniffi::export] @@ -56,6 +62,15 @@ impl TablePageRead { self.can_seek } + // Where the server stopped this page, set before the run finishes. None for an engine that seeks, or at the end. + pub fn next_page(&self) -> Option> { + self.next + .lock() + .unwrap_or_else(PoisonError::into_inner) + .clone() + .map(|position| Arc::new(PageResume { position })) + } + // The query the table view stands for: every row its filter and sort select, with no row window and the // filter's values written in, for a share link or the editor. None when the engine cannot write it that way. pub fn view_sql(&self) -> Option { @@ -63,6 +78,38 @@ impl TablePageRead { } } +// The paging state a server handed back with a page, which only the same table, sort, filter and size read again. +#[derive(uniffi::Object)] +pub struct PageResume { + position: PagePosition, +} + +impl std::fmt::Debug for PageResume { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("PageResume").field("position", &self.position).finish() + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)] +pub enum DatabaseLayoutTag { + // One database a connection reaches: a file, or numbered databases of keys. + Single, + // The server's databases are the schemas the catalog lists. + AsSchemas, + // Each database holds schemas of its own, and a connection's catalog describes the one it opened. + WithSchemas, +} + +impl From for DatabaseLayoutTag { + fn from(layout: DatabaseLayout) -> Self { + match layout { + DatabaseLayout::Single => Self::Single, + DatabaseLayout::AsSchemas => Self::AsSchemas, + DatabaseLayout::WithSchemas => Self::WithSchemas, + } + } +} + impl std::fmt::Debug for TablePageRead { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("TablePageRead") @@ -231,6 +278,7 @@ impl DatabaseSession { } // Returns once the page is built and its read started, so a bad filter fails the call; rows come as run events. + // `resume` is a server-paged table's next page, from the page before; `offset` is read through otherwise. #[expect( clippy::too_many_arguments, reason = "the page's table, sort, filter and window, the app's listener and its cancel, as the app passes them" @@ -242,16 +290,22 @@ impl DatabaseSession { filter: Option, limit: u64, offset: u64, + resume: Option>, listener: Box, cancel: Option>, ) -> Result, CoreError> { let session = self.session.clone(); let tasks = self.tasks.clone(); let cancel = token(cancel); + let position = match (resume, offset) { + (Some(resume), _) => resume.position.clone(), + (None, 0) => PagePosition::First, + (None, rows) => PagePosition::Offset(rows), + }; on_runtime(&self.tasks, async move { let dialect = session.current_dialect().ok_or_else(not_connected)?; let filter = filter::filter_set(filter, &*dialect)?; - let plan = plan_page(&session, table, sort_keys(sort), filter, limit, offset, &cancel).await?; + let plan = plan_page(&session, table, sort_keys(sort), filter, limit, position, &cancel).await?; Ok(Arc::new(start_page(session, &tasks, plan, listener))) }) .await @@ -454,19 +508,72 @@ impl DatabaseSession { TableEditor::open(self.session.clone(), self.tasks.clone(), table, refresh, cancel).await } - pub async fn open_editor(&self, cancel: Option>) -> Result, CoreError> { + // `database` is where the editor runs: an engine that binds it at connect opens there, another moves there. + pub async fn open_editor( + &self, + database: Option, + cancel: Option>, + ) -> Result, CoreError> { let session = self.session.clone(); let tasks = self.tasks.clone(); let cancel = token(cancel); + let database = database.filter(|name| !name.is_empty()); on_runtime(&self.tasks, async move { - let editor = session - .open_editor_session(EditorSessionOptions::default(), &cancel) - .await?; + let options = EditorSessionOptions { + database: database.clone(), + ..EditorSessionOptions::default() + }; + let editor = session.open_editor_session(options, &cancel).await?; + if let Some(database) = database + && editor.database().as_deref() != Some(database.as_str()) + && let Err(error) = editor + .use_database(&database, CallOptions::new(None, cancel.clone())) + .await + { + // Run elsewhere, the tab's text would make its objects in the wrong database. + editor.close().await; + return Err(error.into()); + } Ok(Arc::new(QueryEditor::new(editor, tasks))) }) .await } + // How the server's databases stand to the catalog; Single while there is no dialect to ask. + pub fn database_layout(&self) -> DatabaseLayoutTag { + self.session + .current_dialect() + .map_or(DatabaseLayoutTag::Single, |dialect| dialect.database_layout().into()) + } + + // The database the connection was asked to open, as the user named it. None for a file or a login that named none. + pub fn database(&self) -> Option { + self.session + .database() + .filter(|name| !name.is_empty()) + .map(str::to_owned) + } + + // The server's databases the login sees: the one the connection is in marked default, the engine's own system. + pub async fn databases(&self, cancel: Option>) -> Result, CoreError> { + let session = self.session.clone(); + let cancel = token(cancel); + on_runtime(&self.tasks, async move { + let databases = session + .run_cancellable(OperationKind::Metadata, &cancel, |lease, options| async move { + Ok(lease.list_databases(options).await?) + }) + .await?; + Ok(databases.iter().map(SchemaEntry::from).collect()) + }) + .await + } + + // A key-value engine's key, read a window at a time; nothing is read until `read_more`. + pub fn open_key(&self, key: String) -> Arc { + Arc::new(KeyReader::new(self.session.clone(), self.tasks.clone(), key)) + } + // Editors opened from it close on their own. pub async fn close(&self) -> Result<(), CoreError> { let closing = self.session.begin_shutdown(); @@ -577,7 +684,7 @@ async fn plan_page( sort: Vec, filter: FilterSet, limit: u64, - offset: u64, + position: PagePosition, cancel: &CancellationToken, ) -> Result { let table: TableRef = table.into(); @@ -594,16 +701,6 @@ async fn plan_page( .await?; let dialect = session.current_dialect().ok_or_else(not_connected)?; let can_seek = paging_mode(dialect.table_paging(), &identity, &sort) != PagingMode::ServerPaging; - if offset > 0 && !can_seek { - return Err(CoreError::failed( - "ffi.page_unsupported", - "the engine reads a table only from its start", - )); - } - let position = match offset { - 0 => PagePosition::First, - rows => PagePosition::Offset(rows), - }; // Built once here, so a filter the engine cannot take fails the call and never reaches the server. let spec = build_page( &*dialect, @@ -648,10 +745,12 @@ fn start_page(session: Arc, tasks: &Tasks, plan: PagePlan, listener: Bo let visible_columns = plan.visible_columns; let can_seek = plan.can_seek; let view_sql = plan.view_sql.clone(); + let next = Arc::new(Mutex::new(None)); + let landed = next.clone(); let run = state.clone(); drop(tasks.spawn_task(async move { let started = Instant::now(); - let outcome = match catch_panic(read_into(&session, &plan, &run)).await { + let outcome = match catch_panic(read_into(&session, &plan, &run, &landed)).await { Ok(Ok(())) => RunOutcome::Completed { elapsed_ms: u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX), }, @@ -669,11 +768,17 @@ fn start_page(session: Arc, tasks: &Tasks, plan: PagePlan, listener: Bo visible_columns, can_seek, view_sql, + next, } } // The run's cancel reaches the driver through the operation, so a cancel stops the statement on the server. -async fn read_into(session: &Session, plan: &PagePlan, state: &Arc) -> Result<(), OperationError> { +async fn read_into( + session: &Session, + plan: &PagePlan, + state: &Arc, + next: &Mutex>, +) -> Result<(), OperationError> { let read = session .run_cancellable(OperationKind::Page, &state.cancel, move |lease, options| async move { let request = PageRequest { @@ -688,11 +793,14 @@ async fn read_into(session: &Session, plan: &PagePlan, state: &Arc) -> read_page::(&*lease, &request, &options).await }) .await?; - // An engine that pages on the server hands back where more rows start, and only page one can be read here. + // An engine that pages on the server hands back where more rows start, which the next page resumes from. let truncation = match read.result.truncated || (read.mode == PagingMode::ServerPaging && read.next.is_some()) { true => Truncation::ReadPastLimit, false => Truncation::Complete, }; + if let Some(position @ PagePosition::Resume(_)) = read.next { + *next.lock().unwrap_or_else(PoisonError::into_inner) = Some(position); + } deliver( RunSink::new(state.clone(), ByteLimit::EDITOR_DEFAULT), read.result, @@ -726,3 +834,112 @@ impl std::fmt::Debug for DatabaseSession { .finish_non_exhaustive() } } + +#[cfg(test)] +mod tests { + use tablepro_core::meta::SchemaInfo; + use tablepro_core::{DriverError, EditorSession, UnsupportedFeature}; + use tablepro_test_support::{ConnectionScript, FakeEditorSession, FakeReply, Replies}; + + use super::*; + use crate::test_session::started; + + fn database(name: &str, is_default: bool, is_system: bool) -> SchemaInfo { + SchemaInfo { + name: name.to_owned(), + is_default, + is_system, + } + } + + fn with_editor(editor: &Arc) -> ConnectionScript { + let mut script = ConnectionScript::default(); + let opened: Arc = editor.clone(); + script.open_editor_session.always(FakeReply::ok(opened)); + script + } + + #[tokio::test] + async fn the_server_s_databases_come_with_the_one_in_use_and_the_engine_s_own_marked() { + let mut script = ConnectionScript::default(); + script.list_databases.always(FakeReply::ok(vec![ + database("shop", true, false), + database("analytics", false, false), + database("mysql", false, true), + ])); + let (session, tasks) = started(script); + let session = DatabaseSession::new(session, tasks); + + let databases = session.databases(None).await.unwrap(); + + let listed: Vec<_> = databases + .iter() + .map(|entry| (entry.name.as_str(), entry.is_default, entry.is_system)) + .collect(); + assert_eq!( + listed, + [ + ("shop", true, false), + ("analytics", false, false), + ("mysql", false, true) + ] + ); + } + + #[tokio::test] + async fn an_editor_opened_for_another_database_moves_there() { + let editor = Arc::new(FakeEditorSession::new(Replies::default())); + editor.set_database(Some("shop")); + let (session, tasks) = started(with_editor(&editor)); + let session = DatabaseSession::new(session, tasks); + + let opened = session.open_editor(Some("analytics".to_owned()), None).await.unwrap(); + + assert_eq!(editor.moves(), ["analytics"]); + assert_eq!(opened.database().as_deref(), Some("analytics")); + } + + #[tokio::test] + async fn an_editor_the_engine_opened_in_its_database_is_not_moved_again() { + let editor = Arc::new(FakeEditorSession::new(Replies::default())); + editor.set_database(Some("analytics")); + editor.refuse_moves(DriverError::Unsupported { + feature: UnsupportedFeature::DatabaseSwitching, + }); + let (session, tasks) = started(with_editor(&editor)); + let session = DatabaseSession::new(session, tasks); + + let opened = session.open_editor(Some("analytics".to_owned()), None).await.unwrap(); + + assert!(editor.moves().is_empty()); + assert_eq!(opened.database().as_deref(), Some("analytics")); + } + + #[tokio::test] + async fn an_editor_that_cannot_reach_its_database_is_closed_and_the_open_fails() { + let editor = Arc::new(FakeEditorSession::new(Replies::default())); + editor.refuse_moves(DriverError::Unsupported { + feature: UnsupportedFeature::DatabaseSwitching, + }); + let (session, tasks) = started(with_editor(&editor)); + let session = DatabaseSession::new(session, tasks); + + let refused = session + .open_editor(Some("analytics".to_owned()), None) + .await + .unwrap_err(); + + assert_eq!(refused.code(), "driver.unsupported"); + assert!(editor.is_closed(), "the editor was left open in the wrong database"); + } + + #[tokio::test] + async fn a_server_with_databases_says_how_they_stand_to_its_schemas() { + let (session, tasks) = started(ConnectionScript::default()); + let session = DatabaseSession::new(session, tasks); + + // The fake dialect, as a file, reaches one database. + assert_eq!(session.database_layout(), DatabaseLayoutTag::Single); + assert_eq!(session.database(), None); + } +} diff --git a/core/crates/ffi/src/test_session.rs b/core/crates/ffi/src/test_session.rs new file mode 100644 index 0000000000..105477a324 --- /dev/null +++ b/core/crates/ffi/src/test_session.rs @@ -0,0 +1,29 @@ +use std::sync::Arc; + +use tablepro_core::LivenessPolicy; +use tablepro_session::fakes::{FakeConnector, FakeCredentialSource}; +use tablepro_session::runtime::Tasks; +use tablepro_session::{DefaultDeadlines, Session, SessionDeps}; +use tablepro_test_support::ConnectionScript; + +// A session of a network server whose connection answers from `script`. +#[expect( + clippy::disallowed_methods, + reason = "a test is already inside its own runtime; production code takes the handle from AppRuntime" +)] +pub(crate) fn started(script: ConnectionScript) -> (Arc, Tasks) { + let tasks = Tasks::new(tokio::runtime::Handle::current()); + let request = FakeConnector::network_request("db.example", 5432).expect("a request"); + let (pending, _) = FakeConnector::pending_session(request, script); + let session = Session::start( + pending, + SessionDeps { + connector: Arc::new(FakeConnector::new([])), + credentials: Arc::new(FakeCredentialSource::new()), + deadlines: Arc::new(DefaultDeadlines::new(LivenessPolicy::DESKTOP)), + tasks: tasks.clone(), + prompter: None, + }, + ); + (session, tasks) +} diff --git a/core/crates/ffi/tests/account.rs b/core/crates/ffi/tests/account.rs index 92d64b2847..16691cc66b 100644 --- a/core/crates/ffi/tests/account.rs +++ b/core/crates/ffi/tests/account.rs @@ -355,7 +355,7 @@ mod shares { } async fn run(session: &DatabaseSession, sql: &str) -> Option> { - let editor = session.open_editor(None).await.unwrap(); + let editor = session.open_editor(None, None).await.unwrap(); let run = editor.run(sql.to_owned(), RunSettings::default(), Box::new(Quiet)); let outcome = run.outcome().await.unwrap(); assert!(matches!(outcome, RunOutcome::Completed { .. }), "{outcome:?}"); @@ -498,7 +498,7 @@ mod shares { name: "notes".to_owned(), }; let page = session - .read_table_page(notes.clone(), None, None, 2, 0, Box::new(Quiet), None) + .read_table_page(notes.clone(), None, None, 2, 0, None, Box::new(Quiet), None) .await .unwrap(); let outcome = page.run().outcome().await.unwrap(); diff --git a/core/crates/ffi/tests/browse.rs b/core/crates/ffi/tests/browse.rs index 07ecdd9c72..de039e2328 100644 --- a/core/crates/ffi/tests/browse.rs +++ b/core/crates/ffi/tests/browse.rs @@ -92,7 +92,7 @@ async fn fixture(dir: &Path, sql: &str) -> (Arc, Arc) { // On an editor of its own, closed before the test reads through the session. async fn execute(session: &DatabaseSession, sql: &str) { - let editor = session.open_editor(None).await.unwrap(); + let editor = session.open_editor(None, None).await.unwrap(); let run = editor.run(sql.to_owned(), RunSettings::default(), Box::new(Quiet)); let outcome = run.outcome().await.unwrap(); assert!(matches!(outcome, RunOutcome::Completed { .. }), "{outcome:?}"); @@ -140,7 +140,16 @@ async fn read( offset: u64, ) -> Result, CoreError> { session - .read_table_page(table("people"), sort, filter, limit, offset, Box::new(Quiet), None) + .read_table_page( + table("people"), + sort, + filter, + limit, + offset, + None, + Box::new(Quiet), + None, + ) .await } @@ -175,7 +184,7 @@ async fn a_page_s_view_sql_selects_every_page_with_its_filter_written_in() { let page = read(&session, by_name, filter, 1, 1).await.unwrap(); let names = column(&page, 1).await; let sql = page.view_sql().unwrap(); - let editor = session.open_editor(None).await.unwrap(); + let editor = session.open_editor(None, None).await.unwrap(); let run = editor.run(sql.clone(), RunSettings::default(), Box::new(Quiet)); let outcome = run.outcome().await.unwrap(); let set = run.result_set(0).unwrap(); @@ -391,7 +400,7 @@ async fn a_cancel_stops_a_page_read_on_the_engine() { let (_core, session) = fixture(dir.path(), &format!("{PEOPLE}; {endless}")).await; let page = session - .read_table_page(table("endless"), None, None, 100, 0, Box::new(Quiet), None) + .read_table_page(table("endless"), None, None, 100, 0, None, Box::new(Quiet), None) .await .unwrap(); let run = page.run(); @@ -539,7 +548,7 @@ async fn a_trigger_reads_back_and_a_function_is_unsupported_on_sqlite() { async fn an_editor_moves_to_a_database_only_where_the_engine_switches_one() { let dir = tempfile::tempdir().unwrap(); let (_core, session) = fixture(dir.path(), PEOPLE).await; - let editor = session.open_editor(None).await.unwrap(); + let editor = session.open_editor(None, None).await.unwrap(); // SQLite binds its database to the file it opened, so a definition from elsewhere cannot run there. let refused = editor.use_database("shop".to_owned(), None).await.unwrap_err(); @@ -562,7 +571,7 @@ async fn page_rows( filter: Option, ) -> Arc { let page = session - .read_table_page(table(name), None, filter, 100, 0, Box::new(Quiet), None) + .read_table_page(table(name), None, filter, 100, 0, None, Box::new(Quiet), None) .await .unwrap(); let outcome = page.run().outcome().await.unwrap(); @@ -636,7 +645,7 @@ async fn a_composite_key_leads_to_its_row_and_back_with_every_value_bound() { assert_eq!(incoming.columns, ["parent_code", "parent_region"]); let (_, filter) = filter_of(followed(&parent_keys, parents, 0, incoming)).unwrap(); let child = session - .read_table_page(table("child"), None, Some(filter), 100, 0, Box::new(Quiet), None) + .read_table_page(table("child"), None, Some(filter), 100, 0, None, Box::new(Quiet), None) .await .unwrap(); assert_eq!(column(&child, 0).await, texts(&["1"])); diff --git a/core/crates/ffi/tests/byte_limit.rs b/core/crates/ffi/tests/byte_limit.rs index cb7cd069a4..3ab643382c 100644 --- a/core/crates/ffi/tests/byte_limit.rs +++ b/core/crates/ffi/tests/byte_limit.rs @@ -79,7 +79,7 @@ async fn a_run_keeps_whole_rows_up_to_its_byte_limit() { }; let core = core(); let session = core.open_file(request, None).await.unwrap(); - let editor = session.open_editor(None).await.unwrap(); + let editor = session.open_editor(None, None).await.unwrap(); let settings = RunSettings { byte_limit: Some(1 << 20), ..RunSettings::default() diff --git a/core/crates/ffi/tests/export.rs b/core/crates/ffi/tests/export.rs index af7535cc0a..7aca63c134 100644 --- a/core/crates/ffi/tests/export.rs +++ b/core/crates/ffi/tests/export.rs @@ -65,7 +65,7 @@ fn table(name: &str) -> TableName { } async fn run(session: &DatabaseSession, sql: &str) -> Option> { - let editor = session.open_editor(None).await.unwrap(); + let editor = session.open_editor(None, None).await.unwrap(); let run = editor.run(sql.to_owned(), RunSettings::default(), Box::new(Quiet)); let outcome = run.outcome().await.unwrap(); assert!(matches!(outcome, RunOutcome::Completed { .. }), "{outcome:?}"); @@ -186,7 +186,7 @@ async fn a_page_exports_only_its_visible_columns() { ) .await; let page = session - .read_table_page(table("notes"), None, None, 100, 0, Box::new(Quiet), None) + .read_table_page(table("notes"), None, None, 100, 0, None, Box::new(Quiet), None) .await .unwrap(); let read = page.run(); @@ -372,7 +372,7 @@ async fn a_failed_export_keeps_the_file_it_would_have_replaced() { async fn rows_still_arriving_are_not_exported() { let dir = tempfile::tempdir().unwrap(); let (_core, session) = fixture(dir.path()).await; - let editor = session.open_editor(None).await.unwrap(); + let editor = session.open_editor(None, None).await.unwrap(); let settings = RunSettings { row_limit: Some(u64::MAX), timeout_ms: None, diff --git a/core/crates/ffi/tests/history.rs b/core/crates/ffi/tests/history.rs index fa738a8d74..87ebd56f91 100644 --- a/core/crates/ffi/tests/history.rs +++ b/core/crates/ffi/tests/history.rs @@ -202,6 +202,41 @@ async fn a_deleted_run_is_gone_and_clear_removes_the_rest() { assert!(after_clear.entries.is_empty()); } +#[tokio::test] +async fn a_prune_drops_runs_past_the_age_kept_then_the_oldest_past_the_count_kept() { + let dir = tempfile::tempdir().unwrap(); + let core = started(Some(dir.path())); + let session = open(&core, &dir.path().join("app.sqlite")).await; + let history = core.history().await.unwrap(); + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_secs(); + let now = i64::try_from(now).unwrap(); + let day = 86_400; + let mut ids = Vec::new(); + for (sql, at) in [ + ("SELECT 'ancient'", now - 400 * day), + ("SELECT 'old'", now - 3 * day), + ("SELECT 'recent'", now - day), + ("SELECT 'newest'", now), + ] { + ids.push(history.record(session.clone(), ran(sql, at)).await.unwrap().unwrap()); + } + + let aged = history.prune(365, 0).await.unwrap(); + let after_age = history.search(String::new(), None, None, 50).await.unwrap(); + let capped = history.prune(0, 2).await.unwrap(); + let after_cap = history.search(String::new(), None, None, 50).await.unwrap(); + + assert_eq!(aged, 1); + let kept: Vec = after_age.entries.iter().map(|entry| entry.id).collect(); + assert_eq!(kept, [ids[3], ids[2], ids[1]]); + assert_eq!(capped, 1); + let kept: Vec = after_cap.entries.iter().map(|entry| entry.id).collect(); + assert_eq!(kept, [ids[3], ids[2]], "the newest two stay"); +} + // SQLite withholds a statement that sets an encryption key, and text whose quote never closes. #[tokio::test] async fn a_statement_the_engine_withholds_is_not_stored() { diff --git a/core/crates/ffi/tests/library.rs b/core/crates/ffi/tests/library.rs index e1bde71892..d1c73167ab 100644 --- a/core/crates/ffi/tests/library.rs +++ b/core/crates/ffi/tests/library.rs @@ -204,7 +204,7 @@ async fn sqlite_file(core: &Core, path: &Path) { ) .await .unwrap(); - let editor = session.open_editor(None).await.unwrap(); + let editor = session.open_editor(None, None).await.unwrap(); struct Quiet; impl tablepro_ffi::RunListener for Quiet { fn events_pending(&self) {} @@ -545,6 +545,7 @@ async fn a_saved_sqlite_file_connects_lists_its_tables_and_becomes_recent() { let session = core .connect_saved( saved.id.clone(), + None, ConnectionSecrets::default(), ConnectionSecrets::default(), None, @@ -567,6 +568,7 @@ async fn a_saved_sqlite_file_connects_lists_its_tables_and_becomes_recent() { None, 100, 0, + None, Box::new(Quiet), None, ) @@ -637,10 +639,10 @@ async fn a_typed_secret_is_kept_once_its_connect_logs_in_and_not_when_it_fails() ..ConnectionSecrets::default() }; - core.connect_saved(people.id.clone(), typed(), typed(), None, None) + core.connect_saved(people.id.clone(), None, typed(), typed(), None, None) .await .unwrap(); - core.connect_saved(shop.id.clone(), typed(), typed(), None, None) + core.connect_saved(shop.id.clone(), None, typed(), typed(), None, None) .await .unwrap_err(); @@ -666,6 +668,7 @@ async fn a_network_login_with_no_saved_password_says_so() { let error = core .connect_saved( saved.id, + None, ConnectionSecrets::default(), ConnectionSecrets::default(), None, @@ -694,6 +697,7 @@ async fn a_password_typed_at_connect_is_used_when_none_is_saved() { let error = core .connect_saved( saved.id, + None, ConnectionSecrets { database_password: Some(SecretString::from("typed")), ..ConnectionSecrets::default() @@ -826,6 +830,7 @@ async fn an_empty_database_password_survives_a_separately_stored_ssh_password() let error = core .connect_saved( saved.id, + None, ConnectionSecrets { database_password: Some(SecretString::from("")), ..ConnectionSecrets::default() diff --git a/core/crates/ffi/tests/row_edits.rs b/core/crates/ffi/tests/row_edits.rs index 457b2700ea..cd80914278 100644 --- a/core/crates/ffi/tests/row_edits.rs +++ b/core/crates/ffi/tests/row_edits.rs @@ -84,7 +84,7 @@ fn people() -> TableName { } async fn run(session: &DatabaseSession, sql: &str) -> Option> { - let editor = session.open_editor(None).await.unwrap(); + let editor = session.open_editor(None, 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); @@ -112,7 +112,7 @@ async fn seeded(core: &Core, path: &Path) { // The page as a table tab reads it. async fn page_of(session: &DatabaseSession, table: TableName) -> Arc { let read = session - .read_table_page(table, None, None, 100, 0, Box::new(Quiet), None) + .read_table_page(table, None, None, 100, 0, None, Box::new(Quiet), None) .await .unwrap(); let run = read.run(); @@ -174,6 +174,7 @@ async fn saved(core: &Core, path: &Path, safe_mode: SafeModeTag) -> Arc FileOpenRequest { async fn people(core: &Core, path: &Path) { let session = core.open_file(file(path, false, true), None).await.unwrap(); - let editor = session.open_editor(None).await.unwrap(); + let editor = session.open_editor(None, None).await.unwrap(); let run = editor.run( "CREATE TABLE people (id INTEGER PRIMARY KEY, name TEXT)".to_owned(), RunSettings::default(), @@ -126,6 +126,7 @@ async fn saved(core: &Core, path: &Path, safe_mode: SafeModeTag) -> Arc (Arc, Arc, Arc (u32, bool, u32, Vec>) { let page = session - .read_table_page(table, sort, None, limit, offset, Box::new(Wakes::default()), None) + .read_table_page(table, sort, None, limit, offset, None, Box::new(Wakes::default()), None) .await .unwrap(); let run = page.run(); diff --git a/core/crates/storage/src/query_history/mod.rs b/core/crates/storage/src/query_history/mod.rs index 352e127204..e6c5343c86 100644 --- a/core/crates/storage/src/query_history/mod.rs +++ b/core/crates/storage/src/query_history/mod.rs @@ -364,6 +364,13 @@ impl QueryHistory { self.prune_with_cap(retention_days, MAX_UNPINNED_ENTRIES).await } + /// `prune`, keeping at most `max_entries` unpinned entries, a user's + /// setting under the store's own cap. + pub async fn prune_keeping(&self, retention_days: u32, max_entries: u32) -> Result { + self.prune_with_cap(retention_days, i64::from(max_entries).min(MAX_UNPINNED_ENTRIES)) + .await + } + pub(crate) async fn prune_with_cap(&self, retention_days: u32, cap: i64) -> Result { let mut report = PruneReport::default(); diff --git a/core/docs/decisions/0022-browsing-through-the-ffi.md b/core/docs/decisions/0022-browsing-through-the-ffi.md index f505ea83fb..f448107fb2 100644 --- a/core/docs/decisions/0022-browsing-through-the-ffi.md +++ b/core/docs/decisions/0022-browsing-through-the-ffi.md @@ -1,6 +1,6 @@ # 0022: A table page is read on the session with its filter bound, and structure, definitions, export and history cross the FFI -- **Status**: Accepted +- **Status**: Accepted; amended 2026-11-14 (Server paging, databases, keys and history retention) - **Date**: 2026-11-12 ## Context @@ -22,6 +22,13 @@ The FFI exposes what the Linux app calls, and does the work the Linux app does, - `ResultSet::cell_text_head` gives a value's start, line breaks kept, and `cell_bytes` a binary value's first bytes and its length, so an app's viewer copies no more of a large cell than it shows, where `cell_text` copies all of it. - `Core::history` opens the query history at `/state/history.db` once. `record` takes the session, so the engine's `history_recording` withholds a statement that holds a secret, as on Linux; `search` pages by the store's keyset; `delete` and `clear` change it. +### Server paging, databases, keys and history retention (2026-11-14) + +- A server-paged engine (Cassandra) is no longer limited to its first page. `TablePageRead::next_page` hands back where the server stopped, as a `PageResume`, once the page's run has finished, and `read_table_page` takes it to read the page after; it resumes only the same table, sort, filter and page size. An offset with no resume is read through the rows before it (`browse::read_page` skips them), so `can_seek` now says whether an offset is cheap, not whether later pages exist. Remembering the resumes for Previous is the host's, as it is the Linux pager's. +- `open_editor` takes the database the editor runs in: an engine that binds the database at connect (PostgreSQL) opens the editor there through `EditorSessionOptions::database`, another moves it there with `use_database`, and an editor that cannot reach it is closed and the call fails. `QueryEditor::database` says where a typed `USE` left it. `DatabaseSession::databases` lists the server's databases (`Connection::list_databases`), `database_layout` says how they stand to the catalog, and `database` names the one the connection was asked to open. `Core::connect_saved` takes a database in place of the saved one, which is how a host opens another database of a server whose databases hold schemas of their own beside its connection (Linux ADR 0030). +- `DatabaseSession::open_key` gives a `KeyReader` that reads one key a window at a time (`Connection::read_key`) into one `ResultSet`, so a grid grows with Load More; an entry a hash or set scan returns again is left out, and a key that changed type starts its rows again. +- `QueryHistoryStore::prune` drops unpinned runs past a host's retention days and entry count (`QueryHistory::prune_keeping`), under the store's own cap. + ## Rationale - One place builds the WHERE, binds its values and pages the table, for every app. @@ -32,7 +39,7 @@ The FFI exposes what the Linux app calls, and does the work the Linux app does, - A table tab's page is no longer on a connection of its own, so a session setting made in a query tab does not reach it, as on Linux. - A page is read whole, under `OperationKind::Page`'s deadline, before its rows reach the app. -- History is pruned to the store's cap when it opens; a retention setting, as Linux has, is the host's to add. +- History is pruned to the store's cap when it opens; a host applies its retention setting through `prune`. - An array value in `export_rows` is written as its text, since the result store keeps arrays only as text; `export_table` writes it as an array. ## Alternatives considered diff --git a/windows/AGENTS.md b/windows/AGENTS.md index 602bbbb48d..8ecd3f645b 100644 --- a/windows/AGENTS.md +++ b/windows/AGENTS.md @@ -41,9 +41,10 @@ This is the guide for work under `windows/`. The root `AGENTS.md` holds the rule - `QueryEditor.Run` returns at once. Read the run's events with `ReadEventsAsync` on the UI thread; rows that arrive while it is busy come as one event. - A grid reads a `ResultSet` through `ResultCursor.Fetch`, one window per visible range. A cursor belongs to one thread, and a window cannot be read after the cursor's next fetch. - `DataGridView.SetData(new ResultSetData(set, columns))` shows a set. Call the grid's `RowsChanged` after each `RowsAppended`. Sorting is the host's: the grid raises `SortRequested` and shows `Sort`. -- The core writes every sorted statement: `ReadTablePageAsync` reads a table's page with its sort and filter on a pooled connection and returns its run, `SortedQuery` writes a query result's, null when the statement cannot run again or the engine cannot name the column. `ResultSet.SortedAsync` then sorts the rows held (`core/docs/decisions/0007-sorting-a-result.md`). `ReadTablePageAsync` takes the page's offset, and `CanSeek` says whether the engine has later pages; `CountRowsAsync` counts the rows the filter picks, and `EstimateRowsAsync` gives the whole table's count from the engine's statistics, null where it keeps none. The filter's values are bound by the core, never written into SQL here (`core/docs/decisions/0022-browsing-through-the-ffi.md`). -- `GetStructureAsync` gives a table's columns, indexes, foreign keys and CREATE script, `GetObjectDefinitionAsync` a routine's, trigger's or sequence's source, `ExportRowsAsync` and `ExportTableAsync` write a file through the core's encoders, and `TableProCore.OpenHistoryAsync` the query history, which withholds what the engine says holds a secret. +- The core writes every sorted statement: `ReadTablePageAsync` reads a table's page with its sort and filter on a pooled connection and returns its run, `SortedQuery` writes a query result's, null when the statement cannot run again or the engine cannot name the column. `ResultSet.SortedAsync` then sorts the rows held (`core/docs/decisions/0007-sorting-a-result.md`). `ReadTablePageAsync` takes the page's offset, or for an engine that pages on the server (`CanSeek` false, Cassandra) the `PageResume` the page before handed back through `NextPage()`, since an offset there reads through every row before it; `CountRowsAsync` counts the rows the filter picks, and `EstimateRowsAsync` gives the whole table's count from the engine's statistics, null where it keeps none. The filter's values are bound by the core, never written into SQL here (`core/docs/decisions/0022-browsing-through-the-ffi.md`). +- `GetStructureAsync` gives a table's columns, indexes, foreign keys and CREATE script, `GetObjectDefinitionAsync` a routine's, trigger's or sequence's source, `ExportRowsAsync` and `ExportTableAsync` write a file through the core's encoders, and `TableProCore.OpenHistoryAsync` the query history, which withholds what the engine says holds a secret and keeps the age and count `PruneAsync` is given. - 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`). +- `DatabaseSession.Layout` says how the server's databases stand to the catalog, `GetDatabasesAsync` lists them, and `OpenEditorAsync(database)` opens an editor that runs in one (opened there or moved there; one that cannot reach it throws). `QueryEditor.Database` follows a typed USE. `TableProCore.ConnectAsync(database:)` opens a saved connection in another of its databases, and `OpenKey` reads a key-value engine's key a window at a time (`KeyReader`). - `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 ed0ba50172..a5c9653ffd 100644 --- a/windows/docs/decisions/0003-data-grid-control.md +++ b/windows/docs/decisions/0003-data-grid-control.md @@ -49,8 +49,8 @@ - Each row is one element with a `SpriteVisual` painted from a `CompositionDrawingSurface` the width of the pane's visible columns. `TablePro.Graphics.SurfaceDevice` makes the composition graphics device from a Direct2D device through Windows App SDK's `ICompositorInterop`, whose IIDs and layout differ from the system's; a draw gets the surface's own device context through `ICompositionDrawingSurfaceInterop::BeginDraw`. - 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. +- 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, unless the host names another (`CellFontFamily`, a family not installed keeping the default) or size (`CellFontSize`, 8 to 36); rows and the header grow with the size as they do with text scale, and the app sets both from Settings, Data grid. The locale is the UI language's, so Han glyphs follow it. +- NULL is the host's `NullText`, the word NULL unless Settings, Data grid, NULL display names another, in italic in the tertiary text color; its accessible name follows it, and a copy still writes NULL as an empty cell. 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. diff --git a/windows/docs/decisions/0004-app-shell.md b/windows/docs/decisions/0004-app-shell.md index 77528d429b..c5811f98ca 100644 --- a/windows/docs/decisions/0004-app-shell.md +++ b/windows/docs/decisions/0004-app-shell.md @@ -18,6 +18,8 @@ On 2026-11-04 the roadmap added a page size picker and Go to page to the table p On 2026-11-05 the maintainer had the app show what the server prints, PostgreSQL's notices and warnings, with the statement that printed them. +On 2026-11-14 the roadmap's Phase 2 added a production cue (W-08), a database switcher per connection and per query tab (W-11), Replace and regular expressions in Find (W-33), .sql files (W-34), the Redis key tab (W-48), paging a Cassandra table past its first page (W-50), and Settings for fonts, the NULL text and the history (W-52). + ## Decision `src/TablePro.App` is one `MainWindow` with the WinUI `TitleBar`, a `MenuBar` under it and a `NavigationView` in `LeftCompact` whose content is a page object kept per surface: `HomeView`, `SettingsView` and a `WorkspaceView` per open connection. A tab moved out of it goes to a tab window, a `MainWindow` for that one connection (Tab windows, below). The core keeps the saved connections and their secrets; the app keeps its settings and its session in two JSON files in the package's LocalState folder. @@ -52,6 +54,7 @@ On 2026-11-05 the maintainer had the app show what the server prints, PostgreSQL ### Rail items - An item's icon is its engine's artwork (Engine artwork, below) in the connection's colour, with the engine's name as the item's `AutomationProperties.HelpText`. The macOS rail puts the colour in a dot on the glyph's corner; `NavigationViewItem.Icon` takes one `IconElement` and its `InfoBadge` slot carries the connecting state, so here the glyph itself takes the colour. The library's changes reach open items: a rename or a new colour shows at once. +- A saved connection opened in another of its server's databases is a rail item of its own, "name · database" (Database switcher, below), with the connection's colour and tags. Editing the connection renames each of them; Safe Mode and a changed connection reach each, since each is a session of that connection. - A rail item appears at once. `NavigationViewItem.Icon` takes an `IconElement`, which cannot host a `ProgressRing`, so the item shows an attention-dot `InfoBadge` while connecting and a critical-icon `InfoBadge` after a failure, with the state in `AutomationProperties.ItemStatus` and the tooltip. The page shows the `ProgressRing`, "Connecting to name..." and Cancel. - A failure is an Error `InfoBar` with Retry, Edit connection and Copy details in its content. It is closed and opened again on each failure, since Narrator reads an InfoBar when it opens ([InfoBar](https://learn.microsoft.com/en-us/windows/apps/develop/ui/controls/infobar)). - Cancel removes the item. At launch, only the front connection connects; another restored item connects when it is selected. A restored table tab reads its first page the first time it shows (its first `Loaded`, which TabView raises only for the content it displays), so a session with many table tabs reads one table. @@ -65,13 +68,16 @@ On 2026-11-05 the maintainer had the app show what the server prints, PostgreSQL | Keys | Command | |---|---| -| Ctrl+N, Ctrl+O | New connection, open a database file | +| Ctrl+N, Ctrl+O | New connection, open a database or .sql file | +| Ctrl+S, Ctrl+Shift+S | Save a table tab's changes or a query tab's file, save the file as | | Ctrl+T, Ctrl+W, Ctrl+Shift+T | New query tab, close the tab, reopen the last closed tab; File also has Move tab to new window | | Ctrl+Tab, Ctrl+Shift+Tab, Ctrl+F4 | TabView's own | | Ctrl+1 to Ctrl+8, Ctrl+9 | That tab, the last tab ([Tab view](https://learn.microsoft.com/en-us/windows/apps/develop/ui/controls/tab-view)) | | Ctrl+Enter, Ctrl+Shift+Enter, Shift+F5 | Run the selection or the whole text, run the statement at the cursor, stop | | F5 | Refresh the object tree | | Ctrl+B, Ctrl+P | Show or hide the object tree, filter objects | +| Ctrl+K | The database menu of the object pane (Database, Switch database) | +| Ctrl+F, Ctrl+H, F3 | Find, Find and Replace, next match (Edit menu, the editor's own keys) | | Ctrl+Shift+H | The Connections page | | F1 | Documentation | | Enter, F2, Delete on the Connections page | Connect; rename the row in place; delete, confirmed (every checked connection in selection mode) | @@ -119,7 +125,7 @@ On 2026-11-05 the maintainer had the app show what the server prints, PostgreSQL - A header click on a query result does what the macOS app does: the result's statement runs again with the column's ORDER BY in place of its own and before its row limit (`DatabaseSession.SortedQuery`, the core's `with_order_by`). The ORDER BY names the column, or gives its position where a name is not unique or not a plain column (core ADR 0007). Only one statement that reads runs again. For a script, a write, SHOW or EXPLAIN, and where the engine takes no position, the core sorts the rows the result holds (`ResultSet.SortedAsync`), as macOS sorts them where they are, and the status says so. - The object pane resizes with the Windows Community Toolkit's `GridSplitter` (Sizers), set up as its [page](https://learn.microsoft.com/en-us/dotnet/communitytoolkit/windows/sizers/gridsplitter) lays it out, between 180 and 640 effective pixels; WinUI's `SplitView` has no user resize. Every workspace shares the width, which `session.json` keeps. - Reopen closed tab (File menu, Ctrl+Shift+T, which the [Tab view](https://learn.microsoft.com/en-us/windows/apps/develop/ui/controls/tab-view) page asks for): a workspace keeps its last 20 closed tabs, newest first, each with its text or its table and its place in the strip. Disconnecting forgets them; Reconnect and connecting an edited connection keep them. -- Table tabs page as macOS pages a table: a page is the default page size long (Settings, Pagination: 100, 500, 1,000, 5,000 or 10,000 rows, 1,000 unless changed, as macOS); First, Previous, Next and Last sit in the tab's `CommandBar`, and its one status words the page as the macOS status bar does, with the run's time: "1,001-2,000 of 3,503 rows · 15 ms", or "Rows 1,001-2,000 · 15 ms" until the count lands. A table that fits one page keeps "Rows: 347 · 12 ms". The core writes each page (`table_query` takes an offset, over `build_page`'s `PagePosition::Offset`) and counts the table (`table_row_count`, `build_count` as the Linux pager counts), in the background after the first full page; until the count lands, Next stays while pages come back full. Before it counts, it reads the engine's estimate (`table_row_estimate`, over `Connection::table_estimate`, as the Linux pager does), and decides as macOS does: an exact count the engine keeps is the total; under the threshold (Settings, Pagination, Count rows if estimate less than: 1,000, 10,000, 100,000, 1,000,000 or Always count, 100,000 unless changed, as macOS), or with no estimate, the server counts; from the threshold on nothing is counted, the status says "1-1,000 of about 2,000,000 rows" (no total under a filter), and Count rows in the command bar counts on request. Last page, Go to page and All rows wait for an exact count. A sort or a refresh goes back to the first page, and a refresh counts again. An engine that pages on the server (Cassandra) cannot seek by offset, so it has only its first page, as on macOS, and the core refuses another (`ffi.page_unsupported`). +- Table tabs page as macOS pages a table: a page is the default page size long (Settings, Pagination: 100, 500, 1,000, 5,000 or 10,000 rows, 1,000 unless changed, as macOS); First, Previous, Next and Last sit in the tab's `CommandBar`, and its one status words the page as the macOS status bar does, with the run's time: "1,001-2,000 of 3,503 rows · 15 ms", or "Rows 1,001-2,000 · 15 ms" until the count lands. A table that fits one page keeps "Rows: 347 · 12 ms". The core writes each page (`table_query` takes an offset, over `build_page`'s `PagePosition::Offset`) and counts the table (`table_row_count`, `build_count` as the Linux pager counts), in the background after the first full page; until the count lands, Next stays while pages come back full. Before it counts, it reads the engine's estimate (`table_row_estimate`, over `Connection::table_estimate`, as the Linux pager does), and decides as macOS does: an exact count the engine keeps is the total; under the threshold (Settings, Pagination, Count rows if estimate less than: 1,000, 10,000, 100,000, 1,000,000 or Always count, 100,000 unless changed, as macOS), or with no estimate, the server counts; from the threshold on nothing is counted, the status says "1-1,000 of about 2,000,000 rows" (no total under a filter), and Count rows in the command bar counts on request. Last page, Go to page and All rows wait for an exact count. A sort or a refresh goes back to the first page, and a refresh counts again. An engine that pages on the server (Cassandra) cannot seek by offset: Next resumes from the paging state the page before handed back (`TablePageRead::next_page`), Previous from the one kept for that page, and a page with none kept is read through the rows before it, as the Linux pager does; the server saying no row follows ends Next even on a full page. Count rows, Last page, Go to page and All rows stay off there, since each reads through the whole table. A sort, a filter, a page size or a refresh drops the kept states (`core/docs/decisions/0022-browsing-through-the-ffi.md`). - Rows per page: a "1,000 rows" button before First page opens the macOS sizes, 5, 10, 20, 100, 500 and 1,000, as `RadioMenuFlyoutItem`s, then All rows..., which asks first and needs the count, and Custom..., up to 1,000,000. A new size keeps the page that holds the first row shown, as macOS does. The size belongs to the tab: `session.json` keeps it with the tab's page, and Reopen closed tab brings both back. - Go to page: between Previous and Next, "Page 3 of 36" opens a flyout with a `NumberBox` from 1 to the page count, as macOS asks in a popover. It is offered once the table is counted, as on macOS, and the box keeps a typed number inside that range (`InvalidInputOverwritten`). - An open transaction: each run's `Finished` event carries the transaction the editor's connection is left in (the core's `RunSummary.transaction_state`). The tab that holds one shows a Warning `InfoBar` above its results, "Transaction open", with Roll back, which asks first, and Commit, hidden on a read-only connection; a failed one is an Error bar with Roll back only. Both send COMMIT or ROLLBACK as typed SQL, EXEC or DISCARD for a key-value engine, as the Linux app does. Over the tabs, a bar names another tab that holds one, with Show; macOS shows its bar above every tab of the connection, and here the owning tab carries the actions, since the transaction lives on that tab's own connection. Closing a tab that holds one asks first, since closing rolls it back. Window close and Exit confirm every affected held transaction before closing any tabs; cancelling keeps them open. Then one dialog lists every query tab still running, as macOS asks before it quits, and says closing rolls back a transaction a run has open; a table tab loading a page is not asked about. Exit then hides the windows and closes every connection, each tab stopping its run, for up to 5 seconds before the process ends. While any tab holds a transaction or unsaved changes, the primary window registers a reason with `ShutdownBlockReasonCreate` ("Table changes are not saved.", "A transaction is open.") and answers `WM_QUERYENDSESSION` with FALSE once it has written the session file: a sign-out or a restart then lists TablePro with its reason and the user can cancel and save, and a Restart Manager request, as from an installer, is cancelled ([Application Shutdown Changes in Windows Vista](https://learn.microsoft.com/en-us/previous-versions/windows/desktop/ms700677(v=vs.85)); Restart Manager, [Guidelines for Applications](https://learn.microsoft.com/en-us/windows/win32/rstmgr/guidelines-for-applications)). A running query does not hold it, since stopping it is the default. A forced end cannot be held: "Sign out anyway" (`ENDSESSION_CRITICAL`) goes on to `WM_ENDSESSION`, which writes the session file again, and a forced Restart Manager close, as an update that closes the app by force, ends the process with no `WM_ENDSESSION`. Either way the server rolls the transaction back, and the session file already holds the work, as Restart Manager's guidelines ask: each table tab's pending changes, with the open cell editor's text as if it were kept (each change of that text starts the 2-second write too), a data row named by its primary key's values, each with the kind the core read it as so a BLOB and a text that read alike stay apart, and a cell by its column's name (a table with no primary key keeps none, since nothing finds its rows again), and each tab that held a transaction (`SavedEdits`, `SessionTab`). The app registers with `RegisterApplicationRestart` at startup (`RESTART_NO_CRASH | RESTART_NO_HANG`, no arguments), so Restart Manager starts it again after an update or a restart, and the new process claims the data folder as any launch does. A launch whose session holds such work reopens those connections and tabs even with Reopen at startup off (`SessionState.Recovered`). A table tab puts its changes back as pending once a page is read, each on the row its key finds there; a key two rows of the page share finds neither. What the page cannot take (a row not on it, a column gone, a value refused, every change while the table is locked) waits on the tab, and each later page read tries it again, so going to the row's page brings it back; a new row goes back whole or waits whole, since each try adds it again. An InfoBar over the rows says how many wait, with Discard, which drops only those and asks nothing more, and closes once none are left. Before a save sends its first statement, the session file is written at once with that tab's changes marked uncertain (`SavedRowEdit.Uncertain`), a write the file refuses being logged and the save going on; the change-triggered write that follows the save's answer clears the mark. Changes from a save whose outcome was unknown keep it too. The server may hold changes so marked already, so once any goes back, the tab is in the state an unknown outcome leaves it in, Save refused with "The last save may have been written" until a reload or Discard changes, and the bar says so. A query tab that held a transaction shows an InfoBar that it was open when TablePro last closed and the server rolled it back; the words name no cause, since a crash or a kill keeps the same work from the write before it. Only the session's own writes carry the work: the last write of a close or Exit leaves out what its questions covered, and a reconnect, a tab window's close and Reopen closed tab never carry it, so an answered change does not come back. Changes still waiting on a tab, and a connection not opened since, keep theirs in every write, Exit's last one too, since nothing has asked about them. 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`). @@ -128,9 +134,31 @@ On 2026-11-05 the maintainer had the app show what the server prints, PostgreSQL - 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. +### Production cue + +- The front connection's colour tints the title bar, the menu bar and its workspace's tab strip, at 18% in Light and 28% in Dark over the theme's own background, so text over it keeps its contrast; a contrast theme keeps its own colours (`ConnectionCue`). macOS tints its toolbar; here the title bar and the menu bar are that band, and the tab strip carries it over the tabs. The tab's command bars and content stay neutral. +- The connection's tags name its environment in the title bar's right header: a dot in each tag's colour and its name, read as "Environment: production". The Connections page, Settings and the rail between connections show none. + +### Database switcher + +- On an engine with more than one database (`DatabaseSession::database_layout` not `Single`), the object pane's first row is a button naming the database the workspace browses, Ctrl+K or Database, Switch database. Its menu is read from the server each time it opens (`databases`): the user's databases, a separator, then the engine's own, the current one checked. +- Where the server's databases are the catalog's schemas (MySQL, MariaDB, ClickHouse, Cassandra, MongoDB) the tree already lists each one, so a pick makes it the database new query tabs run in, kept in `session.json` with the connection, and opens and brings its row into view, as macOS's switch moves where the sidebar and new tabs look. +- Where each database holds schemas of its own (PostgreSQL, SQL Server) a connection's catalog describes only the one it opened, so a pick opens the saved connection in that database as a rail item of its own (`connect_saved` with a database), or brings an open one forward, as the Linux app opens another database beside its connection (Linux ADR 0030). Its tabs, tree, health and transactions are its own; it closes on its own, and comes back with the session. Editing the connection and connecting reconnects each of them too, after asking about their held work. +- A query tab names its database in its command bar, with the same menu. A pick waits while the tab runs or holds a transaction, so a move never rolls one back, as on Linux; with its editor open, the editor moves (`use_database`), keeping its temporary tables and settings, and on an engine that binds the database at connect the editor is let go and the next run opens one there (`open_editor` with a database). A `USE` typed in the tab moves the button with it (`QueryEditor::database`). The session keeps a tab's database where it is not the connection's own. + +### SQL files + +- File, Open file (Ctrl+O) takes `.sql`, `.psql` and `.pgsql` beside the database files, as macOS's Open File sends each file where its type belongs: a SQL file opens in a query tab of the front connection, or the one already open comes forward; with no connection connected it waits and opens in the next one to connect. Files dropped on an editor open the same way, and File, Open recent lists the last 10 opened or saved, kept in `session.json`. +- The tab is named for the file, with a dot while its text differs from the file. Ctrl+S saves it (Save as when it has none or the file is gone) and Ctrl+Shift+S saves as. The encoding is the file's: its byte order mark, else UTF-8, else Latin-1, as the macOS app reads a file without the Mac-only steps; a save writes it back the same way, through a file beside it then a move, and stops with the file untouched when the text holds a character the encoding cannot store. Save as writes UTF-8. +- Closing a tab with unsaved text asks Save, Don't Save or Cancel; Don't Save leaves the file as it was, and the text stays with the tab in the session either way, as macOS keeps a closed tab's SQL. A file another program changed shows a bar with Reload when the tab shows or the window is activated, a deleted one a bar with Save as, and a save over a change asks Overwrite, Reload or Cancel. A file tab's session keeps its text, the file's time and length as last read or saved, and whether the text was unsaved: a relaunch reads a clean tab's file as it is now, and keeps unsaved text, treating a file written while the app was closed as changed on disk. Unsaved text comes back after a forced end even with Reopen at startup off. + +### Key tab + +- A key-value engine's key opens a key tab from the tree or its menu, as a table opens a table tab: the key's type, its length (entries, or a string's bytes) and when it expires over its entries in a read-only grid, read a window at a time (`DatabaseSession::open_key`, 500 entries); Load More adds the next window to the same grid, and Refresh reads it again from the start. A string longer than one window says how much shows; a type the reader does not read names the engine's type and says so. Key tabs are left out of `session.json` as definition tabs are. + ### Settings -A page in the window, built from `SettingsCard` and `SettingsExpander`: Appearance (theme, with a link to Windows color settings), Startup (reopen the previous session), Editor (font size), Queries (row limit, results kept per run, query timeout), Pagination (default page size, count rows if estimate less than), About (version, documentation, report an issue, the data folder). A change applies at once; there is no Save ([App settings guidelines](https://learn.microsoft.com/en-us/windows/apps/design/app-settings/guidelines-for-app-settings)). +A page in the window, built from `SettingsCard` and `SettingsExpander`: Appearance (theme, with a link to Windows color settings), Startup (reopen the previous session), Editor (font size; font, the installed monospaced families, Cascadia Mono unless changed), Data grid (font, every installed family, Segoe UI unless changed; font size, 8 to 36; NULL display, up to 20 characters, NULL unless changed, as macOS), Queries (row limit, results kept per run, query timeout), Pagination (default page size, count rows if estimate less than), Query history (keep runs for 7, 30, 90, 180 days, a year or forever, 90 days unless changed; maximum runs 100 to 10,000 or unlimited, 10,000 unless changed, as macOS; Clear history, which asks first), About (version, documentation, report an issue, the data folder). Fonts and the NULL text reach open editors and grids at once (`DisplaySettings`); the history is pruned to the two limits as it opens and when either changes, pinned runs kept. A change applies at once; there is no Save ([App settings guidelines](https://learn.microsoft.com/en-us/windows/apps/design/app-settings/guidelines-for-app-settings)). ### Where things are kept diff --git a/windows/src/TablePro.App.Model/AppSettings.cs b/windows/src/TablePro.App.Model/AppSettings.cs index 5d7f2d10db..94f4aae328 100644 --- a/windows/src/TablePro.App.Model/AppSettings.cs +++ b/windows/src/TablePro.App.Model/AppSettings.cs @@ -30,12 +30,46 @@ public sealed record AppSettings // As macOS offers them; 0 keeps every result. public static IReadOnlyList ResultsKeptChoices { get; } = [0, 10, 20, 50, 100, 200, 500, 1_000]; + public const string DefaultNullDisplay = "NULL"; + + // macOS caps the NULL text at 20 characters. + public const int NullDisplayMaxLength = 20; + + public const double DefaultGridFontSize = 14; + + public const int DefaultHistoryRetentionDays = 90; + + public const int DefaultHistoryMaxEntries = 10_000; + + // As macOS offers them; 0 keeps every age. + public static IReadOnlyList HistoryRetentionChoices { get; } = [7, 30, 90, 180, 365, 0]; + + // As macOS offers them; 0 keeps as many as the store holds. + public static IReadOnlyList HistoryMaxEntriesChoices { get; } = [100, 500, 1_000, 5_000, 10_000, 0]; + public AppTheme Theme { get; set; } = AppTheme.System; public bool ReopenSession { get; set; } = true; public double EditorFontSize { get; set; } = 14; + // Null keeps the editor's own monospaced family. + public string? EditorFontFamily { get; set; } + + // Null keeps the grid's own family. + public string? GridFontFamily { get; set; } + + public double GridFontSize { get; set; } = DefaultGridFontSize; + + // What a grid shows in a NULL cell. + public string NullDisplay { get; set; } = DefaultNullDisplay; + + // Unpinned history older than this is dropped; 0 keeps every age. + public int HistoryRetentionDays { get; set; } = DefaultHistoryRetentionDays; + + // The newest unpinned runs the history keeps; 0 keeps as many as the store holds. + public int HistoryMaxEntries { get; set; } = DefaultHistoryMaxEntries; + public int RowLimit { get; set; } = DefaultRowLimit; // Rows a new table tab shows on each page; a tab can pick its own. @@ -54,6 +88,14 @@ public AppSettings Normalized() => this with { Theme = Enum.IsDefined(Theme) ? Theme : AppTheme.System, EditorFontSize = Math.Clamp(EditorFontSize, 8, 36), + EditorFontFamily = string.IsNullOrWhiteSpace(EditorFontFamily) ? null : EditorFontFamily.Trim(), + GridFontFamily = string.IsNullOrWhiteSpace(GridFontFamily) ? null : GridFontFamily.Trim(), + GridFontSize = double.IsFinite(GridFontSize) ? Math.Clamp(GridFontSize, 8, 36) : DefaultGridFontSize, + NullDisplay = string.IsNullOrEmpty(NullDisplay) + ? DefaultNullDisplay + : NullDisplay[..Math.Min(NullDisplay.Length, NullDisplayMaxLength)], + HistoryRetentionDays = Math.Max(0, HistoryRetentionDays), + HistoryMaxEntries = Math.Max(0, HistoryMaxEntries), RowLimit = Math.Clamp(RowLimit, 1, 1_000_000), PageSize = Math.Clamp(PageSize, 10, 100_000), QueryTimeoutSeconds = Math.Clamp(QueryTimeoutSeconds, 0, 86_400), diff --git a/windows/src/TablePro.App.Model/ConnectionLife.cs b/windows/src/TablePro.App.Model/ConnectionLife.cs index 94bcb16c15..acaca23fa8 100644 --- a/windows/src/TablePro.App.Model/ConnectionLife.cs +++ b/windows/src/TablePro.App.Model/ConnectionLife.cs @@ -24,8 +24,13 @@ private bool PrintMembers(System.Text.StringBuilder builder) public interface IConnector { // The core stores keep once it logs in, against the record it connected with, so an edit saved meanwhile wins. + // Database, in place of the saved one, opens the connection in another of the server's databases. Task ConnectSavedAsync( - Guid id, ConnectionSecrets secrets, ConnectionSecrets keep, CancellationToken cancellationToken); + Guid id, + string? database, + ConnectionSecrets secrets, + ConnectionSecrets keep, + CancellationToken cancellationToken); Task OpenFileAsync(string path, string? engineId, CancellationToken cancellationToken); } @@ -92,11 +97,20 @@ public ConnectionLife(SessionConnection origin, IConnectionView view, public TSession? Session => Share?.Session; + // The saved connection or the file, in whichever of its databases it is open. 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); + // The same connection open in the same database, so a tab of one runs on the other's session. + public bool IsSame(SessionConnection other) + { + ArgumentNullException.ThrowIfNull(other); + return Matches(other.ConnectionId, other.FilePath) + && string.Equals(other.Database, Origin.Database, StringComparison.Ordinal); + } + public void Rename(string name) => Origin = Origin with { Name = name }; public void SetEngine(string engineId) => Origin = Origin with { EngineId = engineId }; @@ -238,7 +252,7 @@ private async Task ConnectSavedAsync(Guid id, CancellationToken cancel { try { - return await _connector.ConnectSavedAsync(id, secrets, remembered, cancellationToken) + return await _connector.ConnectSavedAsync(id, Origin.Database, secrets, remembered, cancellationToken) .ConfigureAwait(true); } catch (TableProException exception) @@ -311,10 +325,11 @@ public CoreConnector(TableProCore core, ICredentialPrompter prompter) public Task ConnectSavedAsync( Guid id, + string? database, ConnectionSecrets secrets, ConnectionSecrets keep, CancellationToken cancellationToken) => - _core.ConnectAsync(id, secrets, _prompter, keep, cancellationToken); + _core.ConnectAsync(id, secrets, _prompter, keep, database, cancellationToken); public Task OpenFileAsync(string path, string? engineId, CancellationToken cancellationToken) => _core.OpenFileAsync(new FileOpenOptions(path, engineId), cancellationToken); diff --git a/windows/src/TablePro.App.Model/KeyTab.cs b/windows/src/TablePro.App.Model/KeyTab.cs new file mode 100644 index 0000000000..64ccc1d895 --- /dev/null +++ b/windows/src/TablePro.App.Model/KeyTab.cs @@ -0,0 +1,251 @@ +using TablePro.Interop; + +namespace TablePro.App.Model; + +// What a key tab shows; the view words the type, the length and the expiry. +public interface IKeyTabView +{ + // What is shown stays until the read ends. + void ShowReading(); + + // Read from the key's start, or again after it changed type; the set shown before is let go once this returns. + void ShowRows(ResultSet? rows); + + // The set shown already holds this window's rows. + void ShowWindow(KeyWindow window); + + // The grid lets go of its set before the tab disposes it. + void ReleaseRows(); + + void ShowMissing(); + + // The rows shown stay. + void ShowFailure(CoreError failure); + + void ShowStopped(); +} + +// One key's value through a reader of its own, so a test reads a fake. +public interface IKeyRead : IDisposable +{ + // Null when the key does not exist. Past the last window nothing is read and the last window comes back again. + Task ReadMoreAsync(CancellationToken cancellationToken); + + // The rows read so far, a new handle each call; null before the first window. + ResultSet? GetRows(); +} + +public sealed class CoreKeyRead(KeyReader reader) : IKeyRead +{ + public Task ReadMoreAsync(CancellationToken cancellationToken) => + reader.ReadMoreAsync(cancellationToken); + + public ResultSet? GetRows() => reader.GetRows(); + + public void Dispose() => reader.Dispose(); +} + +// A key-value engine's key, read a window at a time into one set that the grid shows while Load More adds to it. +public sealed class KeyTab : IWorkspaceTab +{ + private readonly ITabSession _session; + private readonly IKeyTabView _view; + private readonly Func _open; + private readonly TabWork _work = new(); + private IKeyRead? _reader; + + // The last window _reader read; null until its first, so the next window it reads binds its set. + private KeyWindow? _readerWindow; + private ResultSet? _rows; + private bool _bound; + private CancellationTokenSource? _stop; + private Task? _reading; + private Task? _closing; + + public KeyTab(ITabSession session, IKeyTabView view, string key, Func open) + { + ArgumentNullException.ThrowIfNull(session); + ArgumentNullException.ThrowIfNull(view); + ArgumentNullException.ThrowIfNull(key); + ArgumentNullException.ThrowIfNull(open); + _session = session; + _view = view; + _open = open; + Key = key; + } + + public event EventHandler? StateChanged; + + public string Key { get; } + + public string Title => Key; + + public TabKind Kind => TabKind.Key; + + public bool IsRunning { get; private set; } + + // The reads run on the session's pooled connections, which hold no transaction. + public TransactionState Transaction => TransactionState.Idle; + + public bool HasUnsavedChanges => false; + + // The window shown last: a failed or stopped read keeps it, a key found missing clears it. + public KeyWindow? Window { get; private set; } + + public bool IsMissing { get; private set; } + + // A failed Load More can be tried again; after a failed Refresh only Refresh reads. + public bool CanLoadMore => !IsRunning && !_work.IsClosed && _readerWindow is { HasMore: true }; + + // Null when the tab names no key. + public static string? KeyOf(SessionTab tab) + { + ArgumentNullException.ThrowIfNull(tab); + return tab is { Kind: TabKind.Key, Table: { Length: > 0 } key } ? key : null; + } + + public Task ConfirmCloseAsync(bool offerSave) => Task.FromResult(true); + + // A key tab holds nothing an end without a close would lose. + public SessionTab WithPendingWork(SessionTab snapshot) => snapshot; + + public SessionTab Snapshot() => new() { Kind = TabKind.Key, Title = Key, Table = Key }; + + // Also Refresh, from a new reader; the rows shown stay until it lands, and a read in flight is shared. + public Task LoadAsync() => ReadAsync(fromStart: true); + + public Task LoadMoreAsync() => + _reading is not null || _readerWindow is { HasMore: true } ? ReadAsync(fromStart: false) : Task.CompletedTask; + + public void Stop() => _stop?.Cancel(); + + public Task CloseAsync() => _closing ??= CloseOnceAsync(); + + // The read in flight stops and ends before its reader, the rows and the session are let go. + private async Task CloseOnceAsync() + { + await _work.CloseAsync().ConfigureAwait(true); + ReleaseRows(); + _reader?.Dispose(); + _reader = null; + _readerWindow = null; + Window = null; + await _session.ReleaseAsync().ConfigureAwait(true); + } + + private async Task ReadAsync(bool fromStart) + { + if (_work.IsClosed) + { + return; + } + + _reading ??= _work.RunAsync(cancellationToken => ReadWindowAsync(fromStart, cancellationToken)); + var reading = _reading; + try + { + await reading.ConfigureAwait(true); + } + finally + { + if (ReferenceEquals(_reading, reading)) + { + _reading = null; + } + } + } + + private async Task ReadWindowAsync(bool fromStart, CancellationToken cancellationToken) + { + if (fromStart) + { + // The grid reads its own handle of the set, which outlives the reader it came from. + var last = _reader; + _reader = _open(); + _readerWindow = null; + last?.Dispose(); + } + + if (_reader is not { } reader) + { + return; + } + + using var stop = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + _stop = stop; + SetRunning(true); + _view.ShowReading(); + try + { + var window = await reader.ReadMoreAsync(stop.Token).ConfigureAwait(true); + if (_work.IsClosed) + { + return; + } + + if (window is null) + { + ShowMissing(); + return; + } + + var rebind = _readerWindow is null || window.Restarted; + _readerWindow = window; + Window = window; + IsMissing = false; + if (rebind) + { + var last = _rows; + _rows = reader.GetRows(); + _view.ShowRows(_rows); + _bound = true; + last?.Dispose(); + } + + _view.ShowWindow(window); + } + catch (TableProException exception) + { + if (!_work.IsClosed) + { + _view.ShowFailure(exception.Error); + } + } + catch (OperationCanceledException) when (!_work.IsClosed && stop.IsCancellationRequested) + { + _view.ShowStopped(); + } + finally + { + _stop = null; + SetRunning(false); + } + } + + private void ShowMissing() + { + _readerWindow = null; + Window = null; + IsMissing = true; + ReleaseRows(); + _view.ShowMissing(); + } + + private void ReleaseRows() + { + if (_bound) + { + _view.ReleaseRows(); + _bound = false; + } + + _rows?.Dispose(); + _rows = null; + } + + private void SetRunning(bool running) + { + IsRunning = running; + StateChanged?.Invoke(this, EventArgs.Empty); + } +} diff --git a/windows/src/TablePro.App.Model/QueryTab.cs b/windows/src/TablePro.App.Model/QueryTab.cs index d91f535cb4..4f744e7d6b 100644 --- a/windows/src/TablePro.App.Model/QueryTab.cs +++ b/windows/src/TablePro.App.Model/QueryTab.cs @@ -43,6 +43,49 @@ public interface IQueryTabView void CloseEditor(); } +public enum DiskChange +{ + None, + Changed, + Gone, +} + +public enum SaveOverChange +{ + Overwrite, + Reload, + Cancel, +} + +// What a query tab with a .sql file behind it shows and asks, which its view words. +public interface IQueryFileView +{ + // The editor's text becomes the file's, as Reload asks. + void ReplaceText(string text); + + // Null when the picker was dismissed. + Task PickSavePathAsync(string suggestedName, string? folder); + + // Without Save when offerSave is off. + Task AskSaveBeforeCloseAsync(string tab, bool offerSave); + + Task AskSaveOverChangeAsync(string path); + + // None takes the bar away. + void ShowDiskChange(DiskChange change); + + // A SqlFileEncodingException names the character the file's encoding cannot store. + Task ShowSaveFailedAsync(string path, Exception failure); + + Task ShowReloadFailedAsync(string path, Exception failure); +} + +// The switcher's lists, user databases before the engine's own. +public sealed record DatabaseChoices( + IReadOnlyList UserDatabases, + IReadOnlyList SystemDatabases, + string? Current); + // One editor connection for the tab, so a transaction holds from one run to the next. public sealed class QueryTab : IWorkspaceTab { @@ -52,6 +95,7 @@ public sealed class QueryTab : IWorkspaceTab private readonly DataModel _dataModel; private readonly Func _settings; private readonly IHistoryRecorder? _history; + private readonly IQueryFileView? _files; private readonly TabWork _work = new(); private ITabEditor? _editor; private Task? _closing; @@ -60,7 +104,20 @@ public sealed class QueryTab : IWorkspaceTab private GridSort _sort = GridSort.None; private bool _sorting; private bool _confirming; - + private bool _switching; + private string? _listedDefault; + private SqlFileFormat _format = SqlFileFormat.Utf8; + private SqlFileStamp? _stamp; + private string? _savedText; + private Task? _saving; + + // A restored file tab whose file is still being read, which no check or save compares with yet. + private bool _awaitingFile; + private bool _checking; + private (DiskChange Change, SqlFileStamp? Stamp)? _shownChange; + private (DiskChange Change, SqlFileStamp? Stamp)? _dismissedChange; + + // onDisk is the file as the view read it, null when it could not be; the view's text may differ from it. public QueryTab( string title, ITabSession session, @@ -69,7 +126,12 @@ public QueryTab( DataModel dataModel, Func settings, IHistoryRecorder? history = null, - string? database = null) + string? database = null, + IQueryFileView? files = null, + string? filePath = null, + SqlFileRead? onDisk = null, + bool baselineUnknown = false, + bool restoring = false) { ArgumentNullException.ThrowIfNull(title); ArgumentNullException.ThrowIfNull(session); @@ -83,43 +145,106 @@ public QueryTab( _dataModel = dataModel; _settings = settings; _history = history; - Database = string.IsNullOrEmpty(database) ? null : database; + _files = files; + Database = Kept(database); + if (files is not null && !string.IsNullOrEmpty(filePath)) + { + FilePath = filePath; + Title = Path.GetFileName(filePath); + if (onDisk is not null) + { + _format = onDisk.Format; + _stamp = onDisk.Stamp; + _savedText = baselineUnknown ? null : onDisk.Text; + } + + IsDirty = TextDiffers(); + _awaitingFile = restoring && onDisk is null; + } } public event EventHandler? StateChanged; - public string Title { get; } + // The file the tab wrote, for File > Open Recent. + public event EventHandler? FileSaved; + + // The file's name once the tab has one. + public string Title { get; private set; } public TabKind Kind => TabKind.Query; - // Each editor connection the tab opens moves here before its first run. - public string? Database { get; } + // Where each editor connection the tab opens runs; null for the connection's own. + public string? Database { get; private set; } + + // The tab's own, else the connection's, else the one the server listed as the login's. + public string? ShownDatabase => Database ?? _session.Database ?? _listedDefault; + + public bool ShowsDatabases => _session.Layout != DatabaseLayout.OneDatabase; + + // As the Linux app waits: a move would part a run or a transaction from the database it began in. + public bool CanPickDatabase => + !IsRunning && !_confirming && !_switching && !_work.IsClosed && !WorkspaceNotices.Holds(Transaction); public bool IsRunning { get; private set; } public TransactionState Transaction { get; private set; } - public bool HasUnsavedChanges => false; + public string? FilePath { get; private set; } + + // The text differs from the file as last read or saved; set as the view reports edits. + public bool IsDirty { get; private set; } + + // Read afresh, since the view reports edits a moment later than they land; a file still being written counts too. + public bool HasUnsavedChanges => (FilePath is not null && TextDiffers()) || _saving is { IsCompleted: false }; // The typed SQL whose results the tab shows, which a result share sends; null after Commit or Roll back. public string? LastStatement => _statement; - // 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); + // A scratch tab's text is kept in the session, so only a file tab's unsaved text is asked about. + public async Task ConfirmCloseAsync(bool offerSave) + { + if (_files is null || !HasUnsavedChanges) + { + return true; + } - public SessionTab Snapshot() => - new() { Kind = TabKind.Query, Title = Title, Sql = _view.WholeText, Database = Database }; + // A read-only connection takes away Save for its table edits; a file is written here, not to the database. + var answer = await _files.AskSaveBeforeCloseAsync(Title, offerSave: true).ConfigureAwait(true); + return answer switch + { + // Text typed while the file was written is still unsaved, so the tab stays. + SaveBeforeClose.Save => await SaveAsync().ConfigureAwait(true) && !HasUnsavedChanges, + SaveBeforeClose.DontSave => true, + _ => false, + }; + } + + // Don't Save leaves the file as it was; the text stays with the tab either way, as macOS keeps a closed tab's SQL. + public SessionTab Snapshot() => new() + { + Kind = TabKind.Query, + Title = Title, + Sql = _view.WholeText, + Database = Database, + FilePath = FilePath, + FileStamp = FilePath is null ? null : _stamp, + FileUnsaved = FilePath is not null && TextDiffers(), + }; // The server rolls the transaction back once the app ends, so a relaunch can say so. public SessionTab WithPendingWork(SessionTab snapshot) { ArgumentNullException.ThrowIfNull(snapshot); - return WorkspaceNotices.Holds(Transaction) ? snapshot with { HeldTransaction = true } : snapshot; + return snapshot with + { + HeldTransaction = snapshot.HeldTransaction || WorkspaceNotices.Holds(Transaction), + RecoverFile = snapshot.FileUnsaved, + }; } public async Task RunAsync() { - if (IsRunning || _confirming || _work.IsClosed) + if (IsRunning || _confirming || _switching || _work.IsClosed) { return; } @@ -136,7 +261,7 @@ public async Task RunAsync() // 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) + if (IsRunning || _confirming || _switching || _work.IsClosed) { return; } @@ -168,7 +293,7 @@ public async Task RollBackAsync() // 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) + if (IsRunning || _sorting || _switching) { _results.Sort = _sort; return; @@ -192,6 +317,217 @@ public async Task SortAsync(GridSort sort) // The grid shows another set of the run, unsorted. public void ResultPicked() => _sort = GridSort.None; + // Read each time the switcher opens; null when the server refused, which the results pane says. + public async Task GetDatabaseChoicesAsync() + { + IReadOnlyList? listed = null; + await _work.RunAsync(async token => + { + try + { + listed = await _session.GetDatabasesAsync(token).ConfigureAwait(true); + } + catch (TableProException exception) + { + if (!_work.IsClosed) + { + _results.ShowError(exception.Error); + } + } + }).ConfigureAwait(true); + if (listed is null || _work.IsClosed) + { + return null; + } + + var listedDefault = listed.FirstOrDefault(entry => entry.IsDefault)?.Name; + if (listedDefault != _listedDefault) + { + _listedDefault = listedDefault; + StateChanged?.Invoke(this, EventArgs.Empty); + } + + return new DatabaseChoices( + [.. listed.Where(entry => !entry.IsSystem).Select(entry => entry.Name)], + [.. listed.Where(entry => entry.IsSystem).Select(entry => entry.Name)], + ShownDatabase); + } + + // An open editor keeps its connection, and with it its temporary tables and settings. + public async Task PickDatabaseAsync(string database) + { + ArgumentException.ThrowIfNullOrEmpty(database); + if (!CanPickDatabase || database == ShownDatabase) + { + return; + } + + _switching = true; + StateChanged?.Invoke(this, EventArgs.Empty); + try + { + await _work.RunAsync(token => MoveEditorAsync(database, token)).ConfigureAwait(true); + } + finally + { + _switching = false; + StateChanged?.Invoke(this, EventArgs.Empty); + } + } + + // The view reports an edit; a file tab works out whether its text still matches the file. + public void TextEdited() => UpdateDirty(); + + // To its file; Save As when it has none or the file is gone. + public Task SaveAsync() => Saving(saveAs: false); + + public Task SaveAsAsync() => Saving(saveAs: true); + + // A bar the user closed stays closed until the file changes again. + // Every file operation is tab work, so a close waits for it and nothing it finds reaches a closed tab. + public Task CheckDiskAsync() => _work.RunAsync(_ => CheckDiskOnceAsync()); + + private async Task CheckDiskOnceAsync() + { + if (_files is null || FilePath is not { } path || _checking || _awaitingFile || _work.IsClosed) + { + return; + } + + _checking = true; + try + { + var seen = SqlFile.Stamp(path); + var change = DiskChange.None; + if (seen is null) + { + change = DiskChange.Gone; + } + else if (seen != _stamp && await ChangedOnDiskAsync(path).ConfigureAwait(true)) + { + change = DiskChange.Changed; + } + + if (path != FilePath || _work.IsClosed) + { + return; + } + + var shown = (change, seen); + if (change != DiskChange.None && shown == _dismissedChange) + { + return; + } + + _shownChange = shown; + _files.ShowDiskChange(change); + } + finally + { + _checking = false; + } + } + + public void DiskChangeDismissed() => _dismissedChange = _shownChange; + + // A restored file tab reads its file once it is in the strip, off the UI thread: a clean one takes the file's text + // unless it was edited meanwhile, and the file becomes what a check and a save compare with. + public Task LoadRestoredFileAsync(SqlFileStamp? savedStamp, bool unsaved) => + _work.RunAsync(_ => LoadRestoredFileOnceAsync(savedStamp, unsaved)); + + private async Task LoadRestoredFileOnceAsync(SqlFileStamp? savedStamp, bool unsaved) + { + if (_files is null || FilePath is not { } path || !_awaitingFile) + { + return; + } + + var shown = _view.WholeText; + SqlFileOpening opening; + try + { + opening = await Task.Run( + () => SqlFileOpening.Restored(shown, savedStamp, unsaved, () => SqlFile.TryRead(path))) + .ConfigureAwait(true); + } + finally + { + _awaitingFile = false; + } + + if (_work.IsClosed || path != FilePath) + { + return; + } + + if (opening.Text != shown && _view.WholeText == shown) + { + _files.ReplaceText(opening.Text); + } + + if (opening.Baseline is { } baseline) + { + _format = baseline.Format; + _stamp = baseline.Stamp; + _savedText = opening.BaselineUnknown ? null : baseline.Text; + } + + IsDirty = TextDiffers(); + StateChanged?.Invoke(this, EventArgs.Empty); + // A check asked for while the file was read found nothing to compare with, so it runs now. + await CheckDiskOnceAsync().ConfigureAwait(true); + } + + // The tab's text becomes the file's, dropping what was typed since. + public async Task ReloadAsync() + { + var reloaded = false; + await _work.RunAsync(async _ => reloaded = await ReloadOnceAsync().ConfigureAwait(true)).ConfigureAwait(true); + return reloaded; + } + + private async Task ReloadOnceAsync() + { + if (_files is null || FilePath is not { } path) + { + return false; + } + + var shown = _view.WholeText; + try + { + var read = await Task.Run(() => SqlFile.Read(path)).ConfigureAwait(true); + // Text typed while the file was read is not thrown away for it. + if (path != FilePath || _work.IsClosed || _view.WholeText != shown) + { + return false; + } + + _files.ReplaceText(read.Text); + Adopt(read.Format, read.Stamp, read.Text); + return true; + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + if (_work.IsClosed) + { + return false; + } + + if (SqlFile.Stamp(path) is null) + { + _shownChange = (DiskChange.Gone, null); + _files.ShowDiskChange(DiskChange.Gone); + } + else + { + await _files.ShowReloadFailedAsync(path, exception).ConfigureAwait(true); + } + + return false; + } + } + 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. @@ -275,22 +611,8 @@ private async Task RunOnEditorAsync(string sql, bool record, CancellationToken c // An editor that opens as the tab closes stays in _editor, which the close disposes. if (_editor is null) { - var opened = await _session.OpenEditorAsync(cancellationToken).ConfigureAwait(true); - _editor = opened; - if (Database is { } database && !_work.IsClosed) - { - try - { - await opened.UseDatabaseAsync(database, cancellationToken).ConfigureAwait(true); - } - catch (TableProException) - { - // Run elsewhere, the text would make its object in the wrong database, so the editor goes. - _editor = null; - await opened.DisposeAsync().ConfigureAwait(true); - throw; - } - } + // Run elsewhere, the text would make its objects in the wrong database, so the core refuses the open. + _editor = await _session.OpenEditorAsync(Database, cancellationToken).ConfigureAwait(true); } if (_work.IsClosed) @@ -379,6 +701,12 @@ private async Task AfterRunAsync() return; } + // A typed USE moved the editor, so the tab runs there from now on. + if (_editor?.Database is { } now) + { + SetDatabase(now); + } + var state = _results.Transaction == TransactionState.Unknown ? Transaction : _results.Transaction; ShowTransaction(WorkspaceNotices.Holds(state) ? state : TransactionState.Idle); } @@ -431,6 +759,203 @@ private void SetRunning(bool running) StateChanged?.Invoke(this, EventArgs.Empty); } + private string? Kept(string? database) => + string.IsNullOrEmpty(database) || database == _session.Database ? null : database; + + // A switch the user picked leaves the rows shown from the database before, so a sort orders them where they are; + // a database a run itself moved to is where its own rows came from. + private void SetDatabase(string? database, bool switched = false) + { + var kept = Kept(database); + if (kept != Database) + { + Database = kept; + if (switched) + { + _statement = null; + } + + StateChanged?.Invoke(this, EventArgs.Empty); + } + } + + private async Task MoveEditorAsync(string database, CancellationToken cancellationToken) + { + if (await ReleaseLostEditorAsync().ConfigureAwait(true) || _editor is not { } editor) + { + SetDatabase(database, switched: true); + return; + } + + try + { + await editor.UseDatabaseAsync(database, cancellationToken).ConfigureAwait(true); + SetDatabase(editor.Database ?? database, switched: true); + } + catch (TableProException exception) when (IsUnsupported(exception.Error)) + { + // The engine binds a connection to its database, so the next run opens one there. + _editor = null; + await editor.DisposeAsync().ConfigureAwait(true); + SetDatabase(database, switched: true); + } + catch (TableProException exception) + { + if (!_work.IsClosed) + { + _results.ShowError(exception.Error); + } + } + } + + private static bool IsUnsupported(CoreError error) => + error.Code == "driver.unsupported" || error.Codes.Contains("driver.unsupported"); + + // A save already writing ends first, and text typed since is saved after it, so a Save never joins an older one. + private async Task Saving(bool saveAs) + { + var waited = false; + while (_saving is { IsCompleted: false } pending) + { + waited = true; + await pending.ConfigureAwait(true); + } + + if (waited && !saveAs && FilePath is not null && !TextDiffers()) + { + return true; + } + + var saving = SaveWithinWorkAsync(saveAs); + _saving = saving; + return await saving.ConfigureAwait(true); + } + + // Inside the tab's work, so a close waits for the file to be written before the tab goes. + private async Task SaveWithinWorkAsync(bool saveAs) + { + var saved = false; + await _work.RunAsync(async _ => saved = await SaveOnceAsync(saveAs).ConfigureAwait(true)).ConfigureAwait(true); + return saved; + } + + private async Task SaveOnceAsync(bool saveAs) + { + if (_files is null) + { + return false; + } + + if (saveAs || FilePath is not { } path || SqlFile.Stamp(path) is not { } seen) + { + return await SaveAsNewAsync(_files).ConfigureAwait(true); + } + + if (seen != _stamp && await ChangedOnDiskAsync(path).ConfigureAwait(true)) + { + switch (await _files.AskSaveOverChangeAsync(path).ConfigureAwait(true)) + { + case SaveOverChange.Overwrite: + break; + case SaveOverChange.Reload: + await ReloadAsync().ConfigureAwait(true); + return false; + default: + return false; + } + } + + return await WriteAsync(_files, path, _format).ConfigureAwait(true); + } + + // Save As writes UTF-8, and the tab keeps saving the new file that way. + private async Task SaveAsNewAsync(IQueryFileView files) + { + var folder = FilePath is { } path ? Path.GetDirectoryName(path) : null; + var picked = await files.PickSavePathAsync(SuggestedFileName(), folder).ConfigureAwait(true); + return picked is not null && await WriteAsync(files, picked, SqlFileFormat.Utf8).ConfigureAwait(true); + } + + private string SuggestedFileName() + { + if (FilePath is { } path) + { + return Path.GetFileName(path); + } + + var invalid = Path.GetInvalidFileNameChars(); + return string.Concat(Title.Select(character => invalid.Contains(character) ? '_' : character)) + ".sql"; + } + + private async Task WriteAsync(IQueryFileView files, string path, SqlFileFormat format) + { + var text = _view.WholeText; + try + { + var stamp = await Task.Run(() => SqlFile.Write(path, text, format)).ConfigureAwait(true); + FilePath = path; + Title = Path.GetFileName(path); + Adopt(format, stamp, text); + FileSaved?.Invoke(this, path); + return true; + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + await files.ShowSaveFailedAsync(path, exception).ConfigureAwait(true); + return false; + } + } + + // The file as read or written now is the one the tab's text is measured against. + private void Adopt(SqlFileFormat format, SqlFileStamp stamp, string text) + { + _format = format; + _stamp = stamp; + _savedText = text; + _shownChange = null; + _dismissedChange = null; + _files?.ShowDiskChange(DiskChange.None); + IsDirty = TextDiffers(); + StateChanged?.Invoke(this, EventArgs.Empty); + } + + // A newer time alone, as a checkout that wrote the same text leaves, is no change. + private async Task ChangedOnDiskAsync(string path) + { + try + { + var read = await Task.Run(() => SqlFile.Read(path)).ConfigureAwait(true); + if (read.Text != _savedText) + { + return true; + } + + if (path == FilePath) + { + _format = read.Format; + _stamp = read.Stamp; + } + + return false; + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + return true; + } + } + + private bool TextDiffers() => _view.WholeText != _savedText; + + private void UpdateDirty() + { + var dirty = FilePath is not null && TextDiffers(); + if (dirty != IsDirty) + { + IsDirty = dirty; + StateChanged?.Invoke(this, EventArgs.Empty); + } + } + private async Task SortHeldRowsAsync(GridSort sort) { _sorting = true; diff --git a/windows/src/TablePro.App.Model/RecentFiles.cs b/windows/src/TablePro.App.Model/RecentFiles.cs new file mode 100644 index 0000000000..78b6e718a9 --- /dev/null +++ b/windows/src/TablePro.App.Model/RecentFiles.cs @@ -0,0 +1,50 @@ +namespace TablePro.App.Model; + +// File > Open Recent, newest first; one entry per path whatever its case, since Windows paths ignore case. +public sealed class RecentFiles +{ + public const int Limit = 10; + + private readonly List _paths = []; + + public RecentFiles(IEnumerable? paths = null) + { + foreach (var path in paths ?? []) + { + if (_paths.Count < Limit && !string.IsNullOrWhiteSpace(path) && !_paths.Exists(kept => Same(kept, path))) + { + _paths.Add(path); + } + } + } + + // A copy, so a session that keeps it does not change with the list. + public IReadOnlyList Paths => [.. _paths]; + + public void Add(string path) + { + ArgumentException.ThrowIfNullOrWhiteSpace(path); + Remove(path); + _paths.Insert(0, path); + if (_paths.Count > Limit) + { + _paths.RemoveRange(Limit, _paths.Count - Limit); + } + } + + public bool Remove(string path) + { + ArgumentNullException.ThrowIfNull(path); + return _paths.RemoveAll(kept => Same(kept, path)) > 0; + } + + public void Clear() => _paths.Clear(); + + public bool RemoveMissing(Func? exists = null) + { + var present = exists ?? File.Exists; + return _paths.RemoveAll(path => !present(path)) > 0; + } + + private static bool Same(string kept, string path) => string.Equals(kept, path, StringComparison.OrdinalIgnoreCase); +} diff --git a/windows/src/TablePro.App.Model/SessionState.cs b/windows/src/TablePro.App.Model/SessionState.cs index 2f36601479..ec537d4473 100644 --- a/windows/src/TablePro.App.Model/SessionState.cs +++ b/windows/src/TablePro.App.Model/SessionState.cs @@ -10,6 +10,9 @@ public enum TabKind // A function, procedure, trigger or sequence, shown as its definition. Definition, + + // A key-value engine's key, named in Table. + Key, } public sealed record SessionTab @@ -37,9 +40,25 @@ public sealed record SessionTab public SavedFilter? Filter { get; set; } - // The database a query tab opened from a definition runs in, where the definition names none. + // The database a query tab runs in, where it is not the connection's own. public string? Database { get; set; } + // The .sql file a query tab was opened from or saved to; Sql holds its text as the tab last had it. + public string? FilePath { get; set; } + + // The file as the tab last read or saved it, which a relaunch compares with the file then. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public SqlFileStamp? FileStamp { get; set; } + + // Sql differs from the file, so a relaunch keeps it instead of reading the file again. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)] + public bool FileUnsaved { get; set; } + + // Set only by the session's own writes, so unsaved file text comes back after an end without a close, but a close + // that asked about it follows Reopen at startup. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)] + public bool RecoverFile { get; set; } + // A table tab's pending changes by key, which the session's writes keep until a close has asked about them. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public SavedEdits? Edits { get; set; } @@ -50,7 +69,7 @@ public sealed record SessionTab // What the app ended holding without a close, which a launch brings back even with Reopen at startup off. [JsonIgnore] - public bool HasRecoveredWork => Edits is { Changes: > 0 } || HeldTransaction; + public bool HasRecoveredWork => Edits is { Changes: > 0 } || HeldTransaction || RecoverFile; // A name this build does not define, as from a later build, reads as the fallback. public ObjectKind ObjectKindOr(ObjectKind fallback) => @@ -166,6 +185,12 @@ public sealed record SessionConnection public string EngineId { get; set; } = string.Empty; + // Another of the server's databases the saved connection was opened in, in place of its own. + public string? Database { get; set; } + + // Where the server's databases are the catalog's schemas: the one new query tabs run in. + public string? DefaultDatabase { get; set; } + public IReadOnlyList Tabs { get; set; } = []; public int SelectedTab { get; set; } @@ -212,6 +237,9 @@ public sealed record SessionState public IReadOnlyList TabWindows { get; set; } = []; + // The .sql files opened or saved last, newest first (RecentFiles). + public IReadOnlyList RecentFiles { get; set; } = []; + public static SessionState Empty { get; } = new(); private static WindowPlacement? Usable(WindowPlacement? placement) => placement is { IsUsable: true } ? placement : null; @@ -230,6 +258,7 @@ public SessionState Restorable() TabWindows = [.. TabWindows .Where(window => window.Connection is { IsRestorable: true, Tabs.Count: > 0 }) .Select(window => window with { Placement = Usable(window.Placement) })], + RecentFiles = [.. (RecentFiles ?? []).Where(path => !string.IsNullOrWhiteSpace(path))], }; } diff --git a/windows/src/TablePro.App.Model/SessionTabs.cs b/windows/src/TablePro.App.Model/SessionTabs.cs index 189e76a58d..8e83c47766 100644 --- a/windows/src/TablePro.App.Model/SessionTabs.cs +++ b/windows/src/TablePro.App.Model/SessionTabs.cs @@ -2,7 +2,7 @@ namespace TablePro.App.Model; public static class SessionTabs { - // Definition tabs are left out: an older build reads an unknown TabKind as a broken file and loses the session. + // Definition and key tabs are left out: an older build reads an unknown TabKind as a broken file and loses the session. public static (IReadOnlyList Tabs, int Selected) Persisted( IReadOnlyList tabs, int selected) @@ -12,7 +12,7 @@ public static (IReadOnlyList Tabs, int Selected) Persisted( var keptSelected = 0; for (var index = 0; index < tabs.Count; index++) { - if (tabs[index].Kind == TabKind.Definition) + if (tabs[index].Kind is TabKind.Definition or TabKind.Key) { continue; } diff --git a/windows/src/TablePro.App.Model/SqlFile.cs b/windows/src/TablePro.App.Model/SqlFile.cs new file mode 100644 index 0000000000..e1227305d6 --- /dev/null +++ b/windows/src/TablePro.App.Model/SqlFile.cs @@ -0,0 +1,275 @@ +using System.Security.AccessControl; +using System.Text; + +namespace TablePro.App.Model; + +public enum SqlFileEncoding +{ + Utf8, + Utf16LittleEndian, + Utf16BigEndian, + Utf32LittleEndian, + Utf32BigEndian, + Latin1, +} + +// How a file's text was stored, so a save writes it back the same way. +public sealed record SqlFileFormat(SqlFileEncoding Encoding, bool ByteOrderMark) +{ + // What Save As writes. + public static SqlFileFormat Utf8 { get; } = new(SqlFileEncoding.Utf8, ByteOrderMark: false); +} + +// The file as it was read or written last; a write elsewhere, or an older copy restored over it, changes it. +public readonly record struct SqlFileStamp(DateTime LastWriteUtc, long Length); + +public sealed record SqlFileRead(string Text, SqlFileFormat Format, SqlFileStamp Stamp); + +// What a file tab opens with: its text, the file as last read or saved, and whether that read's text is unknown. +public sealed record SqlFileOpening(string Text, SqlFileRead? Baseline, bool BaselineUnknown) +{ + // A tab saved clean shows the file as it is now. One with unsaved text keeps it; a file written while the app was + // closed then has a baseline whose text is unknown, so the tab reads as changed on disk and a save asks first. + public static SqlFileOpening Restored( + string sessionText, + SqlFileStamp? savedStamp, + bool unsaved, + Func read) + { + ArgumentNullException.ThrowIfNull(sessionText); + ArgumentNullException.ThrowIfNull(read); + if (read() is not { } disk) + { + return new(sessionText, null, false); + } + + if (!unsaved) + { + return new(disk.Text, disk, false); + } + + // With no stamp kept, as when the file was gone at the last launch, what is there now is not what was saved. + return savedStamp is { } stamp && stamp == disk.Stamp + ? new(sessionText, disk, false) + : new(sessionText, disk with { Stamp = savedStamp ?? default }, true); + } +} + +// The text holds a character the file's encoding cannot store, so the file was left as it was. +public sealed class SqlFileEncodingException : IOException +{ + public SqlFileEncodingException(string filePath, SqlFileEncoding encoding, string character, Exception inner) + : base($"{filePath} cannot store {character} in {encoding}.", inner) + { + FilePath = filePath; + FileEncoding = encoding; + Character = character; + } + + public string FilePath { get; } + + public SqlFileEncoding FileEncoding { get; } + + public string Character { get; } +} + +// The encoding comes from the byte order mark, else strict UTF-8, else Latin-1, which takes any bytes. +public static class SqlFile +{ + private static readonly UTF8Encoding StrictUtf8 = new(false, throwOnInvalidBytes: true); + + // UTF-32 LE before UTF-16 LE, since its mark starts with UTF-16 LE's. + private static readonly SqlFileEncoding[] MarkOrder = + [ + SqlFileEncoding.Utf32LittleEndian, + SqlFileEncoding.Utf32BigEndian, + SqlFileEncoding.Utf8, + SqlFileEncoding.Utf16LittleEndian, + SqlFileEncoding.Utf16BigEndian, + ]; + + public static SqlFileRead Read(string path) + { + ArgumentException.ThrowIfNullOrEmpty(path); + // Taken before the bytes, so a write in between reads as a change later rather than going unseen. + var stamp = Stamp(path) ?? throw new FileNotFoundException(null, path); + var (text, format) = Decode(File.ReadAllBytes(path)); + return new SqlFileRead(text, format, stamp); + } + + public static (string Text, SqlFileFormat Format) Decode(ReadOnlySpan bytes) + { + foreach (var encoding in MarkOrder) + { + var mark = Mark(encoding); + if (bytes.StartsWith(mark)) + { + return (ReadingEncoding(encoding).GetString(bytes[mark.Length..]), new SqlFileFormat(encoding, true)); + } + } + + try + { + return (StrictUtf8.GetString(bytes), SqlFileFormat.Utf8); + } + catch (DecoderFallbackException) + { + return (Encoding.Latin1.GetString(bytes), new SqlFileFormat(SqlFileEncoding.Latin1, false)); + } + } + + // Written beside the file, then moved over it, so a failed write leaves the old file whole. + public static SqlFileStamp Write(string path, string text, SqlFileFormat format) + { + ArgumentException.ThrowIfNullOrEmpty(path); + ArgumentNullException.ThrowIfNull(text); + ArgumentNullException.ThrowIfNull(format); + byte[] body; + try + { + body = WritingEncoding(format.Encoding).GetBytes(text); + } + catch (EncoderFallbackException exception) + { + throw new SqlFileEncodingException(path, format.Encoding, Unstorable(exception), exception); + } + + var full = Path.GetFullPath(path); + var temporary = Path.Combine( + Path.GetDirectoryName(full) ?? string.Empty, + $".{Path.GetFileName(full)}.{Path.GetRandomFileName()}.tmp"); + var moved = false; + try + { + using (var stream = CreateBeside(temporary, full)) + { + if (format.ByteOrderMark) + { + stream.Write(Mark(format.Encoding)); + } + + stream.Write(body); + // On disk before the move is, so a power cut after it cannot leave a file of zeros. + stream.Flush(flushToDisk: true); + } + + // Replace keeps the file's own attributes and access list, which a move would swap for the folder's. + if (File.Exists(full)) + { + File.Replace(temporary, full, destinationBackupFileName: null, ignoreMetadataErrors: false); + } + else + { + File.Move(temporary, full); + } + + moved = true; + } + finally + { + if (!moved) + { + TryDelete(temporary); + } + } + + return Stamp(full) ?? throw new FileNotFoundException(null, full); + } + + // On Windows the new bytes take the access list of the file they replace from the first write, not the folder's. + private static FileStream CreateBeside(string temporary, string destination) + { + if (OperatingSystem.IsWindows() && File.Exists(destination)) + { + FileSecurity? security = null; + try + { + security = new FileInfo(destination).GetAccessControl(AccessControlSections.Access); + } + catch (Exception exception) when (exception is UnauthorizedAccessException or IOException) + { + // The access list cannot be read; File.Replace still carries it over once the write is done. + } + + if (security is not null) + { + return new FileInfo(temporary).Create( + FileMode.CreateNew, FileSystemRights.Write, FileShare.None, 4096, FileOptions.None, security); + } + } + + return new FileStream(temporary, FileMode.CreateNew, FileAccess.Write, FileShare.None); + } + + // Null when the file is gone or cannot be read. + public static SqlFileRead? TryRead(string path) + { + try + { + return Read(path); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + return null; + } + } + + // Null when the file is gone. + public static SqlFileStamp? Stamp(string path) + { + ArgumentException.ThrowIfNullOrEmpty(path); + var info = new FileInfo(path); + return info.Exists ? new SqlFileStamp(info.LastWriteTimeUtc, info.Length) : null; + } + + private static byte[] Mark(SqlFileEncoding encoding) => encoding switch + { + SqlFileEncoding.Utf8 => [0xEF, 0xBB, 0xBF], + SqlFileEncoding.Utf16LittleEndian => [0xFF, 0xFE], + SqlFileEncoding.Utf16BigEndian => [0xFE, 0xFF], + SqlFileEncoding.Utf32LittleEndian => [0xFF, 0xFE, 0x00, 0x00], + SqlFileEncoding.Utf32BigEndian => [0x00, 0x00, 0xFE, 0xFF], + _ => [], + }; + + private static Encoding ReadingEncoding(SqlFileEncoding encoding) => encoding switch + { + SqlFileEncoding.Utf16LittleEndian => new UnicodeEncoding(bigEndian: false, byteOrderMark: false), + SqlFileEncoding.Utf16BigEndian => new UnicodeEncoding(bigEndian: true, byteOrderMark: false), + SqlFileEncoding.Utf32LittleEndian => new UTF32Encoding(bigEndian: false, byteOrderMark: false), + SqlFileEncoding.Utf32BigEndian => new UTF32Encoding(bigEndian: true, byteOrderMark: false), + SqlFileEncoding.Latin1 => Encoding.Latin1, + _ => new UTF8Encoding(encoderShouldEmitUTF8Identifier: false), + }; + + // Each one refuses a character it cannot store instead of writing a question mark in its place. + private static Encoding WritingEncoding(SqlFileEncoding encoding) => encoding switch + { + SqlFileEncoding.Utf16LittleEndian => new UnicodeEncoding(false, false, throwOnInvalidBytes: true), + SqlFileEncoding.Utf16BigEndian => new UnicodeEncoding(true, false, throwOnInvalidBytes: true), + SqlFileEncoding.Utf32LittleEndian => new UTF32Encoding(false, false, throwOnInvalidCharacters: true), + SqlFileEncoding.Utf32BigEndian => new UTF32Encoding(true, false, throwOnInvalidCharacters: true), + SqlFileEncoding.Latin1 => Encoding.GetEncoding( + Encoding.Latin1.CodePage, + EncoderFallback.ExceptionFallback, + DecoderFallback.ReplacementFallback), + _ => StrictUtf8, + }; + + private static string Unstorable(EncoderFallbackException exception) => + exception.CharUnknownHigh != '\0' + ? new string([exception.CharUnknownHigh, exception.CharUnknownLow]) + : new string(exception.CharUnknown, 1); + + private static void TryDelete(string path) + { + try + { + File.Delete(path); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + // The write's own failure is the one to report. + } + } +} diff --git a/windows/src/TablePro.App.Model/TabSession.cs b/windows/src/TablePro.App.Model/TabSession.cs index 24c79f80ef..0704303809 100644 --- a/windows/src/TablePro.App.Model/TabSession.cs +++ b/windows/src/TablePro.App.Model/TabSession.cs @@ -11,15 +11,27 @@ public interface ITabSession bool IsReadOnly { get; } - Task OpenEditorAsync(CancellationToken cancellationToken); + // How the server's databases stand to the catalog; OneDatabase where a connection reaches one. + DatabaseLayout Layout { get; } - // Starts the page's read on a pooled connection and returns at once; the token stops the read as well. + // The database the connection was asked to open; null for a file or a login that named none. + string? Database { get; } + + // Opened in database, or moved there before it returns; one that cannot reach it is closed and the call throws. + Task OpenEditorAsync(string? database, CancellationToken cancellationToken); + + // The server's databases the login sees, the connection's own marked default and the engine's own system. + Task> GetDatabasesAsync(CancellationToken cancellationToken); + + // Starts the page's read on a pooled connection and returns at once; the token stops the read as well. Continuation + // is where a server-paged table's next page starts, from the page before; offset is read through otherwise. Task ReadTablePageAsync( TableName table, ColumnSort? sort, TableFilter? filter, long limit, long offset, + IPageResume? continuation, CancellationToken cancellationToken); Task CountRowsAsync(TableName table, TableFilter? filter, CancellationToken cancellationToken); @@ -49,7 +61,16 @@ Task ReadTablePageAsync( } // The run gives the page's rows as an editor run's events do; columns past VisibleColumns are the row's address. -public sealed record TablePageRead(ITabRun Run, int VisibleColumns, bool CanSeek, string? ViewSql = null); +// Without CanSeek an offset reads through the rows before it; NextPage, once the run finished, resumes after it. +public sealed record TablePageRead( + ITabRun Run, + int VisibleColumns, + bool CanSeek, + string? ViewSql = null, + Func? NextPage = null); + +// Where a server-paged table's next page starts; only a read of the same table, sort, filter and size takes it. +public interface IPageResume : IDisposable; // 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 @@ -102,6 +123,10 @@ public interface ITabEditor : IAsyncDisposable ITabRun Run(string sql, QueryOptions options, CancellationToken cancellationToken); + // Where an unqualified name resolves now, as the server last said, a typed USE included; null where not followed. + string? Database { get; } + + // Keeps the transaction; an engine that binds the database at connect refuses with driver.unsupported. Task UseDatabaseAsync(string database, CancellationToken cancellationToken); } @@ -134,8 +159,15 @@ public CoreTabSession(SessionShare share) public bool IsReadOnly => _share.Session.IsReadOnly; - public async Task OpenEditorAsync(CancellationToken cancellationToken) => - new CoreTabEditor(await _share.Session.OpenEditorAsync(cancellationToken).ConfigureAwait(true)); + public DatabaseLayout Layout => _share.Session.Layout; + + public string? Database => _share.Session.Database; + + public async Task OpenEditorAsync(string? database, CancellationToken cancellationToken) => + new CoreTabEditor(await _share.Session.OpenEditorAsync(database, cancellationToken).ConfigureAwait(true)); + + public Task> GetDatabasesAsync(CancellationToken cancellationToken) => + _share.Session.GetDatabasesAsync(cancellationToken); public async Task ReadTablePageAsync( TableName table, @@ -143,11 +175,18 @@ public async Task ReadTablePageAsync( TableFilter? filter, long limit, long offset, + IPageResume? continuation, CancellationToken cancellationToken) { - var page = await _share.Session.ReadTablePageAsync(table, sort, filter, limit, offset, cancellationToken) + var page = await _share.Session.ReadTablePageAsync( + table, sort, filter, limit, offset, (continuation as CorePageResume)?.Resume, cancellationToken) .ConfigureAwait(true); - return new TablePageRead(new CoreTabRun(page.Run), page.VisibleColumns, page.CanSeek, page.ViewSql); + return new TablePageRead( + new CoreTabRun(page.Run, page), + page.VisibleColumns, + page.CanSeek, + page.ViewSql, + () => page.NextPage() is { } next ? new CorePageResume(next) : null); } public Task CountRowsAsync(TableName table, TableFilter? filter, CancellationToken cancellationToken) => @@ -282,10 +321,19 @@ public Task RunAsync(bool confirmed, CancellationToken cancellat public void Dispose() => save.Dispose(); } +internal sealed class CorePageResume(PageResume resume) : IPageResume +{ + public PageResume Resume => resume; + + public void Dispose() => resume.Dispose(); +} + internal sealed class CoreTabEditor(QueryEditor editor) : ITabEditor { public bool IsLost => editor.IsLost; + public string? Database => editor.Database; + public ITabRun Run(string sql, QueryOptions options, CancellationToken cancellationToken) => new CoreTabRun(editor.Run(sql, options, cancellationToken)); @@ -295,7 +343,8 @@ public Task UseDatabaseAsync(string database, CancellationToken cancellationToke public ValueTask DisposeAsync() => editor.DisposeAsync(); } -internal sealed class CoreTabRun(QueryRun run) : ITabRun +// A table page's run also holds the page, which says where the next one resumes until the run is let go. +internal sealed class CoreTabRun(QueryRun run, IDisposable? page = null) : ITabRun { public IAsyncEnumerable ReadEventsAsync(CancellationToken cancellationToken) => run.ReadEventsAsync(cancellationToken); @@ -306,5 +355,9 @@ public IAsyncEnumerable ReadEventsAsync(CancellationToken cancellati public void Cancel() => run.Cancel(); - public void Dispose() => run.Dispose(); + public void Dispose() + { + run.Dispose(); + page?.Dispose(); + } } diff --git a/windows/src/TablePro.App.Model/TablePage.cs b/windows/src/TablePro.App.Model/TablePage.cs index c8dba4939a..2568c802c4 100644 --- a/windows/src/TablePro.App.Model/TablePage.cs +++ b/windows/src/TablePro.App.Model/TablePage.cs @@ -1,6 +1,6 @@ namespace TablePro.App.Model; -// An engine that cannot seek has only the first page, as on macOS. +// Without CanSeek an offset reads through every row before it, so the pager steps a page at a time and never jumps. public sealed record TablePage(long Offset, int Size, long Rows, long? Total, bool CanSeek) { // Past this a typed size is a mistake, not an intent, as macOS caps its Custom size. @@ -22,14 +22,17 @@ public sealed record TablePage(long Offset, int Size, long Rows, long? Total, bo // Statistics can lag far behind the table, as MySQL's cached TABLE_ROWS or a table never analysed reading 0. public long? ShownEstimate => Estimate is { } estimate && estimate > LastRow ? estimate : null; + // The server that pages the table said no row follows this page, however full it is. + public bool EndsTable { get; init; } + public long FirstRow => Rows == 0 ? 0 : Offset + 1; public long LastRow => Offset + Rows; - public bool HasPrevious => CanSeek && Offset > 0; + public bool HasPrevious => Offset > 0; // Without a count, a full page may have more after it. - public bool HasNext => CanSeek && (Total is { } total ? LastRow < total : Rows >= Size); + public bool HasNext => !EndsTable && (Total is { } total ? LastRow < total : Rows >= Size); public bool HasLast => CanSeek && Total is not null && LastOffset > Offset; @@ -46,7 +49,7 @@ public sealed record TablePage(long Offset, int Size, long Rows, long? Total, bo // Known once the table is counted; an empty table is one page. public long? Count => Total is { } total ? Math.Max(1, (total / Size) + (total % Size == 0 ? 0 : 1)) : null; - public TablePage At(long offset) => this with { Offset = Math.Max(0, offset), Rows = 0 }; + public TablePage At(long offset) => this with { Offset = Math.Max(0, offset), Rows = 0, EndsTable = false }; // Only a page the count holds, as macOS goes to a page only within an exact total. public bool Accepts(long number) => CanSeek && number >= 1 && Count is { } count && number <= count; @@ -57,9 +60,11 @@ public sealed record TablePage(long Offset, int Size, long Rows, long? Total, bo public TablePage Resized(int size) { var clamped = Clamp(size); - return this with { Size = clamped, Offset = Offset / clamped * clamped, Rows = 0 }; + return this with { Size = clamped, Offset = Offset / clamped * clamped, Rows = 0, EndsTable = false }; } public TablePage AllRows() => - Total is { } total ? this with { Size = (int)Math.Clamp(total, 1, LargestSize), Offset = 0, Rows = 0 } : this; + Total is { } total + ? this with { Size = (int)Math.Clamp(total, 1, LargestSize), Offset = 0, Rows = 0, EndsTable = false } + : this; } diff --git a/windows/src/TablePro.App.Model/TableTab.cs b/windows/src/TablePro.App.Model/TableTab.cs index 198a0d20b3..19edd7188e 100644 --- a/windows/src/TablePro.App.Model/TableTab.cs +++ b/windows/src/TablePro.App.Model/TableTab.cs @@ -148,6 +148,9 @@ public sealed class TableTab : IWorkspaceTab private readonly TabWork _work = new(); private readonly KeptRead _structure; private readonly KeptRead _choices; + + // Where each page of a server-paged table resumes, by its offset: a paging state only goes forward. + private readonly Dictionary _resumes = []; private ITableEditor? _tableEditor; private bool _reopenTableEditor; private Task? _closing; @@ -265,8 +268,9 @@ public TableTab( public bool IsCounting => _counting is not null; - // Only an exact total pages to the end; a count the tab runs by itself is on its way, so Count rows waits for it. - public bool OffersCount => _page.Total is null && _page.IsPaged && (_counting is null || _countAsked); + // Only an exact total pages to the end, and only where the engine seeks; one the tab runs by itself is on its way. + public bool OffersCount => + _page.CanSeek && _page.Total is null && _page.IsPaged && (_counting is null || _countAsked); public bool CanCountRows => OffersCount && !IsCounting && !IsRunning && !IsSaving && !_work.IsClosed; @@ -542,13 +546,13 @@ public async Task SortAsync(GridSort sort) await LoadAsync(_page.Offset).ConfigureAwait(true); } - public Task FirstPageAsync() => PageToAsync(_ => 0); + public Task FirstPageAsync() => PageToAsync(_ => 0, keepsResumes: true); - public Task PreviousPageAsync() => PageToAsync(page => page.PreviousOffset); + public Task PreviousPageAsync() => PageToAsync(page => page.PreviousOffset, keepsResumes: true); - public Task NextPageAsync() => PageToAsync(page => page.NextOffset); + public Task NextPageAsync() => PageToAsync(page => page.NextOffset, keepsResumes: true); - public Task LastPageAsync() => PageToAsync(page => page.LastOffset); + public Task LastPageAsync() => _page.HasLast ? PageToAsync(page => page.LastOffset) : Task.CompletedTask; public async Task GoToPageAsync(long number) { @@ -787,7 +791,7 @@ public async Task ReadForShareAsync(long maxRows, CancellationTo ? null : new ColumnSort(_shownSort.Column, _shownSort.Direction == SortDirection.Ascending); var filter = _shownFilter; - var read = await _session.ReadTablePageAsync(Table, sort, filter, maxRows, 0, cancellationToken) + var read = await _session.ReadTablePageAsync(Table, sort, filter, maxRows, 0, null, cancellationToken) .ConfigureAwait(true); try { @@ -835,6 +839,7 @@ private async Task CloseOnceAsync() await _work.CloseAsync().ConfigureAwait(true); _run?.Dispose(); _run = null; + ForgetResumes(); _results.Clear(); SetEdits(null, null); _tableEditor?.Dispose(); @@ -854,11 +859,11 @@ private async Task MayReloadNowAsync(ReloadReason reason) => && !IsSaving && !_work.IsClosed; - private async Task PageToAsync(Func offset) + private async Task PageToAsync(Func offset, bool keepsResumes = false) { if (await MayReloadNowAsync(ReloadReason.Page).ConfigureAwait(true)) { - await LoadAsync(offset(_page)).ConfigureAwait(true); + await LoadAsync(offset(_page), keepsResumes: keepsResumes).ConfigureAwait(true); } } @@ -884,11 +889,17 @@ private async Task ResizeToAsync(TablePage page, int chosen) } // Recount after a filter, a refresh or a save, which can change the total; it is counted once the page is read. - private async Task LoadAsync(long offset, bool recount = false) + private async Task LoadAsync(long offset, bool recount = false, bool keepsResumes = false) { _shown = true; if (!IsRunning) { + // Any read but a step between pages may change the rows, sort, filter or size a paging state was for. + if (!keepsResumes) + { + ForgetResumes(); + } + await _work.RunAsync(token => LoadPageAsync(offset, recount, token)).ConfigureAwait(true); } } @@ -907,14 +918,18 @@ private async Task LoadPageAsync(long offset, bool recount, CancellationToken ca if (_chosenSize is null && page.Size != PageSize) { page = page.Resized(PageSize); + // A paging state resumes only a read of the size it was handed back for. + ForgetResumes(); } var sort = _sort.Direction == SortDirection.None ? null : new ColumnSort(_sort.Column, _sort.Direction == SortDirection.Ascending); var filter = Filter; + var resume = _resumes.GetValueOrDefault(page.Offset); // The core binds the filter's values and stops the read at the page's size. - var read = await _session.ReadTablePageAsync(Table, sort, filter, page.Size, page.Offset, cancellationToken) + var read = await _session.ReadTablePageAsync( + Table, sort, filter, page.Size, page.Offset, resume, cancellationToken) .ConfigureAwait(true); if (_work.IsClosed) { @@ -962,7 +977,9 @@ await _results.ShowRunAsync(_run, _sort, read.VisibleColumns, keptSets: 0, cance _shownSort = _sort; _shownFilter = filter; - _page = _page with { Rows = _results.RowCount }; + var next = read.NextPage?.Invoke(); + KeepResume(page.NextOffset, next); + _page = _page with { Rows = _results.RowCount, EndsTable = !read.CanSeek && next is null }; // The server's rows are read again, so a save whose outcome was unknown may be judged by them now. Unblock(); BindEdits(); @@ -988,6 +1005,30 @@ await _results.ShowRunAsync(_run, _sort, read.VisibleColumns, keptSets: 0, cance } } + // The page at offset resumes here; once the server says nothing follows, that page is read by offset. + private void KeepResume(long offset, IPageResume? resume) + { + if (_resumes.Remove(offset, out var kept) && !ReferenceEquals(kept, resume)) + { + kept.Dispose(); + } + + if (resume is not null) + { + _resumes[offset] = resume; + } + } + + private void ForgetResumes() + { + foreach (var resume in _resumes.Values) + { + resume.Dispose(); + } + + _resumes.Clear(); + } + // Once per tab, and again on a refresh, since the table's columns can change. private async Task OpenTableEditorAsync(CancellationToken cancellationToken) { diff --git a/windows/src/TablePro.App/MainWindow.xaml b/windows/src/TablePro.App/MainWindow.xaml index 954de63c53..d2293f6a77 100644 --- a/windows/src/TablePro.App/MainWindow.xaml +++ b/windows/src/TablePro.App/MainWindow.xaml @@ -36,6 +36,7 @@ + @@ -59,13 +60,18 @@ - + + + + + + @@ -112,6 +118,7 @@ + @@ -158,6 +165,12 @@ + + + + + + diff --git a/windows/src/TablePro.App/MainWindow.xaml.cs b/windows/src/TablePro.App/MainWindow.xaml.cs index b0dd7e6b74..686cac286e 100644 --- a/windows/src/TablePro.App/MainWindow.xaml.cs +++ b/windows/src/TablePro.App/MainWindow.xaml.cs @@ -34,6 +34,9 @@ public sealed partial class MainWindow : Window, IShell, IWorkspaceHost private readonly MainWindow _primary; private readonly HomeView? _home; private readonly List _open = []; + + // .sql files opened while no connection was connected, which the next workspace to connect opens. + private readonly List _waitingFiles = []; private readonly Dictionary _forms = []; private readonly List _tabWindows = []; // Native AOT trims OverlappedPresenter's wrapper, so AppWindow.Presenter reads back as its base type. @@ -49,6 +52,9 @@ public sealed partial class MainWindow : Window, IShell, IWorkspaceHost private SettingsView? _settings; private OpenConnection? _front; + // The connection whose cue the title bar shows, painted again when the theme changes. + private OpenConnection? _cue; + // A tab window that has not taken a tab yet, kept hidden for the next drag out of a strip. private MainWindow? _spare; private bool _isSpare; @@ -84,6 +90,7 @@ internal MainWindow(Workbench workbench) } workbench.ObjectPaneWidth = session.ObjectPaneWidth ?? ObjectPane.DefaultWidth; + workbench.LoadRecentFiles(session.RecentFiles); _home = new HomeView(workbench, this); Rail.Content = _home; Rail.SelectedItem = HomeItem; @@ -121,6 +128,8 @@ private MainWindow( Show(connection); } + private static readonly string[] SqlSuffixes = [".sql", ".psql", ".pgsql"]; + // Raised once the last session is written, before the connections close, so a new launch may own the data folder. internal event EventHandler? SessionSaved; @@ -184,28 +193,142 @@ public void Connect(SavedConnection connection) EngineId = connection.EngineId, }); open.Mark(connection.EngineId, connection.Color); + // The tags come from the library's snapshot, which names each one. + _ = RefreshMarksAsync(); } + // A tab window picks too: a .sql file opens on its own connection, a database file in the primary window. public async Task OpenFileAsync() { - if (!IsPrimary) - { - await _primary.OpenFileAsync(); - return; - } - var picker = new FileOpenPicker(AppWindow.Id) { SuggestedStartLocation = PickerLocationId.DocumentsLibrary }; foreach (var suffix in _workbench.Engines.SelectMany(engine => engine.FileSuffixes).Distinct()) { picker.FileTypeFilter.Add("." + suffix); } + foreach (var suffix in SqlSuffixes) + { + picker.FileTypeFilter.Add(suffix); + } + picker.FileTypeFilter.Add("*"); var result = await picker.PickSingleFileAsync(); if (result is not null) { - OpenFile(result.Path); + await OpenAnyFileAsync(result.Path); + } + } + + // As macOS's Open File: a .sql file goes to a query tab, any other file opens as a database. + private async Task OpenAnyFileAsync(string path) + { + if (SqlSuffixes.Contains(Path.GetExtension(path), StringComparer.OrdinalIgnoreCase)) + { + await OpenSqlFileAsync(path); + } + else if (!IsPrimary) + { + _primary.Activate(); + _primary.OpenFile(path); + } + else + { + OpenFile(path); + } + } + + // The front connection's workspace takes the file; with none connected, it waits for the next one to connect. + internal async Task OpenSqlFileAsync(string path) + { + if (!IsPrimary && Workspace is not { IsConnected: true }) + { + _primary.Activate(); + await _primary.OpenSqlFileAsync(path); + return; + } + + var target = Rail.Content is WorkspaceView { IsConnected: true } shown + ? shown + : _front?.View is { IsConnected: true } front ? front : null; + if (target is not null) + { + if (_front is { } open && ReferenceEquals(open.View, target) && !ReferenceEquals(Rail.Content, target)) + { + Select(open); + } + + await target.OpenSqlFileAsync(path); + return; + } + + if (!_waitingFiles.Contains(path, StringComparer.OrdinalIgnoreCase)) + { + _waitingFiles.Add(path); + } + + ShowHome(); + _home?.ShowMessage(Strings.Format("SqlFileWaits", Path.GetFileName(path)), InfoBarSeverity.Informational); + } + + private async Task OpenWaitingFilesAsync(OpenConnection open) + { + if (_waitingFiles.Count == 0 || !open.View.IsConnected) + { + return; + } + + var files = _waitingFiles.ToList(); + _waitingFiles.Clear(); + foreach (var file in files) + { + await open.View.OpenSqlFileAsync(file); + } + } + + // session.json keeps the list, so a change is written as any other session change is. + private void OnRecentFilesChanged(object? sender, EventArgs e) + { + ShowRecentFiles(); + if (IsPrimary) + { + SessionChanged(); + } + } + + // Built again when the list changes, in each window's own menu bar. + private void ShowRecentFiles() + { + MenuOpenRecent.Items.Clear(); + foreach (var path in _workbench.RecentFiles.Paths) + { + var item = new MenuFlyoutItem { Text = path }; + ToolTipService.SetToolTip(item, path); + item.Click += async (_, _) => + { + if (File.Exists(path)) + { + await OpenSqlFileAsync(path); + } + else + { + _workbench.ForgetFile(path); + } + }; + MenuOpenRecent.Items.Add(item); + } + + if (MenuOpenRecent.Items.Count > 0) + { + MenuOpenRecent.Items.Add(new MenuFlyoutSeparator()); } + + var clear = new MenuFlyoutItem + { + Text = Strings.Get("MenuClearRecent"), + IsEnabled = _workbench.RecentFiles.Paths.Count > 0, + }; + clear.Click += (_, _) => _workbench.ClearRecentFiles(); + MenuOpenRecent.Items.Add(clear); } public async Task ImportAsync() @@ -382,6 +505,17 @@ private void Prepare() width, height)); Themes.Apply(this, _workbench.Settings.Theme); + Root.ActualThemeChanged += (_, _) => ShowCue(_cue); + // Another program may have changed an open .sql file while the window was in the background. + Activated += async (_, args) => + { + if (args.WindowActivationState != WindowActivationState.Deactivated && Workspace is { } workspace) + { + await workspace.CheckFileAsync(); + } + }; + ShowRecentFiles(); + _workbench.RecentFilesChanged += OnRecentFilesChanged; _workbench.SettingsChanged += OnSettingsChanged; _workbench.LibraryChanged += OnLibraryChanged; AppWindow.Closing += OnClosing; @@ -439,7 +573,7 @@ private void Restore(SessionState state) private OpenConnection Open(SessionConnection origin) { - var open = _open.FirstOrDefault(item => item.Matches(origin.ConnectionId, origin.FilePath)) ?? Add(origin); + var open = _open.FirstOrDefault(item => item.IsSame(origin)) ?? Add(origin); Select(open); if (open.State == ConnectionState.Failed) { @@ -449,6 +583,41 @@ private OpenConnection Open(SessionConnection origin) return open; } + // Another database of a server whose databases hold their own schemas opens as its own rail item, as Linux opens + // it beside the connection; one already open, the connection's own included, is brought forward. + private void OpenDatabase(OpenConnection from, string database) + { + if (!IsPrimary) + { + _primary.Activate(); + _primary.OpenDatabase(from, database); + return; + } + + if (from.ConnectionId is not { } id) + { + return; + } + + var own = _open.FirstOrDefault(item => item.Matches(id, null) && item.Database is null); + if (own?.Session?.Database == database) + { + Select(own); + return; + } + + var open = Open(new SessionConnection + { + ConnectionId = id, + Name = from.Name, + EngineId = from.Origin.EngineId, + Database = database, + }); + open.Mark(from.Origin.EngineId, from.Color); + open.SetTags(from.Tags); + ShowCue(open); + } + private async void OnLibraryChanged(object? sender, EventArgs e) => await RefreshMarksAsync(); private void OnSettingsChanged(object? sender, EventArgs e) => Themes.Apply(this, _workbench.Settings.Theme); @@ -468,6 +637,14 @@ private async Task RefreshMarksAsync() if (snapshot.Connections.FirstOrDefault(saved => saved.Id == open.ConnectionId) is { } saved) { open.Mark(saved.EngineId, saved.Color); + open.SetTags([.. saved.Tags + .Select(id => snapshot.Tags.FirstOrDefault(tag => tag.Id == id)) + .OfType()]); + if (ReferenceEquals(_front, open) && ReferenceEquals(Rail.Content, open.View)) + { + ShowCue(open); + } + if (saved.Name != open.Name) { open.Rename(saved.Name); @@ -495,6 +672,16 @@ private OpenConnection Add(OpenConnection open) open.View.CommandsChanged += (_, _) => UpdateCommands(); open.View.SessionChanged += (_, _) => SessionChanged(); open.View.EditRequested += async (_, _) => await EditAsync(open); + open.View.DatabaseRequested += (_, database) => OpenDatabase(open, database); + open.View.FileUsed += (_, path) => _workbench.UseFile(path); + open.View.OpenFilesRequested += async (_, paths) => + { + foreach (var path in paths) + { + await OpenAnyFileAsync(path); + } + }; + open.View.CommandsChanged += async (_, _) => await OpenWaitingFilesAsync(open); open.View.Host = this; _open.Add(open); SessionChanged(); @@ -544,6 +731,7 @@ private void Show(UIElement page) { SetContent(page); AppTitleBar.Subtitle = string.Empty; + ShowCue(null); // While the rail is hidden, Settings is reached from the Connections page, so the title bar leads back. AppTitleBar.IsBackButtonVisible = !Rail.IsPaneVisible && ReferenceEquals(page, _settings); UpdateCommands(); @@ -562,13 +750,25 @@ private void SetContent(UIElement page) // A tab window is named for its connection in the taskbar and in Alt+Tab, once it shows. private void ShowName(OpenConnection open) { - AppTitleBar.Subtitle = IsPrimary || _isSpare ? open.Name : string.Empty; + AppTitleBar.Subtitle = IsPrimary || _isSpare ? open.Title : string.Empty; + ShowCue(open); if (!IsPrimary && !_isSpare) { - AppTitleBar.Title = Strings.Format("TabWindowTitle", open.Name); + AppTitleBar.Title = Strings.Format("TabWindowTitle", open.Title); } } + // The connection in front tints the title bar and the menu bar, and the title bar names its tags. + private void ShowCue(OpenConnection? open) + { + _cue = open; + var theme = Root.ActualTheme; + var tint = open is null ? null : ConnectionCue.Tint(theme, open.Color); + ConnectionCue.Paint(AppTitleBar, tint); + ConnectionCue.Paint(AppMenuBar, tint); + AppTitleBar.RightHeader = open is null ? null : ConnectionCue.Label(open.Tags, theme); + } + private void ShowHome() { if (_home is null) @@ -687,12 +887,14 @@ private void ShowForm(SavedConnection? existing) private async Task OnFormCompletedAsync(FormResult result) { - var open = _open.FirstOrDefault(item => item.Matches(result.Saved.Id, null)); - if (open is not null) + // Each database the connection is open in takes the new name, and with Connect each connects again. + foreach (var each in _open.Where(item => item.Matches(result.Saved.Id, null))) { - open.Rename(result.Saved.Name); + each.Rename(result.Saved.Name); } + var open = _open.FirstOrDefault(item => item.Matches(result.Saved.Id, null) && item.Database is null); + // An edited connection that is open connects again with what was saved, and keeps its tabs. var reconnecting = result.Connect && open is { State: ConnectionState.Connected or ConnectionState.Failed } ? open @@ -721,6 +923,36 @@ private async Task OnFormCompletedAsync(FormResult result) } Connect(result.Saved); + await ReconnectDatabasesAsync(result.Saved); + } + + // The connection's other databases connect again with what was saved too, each keeping its database and its tabs. + private async Task ReconnectDatabasesAsync(SavedConnection saved) + { + var databases = _open + .Where(item => item.Matches(saved.Id, null) + && item.Database is not null + && item.State is ConnectionState.Connected or ConnectionState.Failed) + .ToList(); + foreach (var each in databases) + { + if (!await ConfirmDisconnectAsync(each, offerSave: saved.SafeMode != SafeMode.ReadOnly)) + { + ShowChangesOnConnect(each, saved); + continue; + } + + DropSpare(); + await each.DisconnectAsync(keepTabs: true); + await each.ConnectAsync(); + } + + // A question above brought a database forward; the connection the user connected comes back to the front. + if (databases.Count > 0 + && _open.FirstOrDefault(item => item.Matches(saved.Id, null) && item.Database is null) is { } own) + { + Select(own); + } } // The core read the saved connection as each connect under way began, in every window. @@ -956,7 +1188,7 @@ private static async Task ConfirmTabsAsync(List windows, HashS [.. 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)))]; + .Select(tab => (Connection: open.Title, 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, IWorkspaceTab Tab)> running) @@ -996,7 +1228,7 @@ private void HandTabsToPrimary() { var tabs = open.Snapshot().Tabs; if (tabs.Count > 0 - && _primary._open.FirstOrDefault(each => each.Matches(open.ConnectionId, open.Origin.FilePath)) is { } home) + && _primary._open.FirstOrDefault(each => each.IsSame(open.Origin)) is { } home) { home.View.KeepClosed(tabs); } @@ -1071,6 +1303,7 @@ private void OnClosed(object sender, WindowEventArgs args) { _workbench.SettingsChanged -= OnSettingsChanged; _workbench.LibraryChanged -= OnLibraryChanged; + _workbench.RecentFilesChanged -= OnRecentFilesChanged; if (IsPrimary) { return; @@ -1250,6 +1483,7 @@ private SessionState SessionSnapshot(bool withWork) Window = WindowInterop.Placement(this), ObjectPaneWidth = _workbench.ObjectPaneWidth, TabWindows = windows, + RecentFiles = _workbench.RecentFiles.Paths, }; } @@ -1284,9 +1518,11 @@ private void UpdateCommands() // A definition tab reads its text with Reload, not Run, and has nothing to stop. MenuRun.IsEnabled = tab is QueryTabView { IsRunning: false } or TableTabView { IsRunning: false }; MenuRunStatement.IsEnabled = tab is QueryTabView { IsRunning: false }; - MenuStop.IsEnabled = tab is QueryTabView { IsRunning: true } or TableTabView { IsRunning: true }; + MenuStop.IsEnabled = tab is QueryTabView { IsRunning: true } or TableTabView { IsRunning: true } + or KeyTabView { IsRunning: true }; var editor = tab?.Editor is not null; - foreach (var item in new[] { MenuUndo, MenuRedo, MenuCut, MenuPaste, MenuFind }) + MenuSwitchDatabase.IsEnabled = workspace?.CanSwitchDatabase ?? false; + foreach (var item in new[] { MenuUndo, MenuRedo, MenuCut, MenuPaste, MenuFind, MenuReplace }) { item.IsEnabled = editor; } @@ -1296,7 +1532,8 @@ private void UpdateCommands() // A query tab never edits; a table tab says what its page can do now. var table = tab as TableTabView; MenuFilterRows.IsEnabled = table is not null; - MenuSaveChanges.IsEnabled = table is { CanSave: true }; + MenuSaveChanges.IsEnabled = table is { CanSave: true } || tab is QueryTabView; + MenuSaveAs.IsEnabled = tab is QueryTabView; MenuDiscardChanges.IsEnabled = table is { CanDiscard: true }; MenuPreviewSql.IsEnabled = table is { CanPreview: true }; MenuAddRow.IsEnabled = table is { CanAddRow: true }; @@ -1377,13 +1614,21 @@ private void OnSelectAll(object sender, RoutedEventArgs e) private void OnFind(object sender, RoutedEventArgs e) => EditorKey(VirtualKey.F); + private void OnReplace(object sender, RoutedEventArgs e) => EditorKey(VirtualKey.H); + + private void OnSwitchDatabase(object sender, RoutedEventArgs e) => Workspace?.OpenDatabaseMenu(); + // The menu sends the editor the key it already answers, so a menu command and its shortcut cannot differ. private void EditorKey(VirtualKey key) { if (Workspace?.ActiveTab?.Editor is { } editor) { editor.HandleKey(key, control: true, shift: false, alt: false); - editor.Focus(FocusState.Programmatic); + // Find and Replace put the keyboard in the find bar's box, which a focus on the editor would take back. + if (key is not (VirtualKey.F or VirtualKey.H)) + { + editor.Focus(FocusState.Programmatic); + } } } @@ -1468,11 +1713,27 @@ private async void OnDisconnect(object sender, RoutedEventArgs e) private void OnStop(object sender, RoutedEventArgs e) => Workspace?.ActiveTab?.Stop(); + // A table tab saves its pending changes, a query tab its .sql file, through Save As when it has none. private async void OnSaveChanges(object sender, RoutedEventArgs e) { - if (Workspace?.ActiveTab is TableTabView table) + switch (Workspace?.ActiveTab) + { + case TableTabView table: + await table.SaveAsync(); + break; + case QueryTabView query: + await query.SaveAsync(); + break; + default: + break; + } + } + + private async void OnSaveAs(object sender, RoutedEventArgs e) + { + if (Workspace?.ActiveTab is QueryTabView query) { - await table.SaveAsync(); + await query.SaveAsAsync(); } } diff --git a/windows/src/TablePro.App/Services/ConnectionCue.cs b/windows/src/TablePro.App/Services/ConnectionCue.cs new file mode 100644 index 0000000000..b9be5f4ad0 --- /dev/null +++ b/windows/src/TablePro.App/Services/ConnectionCue.cs @@ -0,0 +1,81 @@ +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Automation; +using Microsoft.UI.Xaml.Controls; +using Microsoft.UI.Xaml.Media; +using Microsoft.UI.Xaml.Shapes; +using TablePro.Interop; +using Windows.UI; + +namespace TablePro.App.Services; + +// The production cue: the front connection's colour behind the title bar, the menu bar and the tab strip, and its tags +// named in the title bar, so a window on production reads as production at a glance. +internal static class ConnectionCue +{ + // Light enough that text over the tint keeps its contrast; a dark theme needs more to show at all. + private const byte LightAlpha = 0x2E; + private const byte DarkAlpha = 0x47; + + // Null for no colour and in a contrast theme, which keeps its own colours. + public static SolidColorBrush? Tint(ElementTheme theme, string? color) => + EngineIcons.Brush(theme, color) is { Color: var shade } + ? new SolidColorBrush(Color.FromArgb(theme == ElementTheme.Dark ? DarkAlpha : LightAlpha, shade.R, shade.G, shade.B)) + : null; + + public static void Paint(Control control, Brush? tint) + { + ArgumentNullException.ThrowIfNull(control); + if (tint is null) + { + control.ClearValue(Control.BackgroundProperty); + } + else + { + control.Background = tint; + } + } + + // A dot in each tag's colour beside its name, read as one environment label; null for a connection with no tags. + public static FrameworkElement? Label(IReadOnlyList tags, ElementTheme theme) + { + ArgumentNullException.ThrowIfNull(tags); + if (tags.Count == 0) + { + return null; + } + + var label = new StackPanel + { + Orientation = Orientation.Horizontal, + Spacing = 12, + Margin = new Thickness(0, 0, 12, 0), + VerticalAlignment = VerticalAlignment.Center, + }; + foreach (var tag in tags) + { + var chip = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6 }; + var dot = new Ellipse { Width = 8, Height = 8, VerticalAlignment = VerticalAlignment.Center }; + if (EngineIcons.Brush(theme, tag.Color) is { } brush) + { + dot.Fill = brush; + } + else + { + dot.Fill = (Brush)Application.Current.Resources["TextFillColorSecondaryBrush"]; + } + + chip.Children.Add(dot); + chip.Children.Add(new TextBlock + { + Text = tag.Name, + VerticalAlignment = VerticalAlignment.Center, + Style = (Style)Application.Current.Resources["CaptionTextBlockStyle"], + }); + label.Children.Add(chip); + } + + AutomationProperties.SetName(label, Strings.Format("EnvironmentLabel", string.Join(", ", tags.Select(tag => tag.Name)))); + AutomationProperties.SetAutomationId(label, "EnvironmentLabel"); + return label; + } +} diff --git a/windows/src/TablePro.App/Services/DisplaySettings.cs b/windows/src/TablePro.App/Services/DisplaySettings.cs new file mode 100644 index 0000000000..ba54ddddd8 --- /dev/null +++ b/windows/src/TablePro.App/Services/DisplaySettings.cs @@ -0,0 +1,65 @@ +using Microsoft.UI.Xaml; +using TablePro.App.Model; +using TablePro.DataGrid; +using TablePro.Editor; + +namespace TablePro.App.Services; + +// The font and NULL settings every editor and grid follows: applied as each one loads and again when Settings changes +// them, so an open tab takes a change at once. +internal static class DisplaySettings +{ + private static AppSettings s_current = new(); + + private static event EventHandler? Changed; + + public static void Update(AppSettings settings) + { + ArgumentNullException.ThrowIfNull(settings); + var before = s_current; + s_current = settings; + if (before.EditorFontSize != settings.EditorFontSize + || before.EditorFontFamily != settings.EditorFontFamily + || before.GridFontFamily != settings.GridFontFamily + || before.GridFontSize != settings.GridFontSize + || before.NullDisplay != settings.NullDisplay) + { + Changed?.Invoke(null, EventArgs.Empty); + } + } + + public static void Follow(DataGridView grid) + { + ArgumentNullException.ThrowIfNull(grid); + Follow(grid, () => + { + grid.NullText = s_current.NullDisplay; + grid.CellFontFamily = s_current.GridFontFamily; + grid.CellFontSize = s_current.GridFontSize; + }); + } + + public static void Follow(SqlEditor editor) + { + ArgumentNullException.ThrowIfNull(editor); + Follow(editor, () => + { + editor.EditorFontFamily = s_current.EditorFontFamily; + editor.EditorFontSize = (float)s_current.EditorFontSize; + }); + } + + // A tab not on screen is unloaded and hears nothing, so it applies the settings again as it loads. + private static void Follow(FrameworkElement element, Action apply) + { + void OnChanged(object? sender, EventArgs e) => apply(); + element.Loaded += (_, _) => + { + Changed -= OnChanged; + Changed += OnChanged; + apply(); + }; + element.Unloaded += (_, _) => Changed -= OnChanged; + apply(); + } +} diff --git a/windows/src/TablePro.App/Services/Workbench.cs b/windows/src/TablePro.App/Services/Workbench.cs index f39ae995ea..378bbf2a1c 100644 --- a/windows/src/TablePro.App/Services/Workbench.cs +++ b/windows/src/TablePro.App/Services/Workbench.cs @@ -19,6 +19,7 @@ public Workbench(TableProCore core, string folder) _settings = new SettingsStore(Path.Combine(folder, "settings.json")); Sessions = new SessionStore(Path.Combine(folder, "session.json")); Settings = _settings.Load(); + DisplaySettings.Update(Settings); } public event EventHandler? SettingsChanged; @@ -26,6 +27,9 @@ public Workbench(TableProCore core, string folder) // Raised after this app changed the saved connections, so every list rebuilds from a new snapshot. public event EventHandler? LibraryChanged; + // Raised after Settings cleared the query history, so an open history pane reads it again. + public event EventHandler? HistoryCleared; + // Raised on the UI thread after the account's status or a sign-in's progress changed. public event EventHandler? AccountChanged; @@ -44,6 +48,37 @@ public Workbench(TableProCore core, string folder) // Shared by every workspace and kept in the session file. public double ObjectPaneWidth { get; set; } = ObjectPane.DefaultWidth; + // File, Open recent in every window; kept in the session file. + public RecentFiles RecentFiles { get; private set; } = new(); + + public event EventHandler? RecentFilesChanged; + + public void LoadRecentFiles(IEnumerable paths) + { + RecentFiles = new RecentFiles(paths); + RecentFilesChanged?.Invoke(this, EventArgs.Empty); + } + + public void UseFile(string path) + { + RecentFiles.Add(path); + RecentFilesChanged?.Invoke(this, EventArgs.Empty); + } + + public void ForgetFile(string path) + { + if (RecentFiles.Remove(path)) + { + RecentFilesChanged?.Invoke(this, EventArgs.Empty); + } + } + + public void ClearRecentFiles() + { + RecentFiles.Clear(); + RecentFilesChanged?.Invoke(this, EventArgs.Empty); + } + public AccountStatus AccountStatus { get; private set; } = AccountStatus.SignedOut; // The error that kept the account from starting, as a machine with no ID does. @@ -72,9 +107,16 @@ public void UpdateSettings(Func change) return; } + var pruneAgain = next.HistoryRetentionDays != Settings.HistoryRetentionDays + || next.HistoryMaxEntries != Settings.HistoryMaxEntries; Settings = next; SaveSettings(); + DisplaySettings.Update(next); SettingsChanged?.Invoke(this, EventArgs.Empty); + if (pruneAgain && _history is { IsCompletedSuccessfully: true, Result: { } history }) + { + _ = PruneHistoryAsync(history); + } } public void SaveUnsavedSettings() @@ -187,14 +229,48 @@ private async Task WatchAccountAsync(TableProAccount account) private async Task OpenHistoryAsync() { + QueryHistory history; try { - return await Core.OpenHistoryAsync().ConfigureAwait(true); + history = await Core.OpenHistoryAsync().ConfigureAwait(true); } catch (TableProException) { return null; } + + await PruneHistoryAsync(history).ConfigureAwait(true); + return history; + } + + // To the age and count Settings keeps, when the store opens and when either changes; pinned runs stay. + private async Task PruneHistoryAsync(QueryHistory history) + { + try + { + await history.PruneAsync(Settings.HistoryRetentionDays, Settings.HistoryMaxEntries).ConfigureAwait(true); + } + catch (TableProException) + { + // The runs stay until the next prune; recording and search do not depend on it. + } + catch (ObjectDisposedException) + { + // The app closed the store as it quit. + } + } + + // Every connection's runs, pinned ones too, as Settings' Clear history asks. False when the store could not open. + public async Task ClearHistoryAsync() + { + if (await GetHistoryAsync().ConfigureAwait(true) is not { } history) + { + return false; + } + + await history.ClearAsync().ConfigureAwait(true); + HistoryCleared?.Invoke(this, EventArgs.Empty); + return true; } // The Chinook sample is copied out of the app once, so edits to it stay. diff --git a/windows/src/TablePro.App/Strings/en-US/Resources.resw b/windows/src/TablePro.App/Strings/en-US/Resources.resw index 68b3a4293f..e50043e58c 100644 --- a/windows/src/TablePro.App/Strings/en-US/Resources.resw +++ b/windows/src/TablePro.App/Strings/en-US/Resources.resw @@ -46,7 +46,7 @@ N - Open database file... + Open file... O @@ -1260,9 +1260,6 @@ That tag is gone. The list shows the tags there are now. - - This engine reads a table only from its start, so it has no later pages. - Password @@ -1366,13 +1363,13 @@ Close and roll back - Table changes are not saved. + Changes are not saved. A transaction is open. - Table changes are not saved, and a transaction is open. + Changes are not saved, and a transaction is open. Run this statement? @@ -2688,9 +2685,6 @@ New fingerprint: {2} This engine takes no Raw SQL filter. Clear the filter and add rules instead. - - Runs in {0} - Queries run on every connection @@ -3279,4 +3273,361 @@ New fingerprint: {2} The rows are still arriving. Share them once the query finishes. + + Key commands + + + Load more + + + Read the next entries + + + Refresh + + + Read the key again from the start + + + Could not read the key + + + Value + + + Reading the key + + + This key does not exist + + + It may have expired or been deleted. Refresh reads it again. + + + No viewer for this type + + + TablePro cannot show a value of type {0} here. Read it with the module's own commands in a query tab. + + + Reading... + + + {0:N0} shown + + + {0:N0} of {1:N0} shown + + + Key not found + + + Read failed + + + Stopped + + + String + + + Hash + + + List + + + Set + + + Sorted set + + + Stream + + + 1 byte + + + {0:N0} bytes + + + 1 field + + + {0:N0} fields + + + 1 element + + + {0:N0} elements + + + 1 member + + + {0:N0} members + + + 1 entry + + + {0:N0} entries + + + No expiry + + + Expiry unknown + + + Expires in {0} s + + + Expires in {0} min + + + Expires in {0} min {1} s + + + Expires in {0} h + + + Expires in {0} h {1} min + + + Expires in {0:N0} d + + + Expires in {0:N0} d {1} h + + + Showing the first {0:N0} bytes of {1:N0}. + + + The database this tab runs in + + + Database: {0} + + + No database + + + No databases + + + SQL file + + + Changed on disk + + + Another program changed {0}. + + + Reload + + + File deleted or moved + + + {0} is no longer where it was. Save as... keeps your text in a new file. + + + Save as... + + + {0} changed on disk + + + Another program changed the file since it was opened or saved here. Overwrite it with your text, or reload it and lose your changes. + + + Overwrite + + + Reload from disk + + + Couldn't save {0} + + + The text holds {0}, which {1} can't store, so the file was left as it was. Save as... writes UTF-8. + + + Couldn't reload {0} + + + UTF-8 + + + UTF-16 LE + + + UTF-16 BE + + + UTF-32 LE + + + UTF-32 BE + + + Western (ISO Latin 1) + + + Font + + + The monospaced font of the SQL editor + + + Editor font + + + Default (Cascadia Mono) + + + Data grid + + + Font + + + The font of the cells in every result and table grid + + + Grid font + + + Default (Segoe UI) + + + Font size + + + The size of the text in the grid's cells + + + Grid font size + + + NULL display + + + What a grid shows in a cell that holds NULL, up to 20 characters + + + NULL display + + + Keep runs for + + + Older runs are removed, except pinned ones + + + Keep runs for + + + {0:N0} days + + + 1 year + + + Forever + + + Maximum runs + + + The oldest runs past this number are removed, except pinned ones + + + Maximum runs + + + {0:N0} + + + Unlimited + + + Clear history + + + Removes every connection's runs, pinned ones too + + + Clear history... + + + Clear history + + + The history could not be opened, so nothing was cleared. + + + The history is empty. + + + Environment: {0} + + + {0} · {1} + + + No database + + + Database: {0} + + + Switch database (Ctrl+K) + + + No databases to switch to + + + Replace + + + E + + + Switch database... + + + S + + + Open recent + + + F + + + Save as... + + + A + + + Clear recent files + + + {0} opens in a query tab once a connection is connected. + + + Couldn't open {0} + + + {0} • + + + Unsaved changes + diff --git a/windows/src/TablePro.App/Views/KeyTabView.xaml b/windows/src/TablePro.App/Views/KeyTabView.xaml new file mode 100644 index 0000000000..d660155bd7 --- /dev/null +++ b/windows/src/TablePro.App/Views/KeyTabView.xaml @@ -0,0 +1,149 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/windows/src/TablePro.App/Views/KeyTabView.xaml.cs b/windows/src/TablePro.App/Views/KeyTabView.xaml.cs new file mode 100644 index 0000000000..7d2822b4ed --- /dev/null +++ b/windows/src/TablePro.App/Views/KeyTabView.xaml.cs @@ -0,0 +1,252 @@ +using System.Text; +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Controls; +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 key's value a window at a time; the reads and the close are KeyTab's, so Run does nothing here. +public sealed partial class KeyTabView : UserControl, ITabContent, IKeyTabView +{ + private readonly KeyTab _model; + private ResultSet? _rows; + private bool _gridIsTarget; + + internal KeyTabView(SessionShare share, string key) + { + InitializeComponent(); + _model = new KeyTab(new CoreTabSession(share), this, key, () => new CoreKeyRead(share.Session.OpenKey(key))); + _model.StateChanged += (_, _) => + { + UpdateCommands(); + StateChanged?.Invoke(this, EventArgs.Empty); + }; + Title = key; + KeyGrid.SizeColumnsToContent = true; + // The rows arrive a window at a time in the engine's order, which a sort of the rows held would break. + KeyGrid.SortRequested += (_, _) => KeyGrid.Sort = GridSort.None; + KeyGrid.GotFocus += (_, _) => _gridIsTarget = true; + DisplaySettings.Follow(KeyGrid); + } + + public event EventHandler? StateChanged; + + public string Title { get; } + + public TabKind Kind => _model.Kind; + + public bool IsRunning => _model.IsRunning; + + public TransactionState Transaction => _model.Transaction; + + public bool HasUnsavedChanges => _model.HasUnsavedChanges; + + public SqlEditor? Editor => null; + + public DataGridView? Grid => KeyGrid; + + public bool GridIsTarget => _gridIsTarget && KeyGrid.Visibility == Visibility.Visible; + + public TextBox? MessagesTarget => null; + + public bool Shows(string key) => string.Equals(_model.Key, key, StringComparison.Ordinal); + + public async void Load() => await _model.LoadAsync().ConfigureAwait(true); + + public void Run() + { + } + + public void Stop() => _model.Stop(); + + public void FocusContent() + { + if (KeyGrid.Visibility == Visibility.Visible) + { + KeyGrid.Focus(FocusState.Programmatic); + } + else + { + RefreshButton.Focus(FocusState.Programmatic); + } + } + + public SessionTab Snapshot() => _model.Snapshot(); + + public SessionTab WithPendingWork(SessionTab snapshot) => _model.WithPendingWork(snapshot); + + public Task ConfirmCloseAsync(bool offerSave) => _model.ConfirmCloseAsync(offerSave); + + public Task CloseAsync() => _model.CloseAsync(); + + void IKeyTabView.ShowReading() + { + ShowBar(ErrorBar, false); + StatusText.Text = Strings.Get("KeyStatusReading"); + // What the last read found stays on screen until this one lands. + LoadingRing.IsActive = + Header.Visibility == Visibility.Collapsed && MissingPanel.Visibility == Visibility.Collapsed; + UpdateCommands(); + } + + void IKeyTabView.ShowRows(ResultSet? rows) + { + _rows = rows; + KeyGrid.SetData(rows is null ? null : new ResultSetData(rows, rows.GetColumns())); + } + + void IKeyTabView.ShowWindow(KeyWindow window) + { + var other = window.Kind == KeyKind.Other; + LoadingRing.IsActive = false; + MissingPanel.Visibility = Visibility.Collapsed; + Header.Visibility = Visibility.Visible; + TypeText.Text = other ? window.TypeName : Strings.Get("KeyType_" + window.Kind); + LengthText.Text = window.Length is { } length ? LengthWords(window.Kind, length) : string.Empty; + LengthText.Visibility = window.Length is null ? Visibility.Collapsed : Visibility.Visible; + TtlText.Text = TtlWords(window.Ttl); + OtherText.Text = other ? Strings.Format("KeyOtherMessage", window.TypeName) : string.Empty; + OtherPanel.Visibility = other ? Visibility.Visible : Visibility.Collapsed; + KeyGrid.Visibility = other ? Visibility.Collapsed : Visibility.Visible; + KeyGrid.RowsChanged(); + ShowCut(window); + StatusText.Text = window.Kind is KeyKind.Text or KeyKind.Other ? string.Empty : ShownWords(window); + UpdateCommands(); + } + + void IKeyTabView.ReleaseRows() + { + KeyGrid.SetData(null); + _rows = null; + } + + void IKeyTabView.ShowMissing() + { + LoadingRing.IsActive = false; + Header.Visibility = Visibility.Collapsed; + KeyGrid.Visibility = Visibility.Collapsed; + OtherPanel.Visibility = Visibility.Collapsed; + ShowBar(CutBar, false); + MissingPanel.Visibility = Visibility.Visible; + StatusText.Text = Strings.Get("KeyStatusMissing"); + UpdateCommands(); + } + + void IKeyTabView.ShowFailure(CoreError failure) + { + LoadingRing.IsActive = false; + ErrorBar.Message = Strings.Error(failure); + // Opened again, so a second failure in a row is announced as well. + ShowBar(ErrorBar, false); + ShowBar(ErrorBar, true); + StatusText.Text = Strings.Get("KeyStatusFailed"); + UpdateCommands(); + } + + void IKeyTabView.ShowStopped() + { + LoadingRing.IsActive = false; + StatusText.Text = Strings.Get("KeyStatusStopped"); + UpdateCommands(); + } + + private static string LengthWords(KeyKind kind, long length) + { + var unit = kind switch + { + KeyKind.Text => "Bytes", + KeyKind.Hash => "Fields", + KeyKind.List => "Elements", + KeyKind.Set or KeyKind.SortedSet => "Members", + _ => "Entries", + }; + return length == 1 + ? Strings.Get("KeyLength" + unit + "One") + : Strings.Format("KeyLength" + unit + "Many", length); + } + + private static string TtlWords(KeyTtl ttl) + { + if (ttl is not KeyTtl.ExpiresIn { Left: var left }) + { + return Strings.Get(ttl is KeyTtl.Persistent ? "KeyTtlNone" : "KeyTtlUnknown"); + } + + // A key with under a second left has not expired, so it reads as one second rather than none. + var seconds = Math.Max(1, (long)left.TotalSeconds); + return seconds switch + { + < 60 => Strings.Format("KeyTtlSeconds", seconds), + < 3_600 => TwoUnits("KeyTtlMinutes", seconds / 60, seconds % 60), + < 86_400 => TwoUnits("KeyTtlHours", seconds / 3_600, (seconds % 3_600) / 60), + _ => TwoUnits("KeyTtlDays", seconds / 86_400, (seconds % 86_400) / 3_600), + }; + } + + private static string TwoUnits(string name, long whole, long part) => + part == 0 ? Strings.Format(name, whole) : Strings.Format(name + "And", whole, part); + + private static string ShownWords(KeyWindow window) => + window.Length is { } length && length > window.Rows + ? Strings.Format("KeyStatusShownOf", window.Rows, length) + : Strings.Format("KeyStatusShown", window.Rows); + + // A string longer than one window: its row holds the start, cut where a character ends. + private void ShowCut(KeyWindow window) + { + string? message = null; + if (window is { Kind: KeyKind.Text, Truncated: true, Length: { } total } && _rows is { RowCount: > 0 } rows) + { + message = Strings.Format("KeyCut", ByteCount(rows.GetCellText(0, 0) ?? string.Empty), total); + } + + CutBar.Message = message ?? string.Empty; + ShowBar(CutBar, message is not null); + } + + // A value that is not UTF-8 reads as 0x and its bytes in hex. + private static long ByteCount(string text) => + text.StartsWith("0x", StringComparison.Ordinal) && text.Length % 2 == 0 && IsHex(text.AsSpan(2)) + ? (text.Length - 2) / 2 + : Encoding.UTF8.GetByteCount(text); + + private static bool IsHex(ReadOnlySpan digits) + { + foreach (var digit in digits) + { + if (!char.IsAsciiHexDigitLower(digit)) + { + return false; + } + } + + return true; + } + + // A closed InfoBar keeps its margin, so a bar is collapsed while it is closed. + private static void ShowBar(InfoBar bar, bool show) + { + bar.Visibility = show ? Visibility.Visible : Visibility.Collapsed; + bar.IsOpen = show; + } + + private void UpdateCommands() + { + RefreshButton.IsEnabled = !_model.IsRunning; + LoadMoreButton.Visibility = _model.Window is { HasMore: true } ? Visibility.Visible : Visibility.Collapsed; + LoadMoreButton.IsEnabled = _model.CanLoadMore; + } + + private void OnErrorBarClosed(InfoBar sender, InfoBarClosedEventArgs args) => + ErrorBar.Visibility = Visibility.Collapsed; + + private async void OnLoadMore(object sender, RoutedEventArgs e) => + await _model.LoadMoreAsync().ConfigureAwait(true); + + private async void OnRefresh(object sender, RoutedEventArgs e) => await _model.LoadAsync().ConfigureAwait(true); +} diff --git a/windows/src/TablePro.App/Views/OpenConnection.cs b/windows/src/TablePro.App/Views/OpenConnection.cs index a7e83b175b..6e7789a877 100644 --- a/windows/src/TablePro.App/Views/OpenConnection.cs +++ b/windows/src/TablePro.App/Views/OpenConnection.cs @@ -20,19 +20,20 @@ public OpenConnection(Workbench workbench, SessionConnection origin) _life = new ConnectionLife( origin, this, new CoreConnector(workbench.Core, View.CredentialPrompter)); _life.Cancelled += (_, _) => Cancelled?.Invoke(this, EventArgs.Empty); + var title = TitleOf(origin); RailItem = new NavigationViewItem { - Content = origin.Name, + Content = title, Tag = this, Icon = EngineIcons.Mark(origin.EngineId, null), }; - AutomationProperties.SetName(RailItem, origin.Name); - AutomationProperties.SetAutomationId(RailItem, "Rail_" + origin.Name); + AutomationProperties.SetName(RailItem, title); + AutomationProperties.SetAutomationId(RailItem, "Rail_" + title); if (origin.EngineId.Length > 0) { AutomationProperties.SetHelpText(RailItem, workbench.EngineName(origin.EngineId)); } - ToolTipService.SetToolTip(RailItem, origin.Name); + ToolTipService.SetToolTip(RailItem, title); } public event EventHandler? StateChanged; @@ -44,6 +45,12 @@ public OpenConnection(Workbench workbench, SessionConnection origin) public string Name => Origin.Name; + // The rail and the title bar name a connection opened in another of its databases with that database. + public string Title => TitleOf(Origin); + + // Another of the server's databases this item opened the saved connection in, null for its own. + public string? Database => Origin.Database; + public Guid? ConnectionId => Origin.ConnectionId; public NavigationViewItem RailItem { get; } @@ -56,8 +63,15 @@ public OpenConnection(Workbench workbench, SessionConnection origin) public bool Matches(Guid? connectionId, string? filePath) => _life.Matches(connectionId, filePath); + public bool IsSame(SessionConnection origin) => _life.IsSame(origin); + public string? Color { get; private set; } + // The library's tags on the connection, which the title bar names as its environment. + public IReadOnlyList Tags { get; private set; } = []; + + public void SetTags(IReadOnlyList tags) => Tags = tags; + // The engine's artwork in the connection's colour, as the macOS rail marks it. public void Mark(string engineId, string? color) { @@ -69,6 +83,7 @@ public void Mark(string engineId, string? color) _life.SetEngine(engineId); Color = color; RailItem.Icon = EngineIcons.Mark(engineId, color); + View.ShowCue(color); // The glyph says the engine to the eye; the item says it to a screen reader. AutomationProperties.SetHelpText(RailItem, _workbench.EngineName(engineId)); } @@ -76,10 +91,10 @@ public void Mark(string engineId, string? color) public void Rename(string name) { _life.Rename(name); - RailItem.Content = name; - AutomationProperties.SetName(RailItem, name); - ToolTipService.SetToolTip(RailItem, name); - View.Rename(name); + RailItem.Content = Title; + AutomationProperties.SetName(RailItem, Title); + ToolTipService.SetToolTip(RailItem, Title); + View.Rename(Title); } public Task ConnectAsync() => _life.ConnectAsync(); @@ -98,6 +113,7 @@ public OpenConnection Adopt() var adopted = new OpenConnection(_workbench, Origin with { Tabs = [], SelectedTab = 0 }); adopted.Mark(Origin.EngineId, Color); + adopted.SetTags(Tags); adopted._life.Adopt(_life); return adopted; } @@ -122,7 +138,7 @@ void IConnectionView.ShowState(ConnectionState state) _ => string.Empty, }; AutomationProperties.SetItemStatus(RailItem, status); - ToolTipService.SetToolTip(RailItem, status.Length == 0 ? Name : $"{Name} ({status})"); + ToolTipService.SetToolTip(RailItem, status.Length == 0 ? Title : $"{Title} ({status})"); StateChanged?.Invoke(this, EventArgs.Empty); } @@ -174,6 +190,9 @@ SessionConnection IConnectionView.Snapshot(SessionConnection or private static Style Badge(string key) => (Style)Application.Current.Resources[key]; + private static string TitleOf(SessionConnection origin) => + origin.Database is { Length: > 0 } database ? Strings.Format("ConnectionInDatabase", origin.Name, database) : origin.Name; + private static string Details(CoreError error) { var lines = new List { error.Message, string.Join(" > ", error.Codes) }; diff --git a/windows/src/TablePro.App/Views/QueryTabView.xaml b/windows/src/TablePro.App/Views/QueryTabView.xaml index 4ff8db22e7..3913ee24e7 100644 --- a/windows/src/TablePro.App/Views/QueryTabView.xaml +++ b/windows/src/TablePro.App/Views/QueryTabView.xaml @@ -31,6 +31,15 @@ Foreground="{ThemeResource TextFillColorSecondaryBrush}" Style="{StaticResource CaptionTextBlockStyle}" /> + + + + @@ -38,6 +47,18 @@ + + +