diff --git a/linux/changelog.d/4132.fixed.md b/linux/changelog.d/4132.fixed.md new file mode 100644 index 0000000000..3bb82b70b7 --- /dev/null +++ b/linux/changelog.d/4132.fixed.md @@ -0,0 +1 @@ +The sidebar could select the wrong database after a query tab changed databases. diff --git a/linux/crates/app/src/ui/editor/tab_scope.rs b/linux/crates/app/src/ui/editor/tab_scope.rs index 7280cd3e80..31519a6f54 100644 --- a/linux/crates/app/src/ui/editor/tab_scope.rs +++ b/linux/crates/app/src/ui/editor/tab_scope.rs @@ -237,16 +237,17 @@ impl SqlEditor { ) } - /// Completion reads `session`'s catalog: the session the window holds - /// for the tab's database, or `None` back on the connection's own. pub(crate) fn follow_catalog(&self, session: Option>) { - // A session opened late for a database the tab has since left - // changes nothing; the one it is in may have answered first. - let current = self.imp().named_database.borrow().clone(); - if session + let database = session .as_ref() - .is_some_and(|session| session.database() != current.as_deref()) - { + .and_then(|session| session.database()) + .map(str::to_owned); + self.follow_catalog_for(database.as_deref(), session); + } + + pub(crate) fn follow_catalog_for(&self, database: Option<&str>, session: Option>) { + // A late catalog must not replace the one for a newer database choice. + if session.is_some() && self.imp().named_database.borrow().as_deref() != database { return; } for provider in self.imp().completion_providers.borrow().iter() { @@ -256,17 +257,18 @@ impl SqlEditor { } } - /// The database of the session whose catalog completion reads, when - /// the window handed one over. - #[cfg(test)] - pub(crate) fn followed_catalog(&self) -> Option { + pub(crate) fn catalog_session(&self) -> Option> { self.imp().completion_providers.borrow().iter().find_map(|provider| { let provider = provider.downcast_ref::()?; - let session = provider.imp().catalog_session.borrow().clone()?; - session.database().map(str::to_owned) + provider.imp().catalog_session.borrow().clone() }) } + #[cfg(test)] + pub(crate) fn followed_catalog(&self) -> Option { + self.catalog_session()?.database().map(str::to_owned) + } + /// Where unqualified names in this tab resolve, for what the assistant /// says about it. pub(crate) fn catalog_home(&self) -> CatalogHome { diff --git a/linux/crates/app/src/ui/editor/tests.rs b/linux/crates/app/src/ui/editor/tests.rs index ce7c335ef7..f370a836a6 100644 --- a/linux/crates/app/src/ui/editor/tests.rs +++ b/linux/crates/app/src/ui/editor/tests.rs @@ -3091,6 +3091,29 @@ fn completion_reads_only_the_session_of_the_tabs_database() { assert_eq!(followed_catalog(&harness), None, "the last database's catalog stayed"); } +#[gtk4::test] +fn a_catalog_reply_keeps_the_database_choice_that_requested_it() { + let harness = databases_editor(answering(), false); + let catalog = session_in("", harness.runtime.tasks()); + pick_database(&harness, "analytics"); + harness + .editor + .follow_catalog_for(Some("analytics"), Some(catalog.clone())); + assert!( + harness + .editor + .catalog_session() + .is_some_and(|held| Arc::ptr_eq(&held, &catalog)) + ); + + pick_database(&harness, "shop"); + harness.editor.follow_catalog_for(Some("analytics"), Some(catalog)); + assert!( + harness.editor.catalog_session().is_none(), + "a late lookup restored the old catalog" + ); +} + mod result_edits { use tablepro_core::column::{ColumnDefault, ColumnInfo, ColumnOrigin}; use tablepro_core::edit::CellInput; diff --git a/linux/crates/app/src/ui/session_window/other_databases.rs b/linux/crates/app/src/ui/session_window/other_databases.rs index 80f5f87d85..a440a766f4 100644 --- a/linux/crates/app/src/ui/session_window/other_databases.rs +++ b/linux/crates/app/src/ui/session_window/other_databases.rs @@ -28,7 +28,7 @@ use super::{MovedTab, SessionWindow}; use crate::i18n::{gettext, gettext_f}; use crate::runtime::DeliverInput; use crate::ui::error_text::{connect_error_message, operation_error_message}; -use crate::ui::workspace::{DatabaseDrop, Workspace, WorkspaceInput}; +use crate::ui::workspace::{DatabaseDrop, EditorInput, Workspace, WorkspaceInput}; use crate::workspace::CloseDecision; /// The response of the chooser that opens the database picked. @@ -335,7 +335,7 @@ impl SessionWindow { // The connection's tabs in that database read its catalog now. for other in others { if let Some(input) = other.sender() { - input.deliver(WorkspaceInput::DatabaseOpened(joined.clone())); + input.deliver(WorkspaceInput::Editor(EditorInput::DatabaseOpened(joined.clone()))); } } } @@ -349,31 +349,114 @@ impl SessionWindow { } } - /// Editor tab `tab_id` of the session under `key` moved to - /// `database`, `None` for the connection's own. Its completion reads - /// the session the window holds for that database, opened beside - /// the connection where a connection's catalog holds one database. fn follow_database(&self, key: &SessionKey, tab_id: Uuid, database: Option) { - // A tab of another database's own workspace keeps that catalog: - // the connection's session may not know the name of its own. - let SessionKey::Saved(id) = *key else { + let Some(id) = connection_of(key) else { + return; + }; + let Some(database) = database else { + self.deliver_to( + key, + WorkspaceInput::Editor(EditorInput::FollowCatalog { + tab_id, + database: None, + session: None, + }), + ); return; }; if !self.opens_databases(id) { return; } - let session = match self.holding(id, database.as_deref()) { - // The tab's own workspace reads that catalog already. - Some((held, _)) if &held == key => None, - Some((_, session)) => Some(session), - None => { - if let Some(database) = database { - self.open_database(id, database); - } + if let Some((held, session)) = self.holding(id, Some(&database)) { + self.deliver_to( + key, + WorkspaceInput::Editor(EditorInput::FollowCatalog { + tab_id, + database: Some(database), + session: (held != *key).then_some(session), + }), + ); + return; + } + let Some(root) = self.held_session(&SessionKey::Saved(id)) else { + return; + }; + if root.database().is_some_and(|name| !name.is_empty()) { + self.open_database(id, database); + return; + } + self.resolve_default_catalog(key, tab_id, id, database, root); + } + + fn resolve_default_catalog(&self, key: &SessionKey, tab_id: Uuid, id: Uuid, database: String, root: Arc) { + let (Some(state), Some(owner)) = (self.state(), self.held_session(key)) else { + return; + }; + let reading = root.clone(); + let listing = state.services.tasks.spawn_task(async move { + reading + .run(OperationKind::Metadata, |lease, options| async move { + Ok(lease.list_databases(options).await?) + }) + .await + }); + let window = self.downgrade(); + let key = key.clone(); + glib::spawn_future_local(async move { + let listed = listing.await; + let Some(window) = window.upgrade() else { + return; + }; + // A replaced connection or a newer tab choice owns the next lookup. + if !window + .held_session(&SessionKey::Saved(id)) + .is_some_and(|held| Arc::ptr_eq(&held, &root)) + || !window.held_session(&key).is_some_and(|held| Arc::ptr_eq(&held, &owner)) + || !window + .find_open(|open| (open.claim.key() == &key).then(|| open.workspace.tab_database(tab_id))) + .flatten() + .is_some_and(|current| current == database) + { return; } - }; - self.deliver_to(key, WorkspaceInput::FollowCatalog { tab_id, session }); + let databases = match listed { + Ok(Ok(databases)) => databases, + Ok(Err(error)) => { + window.show_toast(&operation_error_message(&error)); + return; + } + Err(failure) => { + tracing::warn!(%failure, "the connection's default database could not be read"); + return; + } + }; + if databases + .iter() + .any(|listed| listed.is_default && listed.name == database) + { + window.deliver_to( + &key, + WorkspaceInput::Editor(EditorInput::FollowCatalog { + tab_id, + database: Some(database), + session: Some(root), + }), + ); + } else { + // A sibling may have joined while the metadata was being read. + match window.holding(id, Some(&database)) { + Some((_, session)) => window.deliver_to( + &key, + WorkspaceInput::Editor(EditorInput::FollowCatalog { + tab_id, + database: Some(database), + session: Some(session), + }), + ), + None => window.open_database(id, database), + } + } + }); } /// A tab of the session under `key` changed the catalog of diff --git a/linux/crates/app/src/ui/session_window/tests/other_databases.rs b/linux/crates/app/src/ui/session_window/tests/other_databases.rs index aa406a9217..99e0398bb5 100644 --- a/linux/crates/app/src/ui/session_window/tests/other_databases.rs +++ b/linux/crates/app/src/ui/session_window/tests/other_databases.rs @@ -299,6 +299,7 @@ fn a_tab_moved_where_the_catalog_lists_every_database_opens_nothing() { ); assert_eq!(test.connector.calls().len(), 1, "a session opened for the database"); assert_eq!(tabs[0].followed_catalog(), None); + assert_eq!(selected_session(&test), Some(test.key())); } fn postgres() -> std::sync::Arc { @@ -525,3 +526,239 @@ fn a_drop_offers_neither_the_connections_database_nor_the_servers_own() { assert_eq!(offered, ["shop"]); } + +fn selected_session(test: &TestWindow) -> Option { + test.window.shell()?.tree()?.selected_session() +} + +fn query_in(test: &TestWindow, key: &SessionKey) -> (libadwaita::TabPage, crate::ui::editor::SqlEditor) { + let shell = test.window.shell().expect("the shell"); + let count = shell.tab_view().n_pages(); + WidgetExt::activate_action( + &test.window, + "win.new-query-in", + Some(&crate::ui::session_target::to_variant(key)), + ) + .expect("new query"); + wait_until(WAIT, || shell.tab_view().n_pages() == count + 1).expect("the query tab"); + let page = shell.tab_view().selected_page().expect("the selected page"); + let editor = crate::test_support::descendants(&page.child()) + .into_iter() + .chain([page.child()]) + .find_map(|widget| widget.downcast::().ok()) + .expect("the editor"); + (page, editor) +} + +#[gtk4::test] +fn the_sidebar_selects_a_moved_query_tabs_database_when_its_tab_is_selected() { + let test = on_engine("SidebarMovedTab", postgres()); + connect(&test); + let (moved_page, moved) = query_in(&test, &test.key()); + let (home_page, _) = query_in(&test, &test.key()); + moved.move_to_database(ANALYTICS); + wait_until(WAIT, || moved.followed_catalog().as_deref() == Some(ANALYTICS)).expect("the sibling catalog"); + assert_eq!( + selected_session(&test), + Some(test.key()), + "a background move stole selection" + ); + let view = test.window.shell().expect("the shell").tab_view(); + view.set_selected_page(&moved_page); + wait_until(WAIT, || selected_session(&test) == Some(analytics(&test))).expect("the database row"); + view.set_selected_page(&home_page); + wait_until(WAIT, || selected_session(&test) == Some(test.key())).expect("the owner row"); + view.set_selected_page(&moved_page); + wait_until(WAIT, || selected_session(&test) == Some(analytics(&test))).expect("the database row again"); + moved.move_to_database(&test.saved.database); + wait_until(WAIT, || selected_session(&test) == Some(test.key())).expect("a return home without switching tabs"); +} + +#[gtk4::test] +fn the_sidebar_follows_a_sibling_owned_query_to_another_database_and_home() { + let test = on_engine("SidebarSiblingTab", postgres()); + connect(&test); + test.window.open_database(test.saved.id, ANALYTICS.to_owned()); + wait_until(WAIT, || test.window.held_session(&analytics(&test)).is_some()).expect("the sibling"); + let (_, editor) = query_in(&test, &analytics(&test)); + let reports = SessionKey::SavedIn { + id: test.saved.id, + database: "reports".to_owned(), + }; + editor.move_to_database("reports"); + wait_until(WAIT, || selected_session(&test) == Some(reports.clone())).expect("another database's row"); + wait_until(WAIT, || editor.followed_catalog().as_deref() == Some("reports")).expect("its catalog"); + editor.move_to_database(&test.saved.database); + wait_until(WAIT, || selected_session(&test) == Some(test.key())).expect("the root connection's row"); + wait_until(WAIT, || { + editor.followed_catalog().as_deref() == Some(test.saved.database.as_str()) + }) + .expect("the root catalog"); + editor.move_to_database(ANALYTICS); + wait_until(WAIT, || selected_session(&test) == Some(analytics(&test))).expect("the owner's row"); + assert_eq!(editor.followed_catalog(), None, "the owner's catalog needs no override"); +} + +#[gtk4::test] +fn the_sidebar_follows_a_moved_tab_after_its_database_opens_late() { + let mut script = answering_script(); + script.dialect = postgres(); + let test = network_window_with( + "SidebarLateDatabase", + Script { + establish: vec![ + FakeEstablish::Connect(script.clone()), + FakeEstablish::Late { + after: Duration::from_millis(250), + script: script.clone(), + }, + ], + connection: script, + ..Script::default() + }, + ); + connect(&test); + let (_, editor) = query_in(&test, &test.key()); + editor.move_to_database(ANALYTICS); + wait_until(WAIT, || selected_session(&test) == Some(analytics(&test))).expect("the late database row"); +} + +#[gtk4::test] +fn a_failed_database_open_keeps_the_moved_tabs_owner_selected() { + let mut script = answering_script(); + script.dialect = postgres(); + let test = network_window_with( + "SidebarFailedDatabase", + Script { + establish: vec![ + FakeEstablish::Connect(script.clone()), + FakeEstablish::Fail(tablepro_session::ConnectError::Driver( + tablepro_core::DriverError::Protocol("unavailable".to_owned()), + )), + ], + connection: script, + ..Script::default() + }, + ); + connect(&test); + let (_, editor) = query_in(&test, &test.key()); + editor.move_to_database(ANALYTICS); + wait_until(WAIT, || { + test.connector.calls().len() == 2 && test.services.sessions.window_for(&analytics(&test)).is_none() + }) + .expect("the failed open to release its claim"); + assert_eq!(selected_session(&test), Some(test.key())); +} + +#[gtk4::test] +fn closing_and_reopening_a_moved_tabs_database_refreshes_the_selected_row() { + let test = on_engine("SidebarClosedDatabase", postgres()); + connect(&test); + let (page, editor) = query_in(&test, &test.key()); + editor.move_to_database(ANALYTICS); + wait_until(WAIT, || selected_session(&test) == Some(analytics(&test))).expect("the database row"); + test.window + .send(SessionWindowInput::DisconnectSession(analytics(&test))); + wait_until(WAIT, || test.window.held_session(&analytics(&test)).is_none()).expect("the sibling closed"); + assert_eq!( + test.window.shell().expect("the shell").tab_view().selected_page(), + Some(page) + ); + assert_eq!(selected_session(&test), Some(test.key())); + test.window.open_database(test.saved.id, ANALYTICS.to_owned()); + wait_until(WAIT, || selected_session(&test) == Some(analytics(&test))).expect("the reopened database row"); +} + +fn unnamed_root(name: &str, reply: FakeReply>) -> TestWindow { + let mut root = answering_script(); + root.dialect = postgres(); + root.list_databases.always(reply); + let mut sibling = answering_script(); + sibling.dialect = postgres(); + sibling.list_databases.always(FakeReply::ok(Vec::new())); + let mut test = network_window_with( + name, + Script { + establish: vec![FakeEstablish::Connect(root)], + connection: sibling, + ..Script::default() + }, + ); + test.saved.database.clear(); + test.services + .storage + .connections() + .upsert_blocking(test.saved.clone()) + .expect("save the unnamed connection"); + connect(&test); + test.window.open_database(test.saved.id, ANALYTICS.to_owned()); + wait_until(WAIT, || test.window.held_session(&analytics(&test)).is_some()).expect("the sibling"); + test +} + +fn default_database() -> Vec { + vec![tablepro_core::meta::SchemaInfo { + name: "app".to_owned(), + is_default: true, + is_system: false, + }] +} + +#[gtk4::test] +fn a_sibling_tab_returns_to_the_unnamed_roots_default_database_without_another_connection() { + let test = unnamed_root("SidebarServerDefault", FakeReply::ok(default_database())); + let root = test.window.held_session(&test.key()).expect("the root session"); + assert!(root.database().is_none_or(str::is_empty)); + let (_, editor) = query_in(&test, &analytics(&test)); + + editor.move_to_database("app"); + + wait_until(WAIT, || { + selected_session(&test) == Some(test.key()) + && editor + .catalog_session() + .is_some_and(|catalog| std::sync::Arc::ptr_eq(&catalog, &root)) + }) + .expect("the root row and its catalog"); + assert_eq!( + test.connector.calls().len(), + 2, + "the server's default database opened twice" + ); +} + +#[gtk4::test] +fn a_default_database_lookup_cannot_open_a_sibling_after_its_connection_closes() { + let release = tokio_util::sync::CancellationToken::new(); + let test = unnamed_root( + "SidebarDefaultAfterClose", + FakeReply::UntilReleased { + release: release.clone(), + outcome: Ok(default_database()), + }, + ); + let root = test.window.held_session(&test.key()).expect("the root session"); + let old = std::sync::Arc::downgrade(&root); + let counters = test.connector.connections()[0].counters(); + let (_, editor) = query_in(&test, &analytics(&test)); + editor.move_to_database("reports"); + wait_until(WAIT, || CallCounters::get(&counters.list_databases) == 1).expect("the root metadata lookup to start"); + drop(root); + + test.window.send(SessionWindowInput::DisconnectSession(test.key())); + test.wait_for_page("picker"); + release.cancel(); + + wait_until(WAIT, || old.upgrade().is_none()).expect("the old session and its lookup to be released"); + assert_eq!(test.connector.calls().len(), 2, "a late lookup opened another database"); + assert!(test.window.workspaces().is_empty()); + assert!( + test.services + .sessions + .window_for(&SessionKey::SavedIn { + id: test.saved.id, + database: "reports".to_owned(), + }) + .is_none() + ); +} diff --git a/linux/crates/app/src/ui/workspace/mod.rs b/linux/crates/app/src/ui/workspace/mod.rs index 6e4edd63b6..7d344250fe 100644 --- a/linux/crates/app/src/ui/workspace/mod.rs +++ b/linux/crates/app/src/ui/workspace/mod.rs @@ -468,6 +468,22 @@ fn close_if_presented(dialog: &adw::Dialog) { } } +#[derive(Debug)] +pub(crate) enum EditorInput { + RunStateChanged(Uuid, bool), + RunFinished(Uuid, crate::workspace::WorkOutcome), + ContentChanged(Uuid), + FileChanged(Uuid), + DatabaseChanged(Uuid), + TransactionChanged, + FollowCatalog { + tab_id: Uuid, + database: Option, + session: Option>, + }, + DatabaseOpened(Arc), +} + #[derive(Debug)] pub(crate) enum WorkspaceInput { HealthChanged(SessionHealth), @@ -514,15 +530,7 @@ pub(crate) enum WorkspaceInput { }, NewEditorTab, CloseActiveWorkspaceTab, - EditorTabRunStateChanged(Uuid, bool), - EditorTabRunFinished(Uuid, crate::workspace::WorkOutcome), - EditorTabContentChanged(Uuid), - /// An editor tab was saved, opened a file, or its text came to - /// differ from its file's or match it again. - EditorTabFileChanged(Uuid), - /// An editor tab moved to another database, which its record keeps - /// and its title names. - EditorTabDatabaseChanged(Uuid), + Editor(EditorInput), /// The session's saved tabs and their editor text, read off the GTK /// thread. WorkspaceLoaded(workspace_tabs::LoadedWorkspace), @@ -530,14 +538,6 @@ pub(crate) enum WorkspaceInput { ResetWorkspaceLayout, /// The session moved to another Safe Mode level, which the title names. SafeModeChanged, - /// Completion in editor tab `tab_id` reads `session`'s catalog, its - /// database's, or its own connection's again with `None`. - FollowCatalog { - tab_id: Uuid, - session: Option>, - }, - /// Another database of the connection opened beside it. - DatabaseOpened(Arc), /// The saved connections changed, the title's icon perhaps with them. SavedConnectionsChanged, WorkspaceLayoutReset(Result, crate::workspace::WorkspaceSaveError>), @@ -594,8 +594,6 @@ pub(crate) enum WorkspaceInput { /// A save started or settled, or tabs' changes were dropped. Workspace(crate::workspace::WorkspaceEvent), SavesInFlightChanged(usize), - /// An editor tab's transaction opened, failed or ended. - EditorTransactionChanged, /// The transaction banner's Show. ShowTransactionTab, ShowAlert { @@ -962,6 +960,11 @@ impl Workspace { self.imp().index.get()?.id_of(page) } + pub(crate) fn tab_database(&self, id: Uuid) -> Option { + self.read(|model| model.editor_tab(id).and_then(|editor| editor.tab_database())) + .flatten() + } + /// Whether the session has a tab open. pub(super) fn has_tabs(&self) -> bool { self.imp().index.get().is_some_and(|index| !index.is_empty()) @@ -1345,7 +1348,6 @@ impl WorkspaceModel { WorkspaceInput::StopSaving(id) => self.stop_saving(id), WorkspaceInput::Workspace(event) => self.on_workspace_event(event), WorkspaceInput::SavesInFlightChanged(count) => self.on_saves_in_flight_changed(count), - WorkspaceInput::EditorTransactionChanged => self.on_editor_transaction_changed(), WorkspaceInput::ShowTransactionTab => self.show_transaction_tab(), WorkspaceInput::WorkspaceTabClosed(id) => self.close_workspace_tab_by_id(id), WorkspaceInput::CloseWorkspaceTab(id) => self.close_workspace_tab(id), @@ -1379,13 +1381,7 @@ impl WorkspaceModel { } WorkspaceInput::SchemaChanged { schema, table } => self.on_schema_changed(schema, table), WorkspaceInput::NewEditorTab => self.open_editor_tab(None), - WorkspaceInput::EditorTabRunStateChanged(id, running) => self.on_editor_tab_run_state_changed(id, running), - WorkspaceInput::EditorTabRunFinished(id, outcome) => self.on_editor_tab_run_finished(id, outcome), - WorkspaceInput::EditorTabContentChanged(id) => self.on_editor_tab_content_changed(id), - WorkspaceInput::EditorTabFileChanged(id) => self.on_editor_tab_file_changed(id), - WorkspaceInput::EditorTabDatabaseChanged(id) => self.on_editor_tab_database_changed(id), - WorkspaceInput::FollowCatalog { tab_id, session } => self.follow_catalog(tab_id, session), - WorkspaceInput::DatabaseOpened(session) => self.on_database_opened(&session), + WorkspaceInput::Editor(input) => self.on_editor_input(input), WorkspaceInput::WorkspaceLoaded(loaded) => self.on_workspace_loaded(loaded), WorkspaceInput::ResetWorkspaceLayout => self.on_reset_workspace_layout(), WorkspaceInput::SafeModeChanged => self.refresh_title(), diff --git a/linux/crates/app/src/ui/workspace/sidebar/connection_tree.rs b/linux/crates/app/src/ui/workspace/sidebar/connection_tree.rs index a970d01a4b..c1d225ffdb 100644 --- a/linux/crates/app/src/ui/workspace/sidebar/connection_tree.rs +++ b/linux/crates/app/src/ui/workspace/sidebar/connection_tree.rs @@ -372,6 +372,13 @@ impl ConnectionTree { })); } + #[cfg(test)] + pub(crate) fn selected_session(&self) -> Option { + let which = self.inner.shown(); + let position = self.inner.pane(which).selection.selected(); + self.inner.item_at(which, position)?.1 + } + pub(crate) fn shutdown(&self) { let inner = &self.inner; if let Some(watch) = inner.saved_watch.take() { diff --git a/linux/crates/app/src/ui/workspace/tab_factory.rs b/linux/crates/app/src/ui/workspace/tab_factory.rs index 55b8f44575..d55e70d5c6 100644 --- a/linux/crates/app/src/ui/workspace/tab_factory.rs +++ b/linux/crates/app/src/ui/workspace/tab_factory.rs @@ -19,7 +19,7 @@ use super::tab_title::{ConnectionLabel, apply_tab_title, resolve_tab_title}; use super::table_naming::TableNaming; use super::workspace_persistence::WorkspaceTabs; use super::{ - DiagramTabSlot, EditorTabSlot, KeyTabSlot, OpenMode, StructureTabSlot, TableTabSlot, WorkspaceInput, + DiagramTabSlot, EditorInput, EditorTabSlot, KeyTabSlot, OpenMode, StructureTabSlot, TableTabSlot, WorkspaceInput, WorkspaceSender, WorkspaceShell, WorkspaceTab, }; use crate::runtime::DeliverInput; @@ -194,7 +194,9 @@ impl TabFactory { // It moved before the workspace heard it, which follows it once // the tab is in. if moved { - parts.input.deliver(WorkspaceInput::EditorTabDatabaseChanged(id)); + parts + .input + .deliver(WorkspaceInput::Editor(EditorInput::DatabaseChanged(id))); } editor.attach_assistant(parts.assistant.clone()); // After the signals are connected, so the workspace marks a tab @@ -504,20 +506,25 @@ pub(super) fn connect_editor( ) { let run_state = input.clone(); editor.connect_run_state_changed(move |_, running| { - run_state.deliver(WorkspaceInput::EditorTabRunStateChanged(tab_id, running)); + run_state.deliver(WorkspaceInput::Editor(EditorInput::RunStateChanged(tab_id, running))); }); let finished = input.clone(); editor.connect_run_finished(move |_, outcome| { - finished.deliver(WorkspaceInput::EditorTabRunFinished(tab_id, outcome)) + finished.deliver(WorkspaceInput::Editor(EditorInput::RunFinished(tab_id, outcome))) }); let content = input.clone(); - editor.connect_content_changed(move |_| content.deliver(WorkspaceInput::EditorTabContentChanged(tab_id))); + editor + .connect_content_changed(move |_| content.deliver(WorkspaceInput::Editor(EditorInput::ContentChanged(tab_id)))); let file = input.clone(); - editor.connect_file_changed(move |_| file.deliver(WorkspaceInput::EditorTabFileChanged(tab_id))); + editor.connect_file_changed(move |_| file.deliver(WorkspaceInput::Editor(EditorInput::FileChanged(tab_id)))); let database = input.clone(); - editor.connect_database_changed(move |_| database.deliver(WorkspaceInput::EditorTabDatabaseChanged(tab_id))); + editor.connect_database_changed(move |_| { + database.deliver(WorkspaceInput::Editor(EditorInput::DatabaseChanged(tab_id))) + }); let transaction = input.clone(); - editor.connect_transaction_changed(move |_, _| transaction.deliver(WorkspaceInput::EditorTransactionChanged)); + editor.connect_transaction_changed(move |_, _| { + transaction.deliver(WorkspaceInput::Editor(EditorInput::TransactionChanged)) + }); let toast = input.clone(); editor.connect_toast(move |_, text| toast.deliver(WorkspaceInput::ShowToast(text))); let save = input.clone(); diff --git a/linux/crates/app/src/ui/workspace/workspace_shell.rs b/linux/crates/app/src/ui/workspace/workspace_shell.rs index 25eb2ae449..b73fcc1f1f 100644 --- a/linux/crates/app/src/ui/workspace/workspace_shell.rs +++ b/linux/crates/app/src/ui/workspace/workspace_shell.rs @@ -482,6 +482,9 @@ impl WorkspaceShell { if let (Some(tree), Some(key)) = (imp.tree.get(), workspace.key()) { tree.remove_session(&key); } + if let Some(front) = self.front() { + front.read(super::WorkspaceModel::select_in_tree); + } self.tell_sharing(); self.refresh_saving(); } diff --git a/linux/crates/app/src/ui/workspace/workspace_tabs.rs b/linux/crates/app/src/ui/workspace/workspace_tabs.rs index b599dce1d3..21ebde7b1e 100644 --- a/linux/crates/app/src/ui/workspace/workspace_tabs.rs +++ b/linux/crates/app/src/ui/workspace/workspace_tabs.rs @@ -26,10 +26,29 @@ use super::tab_factory::EditorPreview; use super::tab_index::TabIndex; use super::tab_spec::{TabSpec, TablePage}; use super::workspace_persistence::reopen; -use super::{ClosedTabDescriptor, OpenMode, WorkspaceInput, WorkspaceModel, WorkspaceSender, WorkspaceTab}; +use super::{ + ClosedTabDescriptor, EditorInput, OpenMode, WorkspaceInput, WorkspaceModel, WorkspaceSender, WorkspaceTab, +}; use crate::runtime::DeliverInput; impl WorkspaceModel { + pub(super) fn on_editor_input(&mut self, input: EditorInput) { + match input { + EditorInput::RunStateChanged(id, running) => self.on_editor_tab_run_state_changed(id, running), + EditorInput::RunFinished(id, outcome) => self.on_editor_tab_run_finished(id, outcome), + EditorInput::ContentChanged(id) => self.on_editor_tab_content_changed(id), + EditorInput::FileChanged(id) => self.on_editor_tab_file_changed(id), + EditorInput::DatabaseChanged(id) => self.on_editor_tab_database_changed(id), + EditorInput::TransactionChanged => self.on_editor_transaction_changed(), + EditorInput::FollowCatalog { + tab_id, + database, + session, + } => self.follow_catalog(tab_id, database, session), + EditorInput::DatabaseOpened(session) => self.on_database_opened(&session), + } + } + /// Read the saved tabs of the session just adopted, and the editor /// text that goes with them, off the GTK thread. pub(super) fn restore_workspace_tabs(&mut self, key: SessionKey) { @@ -498,29 +517,55 @@ impl WorkspaceModel { self.report_tabs_changed(); } - /// While the session is in front, the tree selects the table or key - /// its tab shows, or its connection for any other tab. With no tab - /// open no row stays selected: one would say a tab shows it. pub(super) fn select_in_tree(&self) { if !self.is_front() { return; } - let Some(tree) = self.shell.upgrade().and_then(|shell| shell.tree()) else { + let Some(shell) = self.shell.upgrade() else { + return; + }; + let Some(tree) = shell.tree() else { return; }; match self.selected_workspace_tab_id() { Some(id) => { - let shown = self - .workspace_tabs - .borrow() - .get(&id) - .and_then(WorkspaceTab::sidebar_object); - tree.select(Some(&self.key), shown.as_ref()); + let (shown, catalog) = { + let tabs = self.workspace_tabs.borrow(); + let tab = tabs.get(&id); + ( + tab.and_then(WorkspaceTab::sidebar_object), + tab.and_then(|tab| match tab { + WorkspaceTab::Editor(slot) => slot.editor.catalog_session(), + _ => None, + }), + ) + }; + let row = catalog + .and_then(|catalog| self.sidebar_catalog_session(&shell, &catalog)) + .unwrap_or_else(|| self.key.clone()); + tree.select(Some(&row), shown.as_ref()); } None => tree.select(None, None), } } + fn sidebar_catalog_session(&self, shell: &super::WorkspaceShell, catalog: &Arc) -> Option { + // Completion and the sidebar follow the same accepted session, including + // a server-default database whose connection request had no name. + shell.sessions().into_iter().find_map(|workspace| { + let matches = workspace + .read(|model| { + model + .context + .active + .get() + .is_some_and(|session| Arc::ptr_eq(&session, catalog)) + }) + .unwrap_or(false); + matches.then(|| workspace.key()).flatten() + }) + } + pub(super) fn selected_workspace_tab_id(&self) -> Option { self.index.id_of(&self.tab_view.selected_page()?) } @@ -614,12 +659,11 @@ impl WorkspaceModel { self.persist_workspace_state(); } - /// A tab that moved to another database is restored there and names - /// it in its title. pub(super) fn on_editor_tab_database_changed(&self, id: Uuid) { self.retitle_tab(id); self.persist_workspace_state(); self.follow_editor_database(id); + self.select_in_tree(); } /// Ask the window for the session of the database tab `tab_id` moved @@ -638,20 +682,20 @@ impl WorkspaceModel { } } - pub(super) fn follow_catalog(&self, tab_id: Uuid, session: Option>) { + pub(super) fn follow_catalog(&self, tab_id: Uuid, database: Option, session: Option>) { if let Some(WorkspaceTab::Editor(slot)) = self.workspace_tabs.borrow().get(&tab_id) { - slot.editor.follow_catalog(session); + slot.editor.follow_catalog_for(database.as_deref(), session); } + self.select_in_tree(); } - /// Another database of the connection opened: each editor tab in it - /// reads its catalog. pub(super) fn on_database_opened(&self, session: &Arc) { for tab in self.workspace_tabs.borrow().values() { if let WorkspaceTab::Editor(slot) = tab { slot.editor.follow_catalog(Some(session.clone())); } } + self.select_in_tree(); } pub(super) fn on_editor_tab_run_state_changed(&self, id: Uuid, running: bool) {