diff --git a/linux/ARCHITECTURE.md b/linux/ARCHITECTURE.md index bcc585f83f..e687edd48e 100644 --- a/linux/ARCHITECTURE.md +++ b/linux/ARCHITECTURE.md @@ -141,7 +141,7 @@ Each engine builds its trust as `../core/ARCHITECTURE.md`, Trust, says. On Linux The app tells each session what its connection cannot see, as `../core/ARCHITECTURE.md`, Sessions and health, describes: `GNetworkMonitor` reports a change in the network, and while a session is open a 5 s timer compares `CLOCK_BOOTTIME` with `CLOCK_MONOTONIC` to notice a suspend. A session parked on an SSH host key shows the fingerprint in its banner's Review Key. When the review cannot accept the key, because ssh's configuration takes keys only from known_hosts or the key is revoked, its dialog offers Retry for after the user fixes the key outside TablePro. -The sidebar's tree lists an open connection's schemas, the default one first and the engine's own last, and each schema's tables and views, with one menu whose items carry the table they act on. Its rows come from a `SidebarIndex`, sorted by collation key and given its search keys on a blocking thread, behind a `GListModel` that makes a row's object only when asked for it; `GtkTreeListModel` asks for every table of a schema it opens. Each search, and each new list, picks the rows it keeps on a blocking thread too. What a search finds is a flat `GtkListView`, a section per schema in a `GtkFlattenListModel` that reads only the rows on screen, and it takes a search's rows in one removal and one addition unless a newer search or list overtook them. It follows every schema's list through a watch the window drops before the session closes, and reads that list again when a reconnect commits the default schema's; a refresh that fails keeps the list and says so in a toast. The editor's completion reads the catalog when it opens: the default schema's objects, a named schema's objects after `schema.`, and the columns of the tables the statement names. Its candidates are built with that read on the runtime, and its `ProposalList` ranks them for the typed word and makes a proposal only for a row GtkSourceView shows. Either list thus costs the GTK thread the rows on screen, not the catalog, which the large-catalog case checks with 50,000 tables ([testing.md](docs/testing.md#large-catalog-case)). +The sidebar's tree lists an open connection's schemas, the default one first and the engine's own last, and each schema's tables and views, with one menu whose items carry the table they act on. Its rows come from a `SidebarIndex`, sorted by collation key and given its search keys on a blocking thread, behind a `GListModel` that makes a row's object only when asked for it; `GtkTreeListModel` asks for every table of a schema it opens. Each search, and each new list, picks the rows it keeps on a blocking thread too. What a search finds is a flat `GtkListView`, a section per schema in a `GtkFlattenListModel` that reads only the rows on screen, and it takes a search's rows in one removal and one addition unless a newer search or list overtook them. The Schemas button in the sidebar's bottom bar keeps the schemas the tree and its search list, by connection and database in the filter settings file; none kept lists every schema, and a banner says how many a filter leaves out. It follows every schema's list through a watch the window drops before the session closes, and reads that list again when a reconnect commits the default schema's; a refresh that fails keeps the list and says so in a toast. The editor's completion reads the catalog when it opens: the default schema's objects, a named schema's objects after `schema.`, and the columns of the tables the statement names. Its candidates are built with that read on the runtime, and its `ProposalList` ranks them for the typed word and makes a proposal only for a row GtkSourceView shows. Either list thus costs the GTK thread the rows on screen, not the catalog, which the large-catalog case checks with 50,000 tables ([testing.md](docs/testing.md#large-catalog-case)). ## Workspace tab system diff --git a/linux/changelog.d/4150.added.md b/linux/changelog.d/4150.added.md new file mode 100644 index 0000000000..6189891878 --- /dev/null +++ b/linux/changelog.d/4150.added.md @@ -0,0 +1 @@ +The sidebar's Schemas button chooses which schemas it lists, and remembers the choice for each connection. diff --git a/linux/crates/app/src/persistence/filter_settings_document.rs b/linux/crates/app/src/persistence/filter_settings_document.rs index decb964392..a154ba752a 100644 --- a/linux/crates/app/src/persistence/filter_settings_document.rs +++ b/linux/crates/app/src/persistence/filter_settings_document.rs @@ -1,8 +1,8 @@ -use std::collections::HashMap; +use std::collections::{BTreeSet, HashMap}; use serde::{Deserialize, Serialize}; use tablepro_core::FilterSet; -use tablepro_storage::document::VersionedDocument; +use tablepro_storage::document::{Upgrade, VersionedDocument}; /// Per-table filters, keyed connection, schema, table. /// @@ -12,12 +12,23 @@ use tablepro_storage::document::VersionedDocument; pub struct FilterSettingsDocument { #[serde(default)] pub connections: HashMap, + // A schema name means something only inside its database, so each + // database of a connection keeps its own. + #[serde(default)] + pub sidebar_schemas: HashMap, } pub type Schemas = HashMap; pub type Tables = HashMap; +pub type SidebarSchemas = HashMap>; impl VersionedDocument for FilterSettingsDocument { const KIND: &'static str = "filter-settings"; - const VERSION: u32 = 1; + const VERSION: u32 = 2; + const UPGRADES: &'static [Upgrade] = &[keep_v1]; +} + +// Version 1 had no sidebar filters, which read as none. +fn keep_v1(document: serde_json::Value) -> Result { + Ok(document) } diff --git a/linux/crates/app/src/persistence/filter_settings_store.rs b/linux/crates/app/src/persistence/filter_settings_store.rs index dc396471b9..1d38294e02 100644 --- a/linux/crates/app/src/persistence/filter_settings_store.rs +++ b/linux/crates/app/src/persistence/filter_settings_store.rs @@ -1,3 +1,4 @@ +use std::collections::BTreeSet; use std::rc::Rc; use tablepro_core::FilterSet; @@ -60,13 +61,53 @@ impl FilterSettingsStore { }); } + pub fn sidebar_schemas(&self, connection_id: Uuid, database: &str) -> BTreeSet { + self.file.read(|document| { + document + .sidebar_schemas + .get(&connection_id.to_string()) + .and_then(|databases| databases.get(database)) + .cloned() + .unwrap_or_default() + }) + } + + pub fn set_sidebar_schemas(&self, connection_id: Uuid, database: &str, kept: &BTreeSet) { + self.file.update(|document| { + let connection = connection_id.to_string(); + if kept.is_empty() { + let Some(databases) = document.sidebar_schemas.get_mut(&connection) else { + return false; + }; + let removed = databases.remove(database).is_some(); + if databases.is_empty() { + document.sidebar_schemas.remove(&connection); + } + return removed; + } + let slot = document + .sidebar_schemas + .entry(connection) + .or_default() + .entry(database.to_owned()) + .or_default(); + if slot == kept { + return false; + } + slot.clone_from(kept); + true + }); + } + pub fn forget_connection(&self, connection_id: Uuid) { + let connection = connection_id.to_string(); self.file.update(|document| { let before = document.connections.len(); document .connections .retain(|key, _| !TableStateKey::belongs_to(key, connection_id)); - before != document.connections.len() + let filters = before != document.connections.len(); + document.sidebar_schemas.remove(&connection).is_some() || filters }); } @@ -188,6 +229,48 @@ mod tests { assert!(store.filters(dropped, Some("public"), "users").is_empty()); } + #[tokio::test] + async fn the_sidebars_schemas_are_kept_per_database_and_go_with_the_connection() { + let root = tempfile::tempdir().expect("tempdir"); + let path = root.path().join("filter-settings.json"); + let id = Uuid::new_v4(); + let kept = BTreeSet::from(["public".to_owned(), "sales".to_owned()]); + let store = FilterSettingsStore::load(path.clone(), &paused_tasks()); + store.set_sidebar_schemas(id, "shop", &kept); + store.set_filters(id, None, "users", sample_set()); + store.flush().await.expect("saved"); + + let reopened = FilterSettingsStore::load(path.clone(), &paused_tasks()); + assert_eq!(reopened.sidebar_schemas(id, "shop"), kept); + assert!(reopened.sidebar_schemas(id, "other").is_empty()); + + reopened.set_sidebar_schemas(id, "shop", &BTreeSet::new()); + assert!(reopened.sidebar_schemas(id, "shop").is_empty()); + reopened.set_sidebar_schemas(id, "shop", &kept); + reopened.forget_connection(id); + reopened.flush().await.expect("saved"); + let written = std::fs::read_to_string(&path).expect("the file"); + assert!( + !written.contains("sales"), + "the deleted connection's schemas stayed: {written}" + ); + } + + #[tokio::test] + async fn a_version_1_file_keeps_its_filters_and_has_no_sidebar_filter() { + let root = tempfile::tempdir().expect("tempdir"); + let path = root.path().join("filter-settings.json"); + let id = Uuid::new_v4(); + let filter = serde_json::to_string(&sample_set()).expect("the filter"); + let written = format!(r#"{{"version": 1, "connections": {{"{id}": {{"": {{"users": {filter}}}}}}}}}"#); + std::fs::write(&path, written).expect("the old file"); + + let store = FilterSettingsStore::load(path, &paused_tasks()); + + assert_eq!(store.filters(id, None, "users"), sample_set()); + assert!(store.sidebar_schemas(id, "").is_empty()); + } + #[tokio::test] async fn a_saved_filter_survives_a_reopen() { let root = tempfile::tempdir().expect("tempdir"); diff --git a/linux/crates/app/src/ui/workspace/imp.rs b/linux/crates/app/src/ui/workspace/imp.rs index 35933e54a3..e6b6aaa91b 100644 --- a/linux/crates/app/src/ui/workspace/imp.rs +++ b/linux/crates/app/src/ui/workspace/imp.rs @@ -31,6 +31,8 @@ pub struct Workspace { #[template_child] pub catalog_banner: TemplateChild, #[template_child] + pub schema_filter_banner: TemplateChild, + #[template_child] pub key_limit_banner: TemplateChild, /// The content header's title while the session is in front: the @@ -58,6 +60,9 @@ pub struct Workspace { pub(super) can_refresh: Cell, #[property(get)] pub(super) creation_menu: RefCell>, + // Empty while the session's sidebar has no schemas to choose among. + #[property(get)] + pub(super) schema_filter_label: RefCell, pub(super) key: OnceCell, // File sessions and saved connections must use the editor save's identity. diff --git a/linux/crates/app/src/ui/workspace/mod.rs b/linux/crates/app/src/ui/workspace/mod.rs index 67f1db119d..98dc26594a 100644 --- a/linux/crates/app/src/ui/workspace/mod.rs +++ b/linux/crates/app/src/ui/workspace/mod.rs @@ -22,6 +22,8 @@ mod import_ledger; mod recent_tabs; mod references; mod saves; +mod schema_chooser; +mod schema_filter; mod session_watches; mod sidebar; mod status_pages; @@ -134,6 +136,7 @@ pub(crate) struct WorkspaceModel { /// The last schema read the sidebar asked for; an older one landing /// late is not shown. sidebar_read: u64, + schema_filter: schema_chooser::SidebarFilter, definition_reads: u64, /// The Show Definition read in flight, which a newer one supersedes. definition_read: Option, @@ -520,6 +523,11 @@ pub(crate) enum WorkspaceInput { read: u64, listing: sidebar::SidebarListing, }, + ShowSchema { + name: String, + shown: bool, + }, + ShowAllSchemas, /// List a key-value engine's keys again, as the search now asks. ListKeys, /// The keys a listing found, indexed for the sidebar, or why they @@ -868,6 +876,7 @@ impl Workspace { sidebar, catalog_schemas: Arc::from([]), sidebar_read: 0, + schema_filter: schema_chooser::SidebarFilter::new(&workspace), definition_reads: 0, definition_read: None, all_schemas_listed: false, @@ -949,6 +958,18 @@ impl Workspace { self.notify_creation_menu(); } + fn show_schema_filter_label(&self, label: String) { + if *self.imp().schema_filter_label.borrow() != label { + self.imp().schema_filter_label.replace(label); + self.notify_schema_filter_label(); + } + } + + // None while the workspace is handling input. + pub(super) fn schema_choices(&self) -> Option { + self.read(WorkspaceModel::schema_choices) + } + /// The key the session is open under. pub(crate) fn key(&self) -> Option { self.imp().key.get().cloned() @@ -1182,6 +1203,7 @@ impl WorkspaceModel { fn open(&mut self) { self.reconnect_banner.set_revealed(false); tracing::info!(driver = %self.driver_id, "workspace ready"); + self.load_schema_filter(); self.open_sidebar(); self.refresh_title(); self.restore_workspace_tabs(self.key.clone()); @@ -1358,6 +1380,8 @@ impl WorkspaceModel { WorkspaceInput::RefreshCatalog => self.refresh_catalog(), WorkspaceInput::DefaultListCommitted(snapshot) => self.on_default_list_committed(snapshot), WorkspaceInput::SidebarRead { read, listing } => self.on_sidebar_read(read, listing), + WorkspaceInput::ShowSchema { name, shown } => self.on_schema_shown(&name, shown), + WorkspaceInput::ShowAllSchemas => self.on_all_schemas_shown(), WorkspaceInput::ListKeys => self.list_keys(), WorkspaceInput::KeysListed(listed) => self.on_keys_listed(listed), WorkspaceInput::LinkChanged => self.on_link_changed(), diff --git a/linux/crates/app/src/ui/workspace/schema_chooser.rs b/linux/crates/app/src/ui/workspace/schema_chooser.rs new file mode 100644 index 0000000000..197b2367bc --- /dev/null +++ b/linux/crates/app/src/ui/workspace/schema_chooser.rs @@ -0,0 +1,378 @@ +use std::cell::RefCell; +use std::rc::Rc; +use std::sync::Arc; + +use gtk4 as gtk; +use gtk4::glib; +use gtk4::prelude::*; +use gtk4::subclass::prelude::*; +use libadwaita as adw; +use tablepro_core::meta::{ObjectInfo, SchemaInfo}; + +use super::schema_filter::SchemaFilter; +use super::{Workspace, WorkspaceInput, WorkspaceModel, WorkspaceSender}; +use crate::i18n::{gettext, ngettext_f}; +use crate::runtime::DeliverInput; + +pub(super) struct SidebarFilter { + filter: SchemaFilter, + banner: adw::Banner, + // A change of filter lists these again. + objects: Arc<[ObjectInfo]>, +} + +impl SidebarFilter { + pub(super) fn new(workspace: &Workspace) -> Self { + let banner = workspace.imp().schema_filter_banner.get(); + if let Some(input) = workspace.sender() { + banner.connect_button_clicked(move |_| input.deliver(WorkspaceInput::ShowAllSchemas)); + } + Self { + filter: SchemaFilter::default(), + banner, + objects: Arc::from([]), + } + } + + pub(super) fn filter(&self) -> SchemaFilter { + self.filter.clone() + } + + pub(super) fn remember(&mut self, objects: &Arc<[ObjectInfo]>) { + self.objects = objects.clone(); + } +} + +pub(crate) struct SchemaChoices { + schemas: Arc<[SchemaInfo]>, + filter: SchemaFilter, + // Where the schemas are the server's databases, the user knows them as databases. + databases: bool, +} + +impl SchemaChoices { + fn summary(&self) -> String { + match self.filter.summary(&self.schemas) { + Some((shown, total)) => showing(self.databases, shown, total), + None if self.databases => gettext("Showing all databases"), + None => gettext("Showing all schemas"), + } + } +} + +fn showing(databases: bool, shown: usize, total: usize) -> String { + let (shown, count) = (shown.to_string(), total.to_string()); + let args = [("shown", shown.as_str()), ("total", count.as_str())]; + if databases { + ngettext_f( + "Showing {shown} of {total} database", + "Showing {shown} of {total} databases", + total, + &args, + ) + } else { + ngettext_f( + "Showing {shown} of {total} schema", + "Showing {shown} of {total} schemas", + total, + &args, + ) + } +} + +impl WorkspaceModel { + pub(super) fn schema_choices(&self) -> SchemaChoices { + SchemaChoices { + schemas: self.catalog_schemas.clone(), + filter: self.schema_filter.filter(), + databases: self.sidebar.affordances().lists_databases, + } + } + + pub(super) fn load_schema_filter(&mut self) { + if let Some(session) = self.context.active.get() { + let kept = self + .storage + .filter_settings() + .sidebar_schemas(session.metadata().id, session.database().unwrap_or_default()); + self.schema_filter.filter = SchemaFilter::new(kept); + } + } + + pub(super) fn on_schema_shown(&mut self, name: &str, shown: bool) { + if self.schema_filter.filter.set_shown(&self.catalog_schemas, name, shown) { + self.keep_schema_filter(); + } + } + + pub(super) fn on_all_schemas_shown(&mut self) { + if self.schema_filter.filter.show_all() { + self.keep_schema_filter(); + } + } + + fn keep_schema_filter(&mut self) { + if let Some(session) = self.context.active.get() { + self.storage.filter_settings().set_sidebar_schemas( + session.metadata().id, + session.database().unwrap_or_default(), + self.schema_filter.filter.kept(), + ); + } + self.show_schema_filter(); + self.read_sidebar(self.schema_filter.objects.clone()); + } + + // A filtered list looks like a short one, so the banner says it is filtered. + pub(super) fn show_schema_filter(&self) { + let choices = self.schema_choices(); + let offered = self.keys.is_none() && choices.schemas.len() > 1; + let summary = choices.filter.summary(&choices.schemas).filter(|_| offered); + if let Some((shown, total)) = summary { + self.schema_filter + .banner + .set_title(&showing(choices.databases, shown, total)); + } + self.schema_filter.banner.set_revealed(summary.is_some()); + let label = match (offered, choices.databases) { + (false, _) => String::new(), + (true, true) => gettext("Databases"), + (true, false) => gettext("Schemas"), + }; + if let Some(workspace) = self.this.upgrade() { + workspace.show_schema_filter_label(label); + } + } +} + +struct Chooser { + choices: RefCell, + input: WorkspaceSender, + // Weak, since the widgets' handlers hold the chooser. + summary: glib::WeakRef, + show_all: glib::WeakRef, + checks: RefCell>>, +} + +impl Chooser { + fn toggle(self: &Rc, name: &str, shown: bool) { + let changed = { + let mut choices = self.choices.borrow_mut(); + let SchemaChoices { schemas, filter, .. } = &mut *choices; + filter.set_shown(schemas, name, shown) + }; + if changed { + self.input.deliver(WorkspaceInput::ShowSchema { + name: name.to_owned(), + shown, + }); + } + self.refresh(); + } + + fn show_all(self: &Rc) { + if self.choices.borrow_mut().filter.show_all() { + self.input.deliver(WorkspaceInput::ShowAllSchemas); + } + self.refresh(); + } + + // From idle, as the check that was toggled is still emitting its signal. The rows + // change in place: a new list would drop the row that holds the focus. + fn refresh(self: &Rc) { + self.show_summary(); + let chooser = Rc::downgrade(self); + glib::idle_add_local_once(move || { + if let Some(chooser) = chooser.upgrade() { + let checks: Vec = chooser + .checks + .borrow() + .iter() + .filter_map(glib::WeakRef::upgrade) + .collect(); + for check in checks { + chooser.show_state(&check); + } + } + }); + } + + fn show_state(&self, check: >k::CheckButton) { + let Some(name) = check.label() else { + return; + }; + let choices = self.choices.borrow(); + let shows = choices.shows(&name); + check.set_active(shows); + // The last schema listed stays listed. + let last = shows + && choices + .filter + .summary(&choices.schemas) + .is_some_and(|(shown, _)| shown == 1); + check.set_sensitive(!last); + } + + fn show_summary(&self) { + let choices = self.choices.borrow(); + if let Some(summary) = self.summary.upgrade() { + summary.set_label(&choices.summary()); + } + if let Some(show_all) = self.show_all.upgrade() { + show_all.set_sensitive(choices.filter.summary(&choices.schemas).is_some()); + } + } +} + +// Built each time it opens, so it lists the schemas of the session in front as they are then. +pub(super) fn popover(choices: SchemaChoices, input: WorkspaceSender) -> gtk::Popover { + let databases = choices.databases; + let names = gtk::StringList::new( + &choices + .schemas + .iter() + .map(|schema| schema.name.as_str()) + .collect::>(), + ); + let summary = gtk::Label::builder() + .xalign(0.0) + .hexpand(true) + .ellipsize(gtk::pango::EllipsizeMode::End) + .css_classes(["caption", "dimmed"]) + .build(); + let show_all = gtk::Button::builder() + .label(gettext("Show _All")) + .use_underline(true) + .css_classes(["flat"]) + .build(); + let chooser = Rc::new(Chooser { + choices: RefCell::new(choices), + input, + summary: summary.downgrade(), + show_all: show_all.downgrade(), + checks: RefCell::default(), + }); + chooser.show_summary(); + show_all.connect_clicked(glib::clone!( + #[strong] + chooser, + move |_| chooser.show_all() + )); + let (search, filter) = search_over_names(databases); + let list = gtk::ListView::builder() + .model(>k::NoSelection::new(Some(gtk::FilterListModel::new( + Some(names), + Some(filter), + )))) + .factory(&check_factory(&chooser)) + .build(); + let scrolled = gtk::ScrolledWindow::builder() + .child(&list) + .hscrollbar_policy(gtk::PolicyType::Never) + .propagate_natural_height(true) + .max_content_height(320) + .min_content_width(240) + .build(); + let footer = gtk::Box::builder().spacing(12).build(); + footer.append(&summary); + footer.append(&show_all); + let content = gtk::Box::builder() + .orientation(gtk::Orientation::Vertical) + .spacing(6) + .build(); + content.append(&search); + content.append(&scrolled); + content.append(>k::Separator::new(gtk::Orientation::Horizontal)); + content.append(&footer); + gtk::Popover::builder().child(&content).build() +} + +fn search_over_names(databases: bool) -> (gtk::SearchEntry, gtk::StringFilter) { + let searching = if databases { + gettext("Search databases") + } else { + gettext("Search schemas") + }; + let search = gtk::SearchEntry::builder().placeholder_text(&searching).build(); + search.update_property(&[gtk::accessible::Property::Label(&searching)]); + let filter = gtk::StringFilter::builder() + .expression(gtk::PropertyExpression::new( + gtk::StringObject::static_type(), + None::, + "string", + )) + .ignore_case(true) + .match_mode(gtk::StringFilterMatchMode::Substring) + .build(); + search.connect_search_changed(glib::clone!( + #[weak] + filter, + move |search| filter.set_search(Some(&search.text())) + )); + (search, filter) +} + +fn check_factory(chooser: &Rc) -> gtk::SignalListItemFactory { + let factory = gtk::SignalListItemFactory::new(); + factory.connect_setup(glib::clone!( + #[strong] + chooser, + move |_, item| { + if let Some(item) = item.downcast_ref::() { + item.set_child(Some(&check(&chooser, item))); + } + } + )); + factory.connect_bind(glib::clone!( + #[strong] + chooser, + move |_, item| { + if let Some(item) = item.downcast_ref::() { + show_check(&chooser, item); + } + } + )); + factory +} + +fn check(chooser: &Rc, item: >k::ListItem) -> gtk::CheckButton { + // The check takes the focus, so Space toggles it and the arrows move between rows. + item.set_focusable(false); + item.set_activatable(false); + let check = gtk::CheckButton::new(); + let mut checks = chooser.checks.borrow_mut(); + checks.retain(|check| check.upgrade().is_some()); + checks.push(check.downgrade()); + drop(checks); + check.connect_toggled(glib::clone!( + #[strong] + chooser, + move |check| { + let Some(name) = check.label() else { + return; + }; + let shown = chooser.choices.borrow().shows(&name); + if check.is_active() != shown { + chooser.toggle(&name, check.is_active()); + } + } + )); + check +} + +fn show_check(chooser: &Chooser, item: >k::ListItem) { + let (Some(check), Some(name)) = ( + item.child().and_downcast::(), + item.item().and_downcast::(), + ) else { + return; + }; + check.set_label(Some(&name.string())); + chooser.show_state(&check); +} + +impl SchemaChoices { + fn shows(&self, name: &str) -> bool { + self.filter.shows(&self.schemas, name) + } +} diff --git a/linux/crates/app/src/ui/workspace/schema_filter.rs b/linux/crates/app/src/ui/workspace/schema_filter.rs new file mode 100644 index 0000000000..7f33654cab --- /dev/null +++ b/linux/crates/app/src/ui/workspace/schema_filter.rs @@ -0,0 +1,201 @@ +use std::borrow::Cow; +use std::collections::{BTreeSet, HashSet}; + +use tablepro_core::meta::{ObjectInfo, SchemaInfo}; + +// The schemas kept, as the macOS app keeps them: none kept lists every +// schema, and a schema made later stays out of a filter until it is added. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub(crate) struct SchemaFilter { + kept: BTreeSet, +} + +impl SchemaFilter { + pub(crate) fn new(kept: BTreeSet) -> Self { + Self { kept } + } + + pub(crate) fn kept(&self) -> &BTreeSet { + &self.kept + } + + // A kept name the list no longer holds counts for nothing, so a filter + // of dropped schemas lists every schema rather than none. + fn shown<'a>(&self, schemas: &'a [SchemaInfo]) -> Option> { + let shown: HashSet<&str> = schemas + .iter() + .map(|schema| schema.name.as_str()) + .filter(|name| self.kept.contains(*name)) + .collect(); + (!shown.is_empty() && shown.len() < schemas.len()).then_some(shown) + } + + pub(crate) fn shows(&self, schemas: &[SchemaInfo], name: &str) -> bool { + self.shown(schemas).is_none_or(|shown| shown.contains(name)) + } + + pub(crate) fn summary(&self, schemas: &[SchemaInfo]) -> Option<(usize, usize)> { + self.shown(schemas).map(|shown| (shown.len(), schemas.len())) + } + + // The last schema listed stays, and listing every schema clears the filter. + pub(crate) fn set_shown(&mut self, schemas: &[SchemaInfo], name: &str, shown: bool) -> bool { + if !schemas.iter().any(|schema| schema.name == name) || self.shows(schemas, name) == shown { + return false; + } + let mut kept: BTreeSet = schemas + .iter() + .filter(|schema| self.shows(schemas, &schema.name)) + .map(|schema| schema.name.clone()) + .collect(); + if shown { + kept.insert(name.to_owned()); + } else { + kept.remove(name); + } + if kept.is_empty() { + return false; + } + if kept.len() == schemas.len() { + kept.clear(); + } + self.kept = kept; + true + } + + pub(crate) fn show_all(&mut self) -> bool { + !std::mem::take(&mut self.kept).is_empty() + } + + // An object with no schema is the default schema's. + pub(crate) fn listed<'a>( + &self, + objects: &'a [ObjectInfo], + schemas: &'a [SchemaInfo], + ) -> (Cow<'a, [ObjectInfo]>, Cow<'a, [SchemaInfo]>) { + let Some(shown) = self.shown(schemas) else { + return (Cow::Borrowed(objects), Cow::Borrowed(schemas)); + }; + let default = schemas + .iter() + .find(|schema| schema.is_default) + .map(|schema| schema.name.as_str()); + let objects = objects + .iter() + .filter(|object| { + object + .schema + .as_deref() + .or(default) + .is_none_or(|schema| shown.contains(schema)) + }) + .cloned() + .collect(); + let schemas = schemas + .iter() + .filter(|schema| shown.contains(schema.name.as_str())) + .cloned() + .collect(); + (Cow::Owned(objects), Cow::Owned(schemas)) + } +} + +#[cfg(test)] +mod tests { + use tablepro_core::meta::ObjectKind; + + use super::*; + + fn object(schema: Option<&str>, name: &str) -> ObjectInfo { + ObjectInfo::new(schema.map(str::to_owned), name, ObjectKind::Table) + } + + fn schemas(names: &[&str]) -> Vec { + names + .iter() + .enumerate() + .map(|(at, name)| SchemaInfo { + name: (*name).to_owned(), + is_default: at == 0, + is_system: false, + }) + .collect() + } + + fn names(items: &[T], name: impl Fn(&T) -> &str) -> Vec<&str> { + items.iter().map(name).collect() + } + + fn kept(filter: &SchemaFilter) -> Vec<&str> { + filter.kept().iter().map(String::as_str).collect() + } + + #[test] + fn nothing_kept_lists_everything_without_a_copy() { + let (objects, schemas) = (vec![object(Some("public"), "users")], schemas(&["public", "sales"])); + let filter = SchemaFilter::default(); + + let (listed_objects, listed_schemas) = filter.listed(&objects, &schemas); + + assert!(matches!(listed_objects, Cow::Borrowed(_))); + assert!(matches!(listed_schemas, Cow::Borrowed(_))); + assert_eq!(filter.summary(&schemas), None); + } + + #[test] + fn a_schema_left_out_takes_its_objects_and_the_default_keeps_those_with_no_schema() { + let objects = vec![ + object(Some("public"), "users"), + object(Some("sales"), "leads"), + object(None, "settings"), + ]; + let schemas = schemas(&["public", "sales"]); + let mut filter = SchemaFilter::default(); + + assert!(filter.set_shown(&schemas, "sales", false)); + let (shown, listed) = filter.listed(&objects, &schemas); + assert_eq!(names(&shown, |object| &object.name), ["users", "settings"]); + assert_eq!(names(&listed, |schema| &schema.name), ["public"]); + assert_eq!(filter.summary(&schemas), Some((1, 2))); + + let mut other = SchemaFilter::default(); + assert!(other.set_shown(&schemas, "public", false)); + assert_eq!( + names(&other.listed(&objects, &schemas).0, |object| &object.name), + ["leads"] + ); + } + + #[test] + fn a_schema_made_later_stays_out_until_it_is_listed() { + let mut filter = SchemaFilter::default(); + assert!(filter.set_shown(&schemas(&["public", "sales", "audit"]), "audit", false)); + assert_eq!(kept(&filter), ["public", "sales"]); + + let grown = schemas(&["public", "sales", "audit", "billing"]); + assert!(!filter.shows(&grown, "billing")); + assert_eq!(filter.summary(&grown), Some((2, 4))); + } + + #[test] + fn the_last_schema_listed_stays_and_listing_every_one_clears_the_filter() { + let schemas = schemas(&["public", "sales"]); + let mut filter = SchemaFilter::default(); + assert!(filter.set_shown(&schemas, "sales", false)); + + assert!(!filter.set_shown(&schemas, "public", false), "nothing would be listed"); + assert!(!filter.set_shown(&schemas, "nowhere", true)); + assert!(filter.set_shown(&schemas, "sales", true)); + assert!(filter.kept().is_empty()); + assert!(!filter.show_all(), "Show All with nothing left out"); + } + + #[test] + fn a_kept_schema_that_was_dropped_counts_for_nothing() { + let filter = SchemaFilter::new(BTreeSet::from(["gone".to_owned()])); + let schemas = schemas(&["public", "sales"]); + + assert_eq!(filter.summary(&schemas), None); + assert!(filter.shows(&schemas, "sales")); + } +} diff --git a/linux/crates/app/src/ui/workspace/sidebar/mod.rs b/linux/crates/app/src/ui/workspace/sidebar/mod.rs index b4379a4a1c..5e75d869ad 100644 --- a/linux/crates/app/src/ui/workspace/sidebar/mod.rs +++ b/linux/crates/app/src/ui/workspace/sidebar/mod.rs @@ -43,6 +43,7 @@ use sidebar_index::SidebarIndex; pub(super) use sidebar_view::SidebarView; pub(super) use tree_menu::creation_menu; +use super::schema_filter::SchemaFilter; use super::table_naming::TableNaming; use super::{OpenMode, WorkspaceInput, WorkspaceModel, WorkspaceSender}; use crate::runtime::DeliverInput; @@ -122,6 +123,7 @@ pub(super) async fn list_catalog( tasks: Tasks, objects: Arc<[ObjectInfo]>, known: Arc<[SchemaInfo]>, + filter: SchemaFilter, ) -> Result { let schemas = match session.schemas().await { Ok(schemas) => Some(schemas), @@ -134,8 +136,9 @@ pub(super) async fn list_catalog( let database = session.database().map(str::to_owned); tasks .spawn_blocking_task(move || { - let listed = schemas.as_deref().unwrap_or(&known); - let mut index = SidebarIndex::build(&objects, listed); + let (shown, listed) = filter.listed(&objects, schemas.as_deref().unwrap_or(&known)); + let listed = &*listed; + let mut index = SidebarIndex::build(&shown, listed); index.withhold_drops(|name| kept(dialect.as_deref(), database.as_deref(), name)); if dialect .as_deref() @@ -210,18 +213,20 @@ impl WorkspaceModel { /// Read the session's schemas, which place the sidebar's sections and /// decide whether tab titles name their schema, then show `objects` /// under them. Only the last read asked for is shown. - fn read_sidebar(&mut self, objects: Arc<[ObjectInfo]>) { + pub(super) fn read_sidebar(&mut self, objects: Arc<[ObjectInfo]>) { let Some(session) = self.context.active.get() else { return; }; self.sidebar_read += 1; let read = self.sidebar_read; let input = self.input.clone(); + self.schema_filter.remember(&objects); let listing = list_catalog( session, self.context.tasks.clone(), objects, self.catalog_schemas.clone(), + self.schema_filter.filter(), ); crate::runtime::spawn_and_deliver(&self.context.tasks, listing, move |listing| { match listing.and_then(|listing| listing) { @@ -241,6 +246,7 @@ impl WorkspaceModel { self.catalog_schemas = schemas; } self.sidebar.show(listing.index); + self.show_schema_filter(); self.on_table_naming(TableNaming::of(&self.catalog_schemas)); } diff --git a/linux/crates/app/src/ui/workspace/tests/large_catalog.rs b/linux/crates/app/src/ui/workspace/tests/large_catalog.rs index 88bd8a8383..15201659d9 100644 --- a/linux/crates/app/src/ui/workspace/tests/large_catalog.rs +++ b/linux/crates/app/src/ui/workspace/tests/large_catalog.rs @@ -839,7 +839,7 @@ impl Screen { .objects(ObjectScope::AllSchemas) .await .map_err(|error| error.to_string())?; - list_catalog(session, runtime, objects, Arc::from([])) + list_catalog(session, runtime, objects, Arc::from([]), Default::default()) .await .map_err(|failure| failure.to_string()) }); diff --git a/linux/crates/app/src/ui/workspace/tests/shell.rs b/linux/crates/app/src/ui/workspace/tests/shell.rs index 262c6ac416..92d0a0085e 100644 --- a/linux/crates/app/src/ui/workspace/tests/shell.rs +++ b/linux/crates/app/src/ui/workspace/tests/shell.rs @@ -892,3 +892,57 @@ fn a_read_only_connection_has_no_add_menu() { assert!(!imp.sidebar_add_button.is_visible()); assert!(!imp.sidebar_bar.is_revealed()); } + +#[gtk4::test] +fn the_schemas_button_chooses_what_the_sidebar_lists_and_keeps_it() { + let test = TestWindow::connected("SchemaFilter"); + let workspace = test.workspace(); + let shell = shell_of(&workspace); + let (button, bar) = (shell.imp().schema_filter_button.get(), shell.imp().sidebar_bar.get()); + let banner = workspace.imp().schema_filter_banner.get(); + assert!(!button.is_visible(), "one schema has nothing to choose among"); + + let schema = |name: &str| tablepro_core::meta::SchemaInfo { + name: name.to_owned(), + is_default: name == "public", + is_system: false, + }; + let session = workspace + .read(|model| model.context.active.get()) + .flatten() + .expect("the session"); + session + .catalog() + .commit(vec![schema("public"), schema("sales")], Vec::new()); + wait_until(WAIT, || button.is_visible()).expect("the Schemas button"); + assert_eq!(button.label().as_deref(), Some("Schemas")); + assert!(bar.is_revealed()); + assert!(!banner.is_revealed()); + + button.popup(); + let popover = button.popover().expect("the chooser"); + let check = |name: &str| { + descendants(&popover) + .into_iter() + .filter_map(|widget| widget.downcast::().ok()) + .find(|check| check.label().as_deref() == Some(name)) + }; + wait_until(WAIT, || check("sales").is_some()).expect("a check for each schema"); + let sales = check("sales").expect("the sales check"); + sales.set_active(false); + wait_until(WAIT, || banner.is_revealed()).expect("the banner"); + assert_eq!(banner.title(), "Showing 1 of 2 schemas"); + let (id, database) = (session.metadata().id, session.database().unwrap_or_default().to_owned()); + let filters = test.services.storage.filter_settings().clone(); + assert_eq!( + filters.sidebar_schemas(id, &database), + std::collections::BTreeSet::from(["public".to_owned()]) + ); + wait_until(WAIT, || check("public").is_some_and(|check| !check.is_sensitive())) + .expect("the last schema listed stays"); + assert_eq!(check("sales"), Some(sales), "the row and its focus stay"); + + banner.emit_by_name::<()>("button-clicked", &[]); + wait_until(WAIT, || !banner.is_revealed()).expect("Show All"); + assert!(filters.sidebar_schemas(id, &database).is_empty()); +} diff --git a/linux/crates/app/src/ui/workspace/workspace_shell.rs b/linux/crates/app/src/ui/workspace/workspace_shell.rs index f8435db5d9..1122d2022a 100644 --- a/linux/crates/app/src/ui/workspace/workspace_shell.rs +++ b/linux/crates/app/src/ui/workspace/workspace_shell.rs @@ -396,6 +396,14 @@ impl WorkspaceShell { ), ) .bind(&imp.sidebar_add_button.get(), "visible", Some(self)), + of_front("schema-filter-label").bind(&imp.schema_filter_button.get(), "label", Some(self)), + gtk::ClosureExpression::new::( + [of_front("schema-filter-label")], + glib::closure!( + |_: Option, label: Option| label.is_some_and(|label| !label.is_empty()) + ), + ) + .bind(&imp.schema_filter_button.get(), "visible", Some(self)), ]; if let Some(window) = imp.window.upgrade() { watches.push(of_front("window-title").bind(&window, "title", Some(self))); @@ -728,19 +736,33 @@ impl WorkspaceShell { } fn connect_sidebar_bar(&self) { - self.imp().sidebar_add_button.connect_visible_notify(glib::clone!( + let imp = self.imp(); + for button in [imp.sidebar_add_button.get(), imp.schema_filter_button.get()] { + button.connect_visible_notify(glib::clone!( + #[weak(rename_to = shell)] + self, + move |_| shell.show_sidebar_bar() + )); + } + imp.schema_filter_button.set_create_popup_func(glib::clone!( #[weak(rename_to = shell)] self, - move |_| shell.show_sidebar_bar() + move |button: >k::MenuButton| { + let chooser = shell.front().and_then(|front| { + let input = front.sender()?; + Some(super::schema_chooser::popover(front.schema_choices()?, input)) + }); + button.set_popover(chooser.as_ref()); + } )); } - // Its commands make objects in the tree, which the Favorites scope does not list. + // Its controls act on the tree, which the Favorites scope does not list. fn show_sidebar_bar(&self) { let imp = self.imp(); let tables = imp.scope_toggle.active_name().as_deref() != Some(FAVORITES); - imp.sidebar_bar - .set_revealed(tables && imp.sidebar_add_button.is_visible()); + let used = imp.sidebar_add_button.is_visible() || imp.schema_filter_button.is_visible(); + imp.sidebar_bar.set_revealed(tables && used); } fn follow_favorites(&self) { diff --git a/linux/crates/app/src/ui/workspace/workspace_shell_imp.rs b/linux/crates/app/src/ui/workspace/workspace_shell_imp.rs index a53301338b..f8c88f1a72 100644 --- a/linux/crates/app/src/ui/workspace/workspace_shell_imp.rs +++ b/linux/crates/app/src/ui/workspace/workspace_shell_imp.rs @@ -67,6 +67,8 @@ pub struct WorkspaceShell { #[template_child] pub list_banners: TemplateChild, #[template_child] + pub schema_filter_button: TemplateChild, + #[template_child] pub sidebar_slot: TemplateChild, #[template_child] pub scope_toggle: TemplateChild, diff --git a/linux/data/resources/ui/workspace-shell.ui b/linux/data/resources/ui/workspace-shell.ui index f6a193dfd2..787e883a84 100644 --- a/linux/data/resources/ui/workspace-shell.ui +++ b/linux/data/resources/ui/workspace-shell.ui @@ -132,6 +132,15 @@ false + + + + Schemas + true + up + false + + diff --git a/linux/data/resources/ui/workspace.ui b/linux/data/resources/ui/workspace.ui index 0d52f95192..03e8b00f58 100644 --- a/linux/data/resources/ui/workspace.ui +++ b/linux/data/resources/ui/workspace.ui @@ -40,6 +40,12 @@ top of the sidebar while the session is in front. --> vertical + + + false + Show All + + diff --git a/linux/docs/storage.md b/linux/docs/storage.md index 56e6f732c2..4f006ab034 100644 --- a/linux/docs/storage.md +++ b/linux/docs/storage.md @@ -136,7 +136,7 @@ nothing reaches outside it. |---|---| | `connections_file()` | `$XDG_CONFIG_HOME//connections.json` | | `column_layouts_file()` | `$XDG_CONFIG_HOME//column_layouts.json`: each table's column layout (order, hidden columns, widths the user set) | -| `filter_settings_file()` | `$XDG_CONFIG_HOME//filter_settings.json` | +| `filter_settings_file()` | `$XDG_CONFIG_HOME//filter_settings.json`, version 2: each table's filter, and the schemas each connection's sidebar lists, per database. Version 1 had no sidebar filters | | `highlight_rules_file()` | `$XDG_CONFIG_HOME//highlight_rules.json`: ordered rules for each table | | `history_database()` | `$XDG_STATE_HOME//history.db` | | `workspaces_dir()` | `$XDG_STATE_HOME//workspaces`: one file per session, and `open-sessions.json`: the sessions open at the last quit as `windows`, one list of keys per window, windows in the order of their first recorded session and keys in the order each window adopted them | diff --git a/linux/po/POTFILES.in b/linux/po/POTFILES.in index 8b8a9fd735..b1c1b1a903 100644 --- a/linux/po/POTFILES.in +++ b/linux/po/POTFILES.in @@ -654,6 +654,8 @@ crates/app/src/ui/workspace/mod.rs crates/app/src/ui/workspace/recent_tabs.rs crates/app/src/ui/workspace/references.rs crates/app/src/ui/workspace/saves.rs +crates/app/src/ui/workspace/schema_chooser.rs +crates/app/src/ui/workspace/schema_filter.rs crates/app/src/ui/workspace/session_watches.rs crates/app/src/ui/workspace/sidebar/catalog_watch.rs crates/app/src/ui/workspace/sidebar/connection_tree.rs