From 0e0eff58880bbf71bff02974d44dc8a0b3af9f07 Mon Sep 17 00:00:00 2001 From: sedax90 <5001801+sedax90@users.noreply.github.com> Date: Sun, 8 Nov 2026 13:39:11 +0100 Subject: [PATCH 01/15] feat(linux-workspace): add Open Quickly to find a table or view by name --- .../app/src/application/accelerators.rs | 2 + linux/crates/app/src/ui/mod.rs | 1 + .../crates/app/src/ui/quick_open/matching.rs | 63 ++++ linux/crates/app/src/ui/quick_open/mod.rs | 344 ++++++++++++++++++ linux/crates/app/src/ui/workspace/mod.rs | 3 + .../app/src/ui/workspace/status_pages.rs | 26 ++ .../app/src/ui/workspace/workspace_actions.rs | 3 +- linux/data/resources/gtk/menus.ui | 5 + linux/data/resources/shortcuts-dialog.ui | 6 + linux/po/POTFILES.in | 2 + 10 files changed, 454 insertions(+), 1 deletion(-) create mode 100644 linux/crates/app/src/ui/quick_open/matching.rs create mode 100644 linux/crates/app/src/ui/quick_open/mod.rs diff --git a/linux/crates/app/src/application/accelerators.rs b/linux/crates/app/src/application/accelerators.rs index a59a763415..bafb98e311 100644 --- a/linux/crates/app/src/application/accelerators.rs +++ b/linux/crates/app/src/application/accelerators.rs @@ -73,6 +73,8 @@ pub const ACCELERATORS: &[Accelerator] = &[ application("app.new-window", &["n"], General), application("app.preferences", &["comma"], General), application("win.show-history", &["h"], General), + // Xcode's Open Quickly is Cmd+Shift+O, which Ctrl+Shift+O already takes here. + application("win.quick-open", &["o"], General), // As in GIMP and Inkscape. application("win.export-results", &["e"], General), // As in GNOME Files. diff --git a/linux/crates/app/src/ui/mod.rs b/linux/crates/app/src/ui/mod.rs index 0d756a2ade..3bcf337369 100644 --- a/linux/crates/app/src/ui/mod.rs +++ b/linux/crates/app/src/ui/mod.rs @@ -40,6 +40,7 @@ mod name_entry; mod picker; mod plain_toast; mod preferences_dialog; +mod quick_open; mod result_pane; pub(crate) mod safe_mode; mod saved_queries_dialog; diff --git a/linux/crates/app/src/ui/quick_open/matching.rs b/linux/crates/app/src/ui/quick_open/matching.rs new file mode 100644 index 0000000000..e6efa1f3a1 --- /dev/null +++ b/linux/crates/app/src/ui/quick_open/matching.rs @@ -0,0 +1,63 @@ +/// How well `name` answers what the user typed, lower the better, or +/// `None` when it does not. A name that starts with the text comes first, +/// then one that holds it, then one whose letters follow it in order with +/// others between, as a fuzzy finder takes them. +pub(super) fn rank(typed: &str, name: &str) -> Option { + let typed: Vec = typed.trim().chars().flat_map(char::to_lowercase).collect(); + if typed.is_empty() { + return Some(0); + } + let name: Vec = name.chars().flat_map(char::to_lowercase).collect(); + if name.starts_with(&typed) { + return Some(0); + } + if let Some(at) = name.windows(typed.len()).position(|window| window == typed.as_slice()) { + return Some(100 + u32::try_from(at).unwrap_or(u32::MAX - 100)); + } + // The letters in order, charged for each one skipped between them. + let mut wanted = typed.iter().peekable(); + let mut skipped = 0u32; + let mut started = false; + for letter in &name { + match wanted.peek() { + Some(next) if *next == letter => { + wanted.next(); + started = true; + } + Some(_) if started => skipped = skipped.saturating_add(1), + _ => {} + } + } + wanted.peek().is_none().then_some(1_000 + skipped) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_blank_search_keeps_everything() { + assert_eq!(rank(" ", "orders"), Some(0)); + } + + #[test] + fn a_prefix_beats_a_hit_inside_beats_scattered_letters() { + let prefix = rank("ord", "orders").expect("a prefix"); + let inside = rank("der", "orders").expect("inside"); + let scattered = rank("ods", "orders").expect("scattered"); + + assert!(prefix < inside && inside < scattered, "{prefix} {inside} {scattered}"); + } + + #[test] + fn case_does_not_matter_and_a_miss_is_none() { + assert_eq!(rank("ORD", "Orders"), Some(0)); + assert_eq!(rank("xyz", "orders"), None); + assert_eq!(rank("sro", "orders"), None, "the letters were out of order"); + } + + #[test] + fn a_nearer_hit_inside_ranks_first() { + assert!(rank("ar", "bar").expect("near") < rank("ar", "xxbar").expect("far")); + } +} diff --git a/linux/crates/app/src/ui/quick_open/mod.rs b/linux/crates/app/src/ui/quick_open/mod.rs new file mode 100644 index 0000000000..cdf4d4d9d2 --- /dev/null +++ b/linux/crates/app/src/ui/quick_open/mod.rs @@ -0,0 +1,344 @@ +//! Open Quickly: a search over the front connection's tables and views, +//! as the macOS Quick Switcher (`QuickSwitcherPanelView`) offers, so a +//! table is one key and a few letters away instead of a scroll through +//! the sidebar. Enter opens it and Ctrl+Enter opens its structure. + +mod matching; + +use std::cell::RefCell; +use std::rc::Rc; + +use gtk4 as gtk; +use gtk4::prelude::*; +use gtk4::subclass::prelude::ObjectSubclassIsExt; +use gtk4::{gdk, gio, glib}; +use libadwaita as adw; +use libadwaita::prelude::*; +use tablepro_core::meta::{ObjectInfo, ObjectKind, TableRef}; + +use crate::i18n::{gettext, gettext_f}; +use crate::ui::icons; + +/// The rows listed at once, which a longer search narrows. +const LISTED: usize = 200; + +/// What the user chose, and whether they asked for its structure. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct Pick { + pub table: TableRef, + pub structure: bool, +} + +type Chosen = Rc; + +/// The tables and views of `objects`, by name. +pub(crate) fn candidates(objects: &[ObjectInfo]) -> Vec { + let mut found: Vec = objects + .iter() + .filter(|object| object.kind.is_browsable()) + .cloned() + .collect(); + found.sort_by_cached_key(|object| (object.name.to_lowercase(), object.schema.clone())); + found +} + +/// The candidates `typed` finds, the best first, at most `LISTED`. +pub(crate) fn search(candidates: &[ObjectInfo], typed: &str) -> Vec { + let mut ranked: Vec<(u32, &ObjectInfo)> = candidates + .iter() + .filter_map(|object| matching::rank(typed, &object.name).map(|rank| (rank, object))) + .collect(); + // Stable, so equals keep the by-name order the candidates came in. + ranked.sort_by_key(|(rank, _)| *rank); + ranked + .into_iter() + .take(LISTED) + .map(|(_, object)| object.clone()) + .collect() +} + +glib::wrapper! { + pub struct QuickOpen(ObjectSubclass) + @extends adw::Dialog, gtk::Widget, + @implements gtk::Accessible, gtk::Buildable, gtk::ConstraintTarget; +} + +mod imp { + use std::cell::RefCell; + + use gtk4::glib; + use gtk4::subclass::prelude::*; + use libadwaita as adw; + use libadwaita::subclass::prelude::*; + use tablepro_core::meta::ObjectInfo; + + #[derive(Default)] + pub struct QuickOpen { + pub candidates: RefCell>, + } + + #[glib::object_subclass] + impl ObjectSubclass for QuickOpen { + const NAME: &'static str = "TableProQuickOpen"; + type Type = super::QuickOpen; + type ParentType = adw::Dialog; + } + + impl ObjectImpl for QuickOpen {} + impl WidgetImpl for QuickOpen {} + impl AdwDialogImpl for QuickOpen {} +} + +impl QuickOpen { + pub(crate) fn new(objects: &[ObjectInfo], chosen: impl Fn(Pick) + 'static) -> Self { + let dialog: Self = glib::Object::new(); + dialog.set_title(&gettext("Open Quickly")); + dialog.set_content_width(520); + dialog.set_content_height(440); + let all = candidates(objects); + let store = gio::ListStore::new::(); + let selection = gtk::SingleSelection::new(Some(store.clone())); + let list = gtk::ListView::new(Some(selection.clone()), Some(factory())); + list.add_css_class("navigation-sidebar"); + list.set_single_click_activate(true); + list.update_property(&[gtk::accessible::Property::Label(&gettext("Tables and views"))]); + let scrolled = gtk::ScrolledWindow::builder() + .hscrollbar_policy(gtk::PolicyType::Never) + .vexpand(true) + .child(&list) + .build(); + let empty = adw::StatusPage::builder() + .title(gettext("No Matches")) + .description(gettext("No table or view matches what you typed.")) + .build(); + empty.add_css_class("compact"); + let stack = gtk::Stack::new(); + stack.add_named(&scrolled, Some("list")); + stack.add_named(&empty, Some("empty")); + let entry = gtk::SearchEntry::builder() + .placeholder_text(gettext("Search tables and views")) + .hexpand(true) + .margin_top(12) + .margin_bottom(6) + .margin_start(12) + .margin_end(12) + .build(); + entry.update_property(&[gtk::accessible::Property::Label(&gettext("Search tables and views"))]); + let body = gtk::Box::new(gtk::Orientation::Vertical, 0); + body.append(&entry); + body.append(&stack); + let header = adw::HeaderBar::new(); + let view = adw::ToolbarView::new(); + view.add_top_bar(&header); + view.set_content(Some(&body)); + dialog.set_child(Some(&view)); + dialog.set_focus(Some(&entry)); + dialog.imp().candidates.replace(all.clone()); + + let show = { + let (store, stack, selection) = (store.clone(), stack.clone(), selection.clone()); + move |typed: &str| { + let found = search(&all, typed); + let items: Vec = found.into_iter().map(glib::BoxedAnyObject::new).collect(); + store.splice(0, store.n_items(), &items); + stack.set_visible_child_name(if items.is_empty() { "empty" } else { "list" }); + selection.set_selected(if items.is_empty() { + gtk::INVALID_LIST_POSITION + } else { + 0 + }); + } + }; + show(""); + entry.connect_search_changed({ + let show = show.clone(); + move |entry| show(&entry.text()) + }); + + let chosen: Chosen = Rc::new(chosen); + let dialog_weak = dialog.downgrade(); + let pick = { + let (store, chosen) = (store.clone(), chosen.clone()); + move |position: u32, structure: bool| { + let Some(object) = store + .item(position) + .and_downcast::() + .map(|item| item.borrow::().clone()) + else { + return; + }; + if let Some(dialog) = dialog_weak.upgrade() { + dialog.close(); + } + chosen(Pick { + table: TableRef::new(object.schema, object.name), + structure, + }); + } + }; + list.connect_activate({ + let pick = pick.clone(); + move |_, position| pick(position, false) + }); + entry.connect_activate({ + let (pick, selection) = (pick.clone(), selection.clone()); + move |_| pick(selection.selected(), false) + }); + // Up and Down move the choice while the text keeps the keyboard. + entry.connect_next_match({ + let selection = selection.clone(); + move |_| step(&selection, 1) + }); + entry.connect_previous_match({ + let selection = selection.clone(); + move |_| step(&selection, -1) + }); + let keys = gtk::EventControllerKey::new(); + let held: Rc> = Rc::default(); + keys.connect_key_pressed(move |_, key, _, modifiers| { + let _ = &held; + if matches!(key, gdk::Key::Return | gdk::Key::KP_Enter) + && modifiers.contains(gdk::ModifierType::CONTROL_MASK) + { + pick(selection.selected(), true); + return glib::Propagation::Stop; + } + glib::Propagation::Proceed + }); + entry.add_controller(keys); + dialog + } + + /// The tables and views the dialog searches. + #[cfg(test)] + pub(crate) fn candidate_names(&self) -> Vec { + use gtk4::subclass::prelude::ObjectSubclassIsExt; + self.imp() + .candidates + .borrow() + .iter() + .map(|object| object.name.clone()) + .collect() + } +} + +fn step(selection: >k::SingleSelection, by: i32) { + let count = selection.n_items(); + if count == 0 { + return; + } + let current = i64::from(selection.selected().min(count - 1)); + let next = (current + i64::from(by)).clamp(0, i64::from(count) - 1); + selection.set_selected(u32::try_from(next).unwrap_or(0)); +} + +fn factory() -> gtk::SignalListItemFactory { + let factory = gtk::SignalListItemFactory::new(); + factory.connect_setup(|_, item| { + let Some(item) = item.downcast_ref::() else { + return; + }; + let icon = gtk::Image::new(); + icon.add_css_class("dimmed"); + icon.set_accessible_role(gtk::AccessibleRole::Presentation); + let name = gtk::Label::builder() + .xalign(0.0) + .hexpand(true) + .ellipsize(gtk::pango::EllipsizeMode::End) + .build(); + let place = gtk::Label::builder() + .xalign(1.0) + .ellipsize(gtk::pango::EllipsizeMode::End) + .build(); + place.add_css_class("dimmed"); + place.add_css_class("caption"); + let row = gtk::Box::builder() + .spacing(10) + .margin_top(6) + .margin_bottom(6) + .margin_start(6) + .margin_end(6) + .build(); + row.append(&icon); + row.append(&name); + row.append(&place); + item.set_child(Some(&row)); + }); + factory.connect_bind(|_, item| { + let Some(item) = item.downcast_ref::() else { + return; + }; + let (Some(object), Some(row)) = (item.item().and_downcast::(), item.child()) else { + return; + }; + let object = object.borrow::().clone(); + let (Some(icon), Some(name), Some(place)) = ( + row.first_child().and_downcast::(), + row.first_child() + .and_then(|icon| icon.next_sibling()) + .and_downcast::(), + row.last_child().and_downcast::(), + ) else { + return; + }; + icon.set_icon_name(Some(match object.kind { + ObjectKind::View | ObjectKind::MaterializedView => icons::VIEW_GRID, + _ => icons::TABLE_RELATION, + })); + name.set_label(&object.name); + place.set_label(object.schema.as_deref().unwrap_or_default()); + let described = match object.schema.as_deref() { + Some(schema) => gettext_f("{table}, in {schema}", &[("table", &object.name), ("schema", schema)]), + None => object.name.clone(), + }; + item.set_accessible_label(&described); + }); + factory +} + +#[cfg(test)] +mod tests { + use super::*; + + fn table(schema: &str, name: &str, kind: ObjectKind) -> ObjectInfo { + ObjectInfo::new(Some(schema.to_owned()), name, kind) + } + + fn names(found: &[ObjectInfo]) -> Vec<&str> { + found.iter().map(|object| object.name.as_str()).collect() + } + + #[test] + fn only_what_the_grid_can_page_is_offered_and_it_is_ordered_by_name() { + let all = candidates(&[ + table("public", "orders", ObjectKind::Table), + table("public", "recount", ObjectKind::Function), + table("public", "Customers", ObjectKind::View), + table("public", "customers_id_seq", ObjectKind::Sequence), + ]); + + assert_eq!(names(&all), ["Customers", "orders"]); + } + + #[test] + fn the_best_match_comes_first_and_a_miss_is_left_out() { + let all = candidates(&[ + table("public", "reorder_log", ObjectKind::Table), + table("public", "orders", ObjectKind::Table), + table("sales", "order_items", ObjectKind::Table), + table("public", "users", ObjectKind::Table), + ]); + + assert_eq!(names(&search(&all, "ord")), ["order_items", "orders", "reorder_log"]); + assert!(search(&all, "zzz").is_empty()); + assert_eq!(search(&all, "").len(), 4); + } + + #[gtk4::test] + fn the_dialog_searches_the_tables_it_was_given() { + libadwaita::init().expect("libadwaita initialises under the test backend"); + let dialog = QuickOpen::new(&[table("public", "orders", ObjectKind::Table)], |_| {}); + + assert_eq!(dialog.candidate_names(), ["orders"]); + } +} diff --git a/linux/crates/app/src/ui/workspace/mod.rs b/linux/crates/app/src/ui/workspace/mod.rs index 6e4edd63b6..459e5200eb 100644 --- a/linux/crates/app/src/ui/workspace/mod.rs +++ b/linux/crates/app/src/ui/workspace/mod.rs @@ -545,6 +545,8 @@ pub(crate) enum WorkspaceInput { DraftsNotSaved, ShowHistory, ShowSavedQueries, + /// Open Quickly: search the connection's tables and views. + ShowQuickOpen, ActiveTab(workspace_tabs::ActiveTabCommand), SaveQueryNamed { name: String, @@ -1395,6 +1397,7 @@ impl WorkspaceModel { WorkspaceInput::DraftsNotSaved => self.on_drafts_not_saved(), WorkspaceInput::ShowHistory => self.on_show_history(), WorkspaceInput::ShowSavedQueries => self.on_show_saved_queries(), + WorkspaceInput::ShowQuickOpen => self.on_show_quick_open(), WorkspaceInput::ImportCsvRequested { schema, table } => self.on_import_csv_requested(schema, table), WorkspaceInput::Transfer(input) => self.on_transfer(input), WorkspaceInput::ImportCsvReady { diff --git a/linux/crates/app/src/ui/workspace/status_pages.rs b/linux/crates/app/src/ui/workspace/status_pages.rs index ee669cee91..a0a768f05c 100644 --- a/linux/crates/app/src/ui/workspace/status_pages.rs +++ b/linux/crates/app/src/ui/workspace/status_pages.rs @@ -84,6 +84,32 @@ impl WorkspaceModel { self.saved_queries_dialog = Some(dialog); } + /// Open Quickly: a search over the session's tables and views, which + /// opens the one chosen as the sidebar's row does, or its structure. + pub(super) fn on_show_quick_open(&mut self) { + let Some(session) = self.context.active.get() else { + return; + }; + let objects = session + .subscribe_objects(tablepro_core::meta::ObjectScope::AllSchemas) + .borrow() + .objects + .clone(); + let input = self.input.clone(); + let dialog = crate::ui::quick_open::QuickOpen::new(&objects, move |pick| { + let tablepro_core::meta::TableRef { schema, name } = pick.table; + input.deliver(match pick.structure { + true => WorkspaceInput::EditStructureTab { schema, table: name }, + false => WorkspaceInput::SelectTable { + schema, + name, + open_mode: super::OpenMode::SwitchOrAppend, + }, + }); + }); + dialog.present(self.dialog_parent().as_ref()); + } + /// Ask what to call the SQL in front of the user, then keep it. /// /// The text is read now rather than when the dialog closes, so what diff --git a/linux/crates/app/src/ui/workspace/workspace_actions.rs b/linux/crates/app/src/ui/workspace/workspace_actions.rs index 6314971252..886abeca0a 100644 --- a/linux/crates/app/src/ui/workspace/workspace_actions.rs +++ b/linux/crates/app/src/ui/workspace/workspace_actions.rs @@ -23,7 +23,7 @@ type ActionInput = fn() -> WorkspaceInput; /// they are not left greyed out with no reason. const HISTORY_ACTIONS: [&str; 2] = ["show-history", "show-saved-queries"]; -const ENTRIES: [(&str, ActionInput); 9] = [ +const ENTRIES: [(&str, ActionInput); 10] = [ ("new-editor-tab", || WorkspaceInput::NewEditorTab), (EXPORT_DATABASE, || { WorkspaceInput::Transfer(TransferInput::ExportDatabase) @@ -38,6 +38,7 @@ const ENTRIES: [(&str, ActionInput); 9] = [ }), ("show-history", || WorkspaceInput::ShowHistory), ("show-saved-queries", || WorkspaceInput::ShowSavedQueries), + ("quick-open", || WorkspaceInput::ShowQuickOpen), (super::health_banner::REVIEW_HOST_KEY, || WorkspaceInput::ReviewHostKey), ]; diff --git a/linux/data/resources/gtk/menus.ui b/linux/data/resources/gtk/menus.ui index 1ee0fd0a97..0460a2bbf2 100644 --- a/linux/data/resources/gtk/menus.ui +++ b/linux/data/resources/gtk/menus.ui @@ -20,6 +20,11 @@
+ + Open _Quickly… + win.quick-open + action-missing + Query _History win.show-history diff --git a/linux/data/resources/shortcuts-dialog.ui b/linux/data/resources/shortcuts-dialog.ui index 0ee1676eb7..6611874e3f 100644 --- a/linux/data/resources/shortcuts-dialog.ui +++ b/linux/data/resources/shortcuts-dialog.ui @@ -27,6 +27,12 @@ <Primary>f + + + Open Quickly + win.quick-open + + Query History diff --git a/linux/po/POTFILES.in b/linux/po/POTFILES.in index 23a2291ef9..686b5bc5c5 100644 --- a/linux/po/POTFILES.in +++ b/linux/po/POTFILES.in @@ -493,6 +493,8 @@ crates/app/src/ui/preferences_dialog/history_group.rs crates/app/src/ui/preferences_dialog/imp.rs crates/app/src/ui/preferences_dialog/mcp_page.rs crates/app/src/ui/preferences_dialog/mod.rs +crates/app/src/ui/quick_open/matching.rs +crates/app/src/ui/quick_open/mod.rs crates/app/src/ui/result_pane/mod.rs crates/app/src/ui/result_pane/result_limit_banner.rs crates/app/src/ui/result_pane/result_set_view.rs From 3c6e7f56c55566e636370ed9b79be29e5787dd99 Mon Sep 17 00:00:00 2001 From: sedax90 <5001801+sedax90@users.noreply.github.com> Date: Sun, 8 Nov 2026 13:40:54 +0100 Subject: [PATCH 02/15] docs(linux-workspace): add the changelog entry --- linux/changelog.d/4121.added.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 linux/changelog.d/4121.added.md diff --git a/linux/changelog.d/4121.added.md b/linux/changelog.d/4121.added.md new file mode 100644 index 0000000000..9a4b37afc0 --- /dev/null +++ b/linux/changelog.d/4121.added.md @@ -0,0 +1 @@ +Open Quickly (Ctrl+Alt+O) searches the connection's tables and views by name and opens one. From a1a7726cd6a56853b29c1e28133bd44c3d690892 Mon Sep 17 00:00:00 2001 From: sedax90 <5001801+sedax90@users.noreply.github.com> Date: Sun, 8 Nov 2026 14:45:28 +0100 Subject: [PATCH 03/15] feat(linux-workspace): find saved queries in Open Quickly --- linux/crates/app/src/ui/quick_open/mod.rs | 170 ++++++++++++------ linux/crates/app/src/ui/workspace/mod.rs | 8 +- .../app/src/ui/workspace/status_pages.rs | 45 ++++- 3 files changed, 167 insertions(+), 56 deletions(-) diff --git a/linux/crates/app/src/ui/quick_open/mod.rs b/linux/crates/app/src/ui/quick_open/mod.rs index cdf4d4d9d2..62a7a94492 100644 --- a/linux/crates/app/src/ui/quick_open/mod.rs +++ b/linux/crates/app/src/ui/quick_open/mod.rs @@ -22,31 +22,64 @@ use crate::ui::icons; /// The rows listed at once, which a longer search narrows. const LISTED: usize = 200; -/// What the user chose, and whether they asked for its structure. +/// What the user chose. #[derive(Debug, Clone, PartialEq, Eq)] -pub(crate) struct Pick { - pub table: TableRef, - pub structure: bool, +pub(crate) enum Pick { + /// A table or view, and whether they asked for its structure. + Table { table: TableRef, structure: bool }, + /// A saved query's SQL, which opens in a new query tab. + Query(String), +} + +/// What the dialog searches: a table or view, or a saved query. +#[derive(Debug, Clone)] +pub(crate) enum Entry { + Object(ObjectInfo), + Query { name: String, sql: String }, +} + +impl Entry { + pub(crate) fn name(&self) -> &str { + match self { + Entry::Object(object) => &object.name, + Entry::Query { name, .. } => name, + } + } } type Chosen = Rc; -/// The tables and views of `objects`, by name. -pub(crate) fn candidates(objects: &[ObjectInfo]) -> Vec { - let mut found: Vec = objects +/// The tables and views of `objects` and the saved `queries` as (name, SQL), +/// by name, a table before a query of the same name. +pub(crate) fn candidates(objects: &[ObjectInfo], queries: &[(String, String)]) -> Vec { + let mut found: Vec = objects .iter() .filter(|object| object.kind.is_browsable()) .cloned() + .map(Entry::Object) + .chain(queries.iter().map(|(name, sql)| Entry::Query { + name: name.clone(), + sql: sql.clone(), + })) .collect(); - found.sort_by_cached_key(|object| (object.name.to_lowercase(), object.schema.clone())); + found.sort_by_cached_key(|entry| { + ( + entry.name().to_lowercase(), + matches!(entry, Entry::Query { .. }), + match entry { + Entry::Object(object) => object.schema.clone(), + Entry::Query { .. } => None, + }, + ) + }); found } /// The candidates `typed` finds, the best first, at most `LISTED`. -pub(crate) fn search(candidates: &[ObjectInfo], typed: &str) -> Vec { - let mut ranked: Vec<(u32, &ObjectInfo)> = candidates +pub(crate) fn search(candidates: &[Entry], typed: &str) -> Vec { + let mut ranked: Vec<(u32, &Entry)> = candidates .iter() - .filter_map(|object| matching::rank(typed, &object.name).map(|rank| (rank, object))) + .filter_map(|entry| matching::rank(typed, entry.name()).map(|rank| (rank, entry))) .collect(); // Stable, so equals keep the by-name order the candidates came in. ranked.sort_by_key(|(rank, _)| *rank); @@ -66,15 +99,15 @@ glib::wrapper! { mod imp { use std::cell::RefCell; + use super::Entry; use gtk4::glib; use gtk4::subclass::prelude::*; use libadwaita as adw; use libadwaita::subclass::prelude::*; - use tablepro_core::meta::ObjectInfo; #[derive(Default)] pub struct QuickOpen { - pub candidates: RefCell>, + pub(super) candidates: RefCell>, } #[glib::object_subclass] @@ -90,18 +123,20 @@ mod imp { } impl QuickOpen { - pub(crate) fn new(objects: &[ObjectInfo], chosen: impl Fn(Pick) + 'static) -> Self { + pub(crate) fn new(objects: &[ObjectInfo], queries: &[(String, String)], chosen: impl Fn(Pick) + 'static) -> Self { let dialog: Self = glib::Object::new(); dialog.set_title(&gettext("Open Quickly")); dialog.set_content_width(520); dialog.set_content_height(440); - let all = candidates(objects); + let all = candidates(objects, queries); let store = gio::ListStore::new::(); let selection = gtk::SingleSelection::new(Some(store.clone())); let list = gtk::ListView::new(Some(selection.clone()), Some(factory())); list.add_css_class("navigation-sidebar"); list.set_single_click_activate(true); - list.update_property(&[gtk::accessible::Property::Label(&gettext("Tables and views"))]); + list.update_property(&[gtk::accessible::Property::Label(&gettext( + "Tables, views and saved queries", + ))]); let scrolled = gtk::ScrolledWindow::builder() .hscrollbar_policy(gtk::PolicyType::Never) .vexpand(true) @@ -109,21 +144,23 @@ impl QuickOpen { .build(); let empty = adw::StatusPage::builder() .title(gettext("No Matches")) - .description(gettext("No table or view matches what you typed.")) + .description(gettext("No table, view or saved query matches what you typed.")) .build(); empty.add_css_class("compact"); let stack = gtk::Stack::new(); stack.add_named(&scrolled, Some("list")); stack.add_named(&empty, Some("empty")); let entry = gtk::SearchEntry::builder() - .placeholder_text(gettext("Search tables and views")) + .placeholder_text(gettext("Search tables, views and saved queries")) .hexpand(true) .margin_top(12) .margin_bottom(6) .margin_start(12) .margin_end(12) .build(); - entry.update_property(&[gtk::accessible::Property::Label(&gettext("Search tables and views"))]); + entry.update_property(&[gtk::accessible::Property::Label(&gettext( + "Search tables, views and saved queries", + ))]); let body = gtk::Box::new(gtk::Orientation::Vertical, 0); body.append(&entry); body.append(&stack); @@ -160,19 +197,22 @@ impl QuickOpen { let pick = { let (store, chosen) = (store.clone(), chosen.clone()); move |position: u32, structure: bool| { - let Some(object) = store + let Some(found) = store .item(position) .and_downcast::() - .map(|item| item.borrow::().clone()) + .map(|item| item.borrow::().clone()) else { return; }; if let Some(dialog) = dialog_weak.upgrade() { dialog.close(); } - chosen(Pick { - table: TableRef::new(object.schema, object.name), - structure, + chosen(match found { + Entry::Object(object) => Pick::Table { + table: TableRef::new(object.schema, object.name), + structure, + }, + Entry::Query { sql, .. } => Pick::Query(sql), }); } }; @@ -217,7 +257,7 @@ impl QuickOpen { .candidates .borrow() .iter() - .map(|object| object.name.clone()) + .map(|entry| entry.name().to_owned()) .collect() } } @@ -271,7 +311,7 @@ fn factory() -> gtk::SignalListItemFactory { let (Some(object), Some(row)) = (item.item().and_downcast::(), item.child()) else { return; }; - let object = object.borrow::().clone(); + let entry = object.borrow::().clone(); let (Some(icon), Some(name), Some(place)) = ( row.first_child().and_downcast::(), row.first_child() @@ -281,15 +321,25 @@ fn factory() -> gtk::SignalListItemFactory { ) else { return; }; - icon.set_icon_name(Some(match object.kind { - ObjectKind::View | ObjectKind::MaterializedView => icons::VIEW_GRID, - _ => icons::TABLE_RELATION, - })); - name.set_label(&object.name); - place.set_label(object.schema.as_deref().unwrap_or_default()); - let described = match object.schema.as_deref() { - Some(schema) => gettext_f("{table}, in {schema}", &[("table", &object.name), ("schema", schema)]), - None => object.name.clone(), + let described = match &entry { + Entry::Object(object) => { + icon.set_icon_name(Some(match object.kind { + ObjectKind::View | ObjectKind::MaterializedView => icons::VIEW_GRID, + _ => icons::TABLE_RELATION, + })); + name.set_label(&object.name); + place.set_label(object.schema.as_deref().unwrap_or_default()); + match object.schema.as_deref() { + Some(schema) => gettext_f("{table}, in {schema}", &[("table", &object.name), ("schema", schema)]), + None => object.name.clone(), + } + } + Entry::Query { name: title, .. } => { + icon.set_icon_name(Some("text-x-generic-symbolic")); + name.set_label(title); + place.set_label(&gettext("Saved query")); + gettext_f("{name}, a saved query", &[("name", title)]) + } }; item.set_accessible_label(&described); }); @@ -304,40 +354,60 @@ mod tests { ObjectInfo::new(Some(schema.to_owned()), name, kind) } - fn names(found: &[ObjectInfo]) -> Vec<&str> { - found.iter().map(|object| object.name.as_str()).collect() + fn names(found: &[Entry]) -> Vec<&str> { + found.iter().map(Entry::name).collect() } #[test] fn only_what_the_grid_can_page_is_offered_and_it_is_ordered_by_name() { - let all = candidates(&[ - table("public", "orders", ObjectKind::Table), - table("public", "recount", ObjectKind::Function), - table("public", "Customers", ObjectKind::View), - table("public", "customers_id_seq", ObjectKind::Sequence), - ]); + let all = candidates( + &[ + table("public", "orders", ObjectKind::Table), + table("public", "recount", ObjectKind::Function), + table("public", "Customers", ObjectKind::View), + table("public", "customers_id_seq", ObjectKind::Sequence), + ], + &[], + ); assert_eq!(names(&all), ["Customers", "orders"]); } #[test] fn the_best_match_comes_first_and_a_miss_is_left_out() { - let all = candidates(&[ - table("public", "reorder_log", ObjectKind::Table), - table("public", "orders", ObjectKind::Table), - table("sales", "order_items", ObjectKind::Table), - table("public", "users", ObjectKind::Table), - ]); + let all = candidates( + &[ + table("public", "reorder_log", ObjectKind::Table), + table("public", "orders", ObjectKind::Table), + table("sales", "order_items", ObjectKind::Table), + table("public", "users", ObjectKind::Table), + ], + &[], + ); assert_eq!(names(&search(&all, "ord")), ["order_items", "orders", "reorder_log"]); assert!(search(&all, "zzz").is_empty()); assert_eq!(search(&all, "").len(), 4); } + #[test] + fn a_saved_query_is_found_by_its_name_beside_the_tables() { + let all = candidates( + &[table("public", "orders", ObjectKind::Table)], + &[ + ("Orders this week".to_owned(), "SELECT 1".to_owned()), + ("Monthly report".to_owned(), "SELECT 2".to_owned()), + ], + ); + + assert_eq!(names(&search(&all, "orders")), ["orders", "Orders this week"]); + assert_eq!(names(&search(&all, "month")), ["Monthly report"]); + } + #[gtk4::test] fn the_dialog_searches_the_tables_it_was_given() { libadwaita::init().expect("libadwaita initialises under the test backend"); - let dialog = QuickOpen::new(&[table("public", "orders", ObjectKind::Table)], |_| {}); + let dialog = QuickOpen::new(&[table("public", "orders", ObjectKind::Table)], &[], |_| {}); assert_eq!(dialog.candidate_names(), ["orders"]); } diff --git a/linux/crates/app/src/ui/workspace/mod.rs b/linux/crates/app/src/ui/workspace/mod.rs index 459e5200eb..64c1db82b9 100644 --- a/linux/crates/app/src/ui/workspace/mod.rs +++ b/linux/crates/app/src/ui/workspace/mod.rs @@ -545,8 +545,13 @@ pub(crate) enum WorkspaceInput { DraftsNotSaved, ShowHistory, ShowSavedQueries, - /// Open Quickly: search the connection's tables and views. + /// Open Quickly: search the connection's tables, views and saved queries. ShowQuickOpen, + /// The saved queries of Open Quickly are read, and its dialog opens. + QuickOpenReady { + objects: std::sync::Arc<[tablepro_core::meta::ObjectInfo]>, + queries: Vec<(String, String)>, + }, ActiveTab(workspace_tabs::ActiveTabCommand), SaveQueryNamed { name: String, @@ -1398,6 +1403,7 @@ impl WorkspaceModel { WorkspaceInput::ShowHistory => self.on_show_history(), WorkspaceInput::ShowSavedQueries => self.on_show_saved_queries(), WorkspaceInput::ShowQuickOpen => self.on_show_quick_open(), + WorkspaceInput::QuickOpenReady { objects, queries } => self.present_quick_open(objects, queries), WorkspaceInput::ImportCsvRequested { schema, table } => self.on_import_csv_requested(schema, table), WorkspaceInput::Transfer(input) => self.on_transfer(input), WorkspaceInput::ImportCsvReady { diff --git a/linux/crates/app/src/ui/workspace/status_pages.rs b/linux/crates/app/src/ui/workspace/status_pages.rs index a0a768f05c..64119fc9a5 100644 --- a/linux/crates/app/src/ui/workspace/status_pages.rs +++ b/linux/crates/app/src/ui/workspace/status_pages.rs @@ -95,12 +95,47 @@ impl WorkspaceModel { .borrow() .objects .clone(); + let connection = self.context.active.metadata().map(|metadata| metadata.id); + let ready = self.history.ready_store(); let input = self.input.clone(); - let dialog = crate::ui::quick_open::QuickOpen::new(&objects, move |pick| { - let tablepro_core::meta::TableRef { schema, name } = pick.table; - input.deliver(match pick.structure { - true => WorkspaceInput::EditStructureTab { schema, table: name }, - false => WorkspaceInput::SelectTable { + // The saved queries are read first, so the dialog opens with them. + crate::runtime::spawn_and_deliver( + &self.tasks, + async move { + match (ready.await, connection) { + (Some(history), Some(id)) => history.saved_queries().list(Some(id)).await.unwrap_or_default(), + _ => Vec::new(), + } + }, + move |saved| { + let queries: Vec<(String, String)> = saved + .unwrap_or_default() + .into_iter() + .map(|query| (query.name, query.query)) + .collect(); + input.deliver(WorkspaceInput::QuickOpenReady { objects, queries }); + }, + ); + } + + pub(super) fn present_quick_open( + &mut self, + objects: std::sync::Arc<[tablepro_core::meta::ObjectInfo]>, + queries: Vec<(String, String)>, + ) { + let input = self.input.clone(); + let dialog = crate::ui::quick_open::QuickOpen::new(&objects, &queries, move |pick| { + use crate::ui::quick_open::Pick; + input.deliver(match pick { + Pick::Query(sql) => WorkspaceInput::OpenHistoryQuery(sql), + Pick::Table { + table: tablepro_core::meta::TableRef { schema, name }, + structure: true, + } => WorkspaceInput::EditStructureTab { schema, table: name }, + Pick::Table { + table: tablepro_core::meta::TableRef { schema, name }, + structure: false, + } => WorkspaceInput::SelectTable { schema, name, open_mode: super::OpenMode::SwitchOrAppend, From 25bd08a9ef830b7cd5c6230295ea1bbe1b62e17d Mon Sep 17 00:00:00 2001 From: sedax90 <5001801+sedax90@users.noreply.github.com> Date: Sun, 8 Nov 2026 14:46:19 +0100 Subject: [PATCH 04/15] docs(linux-workspace): add the changelog entry --- linux/changelog.d/4133.added.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 linux/changelog.d/4133.added.md diff --git a/linux/changelog.d/4133.added.md b/linux/changelog.d/4133.added.md new file mode 100644 index 0000000000..834704ed8d --- /dev/null +++ b/linux/changelog.d/4133.added.md @@ -0,0 +1 @@ +Open Quickly finds saved queries beside tables and views. From 99d9d8a661dd2f83d46c4cbb41aae50daf06ceab Mon Sep 17 00:00:00 2001 From: sedax90 <5001801+sedax90@users.noreply.github.com> Date: Sun, 8 Nov 2026 16:39:36 +0100 Subject: [PATCH 05/15] feat(linux-workspace): find past queries in Open Quickly --- linux/changelog.d/4144.added.md | 1 + linux/crates/app/src/ui/quick_open/mod.rs | 79 ++++++++++++++++--- linux/crates/app/src/ui/workspace/mod.rs | 9 ++- .../app/src/ui/workspace/status_pages.rs | 41 +++++++--- 4 files changed, 109 insertions(+), 21 deletions(-) create mode 100644 linux/changelog.d/4144.added.md diff --git a/linux/changelog.d/4144.added.md b/linux/changelog.d/4144.added.md new file mode 100644 index 0000000000..f04c7fe166 --- /dev/null +++ b/linux/changelog.d/4144.added.md @@ -0,0 +1 @@ +Open Quickly also finds the queries you ran before on the connection. diff --git a/linux/crates/app/src/ui/quick_open/mod.rs b/linux/crates/app/src/ui/quick_open/mod.rs index 62a7a94492..824a09a9fd 100644 --- a/linux/crates/app/src/ui/quick_open/mod.rs +++ b/linux/crates/app/src/ui/quick_open/mod.rs @@ -31,11 +31,13 @@ pub(crate) enum Pick { Query(String), } -/// What the dialog searches: a table or view, or a saved query. +/// What the dialog searches: a table or view, a saved query, or a query +/// run before. #[derive(Debug, Clone)] pub(crate) enum Entry { Object(ObjectInfo), Query { name: String, sql: String }, + History { title: String, sql: String }, } impl Entry { @@ -43,15 +45,29 @@ impl Entry { match self { Entry::Object(object) => &object.name, Entry::Query { name, .. } => name, + Entry::History { title, .. } => title, } } } +/// How long the title of a past query may be, which a long statement is cut to. +const TITLE_CHARS: usize = 120; + +/// A past query's first line, as its title in the list. +fn history_title(sql: &str) -> String { + let line = sql + .lines() + .map(str::trim) + .find(|line| !line.is_empty()) + .unwrap_or_default(); + line.chars().take(TITLE_CHARS).collect() +} + type Chosen = Rc; /// The tables and views of `objects` and the saved `queries` as (name, SQL), /// by name, a table before a query of the same name. -pub(crate) fn candidates(objects: &[ObjectInfo], queries: &[(String, String)]) -> Vec { +pub(crate) fn candidates(objects: &[ObjectInfo], queries: &[(String, String)], history: &[String]) -> Vec { let mut found: Vec = objects .iter() .filter(|object| object.kind.is_browsable()) @@ -61,14 +77,23 @@ pub(crate) fn candidates(objects: &[ObjectInfo], queries: &[(String, String)]) - name: name.clone(), sql: sql.clone(), })) + .chain(history.iter().map(|sql| Entry::History { + title: history_title(sql), + sql: sql.clone(), + })) .collect(); found.sort_by_cached_key(|entry| { ( entry.name().to_lowercase(), - matches!(entry, Entry::Query { .. }), + // A table, then a saved query, then one run before. + match entry { + Entry::Object(_) => 0, + Entry::Query { .. } => 1, + Entry::History { .. } => 2, + }, match entry { Entry::Object(object) => object.schema.clone(), - Entry::Query { .. } => None, + Entry::Query { .. } | Entry::History { .. } => None, }, ) }); @@ -123,19 +148,24 @@ mod imp { } impl QuickOpen { - pub(crate) fn new(objects: &[ObjectInfo], queries: &[(String, String)], chosen: impl Fn(Pick) + 'static) -> Self { + pub(crate) fn new( + objects: &[ObjectInfo], + queries: &[(String, String)], + history: &[String], + chosen: impl Fn(Pick) + 'static, + ) -> Self { let dialog: Self = glib::Object::new(); dialog.set_title(&gettext("Open Quickly")); dialog.set_content_width(520); dialog.set_content_height(440); - let all = candidates(objects, queries); + let all = candidates(objects, queries, history); let store = gio::ListStore::new::(); let selection = gtk::SingleSelection::new(Some(store.clone())); let list = gtk::ListView::new(Some(selection.clone()), Some(factory())); list.add_css_class("navigation-sidebar"); list.set_single_click_activate(true); list.update_property(&[gtk::accessible::Property::Label(&gettext( - "Tables, views and saved queries", + "Tables, views, saved queries and history", ))]); let scrolled = gtk::ScrolledWindow::builder() .hscrollbar_policy(gtk::PolicyType::Never) @@ -144,7 +174,9 @@ impl QuickOpen { .build(); let empty = adw::StatusPage::builder() .title(gettext("No Matches")) - .description(gettext("No table, view or saved query matches what you typed.")) + .description(gettext( + "No table, view, saved query or past query matches what you typed.", + )) .build(); empty.add_css_class("compact"); let stack = gtk::Stack::new(); @@ -212,7 +244,7 @@ impl QuickOpen { table: TableRef::new(object.schema, object.name), structure, }, - Entry::Query { sql, .. } => Pick::Query(sql), + Entry::Query { sql, .. } | Entry::History { sql, .. } => Pick::Query(sql), }); } }; @@ -340,6 +372,12 @@ fn factory() -> gtk::SignalListItemFactory { place.set_label(&gettext("Saved query")); gettext_f("{name}, a saved query", &[("name", title)]) } + Entry::History { title, .. } => { + icon.set_icon_name(Some(icons::DOCUMENT_OPEN_RECENT)); + name.set_label(title); + place.set_label(&gettext("History")); + gettext_f("{query}, a query run before", &[("query", title)]) + } }; item.set_accessible_label(&described); }); @@ -368,6 +406,7 @@ mod tests { table("public", "customers_id_seq", ObjectKind::Sequence), ], &[], + &[], ); assert_eq!(names(&all), ["Customers", "orders"]); @@ -383,6 +422,7 @@ mod tests { table("public", "users", ObjectKind::Table), ], &[], + &[], ); assert_eq!(names(&search(&all, "ord")), ["order_items", "orders", "reorder_log"]); @@ -398,6 +438,7 @@ mod tests { ("Orders this week".to_owned(), "SELECT 1".to_owned()), ("Monthly report".to_owned(), "SELECT 2".to_owned()), ], + &[], ); assert_eq!(names(&search(&all, "orders")), ["orders", "Orders this week"]); @@ -407,8 +448,26 @@ mod tests { #[gtk4::test] fn the_dialog_searches_the_tables_it_was_given() { libadwaita::init().expect("libadwaita initialises under the test backend"); - let dialog = QuickOpen::new(&[table("public", "orders", ObjectKind::Table)], &[], |_| {}); + let dialog = QuickOpen::new(&[table("public", "orders", ObjectKind::Table)], &[], &[], |_| {}); assert_eq!(dialog.candidate_names(), ["orders"]); } + + #[test] + fn a_past_query_is_found_by_its_first_line_after_tables_and_saved_queries() { + let all = candidates( + &[table("public", "orders", ObjectKind::Table)], + &[("Orders this week".to_owned(), "SELECT 1".to_owned())], + &[ + "\n SELECT * FROM orders\nWHERE id = 1".to_owned(), + "DELETE FROM sessions".to_owned(), + ], + ); + + assert_eq!( + names(&search(&all, "orders")), + ["orders", "Orders this week", "SELECT * FROM orders"] + ); + assert_eq!(names(&search(&all, "delete")), ["DELETE FROM sessions"]); + } } diff --git a/linux/crates/app/src/ui/workspace/mod.rs b/linux/crates/app/src/ui/workspace/mod.rs index 64c1db82b9..fc14503ce0 100644 --- a/linux/crates/app/src/ui/workspace/mod.rs +++ b/linux/crates/app/src/ui/workspace/mod.rs @@ -545,12 +545,13 @@ pub(crate) enum WorkspaceInput { DraftsNotSaved, ShowHistory, ShowSavedQueries, - /// Open Quickly: search the connection's tables, views and saved queries. + /// Open Quickly: search the connection's tables, views, saved queries and past queries. ShowQuickOpen, /// The saved queries of Open Quickly are read, and its dialog opens. QuickOpenReady { objects: std::sync::Arc<[tablepro_core::meta::ObjectInfo]>, queries: Vec<(String, String)>, + history: Vec, }, ActiveTab(workspace_tabs::ActiveTabCommand), SaveQueryNamed { @@ -1403,7 +1404,11 @@ impl WorkspaceModel { WorkspaceInput::ShowHistory => self.on_show_history(), WorkspaceInput::ShowSavedQueries => self.on_show_saved_queries(), WorkspaceInput::ShowQuickOpen => self.on_show_quick_open(), - WorkspaceInput::QuickOpenReady { objects, queries } => self.present_quick_open(objects, queries), + WorkspaceInput::QuickOpenReady { + objects, + queries, + history, + } => self.present_quick_open(objects, queries, history), WorkspaceInput::ImportCsvRequested { schema, table } => self.on_import_csv_requested(schema, table), WorkspaceInput::Transfer(input) => self.on_transfer(input), WorkspaceInput::ImportCsvReady { diff --git a/linux/crates/app/src/ui/workspace/status_pages.rs b/linux/crates/app/src/ui/workspace/status_pages.rs index 64119fc9a5..aabc63d4af 100644 --- a/linux/crates/app/src/ui/workspace/status_pages.rs +++ b/linux/crates/app/src/ui/workspace/status_pages.rs @@ -5,6 +5,9 @@ use crate::ui::history_dialog::{HistoryDialog, HistoryDialogInit, QueryDestinati use crate::ui::saved_queries_dialog::{SavedQueriesDialog, SavedQueriesDialogInit}; use super::{WorkspaceInput, WorkspaceModel}; + +/// How many past queries Open Quickly lists, the newest first. +const PAST_QUERIES: usize = 100; use crate::runtime::DeliverInput; use crate::ui::plain_toast; @@ -98,22 +101,41 @@ impl WorkspaceModel { let connection = self.context.active.metadata().map(|metadata| metadata.id); let ready = self.history.ready_store(); let input = self.input.clone(); - // The saved queries are read first, so the dialog opens with them. + // The saved and past queries are read first, so the dialog opens with them. crate::runtime::spawn_and_deliver( &self.tasks, async move { match (ready.await, connection) { - (Some(history), Some(id)) => history.saved_queries().list(Some(id)).await.unwrap_or_default(), - _ => Vec::new(), + (Some(history), Some(id)) => { + let saved = history.saved_queries().list(Some(id)).await.unwrap_or_default(); + let mut query = tablepro_storage::query_history::HistoryQuery::default(); + query.connection = Some(id); + let past = history + .search_page( + &query, + tablepro_storage::query_history::HistoryPageRequest::first(PAST_QUERIES), + ) + .await + .map(|page| page.entries) + .unwrap_or_default(); + (saved, past) + } + _ => (Vec::new(), Vec::new()), } }, - move |saved| { - let queries: Vec<(String, String)> = saved - .unwrap_or_default() + move |read| { + let (saved, past) = read.unwrap_or_default(); + let queries: Vec<(String, String)> = saved.into_iter().map(|query| (query.name, query.query)).collect(); + let history: Vec = past .into_iter() - .map(|query| (query.name, query.query)) + .filter(|entry| entry.success) + .map(|entry| entry.query) .collect(); - input.deliver(WorkspaceInput::QuickOpenReady { objects, queries }); + input.deliver(WorkspaceInput::QuickOpenReady { + objects, + queries, + history, + }); }, ); } @@ -122,9 +144,10 @@ impl WorkspaceModel { &mut self, objects: std::sync::Arc<[tablepro_core::meta::ObjectInfo]>, queries: Vec<(String, String)>, + history: Vec, ) { let input = self.input.clone(); - let dialog = crate::ui::quick_open::QuickOpen::new(&objects, &queries, move |pick| { + let dialog = crate::ui::quick_open::QuickOpen::new(&objects, &queries, &history, move |pick| { use crate::ui::quick_open::Pick; input.deliver(match pick { Pick::Query(sql) => WorkspaceInput::OpenHistoryQuery(sql), From 57b9e747f966ac1102aed232e5559b9518fdb60e Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 8 Nov 2026 22:58:47 +0700 Subject: [PATCH 06/15] fix(linux-workspace): keep Open Quickly current and keyboard accessible --- linux/changelog.d/4121.added.md | 2 +- .../app/src/application/accelerators.rs | 15 +- .../app/src/application/shortcut_owner.rs | 1 + .../crates/app/src/ui/quick_open/matching.rs | 84 ++- linux/crates/app/src/ui/quick_open/mod.rs | 620 ++++++++++++------ .../app/src/ui/quick_open/search_index.rs | 120 ++++ linux/crates/app/src/ui/quick_open/tests.rs | 249 +++++++ linux/crates/app/src/ui/workspace/mod.rs | 3 + .../app/src/ui/workspace/status_pages.rs | 37 +- .../app/src/ui/workspace/tests/shell.rs | 17 + .../app/src/ui/workspace/workspace_shell.rs | 4 + linux/docs/state-management.md | 14 + linux/po/POTFILES.in | 2 + 13 files changed, 924 insertions(+), 244 deletions(-) create mode 100644 linux/crates/app/src/ui/quick_open/search_index.rs create mode 100644 linux/crates/app/src/ui/quick_open/tests.rs diff --git a/linux/changelog.d/4121.added.md b/linux/changelog.d/4121.added.md index 9a4b37afc0..e323646d23 100644 --- a/linux/changelog.d/4121.added.md +++ b/linux/changelog.d/4121.added.md @@ -1 +1 @@ -Open Quickly (Ctrl+Alt+O) searches the connection's tables and views by name and opens one. +Open Quickly (Ctrl+Shift+O) finds tables and views across the connection’s schemas. diff --git a/linux/crates/app/src/application/accelerators.rs b/linux/crates/app/src/application/accelerators.rs index bafb98e311..2974af9be9 100644 --- a/linux/crates/app/src/application/accelerators.rs +++ b/linux/crates/app/src/application/accelerators.rs @@ -8,8 +8,8 @@ use AcceleratorScope::{Application, Component, Local, Stock}; use ShortcutListing::{Listed, Unlisted}; use ShortcutOwner::{ AssistantComposer, BrowseTab, CellEditor, ConnectionTree, DiagramCanvas, DiagramTab, EditorResults, FilterStrip, - Grid, GridCell, HistoryRow, InlineSuggestion, PickerPage, PickerRow, SqlEditor, SqlEditorCursors, SqlEditorTab, - StructureTab, + Grid, GridCell, HistoryRow, InlineSuggestion, PickerPage, PickerRow, QuickOpen, SqlEditor, SqlEditorCursors, + SqlEditorTab, StructureTab, }; use ShortcutSection::{BrowseTable, DataGrid, ErDiagram, General, TableStructure, Tabs}; @@ -73,8 +73,11 @@ pub const ACCELERATORS: &[Accelerator] = &[ application("app.new-window", &["n"], General), application("app.preferences", &["comma"], General), application("win.show-history", &["h"], General), - // Xcode's Open Quickly is Cmd+Shift+O, which Ctrl+Shift+O already takes here. - application("win.quick-open", &["o"], General), + // Matches Open Quickly in the macOS app. + application("win.quick-open", &["o"], General), + component(QuickOpen, "quick-open.next", &["Down"], Unlisted), + component(QuickOpen, "quick-open.previous", &["Up"], Unlisted), + component(QuickOpen, "quick-open.structure", &["Return"], Unlisted), // As in GIMP and Inkscape. application("win.export-results", &["e"], General), // As in GNOME Files. @@ -90,8 +93,7 @@ pub const ACCELERATORS: &[Accelerator] = &[ application("win.reopen-closed-tab", &["t"], Tabs), // Ctrl+Tab stays the tab view's next tab, as across GNOME. application("win.switch-recent-tab", &["e"], Tabs), - // As in GNOME Web and Console. - application("win.show-tabs", &["o"], Tabs), + application("win.show-tabs", &["o"], Tabs), // AdwTabView's own controller, which runs in the capture phase. The // workspace removes its Ctrl+Home and Ctrl+End pairs, so the lists // and the editor inside the tabs keep those keys. @@ -558,6 +560,7 @@ pub fn local_shortcut_controller(owner: ShortcutOwner) -> gtk::ShortcutControlle /// The name `local_shortcut_controller` gives the owner's controller. pub const fn controller_name(owner: ShortcutOwner) -> &'static str { match owner { + QuickOpen => "tablepro-quick-open-shortcuts", BrowseTab => "tablepro-browse-tab-shortcuts", GridCell => "tablepro-grid-cell-shortcuts", Grid => "tablepro-grid-shortcuts", diff --git a/linux/crates/app/src/application/shortcut_owner.rs b/linux/crates/app/src/application/shortcut_owner.rs index 4b94b25b06..d2043b24c9 100644 --- a/linux/crates/app/src/application/shortcut_owner.rs +++ b/linux/crates/app/src/application/shortcut_owner.rs @@ -1,6 +1,7 @@ #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum ShortcutOwner { BrowseTab, + QuickOpen, /// A data grid's column view, ahead of the list's own key bindings. GridCell, /// A data grid's column view, after a focused editor had its turn. diff --git a/linux/crates/app/src/ui/quick_open/matching.rs b/linux/crates/app/src/ui/quick_open/matching.rs index e6efa1f3a1..8ecbf28180 100644 --- a/linux/crates/app/src/ui/quick_open/matching.rs +++ b/linux/crates/app/src/ui/quick_open/matching.rs @@ -1,63 +1,61 @@ -/// How well `name` answers what the user typed, lower the better, or -/// `None` when it does not. A name that starts with the text comes first, -/// then one that holds it, then one whose letters follow it in order with -/// others between, as a fuzzy finder takes them. -pub(super) fn rank(typed: &str, name: &str) -> Option { - let typed: Vec = typed.trim().chars().flat_map(char::to_lowercase).collect(); - if typed.is_empty() { - return Some(0); - } - let name: Vec = name.chars().flat_map(char::to_lowercase).collect(); - if name.starts_with(&typed) { - return Some(0); - } - if let Some(at) = name.windows(typed.len()).position(|window| window == typed.as_slice()) { - return Some(100 + u32::try_from(at).unwrap_or(u32::MAX - 100)); - } - // The letters in order, charged for each one skipped between them. - let mut wanted = typed.iter().peekable(); - let mut skipped = 0u32; - let mut started = false; - for letter in &name { - match wanted.peek() { - Some(next) if *next == letter => { - wanted.next(); - started = true; +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +pub(super) struct Rank(u8, usize); + +pub(super) fn normalize(text: &str) -> Vec { + text.chars().flat_map(char::to_lowercase).collect() +} + +pub(super) fn rank(typed: &[char], name: &[char]) -> Option { + if typed.is_empty() || name.starts_with(typed) { + return Some(Rank(0, 0)); + } + if let Some(at) = name.windows(typed.len()).position(|window| window == typed) { + return Some(Rank(1, at)); + } + let mut wanted = typed.iter(); + let mut next = wanted.next(); + let mut first = None; + for (position, letter) in name.iter().enumerate() { + if next == Some(letter) { + first.get_or_insert(position); + next = wanted.next(); + if next.is_none() { + return Some(Rank(2, position - first.unwrap_or(position) + 1 - typed.len())); } - Some(_) if started => skipped = skipped.saturating_add(1), - _ => {} } } - wanted.peek().is_none().then_some(1_000 + skipped) + None } #[cfg(test)] mod tests { use super::*; - #[test] - fn a_blank_search_keeps_everything() { - assert_eq!(rank(" ", "orders"), Some(0)); + fn score(typed: &str, name: &str) -> Option { + rank(&normalize(typed.trim()), &normalize(name)) } #[test] - fn a_prefix_beats_a_hit_inside_beats_scattered_letters() { - let prefix = rank("ord", "orders").expect("a prefix"); - let inside = rank("der", "orders").expect("inside"); - let scattered = rank("ods", "orders").expect("scattered"); - - assert!(prefix < inside && inside < scattered, "{prefix} {inside} {scattered}"); + fn classes_never_overlap_even_for_long_names() { + let prefix = score("ab", "ab").unwrap(); + let inside = score("ab", &format!("{}ab", "x".repeat(2_000))).unwrap(); + let scattered = score("ab", "axb").unwrap(); + assert!(prefix < inside && inside < scattered); } #[test] - fn case_does_not_matter_and_a_miss_is_none() { - assert_eq!(rank("ORD", "Orders"), Some(0)); - assert_eq!(rank("xyz", "orders"), None); - assert_eq!(rank("sro", "orders"), None, "the letters were out of order"); + fn whitespace_case_unicode_and_order() { + assert_eq!(score(" ", "orders"), Some(Rank(0, 0))); + assert_eq!(score(" ÉT ", "Études"), Some(Rank(0, 0))); + assert_eq!(score("ods", "orders"), Some(Rank(2, 3))); + assert_eq!(score("sro", "orders"), None); + assert_eq!(score("longer", "a"), None); + assert_eq!(score("x", ""), None); } #[test] - fn a_nearer_hit_inside_ranks_first() { - assert!(rank("ar", "bar").expect("near") < rank("ar", "xxbar").expect("far")); + fn nearer_substrings_and_tighter_subsequences_rank_first() { + assert!(score("ar", "bar").unwrap() < score("ar", "xxbar").unwrap()); + assert!(score("ab", "axb").unwrap() < score("ab", "axxxb").unwrap()); } } diff --git a/linux/crates/app/src/ui/quick_open/mod.rs b/linux/crates/app/src/ui/quick_open/mod.rs index cdf4d4d9d2..4e2291f008 100644 --- a/linux/crates/app/src/ui/quick_open/mod.rs +++ b/linux/crates/app/src/ui/quick_open/mod.rs @@ -1,12 +1,11 @@ -//! Open Quickly: a search over the front connection's tables and views, -//! as the macOS Quick Switcher (`QuickSwitcherPanelView`) offers, so a -//! table is one key and a few letters away instead of a scroll through -//! the sidebar. Enter opens it and Ctrl+Enter opens its structure. - mod matching; +mod search_index; +#[cfg(test)] +mod tests; -use std::cell::RefCell; +use std::cell::{Cell, OnceCell, RefCell}; use std::rc::Rc; +use std::sync::Arc; use gtk4 as gtk; use gtk4::prelude::*; @@ -14,47 +13,42 @@ use gtk4::subclass::prelude::ObjectSubclassIsExt; use gtk4::{gdk, gio, glib}; use libadwaita as adw; use libadwaita::prelude::*; -use tablepro_core::meta::{ObjectInfo, ObjectKind, TableRef}; +use tablepro_core::meta::{ObjectKind, ObjectScope}; +use tablepro_session::runtime::{Tasks, WatchForwarder}; +use tablepro_session::{ObjectListSnapshot, Session}; use crate::i18n::{gettext, gettext_f}; +use crate::runtime::{RequestSequencer, spawn_and_deliver}; use crate::ui::icons; +pub(crate) use search_index::Target; +use search_index::{Candidate, SearchIndex}; -/// The rows listed at once, which a longer search narrows. -const LISTED: usize = 200; - -/// What the user chose, and whether they asked for its structure. #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) struct Pick { - pub table: TableRef, - pub structure: bool, + pub(crate) target: Target, + pub(crate) structure: bool, } -type Chosen = Rc; +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +enum Request { + Index, + Search, +} -/// The tables and views of `objects`, by name. -pub(crate) fn candidates(objects: &[ObjectInfo]) -> Vec { - let mut found: Vec = objects - .iter() - .filter(|object| object.kind.is_browsable()) - .cloned() - .collect(); - found.sort_by_cached_key(|object| (object.name.to_lowercase(), object.schema.clone())); - found +struct Context { + session: Arc, + tasks: Tasks, + chosen: Rc, } -/// The candidates `typed` finds, the best first, at most `LISTED`. -pub(crate) fn search(candidates: &[ObjectInfo], typed: &str) -> Vec { - let mut ranked: Vec<(u32, &ObjectInfo)> = candidates - .iter() - .filter_map(|object| matching::rank(typed, &object.name).map(|rank| (rank, object))) - .collect(); - // Stable, so equals keep the by-name order the candidates came in. - ranked.sort_by_key(|(rank, _)| *rank); - ranked - .into_iter() - .take(LISTED) - .map(|(_, object)| object.clone()) - .collect() +struct Widgets { + entry: gtk::SearchEntry, + store: gio::ListStore, + selection: gtk::SingleSelection, + list: gtk::ListView, + stack: gtk::Stack, + status: adw::StatusPage, + banner: adw::Banner, } glib::wrapper! { @@ -64,17 +58,20 @@ glib::wrapper! { } mod imp { - use std::cell::RefCell; - - use gtk4::glib; + use super::*; use gtk4::subclass::prelude::*; - use libadwaita as adw; use libadwaita::subclass::prelude::*; - use tablepro_core::meta::ObjectInfo; #[derive(Default)] pub struct QuickOpen { - pub candidates: RefCell>, + pub(super) widgets: OnceCell, + pub(super) context: RefCell>, + pub(super) watches: RefCell>, + pub(super) requests: RefCell>, + pub(super) index: RefCell>, + pub(super) generation: Cell>, + pub(super) rendered: RefCell>, + pub(super) pending_pick: Cell>, } #[glib::object_subclass] @@ -84,18 +81,58 @@ mod imp { type ParentType = adw::Dialog; } - impl ObjectImpl for QuickOpen {} + impl ObjectImpl for QuickOpen { + fn dispose(&self) { + self.obj().stop(); + } + } impl WidgetImpl for QuickOpen {} impl AdwDialogImpl for QuickOpen {} } impl QuickOpen { - pub(crate) fn new(objects: &[ObjectInfo], chosen: impl Fn(Pick) + 'static) -> Self { + pub(crate) fn new(session: Arc, tasks: Tasks, chosen: impl Fn(Pick) + 'static) -> Self { let dialog: Self = glib::Object::new(); dialog.set_title(&gettext("Open Quickly")); dialog.set_content_width(520); dialog.set_content_height(440); - let all = candidates(objects); + dialog.build(); + dialog.imp().context.replace(Some(Context { + session: session.clone(), + tasks, + chosen: Rc::new(chosen), + })); + dialog.connect_closed(|dialog| dialog.stop()); + let weak = dialog.downgrade(); + let catalog = WatchForwarder::new( + session.subscribe_objects(ObjectScope::AllSchemas), + move |snapshot| { + if let Some(dialog) = weak.upgrade() { + dialog.catalog_changed(snapshot); + } + }, + spawn_local, + ); + let weak = dialog.downgrade(); + let mut link = *session.link_changes().borrow(); + let reconnect = WatchForwarder::new( + session.link_changes(), + move |generation| { + if generation != link { + link = generation; + if let Some(dialog) = weak.upgrade() { + dialog.load(false); + } + } + }, + spawn_local, + ); + dialog.imp().watches.replace(vec![catalog, reconnect]); + dialog.load(false); + dialog + } + + fn build(&self) { let store = gio::ListStore::new::(); let selection = gtk::SingleSelection::new(Some(store.clone())); let list = gtk::ListView::new(Some(selection.clone()), Some(factory())); @@ -107,14 +144,15 @@ impl QuickOpen { .vexpand(true) .child(&list) .build(); - let empty = adw::StatusPage::builder() - .title(gettext("No Matches")) - .description(gettext("No table or view matches what you typed.")) + let status = adw::StatusPage::builder() + .title(gettext("Loading Tables and Views")) .build(); - empty.add_css_class("compact"); + status.add_css_class("compact"); let stack = gtk::Stack::new(); + stack.set_vexpand(true); stack.add_named(&scrolled, Some("list")); - stack.add_named(&empty, Some("empty")); + stack.add_named(&status, Some("status")); + stack.set_visible_child_name("status"); let entry = gtk::SearchEntry::builder() .placeholder_text(gettext("Search tables and views")) .hexpand(true) @@ -124,114 +162,366 @@ impl QuickOpen { .margin_end(12) .build(); entry.update_property(&[gtk::accessible::Property::Label(&gettext("Search tables and views"))]); + let banner = adw::Banner::builder() + .title(gettext("Could not load tables and views.")) + .button_label(gettext("Retry")) + .revealed(false) + .build(); let body = gtk::Box::new(gtk::Orientation::Vertical, 0); body.append(&entry); + body.append(&banner); body.append(&stack); - let header = adw::HeaderBar::new(); let view = adw::ToolbarView::new(); - view.add_top_bar(&header); + view.add_top_bar(&adw::HeaderBar::new()); view.set_content(Some(&body)); - dialog.set_child(Some(&view)); - dialog.set_focus(Some(&entry)); - dialog.imp().candidates.replace(all.clone()); + self.set_child(Some(&view)); + self.set_focus(Some(&entry)); + entry.connect_changed(glib::clone!( + #[weak(rename_to=dialog)] + self, + move |_| { + dialog.imp().pending_pick.set(None); + dialog.imp().requests.borrow_mut().cancel(Request::Search); + } + )); + entry.connect_search_changed(glib::clone!( + #[weak(rename_to=dialog)] + self, + move |_| dialog.search() + )); + entry.connect_activate(glib::clone!( + #[weak(rename_to=dialog)] + self, + move |_| dialog.activate(false) + )); + entry.connect_stop_search(glib::clone!( + #[weak(rename_to=dialog)] + self, + move |_| dialog.dismiss() + )); + entry.connect_next_match(glib::clone!( + #[weak(rename_to=dialog)] + self, + move |_| dialog.step(1) + )); + entry.connect_previous_match(glib::clone!( + #[weak(rename_to=dialog)] + self, + move |_| dialog.step(-1) + )); + list.connect_activate(glib::clone!( + #[weak(rename_to=dialog)] + self, + move |_, position| { + if let Some(widgets) = dialog.imp().widgets.get() { + widgets.selection.set_selected(position); + } + dialog.activate(false); + } + )); + banner.connect_button_clicked(glib::clone!( + #[weak(rename_to=dialog)] + self, + move |_| dialog.load(true) + )); + let keys = gtk::EventControllerKey::new(); + keys.set_propagation_phase(gtk::PropagationPhase::Capture); + keys.connect_key_pressed(glib::clone!( + #[weak(rename_to=dialog)] + self, + #[upgrade_or] + glib::Propagation::Proceed, + move |_, key, _, modifiers| dialog.key(key, modifiers) + )); + view.add_controller(keys); + let _ = self.imp().widgets.set(Widgets { + entry, + store, + selection, + list, + stack, + status, + banner, + }); + } + + fn key(&self, key: gdk::Key, modifiers: gdk::ModifierType) -> glib::Propagation { + let matches = |action| crate::application::component_matches(action, key, modifiers); + if matches("quick-open.structure") { + self.activate(true); + } else if self.entry_has_focus() && matches("quick-open.next") { + self.step(1); + } else if self.entry_has_focus() && matches("quick-open.previous") { + self.step(-1); + } else { + return glib::Propagation::Proceed; + } + glib::Propagation::Stop + } + + fn entry_has_focus(&self) -> bool { + self.imp().widgets.get().is_some_and(|w| { + self.focus() + .is_some_and(|focus| focus == w.entry || focus.is_ancestor(&w.entry)) + }) + } + + pub(crate) fn dismiss(&self) { + self.stop(); + if self.parent().is_some() { + self.close(); + } + } - let show = { - let (store, stack, selection) = (store.clone(), stack.clone(), selection.clone()); - move |typed: &str| { - let found = search(&all, typed); - let items: Vec = found.into_iter().map(glib::BoxedAnyObject::new).collect(); - store.splice(0, store.n_items(), &items); - stack.set_visible_child_name(if items.is_empty() { "empty" } else { "list" }); - selection.set_selected(if items.is_empty() { - gtk::INVALID_LIST_POSITION + fn stop(&self) { + self.imp().context.borrow_mut().take(); + self.imp().watches.borrow_mut().clear(); + self.imp().requests.borrow_mut().cancel_all(); + self.imp().pending_pick.set(None); + } + + fn load(&self, refresh: bool) { + let Some((session, tasks)) = self + .imp() + .context + .borrow() + .as_ref() + .map(|context| (context.session.clone(), context.tasks.clone())) + else { + return; + }; + if refresh { + self.imp().generation.set(None); + } + let weak = self.downgrade(); + spawn_and_deliver( + &tasks, + async move { + if refresh { + session.refresh_objects(ObjectScope::AllSchemas).await } else { - 0 - }); + session.objects(ObjectScope::AllSchemas).await + } + }, + move |result| { + if let Err(error) = result { + tracing::warn!(%error, "could not load quick open catalog"); + if let Some(dialog) = weak.upgrade() { + dialog.search_failed(); + } + } + }, + ); + } + + fn catalog_changed(&self, snapshot: ObjectListSnapshot) { + let imp = self.imp(); + if imp.context.borrow().is_none() { + return; + } + let Some(widgets) = imp.widgets.get() else { + return; + }; + widgets.banner.set_revealed(snapshot.last_error.is_some()); + if snapshot.generation == 0 { + if snapshot.last_error.is_some() { + widgets.status.set_title(&gettext("Could Not Load Tables and Views")); + widgets + .status + .set_description(Some(&gettext("Use Retry to try again."))); } + return; + } + if imp.generation.replace(Some(snapshot.generation)) == Some(snapshot.generation) { + return; + } + imp.requests.borrow_mut().cancel(Request::Search); + let ticket = imp.requests.borrow_mut().issue(Request::Index); + let Some(tasks) = imp.context.borrow().as_ref().map(|context| context.tasks.clone()) else { + return; }; - show(""); - entry.connect_search_changed({ - let show = show.clone(); - move |entry| show(&entry.text()) + let running = tasks.spawn_blocking_task(move || SearchIndex::tables(&snapshot.objects)); + let weak = self.downgrade(); + glib::spawn_future_local(async move { + let result = running.await; + let Some(dialog) = weak.upgrade() else { + return; + }; + if !dialog.imp().requests.borrow_mut().accept(Request::Index, ticket.stamp) { + return; + } + match result { + Ok(index) => { + dialog.imp().index.replace(Arc::new(index)); + dialog.search(); + } + Err(error) => { + tracing::warn!(%error, "could not index quick open results"); + dialog.search_failed(); + } + } }); + } - let chosen: Chosen = Rc::new(chosen); - let dialog_weak = dialog.downgrade(); - let pick = { - let (store, chosen) = (store.clone(), chosen.clone()); - move |position: u32, structure: bool| { - let Some(object) = store - .item(position) - .and_downcast::() - .map(|item| item.borrow::().clone()) - else { - return; - }; - if let Some(dialog) = dialog_weak.upgrade() { - dialog.close(); + fn search(&self) { + let imp = self.imp(); + let Some(widgets) = imp.widgets.get() else { + return; + }; + let Some(tasks) = imp.context.borrow().as_ref().map(|context| context.tasks.clone()) else { + return; + }; + if imp.requests.borrow().is_pending(Request::Index) || imp.generation.get().is_none() { + return; + } + let text = widgets.entry.text().to_string(); + let ticket = imp.requests.borrow_mut().issue(Request::Search); + let index = imp.index.borrow().clone(); + let query = text.clone(); + let running = tasks.spawn_blocking_task(move || index.search(&query)); + let weak = self.downgrade(); + glib::spawn_future_local(async move { + let result = running.await; + let Some(dialog) = weak.upgrade() else { + return; + }; + if !dialog.imp().requests.borrow_mut().accept(Request::Search, ticket.stamp) { + return; + } + match result { + Ok(found) => dialog.show_results(text, found), + Err(error) => { + tracing::warn!(%error, "could not search quick open results"); + dialog.search_failed(); } - chosen(Pick { - table: TableRef::new(object.schema, object.name), - structure, - }); } - }; - list.connect_activate({ - let pick = pick.clone(); - move |_, position| pick(position, false) - }); - entry.connect_activate({ - let (pick, selection) = (pick.clone(), selection.clone()); - move |_| pick(selection.selected(), false) - }); - // Up and Down move the choice while the text keeps the keyboard. - entry.connect_next_match({ - let selection = selection.clone(); - move |_| step(&selection, 1) }); - entry.connect_previous_match({ - let selection = selection.clone(); - move |_| step(&selection, -1) + } + + fn search_failed(&self) { + self.imp().rendered.replace(None); + self.imp().pending_pick.set(None); + if let Some(widgets) = self.imp().widgets.get() { + widgets.banner.set_revealed(true); + } + } + + fn selected(&self) -> Option { + let widgets = self.imp().widgets.get()?; + widgets + .selection + .selected_item() + .and_downcast::() + .map(|item| item.borrow::().clone()) + } + + fn show_results(&self, text: String, found: Vec) { + let imp = self.imp(); + let Some(widgets) = imp.widgets.get() else { + return; + }; + let previous = (imp.rendered.borrow().as_deref() == Some(text.as_str())) + .then(|| self.selected()) + .flatten() + .map(|candidate| candidate.target()); + let selected = previous + .and_then(|target| found.iter().position(|candidate| candidate.target() == target)) + .unwrap_or(0); + let items: Vec<_> = found.into_iter().map(glib::BoxedAnyObject::new).collect(); + widgets.store.splice(0, widgets.store.n_items(), &items); + widgets.selection.set_selected(if items.is_empty() { + gtk::INVALID_LIST_POSITION + } else { + u32::try_from(selected).unwrap_or(0) }); - let keys = gtk::EventControllerKey::new(); - let held: Rc> = Rc::default(); - keys.connect_key_pressed(move |_, key, _, modifiers| { - let _ = &held; - if matches!(key, gdk::Key::Return | gdk::Key::KP_Enter) - && modifiers.contains(gdk::ModifierType::CONTROL_MASK) + if items.is_empty() { + widgets.status.set_title(&gettext("No Matches")); + widgets + .status + .set_description(Some(&gettext("No table or view matches what you typed."))); + } + widgets + .stack + .set_visible_child_name(if items.is_empty() { "status" } else { "list" }); + imp.rendered.replace(Some(text)); + if !items.is_empty() { + widgets + .list + .scroll_to(widgets.selection.selected(), gtk::ListScrollFlags::NONE, None); + } + if let Some(structure) = imp.pending_pick.take() { + self.activate(structure); + } + } + + fn current(&self) -> bool { + let imp = self.imp(); + imp.widgets + .get() + .is_some_and(|widgets| imp.rendered.borrow().as_deref() == Some(widgets.entry.text().as_str())) + && !imp.requests.borrow().is_pending(Request::Index) + && !imp.requests.borrow().is_pending(Request::Search) + } + + fn activate(&self, structure: bool) { + if self.imp().context.borrow().is_none() { + return; + } + if !self.current() { + self.imp().pending_pick.set(Some(structure)); + self.search(); + return; + } + let Some(candidate) = self.selected() else { + return; + }; + let chosen = { + let context = self.imp().context.borrow(); + let Some(context) = context.as_ref() else { + return; + }; + if structure + && (!candidate.object.kind.is_structure_editable() + || !context + .session + .current_dialect() + .is_some_and(|dialect| dialect.ddl().is_some())) { - pick(selection.selected(), true); - return glib::Propagation::Stop; + return; } - glib::Propagation::Proceed - }); - entry.add_controller(keys); - dialog + context.chosen.clone() + }; + let pick = Pick { + target: candidate.target(), + structure, + }; + self.dismiss(); + chosen(pick); } - /// The tables and views the dialog searches. - #[cfg(test)] - pub(crate) fn candidate_names(&self) -> Vec { - use gtk4::subclass::prelude::ObjectSubclassIsExt; - self.imp() - .candidates - .borrow() - .iter() - .map(|object| object.name.clone()) - .collect() + fn step(&self, by: i32) { + if !self.current() { + self.search(); + return; + } + let Some(widgets) = self.imp().widgets.get() else { + return; + }; + let count = widgets.selection.n_items(); + if count == 0 { + return; + } + let current = i64::from(widgets.selection.selected().min(count - 1)); + let next = (current + i64::from(by)).clamp(0, i64::from(count) - 1); + let position = u32::try_from(next).unwrap_or(0); + widgets.selection.set_selected(position); + widgets.list.scroll_to(position, gtk::ListScrollFlags::NONE, None); } } -fn step(selection: >k::SingleSelection, by: i32) { - let count = selection.n_items(); - if count == 0 { - return; - } - let current = i64::from(selection.selected().min(count - 1)); - let next = (current + i64::from(by)).clamp(0, i64::from(count) - 1); - selection.set_selected(u32::try_from(next).unwrap_or(0)); +fn spawn_local(future: futures::future::LocalBoxFuture<'static, ()>) { + glib::spawn_future_local(future); } - fn factory() -> gtk::SignalListItemFactory { let factory = gtk::SignalListItemFactory::new(); factory.connect_setup(|_, item| { @@ -271,7 +561,7 @@ fn factory() -> gtk::SignalListItemFactory { let (Some(object), Some(row)) = (item.item().and_downcast::(), item.child()) else { return; }; - let object = object.borrow::().clone(); + let object = object.borrow::().object.clone(); let (Some(icon), Some(name), Some(place)) = ( row.first_child().and_downcast::(), row.first_child() @@ -287,58 +577,18 @@ fn factory() -> gtk::SignalListItemFactory { })); name.set_label(&object.name); place.set_label(object.schema.as_deref().unwrap_or_default()); + let kind = match object.kind { + ObjectKind::View | ObjectKind::MaterializedView => gettext("View"), + _ => gettext("Table"), + }; let described = match object.schema.as_deref() { - Some(schema) => gettext_f("{table}, in {schema}", &[("table", &object.name), ("schema", schema)]), - None => object.name.clone(), + Some(schema) => gettext_f( + "{table}, {kind}, in {schema}", + &[("table", &object.name), ("kind", &kind), ("schema", schema)], + ), + None => gettext_f("{table}, {kind}", &[("table", &object.name), ("kind", &kind)]), }; item.set_accessible_label(&described); }); factory } - -#[cfg(test)] -mod tests { - use super::*; - - fn table(schema: &str, name: &str, kind: ObjectKind) -> ObjectInfo { - ObjectInfo::new(Some(schema.to_owned()), name, kind) - } - - fn names(found: &[ObjectInfo]) -> Vec<&str> { - found.iter().map(|object| object.name.as_str()).collect() - } - - #[test] - fn only_what_the_grid_can_page_is_offered_and_it_is_ordered_by_name() { - let all = candidates(&[ - table("public", "orders", ObjectKind::Table), - table("public", "recount", ObjectKind::Function), - table("public", "Customers", ObjectKind::View), - table("public", "customers_id_seq", ObjectKind::Sequence), - ]); - - assert_eq!(names(&all), ["Customers", "orders"]); - } - - #[test] - fn the_best_match_comes_first_and_a_miss_is_left_out() { - let all = candidates(&[ - table("public", "reorder_log", ObjectKind::Table), - table("public", "orders", ObjectKind::Table), - table("sales", "order_items", ObjectKind::Table), - table("public", "users", ObjectKind::Table), - ]); - - assert_eq!(names(&search(&all, "ord")), ["order_items", "orders", "reorder_log"]); - assert!(search(&all, "zzz").is_empty()); - assert_eq!(search(&all, "").len(), 4); - } - - #[gtk4::test] - fn the_dialog_searches_the_tables_it_was_given() { - libadwaita::init().expect("libadwaita initialises under the test backend"); - let dialog = QuickOpen::new(&[table("public", "orders", ObjectKind::Table)], |_| {}); - - assert_eq!(dialog.candidate_names(), ["orders"]); - } -} diff --git a/linux/crates/app/src/ui/quick_open/search_index.rs b/linux/crates/app/src/ui/quick_open/search_index.rs new file mode 100644 index 0000000000..9bf104ff7b --- /dev/null +++ b/linux/crates/app/src/ui/quick_open/search_index.rs @@ -0,0 +1,120 @@ +use tablepro_core::meta::{ObjectInfo, TableRef}; + +use super::matching; + +pub(super) const LISTED: usize = 200; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) enum Target { + Table(TableRef), +} + +#[derive(Debug, Clone)] +pub(super) struct Candidate { + pub(super) object: ObjectInfo, +} + +impl Candidate { + pub(super) fn target(&self) -> Target { + Target::Table(TableRef::new(self.object.schema.clone(), self.object.name.clone())) + } +} + +#[derive(Debug, Default)] +pub(super) struct SearchIndex { + entries: Vec<(Candidate, Vec, Vec)>, +} + +impl SearchIndex { + pub(super) fn tables(objects: &[ObjectInfo]) -> Self { + Self::new( + objects + .iter() + .filter(|object| object.kind.is_browsable()) + .cloned() + .map(|object| Candidate { object }) + .collect(), + ) + } + + pub(super) fn new(candidates: Vec) -> Self { + let mut entries: Vec<_> = candidates + .into_iter() + .map(|candidate| { + let name = matching::normalize(&candidate.object.name); + let qualified = matching::normalize(&match candidate.object.schema.as_deref() { + Some(schema) => format!("{schema}.{}", candidate.object.name), + None => candidate.object.name.clone(), + }); + (candidate, name, qualified) + }) + .collect(); + entries.sort_by(|(a, an, _), (b, bn, _)| { + an.cmp(bn) + .then_with(|| a.object.schema.cmp(&b.object.schema)) + .then_with(|| a.object.name.cmp(&b.object.name)) + }); + Self { entries } + } + + pub(super) fn search(&self, typed: &str) -> Vec { + let typed = matching::normalize(typed.trim()); + let mut found: Vec<_> = self + .entries + .iter() + .filter_map(|(candidate, name, qualified)| { + matching::rank(&typed, name) + .into_iter() + .chain(matching::rank(&typed, qualified)) + .min() + .map(|rank| (rank, candidate)) + }) + .collect(); + found.sort_by_key(|(rank, _)| *rank); + found + .into_iter() + .take(LISTED) + .map(|(_, candidate)| candidate.clone()) + .collect() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use tablepro_core::meta::ObjectKind; + + fn object(schema: &str, name: &str, kind: ObjectKind) -> ObjectInfo { + ObjectInfo::new(Some(schema.to_owned()), name, kind) + } + + #[test] + fn browsable_objects_share_ranking_and_qualified_names() { + let index = SearchIndex::tables(&[ + object("public", "orders", ObjectKind::Table), + object("sales", "orders", ObjectKind::View), + object("sales", "order_items", ObjectKind::MaterializedView), + object("sales", "ordered", ObjectKind::Function), + ]); + let names = |text| { + index + .search(text) + .into_iter() + .map(|c| c.object.name) + .collect::>() + }; + assert_eq!(names("ord"), ["order_items", "orders", "orders"]); + assert_eq!(names("sales.orders"), ["orders"]); + assert!(names("zzz").is_empty()); + } + + #[test] + fn the_cap_applies_after_matching_the_entire_catalog() { + let objects: Vec<_> = (0..50_000) + .map(|i| object("main", &format!("table_{i:05}"), ObjectKind::Table)) + .collect(); + let index = SearchIndex::tables(&objects); + assert_eq!(index.search("").len(), LISTED); + assert_eq!(index.search("table_49999")[0].object.name, "table_49999"); + } +} diff --git a/linux/crates/app/src/ui/quick_open/tests.rs b/linux/crates/app/src/ui/quick_open/tests.rs new file mode 100644 index 0000000000..ddae04929f --- /dev/null +++ b/linux/crates/app/src/ui/quick_open/tests.rs @@ -0,0 +1,249 @@ +use std::cell::RefCell; +use std::rc::Rc; +use std::time::Duration; + +use tablepro_core::DriverError; +use tablepro_core::meta::ObjectInfo; +use tablepro_test_support::{ConnectionScript, FakeReply}; + +use super::*; +use crate::test_support::{FakeSession, finish_on_main, test_runtime, wait_until}; + +const WAIT: Duration = Duration::from_secs(5); + +fn object(name: &str, kind: ObjectKind) -> ObjectInfo { + ObjectInfo::new(Some("public".to_owned()), name, kind) +} + +type Fixture = ( + crate::runtime::AppRuntime, + FakeSession, + QuickOpen, + Rc>>, +); + +fn setup(objects: Vec) -> Fixture { + let mut script = ConnectionScript::default(); + script.list_objects.always(FakeReply::ok(objects)); + setup_script(script) +} + +fn setup_script(script: ConnectionScript) -> Fixture { + adw::init().expect("libadwaita"); + let runtime = test_runtime(); + let fake = FakeSession::start(script, [], runtime.tasks()); + let chosen = Rc::new(RefCell::new(Vec::new())); + let sink = chosen.clone(); + let dialog = QuickOpen::new(fake.session.clone(), runtime.tasks(), move |pick| { + sink.borrow_mut().push(pick) + }); + (runtime, fake, dialog, chosen) +} + +fn ready(dialog: &QuickOpen) { + wait_until(WAIT, || dialog.current()).expect("current search results"); +} + +#[gtk4::test] +fn an_unloaded_catalog_arrives_without_reopening() { + let (_runtime, _fake, dialog, _) = setup(vec![object("orders", ObjectKind::Table)]); + assert_eq!(dialog.imp().widgets.get().unwrap().store.n_items(), 0); + ready(&dialog); + assert_eq!(dialog.selected().unwrap().object.name, "orders"); + dialog.dismiss(); +} + +#[gtk4::test] +fn enter_after_typing_uses_the_new_search() { + let (_runtime, _fake, dialog, chosen) = setup(vec![ + object("customers", ObjectKind::Table), + object("orders", ObjectKind::Table), + ]); + ready(&dialog); + let widgets = dialog.imp().widgets.get().unwrap(); + widgets.entry.set_text("orders"); + widgets.entry.emit_by_name::<()>("activate", &[]); + assert!(chosen.borrow().is_empty(), "the previous row opened"); + wait_until(WAIT, || !chosen.borrow().is_empty()).expect("deferred activation"); + assert_eq!( + chosen.borrow()[0].target, + Target::Table(tablepro_core::meta::TableRef::new(Some("public".to_owned()), "orders")) + ); +} + +#[gtk4::test] +fn a_miss_cannot_activate_a_previous_result() { + let (_runtime, _fake, dialog, chosen) = setup(vec![object("orders", ObjectKind::Table)]); + ready(&dialog); + dialog.imp().widgets.get().unwrap().entry.set_text("missing"); + dialog.activate(false); + ready(&dialog); + assert!(chosen.borrow().is_empty()); + assert_eq!( + dialog + .imp() + .widgets + .get() + .unwrap() + .stack + .visible_child_name() + .as_deref(), + Some("status") + ); + dialog.dismiss(); +} + +#[gtk4::test] +fn keyboard_navigation_scrolls_and_keeps_search_focus() { + let (_runtime, _fake, dialog, _) = setup( + (0..100) + .map(|i| object(&format!("table_{i:03}"), ObjectKind::Table)) + .collect(), + ); + let window = adw::Window::new(); + window.set_default_size(800, 600); + window.present(); + dialog.present(Some(&window)); + ready(&dialog); + wait_until(WAIT, || dialog.entry_has_focus()).expect("search focus"); + for _ in 0..60 { + assert_eq!( + dialog.key(gdk::Key::Down, gdk::ModifierType::empty()), + glib::Propagation::Stop + ); + } + let widgets = dialog.imp().widgets.get().unwrap(); + assert_eq!(widgets.selection.selected(), 60); + assert!(dialog.entry_has_focus()); + let scrolled = widgets + .list + .parent() + .and_downcast::() + .expect("scroller"); + wait_until(WAIT, || scrolled.vadjustment().value() > 0.0).expect("selected row scrolled into view"); + widgets.entry.emit_by_name::<()>("stop-search", &[]); + wait_until(WAIT, || dialog.parent().is_none()).expect("Escape closes"); + assert!(dialog.imp().context.borrow().is_none()); + window.destroy(); +} + +#[gtk4::test] +fn structure_is_not_offered_for_views_or_a_dialect_without_ddl() { + let (_runtime, _fake, dialog, chosen) = setup(vec![ + object("orders", ObjectKind::Table), + object("view", ObjectKind::View), + ]); + ready(&dialog); + assert_eq!( + dialog.key(gdk::Key::Return, gdk::ModifierType::CONTROL_MASK), + glib::Propagation::Stop + ); + assert!(chosen.borrow().is_empty(), "the fake dialect has no DDL"); + dialog.step(1); + dialog.activate(true); + assert!(chosen.borrow().is_empty()); + dialog.activate(false); + assert_eq!(chosen.borrow().len(), 1, "a view can still be browsed"); + assert!(!chosen.borrow()[0].structure); +} + +#[gtk4::test] +fn a_catalog_refresh_preserves_identity_and_removes_dropped_objects() { + let mut script = ConnectionScript::default(); + script + .list_objects + .once(FakeReply::ok(vec![ + object("orders", ObjectKind::Table), + object("users", ObjectKind::Table), + ])) + .always(FakeReply::ok(vec![ + object("aardvark", ObjectKind::Table), + object("users", ObjectKind::Table), + ])); + let (runtime, fake, dialog, _) = setup_script(script); + ready(&dialog); + dialog.step(1); + let session = fake.session.clone(); + finish_on_main( + WAIT, + runtime + .tasks() + .spawn_task(async move { session.refresh_objects(ObjectScope::AllSchemas).await }), + ) + .unwrap() + .unwrap() + .unwrap(); + wait_until(WAIT, || dialog.imp().generation.get() == Some(2) && dialog.current()).unwrap(); + assert_eq!(dialog.selected().unwrap().object.name, "users"); + dialog.imp().widgets.get().unwrap().entry.set_text("orders"); + dialog.search(); + ready(&dialog); + assert!(dialog.selected().is_none()); + dialog.dismiss(); +} + +#[gtk4::test] +fn a_failed_read_has_retry_and_recovers() { + adw::init().expect("libadwaita"); + let runtime = test_runtime(); + let mut script = ConnectionScript::default(); + script.list_objects.once(FakeReply::err(DriverError::Cancelled)); + script + .list_objects + .always(FakeReply::ok(vec![object("orders", ObjectKind::Table)])); + let fake = FakeSession::start(script, [], runtime.tasks()); + let dialog = QuickOpen::new(fake.session, runtime.tasks(), |_| {}); + let widgets = dialog.imp().widgets.get().unwrap(); + wait_until(WAIT, || widgets.banner.is_revealed()).expect("read failure visible"); + widgets.banner.emit_by_name::<()>("button-clicked", &[]); + ready(&dialog); + assert_eq!(dialog.selected().unwrap().object.name, "orders"); + assert!(!widgets.banner.is_revealed()); + dialog.dismiss(); +} + +#[gtk4::test] +fn a_closed_dialog_retained_by_its_workspace_stops_work() { + let (runtime, fake, dialog, chosen) = setup(vec![object("orders", ObjectKind::Table)]); + ready(&dialog); + dialog.imp().widgets.get().unwrap().entry.set_text("ord"); + dialog.activate(false); + dialog.dismiss(); + let generation = dialog.imp().generation.get(); + let session = fake.session.clone(); + finish_on_main( + WAIT, + runtime + .tasks() + .spawn_task(async move { session.refresh_objects(ObjectScope::AllSchemas).await }), + ) + .unwrap() + .unwrap() + .unwrap(); + crate::test_support::drain_main_context(); + assert_eq!(dialog.imp().generation.get(), generation); + assert!(dialog.imp().watches.borrow().is_empty()); + assert!(dialog.imp().context.borrow().is_none()); + assert!(chosen.borrow().is_empty()); +} + +#[gtk4::test] +fn control_enter_opens_table_structure_with_a_ddl_dialect() { + let mut script = ConnectionScript { + dialect: Arc::new(tablepro_driver_postgres::PgDialect::new( + &tablepro_core::ServerInfo::new("PostgreSQL", "18.0", 18, 0, 0), + )), + ..ConnectionScript::default() + }; + script + .list_objects + .always(FakeReply::ok(vec![object("orders", ObjectKind::Table)])); + let (_runtime, _fake, dialog, chosen) = setup_script(script); + ready(&dialog); + assert_eq!( + dialog.key(gdk::Key::Return, gdk::ModifierType::CONTROL_MASK), + glib::Propagation::Stop + ); + assert_eq!(chosen.borrow().len(), 1); + assert!(chosen.borrow()[0].structure); +} diff --git a/linux/crates/app/src/ui/workspace/mod.rs b/linux/crates/app/src/ui/workspace/mod.rs index 459e5200eb..a443edd8b1 100644 --- a/linux/crates/app/src/ui/workspace/mod.rs +++ b/linux/crates/app/src/ui/workspace/mod.rs @@ -179,6 +179,7 @@ pub(crate) struct WorkspaceModel { /// The CSV imports running into this workspace's tables. imports: Rc, history_dialog: Option, + quick_open_dialog: Option, saved_queries_dialog: Option, import_dialog: Option, driver_id: String, @@ -896,6 +897,7 @@ impl Workspace { exports: exports.clone(), imports: imports.clone(), history_dialog: None, + quick_open_dialog: None, saved_queries_dialog: None, import_dialog: None, workspace: persistence, @@ -1263,6 +1265,7 @@ impl WorkspaceModel { keys.stop_listing(); } self.sidebar.shutdown(); + self.close_quick_open(); // Their entries name this session's tables and queries. if let Some(dialog) = self.history_dialog.take() { close_if_presented(dialog.upcast_ref()); diff --git a/linux/crates/app/src/ui/workspace/status_pages.rs b/linux/crates/app/src/ui/workspace/status_pages.rs index a0a768f05c..bb486831fd 100644 --- a/linux/crates/app/src/ui/workspace/status_pages.rs +++ b/linux/crates/app/src/ui/workspace/status_pages.rs @@ -84,20 +84,21 @@ impl WorkspaceModel { self.saved_queries_dialog = Some(dialog); } - /// Open Quickly: a search over the session's tables and views, which - /// opens the one chosen as the sidebar's row does, or its structure. + pub(super) fn close_quick_open(&mut self) { + if let Some(dialog) = self.quick_open_dialog.take() { + dialog.dismiss(); + } + } + pub(super) fn on_show_quick_open(&mut self) { let Some(session) = self.context.active.get() else { return; }; - let objects = session - .subscribe_objects(tablepro_core::meta::ObjectScope::AllSchemas) - .borrow() - .objects - .clone(); + self.close_quick_open(); let input = self.input.clone(); - let dialog = crate::ui::quick_open::QuickOpen::new(&objects, move |pick| { - let tablepro_core::meta::TableRef { schema, name } = pick.table; + let dialog = crate::ui::quick_open::QuickOpen::new(session, self.tasks.clone(), move |pick| { + let crate::ui::quick_open::Target::Table(table) = pick.target; + let tablepro_core::meta::TableRef { schema, name } = table; input.deliver(match pick.structure { true => WorkspaceInput::EditStructureTab { schema, table: name }, false => WorkspaceInput::SelectTable { @@ -108,6 +109,7 @@ impl WorkspaceModel { }); }); dialog.present(self.dialog_parent().as_ref()); + self.quick_open_dialog = Some(dialog); } /// Ask what to call the SQL in front of the user, then keep it. @@ -225,6 +227,23 @@ mod tests { use crate::test_support::{finish_on_main, wait_until}; use crate::ui::session_window::tests::{TestWindow, WAIT}; + #[gtk4::test] + fn open_quickly_closes_on_disconnect() { + use gtk4::prelude::*; + let test = TestWindow::connected("QuickOpenDisconnect"); + let dialog = test + .workspace() + .with_model(|model| { + model.on_show_quick_open(); + model.quick_open_dialog.clone().expect("quick open") + }) + .expect("workspace"); + wait_until(WAIT, || dialog.parent().is_some()).expect("shown"); + test.window.send(crate::ui::SessionWindowInput::Disconnect); + wait_until(WAIT, || dialog.parent().is_none()).expect("dialog closed"); + wait_until(WAIT, || test.window.page_name() == "picker").expect("disconnected"); + } + #[gtk4::test] fn a_saved_query_is_written_under_a_hold() { let test = TestWindow::connected("SaveQueryHeld"); diff --git a/linux/crates/app/src/ui/workspace/tests/shell.rs b/linux/crates/app/src/ui/workspace/tests/shell.rs index b264b074a4..b2f21e4219 100644 --- a/linux/crates/app/src/ui/workspace/tests/shell.rs +++ b/linux/crates/app/src/ui/workspace/tests/shell.rs @@ -563,3 +563,20 @@ fn the_main_menu_adds_a_connection_with_none_open() { choose_new_connection(&test, &test.window.content().expect("the picker")); } + +#[gtk4::test] +fn open_quickly_closes_when_another_session_comes_forward() { + let sessions = super::two_sessions("QuickOpenFollowsFront", "Other"); + super::open_editor(&sessions.first); + let dialog = sessions + .first + .with_model(|model| { + model.on_show_quick_open(); + model.quick_open_dialog.clone().expect("quick open") + }) + .expect("workspace"); + wait_until(WAIT, || dialog.parent().is_some()).expect("shown"); + super::open_editor(&sessions.second); + wait_until(WAIT, || dialog.parent().is_none()).expect("old session dialog closed"); + assert_eq!(sessions.shell.front().as_ref(), Some(&sessions.second)); +} diff --git a/linux/crates/app/src/ui/workspace/workspace_shell.rs b/linux/crates/app/src/ui/workspace/workspace_shell.rs index 25eb2ae449..e31f756d41 100644 --- a/linux/crates/app/src/ui/workspace/workspace_shell.rs +++ b/linux/crates/app/src/ui/workspace/workspace_shell.rs @@ -528,6 +528,10 @@ impl WorkspaceShell { if imp.front.borrow().as_ref() == workspace { return; } + let previous = imp.front.borrow().clone(); + if let Some(previous) = previous { + previous.with_model(|model| model.close_quick_open()); + } imp.front.replace(workspace.cloned()); self.notify_front(); } diff --git a/linux/docs/state-management.md b/linux/docs/state-management.md index 8550e8077c..c8caca935a 100644 --- a/linux/docs/state-management.md +++ b/linux/docs/state-management.md @@ -140,6 +140,20 @@ Every `RunSummary` carries the session's `TransactionState`, and the last one a The tab emits `transaction-changed` when that flips, and the workspace reads `WorkspaceHandle::dirty_tabs` again. Through `TabDirectory::tabs` it lists the tab as `DirtyKind::OpenTransaction` when the tab has nothing else pending, so the page shows the unsaved icon and the close prompts ask about it. A close asks once: the tabs the user agreed to lose are not asked about again in that close. +## Open Quickly + +`QuickOpen` owns its session's catalog watch and explicitly reads all schemas when it opens. +Its pure `SearchIndex` prepares names and ranks candidates on a blocking worker, with a limit of +200 displayed results. Request stamps discard older index and search replies. A changed search +cannot activate the old selection; Enter waits for the current results. Catalog updates preserve +the selected object's identity, and failed reads retain the displayed content with Retry. + +The workspace closes the dialog when another session comes forward or the workspace shuts down. +Closing stops watches and cancels delivery even while the workspace still retains the widget. +Ctrl+Shift+O opens it, matching Open Quickly on macOS; Ctrl+Alt+O opens the tab overview. +Up and Down keep focus in the search entry and scroll the selection into view. Ctrl+Enter opens +structure only for objects and dialects that support it. + ## The query history dialog `HistoryDialog` reads the history a page of 100 at a time off the GTK thread, by the keyset [storage.md](storage.md#searching-the-history) describes. diff --git a/linux/po/POTFILES.in b/linux/po/POTFILES.in index 686b5bc5c5..7bed73dad1 100644 --- a/linux/po/POTFILES.in +++ b/linux/po/POTFILES.in @@ -495,6 +495,8 @@ crates/app/src/ui/preferences_dialog/mcp_page.rs crates/app/src/ui/preferences_dialog/mod.rs crates/app/src/ui/quick_open/matching.rs crates/app/src/ui/quick_open/mod.rs +crates/app/src/ui/quick_open/search_index.rs +crates/app/src/ui/quick_open/tests.rs crates/app/src/ui/result_pane/mod.rs crates/app/src/ui/result_pane/result_limit_banner.rs crates/app/src/ui/result_pane/result_set_view.rs From ab018e100950b59bfda6e62c4e3f1e13fabf07da Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 8 Nov 2026 23:03:51 +0700 Subject: [PATCH 07/15] fix(linux-workspace): preserve quick open input order --- linux/crates/app/src/ui/quick_open/mod.rs | 46 +++++++++++++++---- linux/crates/app/src/ui/quick_open/tests.rs | 35 ++++++++++++++ linux/crates/app/src/ui/workspace/mod.rs | 4 ++ .../app/src/ui/workspace/status_pages.rs | 27 +++++++---- .../app/src/ui/workspace/tests/shell.rs | 15 ++++++ .../app/src/ui/workspace/workspace_shell.rs | 7 ++- 6 files changed, 112 insertions(+), 22 deletions(-) diff --git a/linux/crates/app/src/ui/quick_open/mod.rs b/linux/crates/app/src/ui/quick_open/mod.rs index 4e2291f008..47747e4abf 100644 --- a/linux/crates/app/src/ui/quick_open/mod.rs +++ b/linux/crates/app/src/ui/quick_open/mod.rs @@ -72,6 +72,7 @@ mod imp { pub(super) generation: Cell>, pub(super) rendered: RefCell>, pub(super) pending_pick: Cell>, + pub(super) pending_steps: RefCell>, } #[glib::object_subclass] @@ -176,11 +177,31 @@ impl QuickOpen { view.set_content(Some(&body)); self.set_child(Some(&view)); self.set_focus(Some(&entry)); + self.connect_controls(&entry, &list, &banner, &view); + let _ = self.imp().widgets.set(Widgets { + entry, + store, + selection, + list, + stack, + status, + banner, + }); + } + + fn connect_controls( + &self, + entry: >k::SearchEntry, + list: >k::ListView, + banner: &adw::Banner, + view: &adw::ToolbarView, + ) { entry.connect_changed(glib::clone!( #[weak(rename_to=dialog)] self, move |_| { dialog.imp().pending_pick.set(None); + dialog.imp().pending_steps.borrow_mut().clear(); dialog.imp().requests.borrow_mut().cancel(Request::Search); } )); @@ -213,6 +234,10 @@ impl QuickOpen { #[weak(rename_to=dialog)] self, move |_, position| { + if !dialog.current() { + dialog.search(); + return; + } if let Some(widgets) = dialog.imp().widgets.get() { widgets.selection.set_selected(position); } @@ -234,15 +259,6 @@ impl QuickOpen { move |_, key, _, modifiers| dialog.key(key, modifiers) )); view.add_controller(keys); - let _ = self.imp().widgets.set(Widgets { - entry, - store, - selection, - list, - stack, - status, - banner, - }); } fn key(&self, key: gdk::Key, modifiers: gdk::ModifierType) -> glib::Propagation { @@ -278,6 +294,7 @@ impl QuickOpen { self.imp().watches.borrow_mut().clear(); self.imp().requests.borrow_mut().cancel_all(); self.imp().pending_pick.set(None); + self.imp().pending_steps.borrow_mut().clear(); } fn load(&self, refresh: bool) { @@ -371,7 +388,10 @@ impl QuickOpen { let Some(tasks) = imp.context.borrow().as_ref().map(|context| context.tasks.clone()) else { return; }; - if imp.requests.borrow().is_pending(Request::Index) || imp.generation.get().is_none() { + if imp.requests.borrow().is_pending(Request::Index) + || imp.requests.borrow().is_pending(Request::Search) + || imp.generation.get().is_none() + { return; } let text = widgets.entry.text().to_string(); @@ -401,6 +421,7 @@ impl QuickOpen { fn search_failed(&self) { self.imp().rendered.replace(None); self.imp().pending_pick.set(None); + self.imp().pending_steps.borrow_mut().clear(); if let Some(widgets) = self.imp().widgets.get() { widgets.banner.set_revealed(true); } @@ -449,6 +470,10 @@ impl QuickOpen { .list .scroll_to(widgets.selection.selected(), gtk::ListScrollFlags::NONE, None); } + let steps = std::mem::take(&mut *imp.pending_steps.borrow_mut()); + for by in steps { + self.step(by); + } if let Some(structure) = imp.pending_pick.take() { self.activate(structure); } @@ -501,6 +526,7 @@ impl QuickOpen { fn step(&self, by: i32) { if !self.current() { + self.imp().pending_steps.borrow_mut().push(by); self.search(); return; } diff --git a/linux/crates/app/src/ui/quick_open/tests.rs b/linux/crates/app/src/ui/quick_open/tests.rs index ddae04929f..3909f861a5 100644 --- a/linux/crates/app/src/ui/quick_open/tests.rs +++ b/linux/crates/app/src/ui/quick_open/tests.rs @@ -247,3 +247,38 @@ fn control_enter_opens_table_structure_with_a_ddl_dialect() { assert_eq!(chosen.borrow().len(), 1); assert!(chosen.borrow()[0].structure); } + +#[gtk4::test] +fn clicking_a_stale_row_never_opens_a_different_search_result() { + let (_runtime, _fake, dialog, chosen) = setup(vec![ + object("customers", ObjectKind::Table), + object("orders", ObjectKind::Table), + ]); + ready(&dialog); + let widgets = dialog.imp().widgets.get().unwrap(); + widgets.entry.set_text("orders"); + widgets.list.emit_by_name::<()>("activate", &[&0u32]); + ready(&dialog); + assert!(chosen.borrow().is_empty()); + assert_eq!(dialog.selected().unwrap().object.name, "orders"); + widgets.list.emit_by_name::<()>("activate", &[&0u32]); + assert_eq!(chosen.borrow().len(), 1); +} + +#[gtk4::test] +fn arrows_before_search_finishes_apply_before_enter() { + let (_runtime, _fake, dialog, chosen) = setup(vec![ + object("customers", ObjectKind::Table), + object("order_items", ObjectKind::Table), + object("orders", ObjectKind::Table), + ]); + ready(&dialog); + dialog.imp().widgets.get().unwrap().entry.set_text("ord"); + dialog.step(1); + dialog.activate(false); + wait_until(WAIT, || !chosen.borrow().is_empty()).expect("pending navigation and activation"); + assert_eq!( + chosen.borrow()[0].target, + Target::Table(tablepro_core::meta::TableRef::new(Some("public".to_owned()), "orders")) + ); +} diff --git a/linux/crates/app/src/ui/workspace/mod.rs b/linux/crates/app/src/ui/workspace/mod.rs index a443edd8b1..d03184d272 100644 --- a/linux/crates/app/src/ui/workspace/mod.rs +++ b/linux/crates/app/src/ui/workspace/mod.rs @@ -548,6 +548,8 @@ pub(crate) enum WorkspaceInput { ShowSavedQueries, /// Open Quickly: search the connection's tables and views. ShowQuickOpen, + CloseQuickOpen, + QuickOpenChosen(super::quick_open::Pick), ActiveTab(workspace_tabs::ActiveTabCommand), SaveQueryNamed { name: String, @@ -1401,6 +1403,8 @@ impl WorkspaceModel { WorkspaceInput::ShowHistory => self.on_show_history(), WorkspaceInput::ShowSavedQueries => self.on_show_saved_queries(), WorkspaceInput::ShowQuickOpen => self.on_show_quick_open(), + WorkspaceInput::CloseQuickOpen => self.close_quick_open(), + WorkspaceInput::QuickOpenChosen(pick) => self.on_quick_open_chosen(pick), WorkspaceInput::ImportCsvRequested { schema, table } => self.on_import_csv_requested(schema, table), WorkspaceInput::Transfer(input) => self.on_transfer(input), WorkspaceInput::ImportCsvReady { diff --git a/linux/crates/app/src/ui/workspace/status_pages.rs b/linux/crates/app/src/ui/workspace/status_pages.rs index bb486831fd..25bcb41ed9 100644 --- a/linux/crates/app/src/ui/workspace/status_pages.rs +++ b/linux/crates/app/src/ui/workspace/status_pages.rs @@ -97,21 +97,28 @@ impl WorkspaceModel { self.close_quick_open(); let input = self.input.clone(); let dialog = crate::ui::quick_open::QuickOpen::new(session, self.tasks.clone(), move |pick| { - let crate::ui::quick_open::Target::Table(table) = pick.target; - let tablepro_core::meta::TableRef { schema, name } = table; - input.deliver(match pick.structure { - true => WorkspaceInput::EditStructureTab { schema, table: name }, - false => WorkspaceInput::SelectTable { - schema, - name, - open_mode: super::OpenMode::SwitchOrAppend, - }, - }); + input.deliver(WorkspaceInput::QuickOpenChosen(pick)); }); dialog.present(self.dialog_parent().as_ref()); self.quick_open_dialog = Some(dialog); } + pub(super) fn on_quick_open_chosen(&mut self, pick: crate::ui::quick_open::Pick) { + if !self.is_front() { + return; + } + let crate::ui::quick_open::Target::Table(table) = pick.target; + let tablepro_core::meta::TableRef { schema, name } = table; + self.update(match pick.structure { + true => WorkspaceInput::EditStructureTab { schema, table: name }, + false => WorkspaceInput::SelectTable { + schema, + name, + open_mode: super::OpenMode::SwitchOrAppend, + }, + }); + } + /// Ask what to call the SQL in front of the user, then keep it. /// /// The text is read now rather than when the dialog closes, so what diff --git a/linux/crates/app/src/ui/workspace/tests/shell.rs b/linux/crates/app/src/ui/workspace/tests/shell.rs index b2f21e4219..529cc2ce73 100644 --- a/linux/crates/app/src/ui/workspace/tests/shell.rs +++ b/linux/crates/app/src/ui/workspace/tests/shell.rs @@ -580,3 +580,18 @@ fn open_quickly_closes_when_another_session_comes_forward() { wait_until(WAIT, || dialog.parent().is_none()).expect("old session dialog closed"); assert_eq!(sessions.shell.front().as_ref(), Some(&sessions.second)); } + +#[gtk4::test] +fn a_queued_quick_open_pick_does_not_reopen_a_background_session() { + let sessions = super::two_sessions("QuickOpenQueuedPick", "Other"); + super::open_editor(&sessions.second); + let before = sessions.shell.tab_view().n_pages(); + sessions.first.with_model(|model| { + model.on_quick_open_chosen(crate::ui::quick_open::Pick { + target: crate::ui::quick_open::Target::Table(tablepro_core::meta::TableRef::new(None, "orders")), + structure: false, + }) + }); + assert_eq!(sessions.shell.front().as_ref(), Some(&sessions.second)); + assert_eq!(sessions.shell.tab_view().n_pages(), before); +} diff --git a/linux/crates/app/src/ui/workspace/workspace_shell.rs b/linux/crates/app/src/ui/workspace/workspace_shell.rs index e31f756d41..5ebdd771a1 100644 --- a/linux/crates/app/src/ui/workspace/workspace_shell.rs +++ b/linux/crates/app/src/ui/workspace/workspace_shell.rs @@ -529,8 +529,11 @@ impl WorkspaceShell { return; } let previous = imp.front.borrow().clone(); - if let Some(previous) = previous { - previous.with_model(|model| model.close_quick_open()); + if let Some(previous) = previous + && previous.with_model(|model| model.close_quick_open()).is_none() + && let Some(input) = previous.sender() + { + input.deliver(WorkspaceInput::CloseQuickOpen); } imp.front.replace(workspace.cloned()); self.notify_front(); From 7c8f87608dce8e9b5f9774a3564ef5052260a26a Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 8 Nov 2026 23:18:17 +0700 Subject: [PATCH 08/15] fix(linux-workspace): keep loading state until catalog arrives --- linux/crates/app/src/ui/quick_open/mod.rs | 19 ++++++++------- .../app/src/ui/quick_open/query_tests.rs | 23 +++++++++++++++++++ 2 files changed, 32 insertions(+), 10 deletions(-) diff --git a/linux/crates/app/src/ui/quick_open/mod.rs b/linux/crates/app/src/ui/quick_open/mod.rs index 8504cdd9b2..b46db6c57a 100644 --- a/linux/crates/app/src/ui/quick_open/mod.rs +++ b/linux/crates/app/src/ui/quick_open/mod.rs @@ -483,16 +483,15 @@ impl QuickOpen { u32::try_from(selected).unwrap_or(0) }); if items.is_empty() { - widgets - .status - .set_title(&if imp.requests.borrow().is_pending(Request::Queries) { - gettext("Loading Saved Queries") - } else { - gettext("No Matches") - }); - widgets - .status - .set_description(Some(&gettext("No results match what you typed."))); + let loading = imp.requests.borrow().is_pending(Request::Queries) + || (imp.generation.get().is_none() && !imp.catalog_error.get()); + widgets.status.set_title(&if loading { + gettext("Loading Results") + } else { + gettext("No Matches") + }); + let description = (!loading).then(|| gettext("No results match what you typed.")); + widgets.status.set_description(description.as_deref()); } widgets .stack diff --git a/linux/crates/app/src/ui/quick_open/query_tests.rs b/linux/crates/app/src/ui/quick_open/query_tests.rs index 901169e5a3..863f450c41 100644 --- a/linux/crates/app/src/ui/quick_open/query_tests.rs +++ b/linux/crates/app/src/ui/quick_open/query_tests.rs @@ -224,3 +224,26 @@ fn a_deleted_saved_query_reports_an_error_without_opening_sql() { assert!(!widgets.banner.is_revealed()); dialog.dismiss(); } + +#[gtk4::test] +fn an_empty_query_source_does_not_report_no_matches_while_the_catalog_loads() { + adw::init().unwrap(); + let runtime = test_runtime(); + let (_root, history, _store) = history(&runtime.tasks()); + let release = tokio_util::sync::CancellationToken::new(); + let mut script = ConnectionScript::default(); + script.list_objects.always(FakeReply::UntilReleased { + release: release.clone(), + outcome: Ok(vec![]), + }); + let fake = FakeSession::start(script, [], runtime.tasks()); + let dialog = QuickOpen::new(fake.session, runtime.tasks(), |_| {}); + dialog.include_saved_queries(history, Uuid::new_v4()); + ready(&dialog); + let widgets = dialog.imp().widgets.get().unwrap(); + assert_eq!(widgets.status.title(), "Loading Results"); + release.cancel(); + wait_until(WAIT, || dialog.imp().generation.get().is_some() && dialog.current()).unwrap(); + assert_eq!(widgets.status.title(), "No Matches"); + dialog.dismiss(); +} From e2653a4b1bfffea6ed33b94b5631957f72210b33 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 8 Nov 2026 23:20:12 +0700 Subject: [PATCH 09/15] fix(linux-workspace): show pending history in Open Quickly --- linux/crates/app/src/ui/quick_open/mod.rs | 1 + .../app/src/ui/quick_open/past_tests.rs | 28 +++++++++++++++++++ .../app/src/ui/quick_open/query_tests.rs | 6 ++-- 3 files changed, 33 insertions(+), 2 deletions(-) diff --git a/linux/crates/app/src/ui/quick_open/mod.rs b/linux/crates/app/src/ui/quick_open/mod.rs index f3df8b136b..5b5c54d0bd 100644 --- a/linux/crates/app/src/ui/quick_open/mod.rs +++ b/linux/crates/app/src/ui/quick_open/mod.rs @@ -490,6 +490,7 @@ impl QuickOpen { }); if items.is_empty() { let loading = imp.requests.borrow().is_pending(Request::Queries) + || imp.requests.borrow().is_pending(Request::Past) || (imp.generation.get().is_none() && !imp.catalog_error.get()); widgets.status.set_title(&if loading { gettext("Loading Results") diff --git a/linux/crates/app/src/ui/quick_open/past_tests.rs b/linux/crates/app/src/ui/quick_open/past_tests.rs index b50a724c9a..0e01709f1a 100644 --- a/linux/crates/app/src/ui/quick_open/past_tests.rs +++ b/linux/crates/app/src/ui/quick_open/past_tests.rs @@ -153,3 +153,31 @@ fn repeated_executions_have_one_row_and_deleted_history_cannot_open() { assert!(chosen.borrow().is_empty()); dialog.dismiss(); } + +#[gtk4::test] +fn an_empty_list_stays_loading_until_the_history_reply_arrives() { + adw::init().unwrap(); + let runtime = test_runtime(); + let mut script = ConnectionScript::default(); + script.list_objects.always(FakeReply::ok(vec![])); + let fake = FakeSession::start(script, [], runtime.tasks()); + let dialog = QuickOpen::new(fake.session, runtime.tasks(), |_| {}); + wait_until(WAIT, || dialog.current()).unwrap(); + let pending = dialog.imp().requests.borrow_mut().issue(Request::Past); + dialog.show_results(String::new(), vec![]); + let widgets = dialog.imp().widgets.get().unwrap(); + assert_eq!(widgets.status.title(), "Loading Results"); + assert!(widgets.status.description().is_none()); + assert!(dialog.imp().requests.borrow_mut().accept(Request::Past, pending.stamp)); + dialog.show_results( + String::new(), + vec![Candidate::PastQuery { + id: 1, + name: "SELECT 42".into(), + sql: Arc::from("SELECT 42"), + }], + ); + assert_eq!(widgets.stack.visible_child_name().as_deref(), Some("list")); + assert_eq!(dialog.selected().unwrap().name(), "SELECT 42"); + dialog.dismiss(); +} diff --git a/linux/crates/app/src/ui/quick_open/query_tests.rs b/linux/crates/app/src/ui/quick_open/query_tests.rs index ec9d8b3c1d..4d9c6fa6d1 100644 --- a/linux/crates/app/src/ui/quick_open/query_tests.rs +++ b/linux/crates/app/src/ui/quick_open/query_tests.rs @@ -46,7 +46,9 @@ fn save(tasks: &Tasks, history: &QueryHistory, connection: Uuid, name: &str, sql fn ready(dialog: &QuickOpen) { wait_until(WAIT, || { - !dialog.imp().requests.borrow().is_pending(Request::Queries) && dialog.current() + !dialog.imp().requests.borrow().is_pending(Request::Queries) + && !dialog.imp().requests.borrow().is_pending(Request::Past) + && dialog.current() }) .unwrap(); } @@ -238,7 +240,7 @@ fn an_empty_query_source_does_not_report_no_matches_while_the_catalog_loads() { }); let fake = FakeSession::start(script, [], runtime.tasks()); let dialog = QuickOpen::new(fake.session, runtime.tasks(), |_| {}); - dialog.include_saved_queries(history, Uuid::new_v4()); + dialog.include_queries(history, Uuid::new_v4()); ready(&dialog); let widgets = dialog.imp().widgets.get().unwrap(); assert_eq!(widgets.status.title(), "Loading Results"); From 21456ef6fa2075e252f0fc798c5a8b6df32a13bc Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 8 Nov 2026 23:22:33 +0700 Subject: [PATCH 10/15] test(linux-workspace): place query fixtures under tests --- linux/crates/app/src/ui/quick_open/mod.rs | 1 + .../app/src/ui/quick_open/{query_tests.rs => tests/queries.rs} | 0 linux/po/POTFILES.in | 2 +- 3 files changed, 2 insertions(+), 1 deletion(-) rename linux/crates/app/src/ui/quick_open/{query_tests.rs => tests/queries.rs} (100%) diff --git a/linux/crates/app/src/ui/quick_open/mod.rs b/linux/crates/app/src/ui/quick_open/mod.rs index b46db6c57a..702fbef486 100644 --- a/linux/crates/app/src/ui/quick_open/mod.rs +++ b/linux/crates/app/src/ui/quick_open/mod.rs @@ -1,6 +1,7 @@ mod matching; mod query_source; #[cfg(test)] +#[path = "tests/queries.rs"] mod query_tests; mod search_index; #[cfg(test)] diff --git a/linux/crates/app/src/ui/quick_open/query_tests.rs b/linux/crates/app/src/ui/quick_open/tests/queries.rs similarity index 100% rename from linux/crates/app/src/ui/quick_open/query_tests.rs rename to linux/crates/app/src/ui/quick_open/tests/queries.rs diff --git a/linux/po/POTFILES.in b/linux/po/POTFILES.in index c54a888ada..1060208281 100644 --- a/linux/po/POTFILES.in +++ b/linux/po/POTFILES.in @@ -496,9 +496,9 @@ crates/app/src/ui/preferences_dialog/mod.rs crates/app/src/ui/quick_open/matching.rs crates/app/src/ui/quick_open/mod.rs crates/app/src/ui/quick_open/query_source.rs -crates/app/src/ui/quick_open/query_tests.rs crates/app/src/ui/quick_open/search_index.rs crates/app/src/ui/quick_open/tests.rs +crates/app/src/ui/quick_open/tests/queries.rs crates/app/src/ui/result_pane/mod.rs crates/app/src/ui/result_pane/result_limit_banner.rs crates/app/src/ui/result_pane/result_set_view.rs From c18395b11e905f238beb5dbdfe749c933e2f6b99 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Mon, 9 Nov 2026 00:34:15 +0700 Subject: [PATCH 11/15] fix(linux-workspace): match qualified searches and use a unique access key --- linux/crates/app/src/ui/quick_open/matching.rs | 14 ++++++++++++++ linux/data/resources/gtk/menus.ui | 2 +- 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/linux/crates/app/src/ui/quick_open/matching.rs b/linux/crates/app/src/ui/quick_open/matching.rs index 8ecbf28180..db7a289083 100644 --- a/linux/crates/app/src/ui/quick_open/matching.rs +++ b/linux/crates/app/src/ui/quick_open/matching.rs @@ -12,6 +12,10 @@ pub(super) fn rank(typed: &[char], name: &[char]) -> Option { if let Some(at) = name.windows(typed.len()).position(|window| window == typed) { return Some(Rank(1, at)); } + // A qualified name must not pick up letters from a different identifier. + if typed.contains(&'.') { + return None; + } let mut wanted = typed.iter(); let mut next = wanted.next(); let mut first = None; @@ -53,6 +57,16 @@ mod tests { assert_eq!(score("x", ""), None); } + #[test] + fn dotted_searches_keep_the_identifier_contiguous() { + assert_eq!(score("sales.orders", "sales.orders"), Some(Rank(0, 0))); + assert_eq!(score("sales.ord", "sales.orders"), Some(Rank(0, 0))); + assert!(score("sales.orders", "SELECT * FROM sales.orders").is_some()); + assert_eq!(score("sales.orders", "sales.order_items"), None); + assert_eq!(score("sales.orders", "sales_archive.orders"), None); + assert!(score("ods", "orders").is_some()); + } + #[test] fn nearer_substrings_and_tighter_subsequences_rank_first() { assert!(score("ar", "bar").unwrap() < score("ar", "xxbar").unwrap()); diff --git a/linux/data/resources/gtk/menus.ui b/linux/data/resources/gtk/menus.ui index 0460a2bbf2..7c33646bf6 100644 --- a/linux/data/resources/gtk/menus.ui +++ b/linux/data/resources/gtk/menus.ui @@ -21,7 +21,7 @@ - Open _Quickly… + _Open Quickly… win.quick-open action-missing From 6d1cd63e2e4475a1a19a715ecc4684cb2837b9d4 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Mon, 9 Nov 2026 01:40:19 +0700 Subject: [PATCH 12/15] refactor(linux-workspace): group search dialog messages --- linux/crates/app/src/ui/workspace/mod.rs | 14 +++---------- .../app/src/ui/workspace/status_pages.rs | 21 ++++++++++++++++++- .../app/src/ui/workspace/workspace_actions.rs | 8 ++++--- .../app/src/ui/workspace/workspace_shell.rs | 2 +- 4 files changed, 29 insertions(+), 16 deletions(-) diff --git a/linux/crates/app/src/ui/workspace/mod.rs b/linux/crates/app/src/ui/workspace/mod.rs index d03184d272..25220dd8c1 100644 --- a/linux/crates/app/src/ui/workspace/mod.rs +++ b/linux/crates/app/src/ui/workspace/mod.rs @@ -65,6 +65,7 @@ use uuid::Uuid; pub(crate) use self::catalog_ops::DatabaseDrop; pub(crate) use self::database_transfer::TransferInput; use self::session_watches::SessionWatches; +pub(crate) use self::status_pages::SearchInput; use self::tab_title::ConnectionLabel; pub(crate) use self::workspace_actions::show_transfer_actions; pub(crate) use self::workspace_shell::WorkspaceShell; @@ -544,12 +545,7 @@ pub(crate) enum WorkspaceInput { WorkspaceLayoutReset(Result, crate::workspace::WorkspaceSaveError>), /// An editor draft failed to land after the last one did. DraftsNotSaved, - ShowHistory, - ShowSavedQueries, - /// Open Quickly: search the connection's tables and views. - ShowQuickOpen, - CloseQuickOpen, - QuickOpenChosen(super::quick_open::Pick), + Search(SearchInput), ActiveTab(workspace_tabs::ActiveTabCommand), SaveQueryNamed { name: String, @@ -1400,11 +1396,7 @@ impl WorkspaceModel { WorkspaceInput::SavedConnectionsChanged => self.on_saved_connections_changed(), WorkspaceInput::WorkspaceLayoutReset(outcome) => self.on_workspace_layout_reset(outcome), WorkspaceInput::DraftsNotSaved => self.on_drafts_not_saved(), - WorkspaceInput::ShowHistory => self.on_show_history(), - WorkspaceInput::ShowSavedQueries => self.on_show_saved_queries(), - WorkspaceInput::ShowQuickOpen => self.on_show_quick_open(), - WorkspaceInput::CloseQuickOpen => self.close_quick_open(), - WorkspaceInput::QuickOpenChosen(pick) => self.on_quick_open_chosen(pick), + WorkspaceInput::Search(input) => self.on_search(input), WorkspaceInput::ImportCsvRequested { schema, table } => self.on_import_csv_requested(schema, table), WorkspaceInput::Transfer(input) => self.on_transfer(input), WorkspaceInput::ImportCsvReady { diff --git a/linux/crates/app/src/ui/workspace/status_pages.rs b/linux/crates/app/src/ui/workspace/status_pages.rs index 25bcb41ed9..3fee43b466 100644 --- a/linux/crates/app/src/ui/workspace/status_pages.rs +++ b/linux/crates/app/src/ui/workspace/status_pages.rs @@ -8,7 +8,26 @@ use super::{WorkspaceInput, WorkspaceModel}; use crate::runtime::DeliverInput; use crate::ui::plain_toast; +#[derive(Debug)] +pub(crate) enum SearchInput { + History, + SavedQueries, + QuickOpen, + CloseQuickOpen, + QuickOpenChosen(crate::ui::quick_open::Pick), +} + impl WorkspaceModel { + pub(super) fn on_search(&mut self, input: SearchInput) { + match input { + SearchInput::History => self.on_show_history(), + SearchInput::SavedQueries => self.on_show_saved_queries(), + SearchInput::QuickOpen => self.on_show_quick_open(), + SearchInput::CloseQuickOpen => self.close_quick_open(), + SearchInput::QuickOpenChosen(pick) => self.on_quick_open_chosen(pick), + } + } + pub(super) fn show_toast(&self, msg: &str) { self.add_toast(plain_toast(msg)); } @@ -97,7 +116,7 @@ impl WorkspaceModel { self.close_quick_open(); let input = self.input.clone(); let dialog = crate::ui::quick_open::QuickOpen::new(session, self.tasks.clone(), move |pick| { - input.deliver(WorkspaceInput::QuickOpenChosen(pick)); + input.deliver(WorkspaceInput::Search(SearchInput::QuickOpenChosen(pick))); }); dialog.present(self.dialog_parent().as_ref()); self.quick_open_dialog = Some(dialog); diff --git a/linux/crates/app/src/ui/workspace/workspace_actions.rs b/linux/crates/app/src/ui/workspace/workspace_actions.rs index 886abeca0a..6bedf3a900 100644 --- a/linux/crates/app/src/ui/workspace/workspace_actions.rs +++ b/linux/crates/app/src/ui/workspace/workspace_actions.rs @@ -36,9 +36,11 @@ const ENTRIES: [(&str, ActionInput); 10] = [ ("export-results", || { WorkspaceInput::ActiveTab(ActiveTabCommand::ExportResults) }), - ("show-history", || WorkspaceInput::ShowHistory), - ("show-saved-queries", || WorkspaceInput::ShowSavedQueries), - ("quick-open", || WorkspaceInput::ShowQuickOpen), + ("show-history", || WorkspaceInput::Search(super::SearchInput::History)), + ("show-saved-queries", || { + WorkspaceInput::Search(super::SearchInput::SavedQueries) + }), + ("quick-open", || WorkspaceInput::Search(super::SearchInput::QuickOpen)), (super::health_banner::REVIEW_HOST_KEY, || WorkspaceInput::ReviewHostKey), ]; diff --git a/linux/crates/app/src/ui/workspace/workspace_shell.rs b/linux/crates/app/src/ui/workspace/workspace_shell.rs index 5ebdd771a1..9f82f04d58 100644 --- a/linux/crates/app/src/ui/workspace/workspace_shell.rs +++ b/linux/crates/app/src/ui/workspace/workspace_shell.rs @@ -533,7 +533,7 @@ impl WorkspaceShell { && previous.with_model(|model| model.close_quick_open()).is_none() && let Some(input) = previous.sender() { - input.deliver(WorkspaceInput::CloseQuickOpen); + input.deliver(WorkspaceInput::Search(super::SearchInput::CloseQuickOpen)); } imp.front.replace(workspace.cloned()); self.notify_front(); From 8135e547bceb7c762747664c99d5ef757353f5bf Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Mon, 9 Nov 2026 03:33:40 +0700 Subject: [PATCH 13/15] fix(linux-workspace): scroll quick results after native layout --- linux/crates/app/src/ui/quick_open/mod.rs | 74 +++++++++++++++++++-- linux/crates/app/src/ui/quick_open/tests.rs | 68 +++++++++++++++++++ 2 files changed, 138 insertions(+), 4 deletions(-) diff --git a/linux/crates/app/src/ui/quick_open/mod.rs b/linux/crates/app/src/ui/quick_open/mod.rs index 47747e4abf..75d6517957 100644 --- a/linux/crates/app/src/ui/quick_open/mod.rs +++ b/linux/crates/app/src/ui/quick_open/mod.rs @@ -19,6 +19,7 @@ use tablepro_session::{ObjectListSnapshot, Session}; use crate::i18n::{gettext, gettext_f}; use crate::runtime::{RequestSequencer, spawn_and_deliver}; +use crate::ui::handler_guard::HandlerGuard; use crate::ui::icons; pub(crate) use search_index::Target; use search_index::{Candidate, SearchIndex}; @@ -73,6 +74,7 @@ mod imp { pub(super) rendered: RefCell>, pub(super) pending_pick: Cell>, pub(super) pending_steps: RefCell>, + pub(super) scroll_layout: RefCell>, } #[glib::object_subclass] @@ -178,6 +180,7 @@ impl QuickOpen { self.set_child(Some(&view)); self.set_focus(Some(&entry)); self.connect_controls(&entry, &list, &banner, &view); + self.connect_scroll_layout(&list); let _ = self.imp().widgets.set(Widgets { entry, store, @@ -261,6 +264,70 @@ impl QuickOpen { view.add_controller(keys); } + fn connect_scroll_layout(&self, list: >k::ListView) { + list.connect_map(glib::clone!( + #[weak(rename_to=dialog)] + self, + move |_| dialog.scroll_selection_after_layout() + )); + list.connect_unmap(glib::clone!( + #[weak(rename_to=dialog)] + self, + move |_| { + dialog.imp().scroll_layout.borrow_mut().take(); + } + )); + } + + fn scroll_selection_after_layout(&self) { + let imp = self.imp(); + if imp.context.borrow().is_none() || imp.scroll_layout.borrow().is_some() { + return; + } + let Some(widgets) = imp.widgets.get().filter(|widgets| widgets.list.is_mapped()) else { + return; + }; + let Some(surface) = widgets.list.native().and_then(|native| native.surface()) else { + return; + }; + // GtkNative's earlier layout handler allocates rows before scrolling reads their geometry. + let handler = surface.connect_layout(glib::clone!( + #[weak(rename_to=dialog)] + self, + move |_, _, _| dialog.scroll_allocated_selection() + )); + imp.scroll_layout.replace(Some(HandlerGuard::new(&surface, handler))); + widgets.list.queue_allocate(); + surface.request_layout(); + } + + fn scroll_allocated_selection(&self) { + let imp = self.imp(); + let Some(widgets) = imp.widgets.get() else { + return; + }; + if imp.context.borrow().is_none() || !widgets.list.is_mapped() || !self.current() { + imp.scroll_layout.borrow_mut().take(); + return; + } + let allocated = widgets + .list + .hadjustment() + .is_some_and(|adjustment| adjustment.page_size() > 0.0) + && widgets + .list + .vadjustment() + .is_some_and(|adjustment| adjustment.page_size() > 0.0); + if !allocated { + return; + } + imp.scroll_layout.borrow_mut().take(); + let selected = widgets.selection.selected(); + if selected < widgets.store.n_items() { + widgets.list.scroll_to(selected, gtk::ListScrollFlags::NONE, None); + } + } + fn key(&self, key: gdk::Key, modifiers: gdk::ModifierType) -> glib::Propagation { let matches = |action| crate::application::component_matches(action, key, modifiers); if matches("quick-open.structure") { @@ -290,6 +357,7 @@ impl QuickOpen { } fn stop(&self) { + self.imp().scroll_layout.borrow_mut().take(); self.imp().context.borrow_mut().take(); self.imp().watches.borrow_mut().clear(); self.imp().requests.borrow_mut().cancel_all(); @@ -466,9 +534,7 @@ impl QuickOpen { .set_visible_child_name(if items.is_empty() { "status" } else { "list" }); imp.rendered.replace(Some(text)); if !items.is_empty() { - widgets - .list - .scroll_to(widgets.selection.selected(), gtk::ListScrollFlags::NONE, None); + self.scroll_selection_after_layout(); } let steps = std::mem::take(&mut *imp.pending_steps.borrow_mut()); for by in steps { @@ -541,7 +607,7 @@ impl QuickOpen { let next = (current + i64::from(by)).clamp(0, i64::from(count) - 1); let position = u32::try_from(next).unwrap_or(0); widgets.selection.set_selected(position); - widgets.list.scroll_to(position, gtk::ListScrollFlags::NONE, None); + self.scroll_selection_after_layout(); } } diff --git a/linux/crates/app/src/ui/quick_open/tests.rs b/linux/crates/app/src/ui/quick_open/tests.rs index 3909f861a5..e3ddc10bee 100644 --- a/linux/crates/app/src/ui/quick_open/tests.rs +++ b/linux/crates/app/src/ui/quick_open/tests.rs @@ -121,12 +121,80 @@ fn keyboard_navigation_scrolls_and_keeps_search_focus() { .and_downcast::() .expect("scroller"); wait_until(WAIT, || scrolled.vadjustment().value() > 0.0).expect("selected row scrolled into view"); + wait_until(WAIT, || row_is_visible(&dialog, "table_060")).expect("selected row is visible"); widgets.entry.emit_by_name::<()>("stop-search", &[]); wait_until(WAIT, || dialog.parent().is_none()).expect("Escape closes"); assert!(dialog.imp().context.borrow().is_none()); window.destroy(); } +fn row_is_visible(dialog: &QuickOpen, name: &str) -> bool { + let list = &dialog.imp().widgets.get().unwrap().list; + crate::test_support::descendants(list) + .into_iter() + .filter_map(|widget| widget.downcast::().ok()) + .find(|label| label.text() == name) + .and_then(|label| label.compute_bounds(list)) + .is_some_and(|bounds| { + bounds.height() > 0.0 && bounds.y() >= 0.0 && bounds.y() + bounds.height() <= list.height() as f32 + }) +} + +#[gtk4::test] +fn selection_before_presentation_scrolls_after_layout() { + let (_runtime, _fake, dialog, _) = setup( + (0..100) + .map(|i| object(&format!("table_{i:03}"), ObjectKind::Table)) + .collect(), + ); + ready(&dialog); + let widgets = dialog.imp().widgets.get().unwrap(); + assert!(!widgets.list.is_mapped()); + dialog.step(60); + let window = adw::Window::new(); + window.set_default_size(800, 600); + window.present(); + dialog.present(Some(&window)); + dialog.step(-20); + assert_eq!(widgets.selection.selected(), 40); + wait_until(WAIT, || row_is_visible(&dialog, "table_040")).expect("latest selection visible after first layout"); + assert!(dialog.entry_has_focus()); + + dialog.step(30); + assert!(dialog.imp().scroll_layout.borrow().is_some()); + dialog.dismiss(); + assert!( + dialog.imp().scroll_layout.borrow().is_none(), + "close cancels pending scrolling" + ); + window.destroy(); +} + +#[gtk4::test] +fn replaced_results_scroll_after_layout_without_a_viewport_resize() { + let objects: Vec<_> = (0..100) + .map(|i| object(&format!("table_{i:03}"), ObjectKind::Table)) + .collect(); + let (_runtime, _fake, dialog, _) = setup(objects); + let window = adw::Window::new(); + window.set_default_size(800, 600); + window.present(); + dialog.present(Some(&window)); + ready(&dialog); + dialog.step(60); + wait_until(WAIT, || row_is_visible(&dialog, "table_060")).expect("initial selection visible"); + let widgets = dialog.imp().widgets.get().unwrap(); + let page_size = widgets.list.vadjustment().unwrap().page_size(); + let found = dialog.imp().index.borrow().search(""); + dialog.show_results(String::new(), found); + dialog.step(-40); + wait_until(WAIT, || row_is_visible(&dialog, "table_020")).expect("replacement selection visible"); + assert_eq!(widgets.list.vadjustment().unwrap().page_size(), page_size); + assert!(dialog.entry_has_focus()); + dialog.dismiss(); + window.destroy(); +} + #[gtk4::test] fn structure_is_not_offered_for_views_or_a_dialect_without_ddl() { let (_runtime, _fake, dialog, chosen) = setup(vec![ From e83241f1b1a6dc70793e0f370fd968e8ae4d9a83 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Tue, 10 Nov 2026 03:03:03 +0700 Subject: [PATCH 14/15] refactor(linux-workspace): bind the workspace to its session in a helper --- linux/crates/app/src/ui/workspace/mod.rs | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/linux/crates/app/src/ui/workspace/mod.rs b/linux/crates/app/src/ui/workspace/mod.rs index 3cd45e70d0..8fabf5b9c5 100644 --- a/linux/crates/app/src/ui/workspace/mod.rs +++ b/linux/crates/app/src/ui/workspace/mod.rs @@ -815,11 +815,7 @@ impl Workspace { } = init; let workspace: Self = glib::Object::new(); let imp = workspace.imp(); - imp.shell.set(Some(&shell)); - let input = workspace.pump_inputs(); - let _ = imp.sender.set(input.clone()); - let _ = imp.key.set(key.clone()); - let _ = imp.connection_id.set(session.metadata().id); + let input = workspace.bind(&shell, &key, &session); let context = session_slot(&context, &session); let storage = services.storage.clone(); let tasks = services.tasks.clone(); @@ -908,6 +904,16 @@ impl Workspace { workspace } + fn bind(&self, shell: &WorkspaceShell, key: &SessionKey, session: &Session) -> WorkspaceSender { + let imp = self.imp(); + imp.shell.set(Some(shell)); + let input = self.pump_inputs(); + let _ = imp.sender.set(input.clone()); + let _ = imp.key.set(key.clone()); + let _ = imp.connection_id.set(session.metadata().id); + input + } + /// Hold the model, and have every close of the window ask the /// `blockers` first. The session is named before the shell holds it, /// which titles its row and the header bars from these. From 8dc6d90356353c1d1e0b65fb13234bf0c45d6cbb Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Tue, 10 Nov 2026 03:05:30 +0700 Subject: [PATCH 15/15] test(linux-workspace): read a cleared status description as empty --- linux/crates/app/src/ui/quick_open/past_tests.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/linux/crates/app/src/ui/quick_open/past_tests.rs b/linux/crates/app/src/ui/quick_open/past_tests.rs index 0e01709f1a..61e5be2008 100644 --- a/linux/crates/app/src/ui/quick_open/past_tests.rs +++ b/linux/crates/app/src/ui/quick_open/past_tests.rs @@ -167,7 +167,8 @@ fn an_empty_list_stays_loading_until_the_history_reply_arrives() { dialog.show_results(String::new(), vec![]); let widgets = dialog.imp().widgets.get().unwrap(); assert_eq!(widgets.status.title(), "Loading Results"); - assert!(widgets.status.description().is_none()); + // AdwStatusPage reads the description from its label, which holds "" once cleared. + assert!(widgets.status.description().is_none_or(|text| text.is_empty())); assert!(dialog.imp().requests.borrow_mut().accept(Request::Past, pending.stamp)); dialog.show_results( String::new(),