From 80458ffb960555a85a26d2d88e4414298f840a72 Mon Sep 17 00:00:00 2001 From: Kirill Bulatov Date: Tue, 18 Feb 2025 16:27:00 +0200 Subject: [PATCH] Persist selections for editors (#25083) Part of https://github.com/zed-industries/zed/issues/7371 Closes https://github.com/zed-industries/zed/issues/12853 Release Notes: - Started to persist latest selections for editors, to restore those on restart --- crates/editor/src/display_map.rs | 1 + crates/editor/src/editor.rs | 70 +++++++++++++++++-- crates/editor/src/items.rs | 8 +++ crates/editor/src/movement.rs | 1 + crates/editor/src/persistence.rs | 80 ++++++++++++++++++++++ crates/language_tools/src/lsp_log_tests.rs | 1 + crates/search/src/buffer_search.rs | 1 + crates/workspace/src/workspace_settings.rs | 2 +- 8 files changed, 159 insertions(+), 5 deletions(-) diff --git a/crates/editor/src/display_map.rs b/crates/editor/src/display_map.rs index 7b6181310f6a74..5f86b468439f3a 100644 --- a/crates/editor/src/display_map.rs +++ b/crates/editor/src/display_map.rs @@ -2778,6 +2778,7 @@ pub mod tests { fn init_test(cx: &mut App, f: impl Fn(&mut AllLanguageSettingsContent)) { let settings = SettingsStore::test(cx); cx.set_global(settings); + workspace::init_settings(cx); language::init(cx); crate::init(cx); Project::init_settings(cx); diff --git a/crates/editor/src/editor.rs b/crates/editor/src/editor.rs index e17236a71dae22..50f54849625fb5 100644 --- a/crates/editor/src/editor.rs +++ b/crates/editor/src/editor.rs @@ -106,6 +106,7 @@ use language::{ use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange}; use linked_editing_ranges::refresh_linked_ranges; use mouse_context_menu::MouseContextMenu; +use persistence::DB; pub use proposed_changes_editor::{ ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar, }; @@ -171,8 +172,14 @@ use ui::{ Tooltip, }; use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt}; -use workspace::item::{ItemHandle, PreviewTabsSettings}; -use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt}; +use workspace::{ + item::{ItemHandle, PreviewTabsSettings}, + ItemId, RestoreOnStartupBehavior, +}; +use workspace::{ + notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt}, + WorkspaceSettings, +}; use workspace::{ searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId, }; @@ -763,6 +770,7 @@ pub struct Editor { selection_mark_mode: bool, toggle_fold_multiple_buffers: Task<()>, _scroll_cursor_center_top_bottom_task: Task<()>, + serialize_selections: Task<()>, } #[derive(Copy, Clone, Debug, PartialEq, Eq, Default)] @@ -1475,6 +1483,7 @@ impl Editor { _scroll_cursor_center_top_bottom_task: Task::ready(()), selection_mark_mode: false, toggle_fold_multiple_buffers: Task::ready(()), + serialize_selections: Task::ready(()), text_style_refinement: None, load_diff_task: load_uncommitted_diff, }; @@ -2181,9 +2190,37 @@ impl Editor { self.blink_manager.update(cx, BlinkManager::pause_blinking); cx.emit(EditorEvent::SelectionsChanged { local }); - if self.selections.disjoint_anchors().len() == 1 { + let selections = &self.selections.disjoint; + if selections.len() == 1 { cx.emit(SearchEvent::ActiveMatchChanged) } + if local + && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None + { + if let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) { + let background_executor = cx.background_executor().clone(); + let editor_id = cx.entity().entity_id().as_u64() as ItemId; + let snapshot = self.buffer().read(cx).snapshot(cx); + let selections = selections.clone(); + self.serialize_selections = cx.background_spawn(async move { + background_executor.timer(Duration::from_millis(100)).await; + let selections = selections + .iter() + .map(|selection| { + ( + selection.start.to_offset(&snapshot), + selection.end.to_offset(&snapshot), + ) + }) + .collect(); + DB.save_editor_selections(editor_id, workspace_id, selections) + .await + .context("persisting editor selections") + .log_err(); + }); + } + } + cx.notify(); } @@ -2197,7 +2234,7 @@ impl Editor { self.change_selections_inner(autoscroll, true, window, cx, change) } - pub fn change_selections_inner( + fn change_selections_inner( &mut self, autoscroll: Option, request_completions: bool, @@ -14982,6 +15019,31 @@ impl Editor { pub fn wait_for_diff_to_load(&self) -> Option>> { self.load_diff_task.clone() } + + fn read_selections_from_db( + &mut self, + item_id: u64, + workspace_id: WorkspaceId, + window: &mut Window, + cx: &mut Context, + ) { + if WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None { + return; + } + let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() else { + return; + }; + if selections.is_empty() { + return; + } + + let snapshot = self.buffer.read(cx).snapshot(cx); + self.change_selections(None, window, cx, |s| { + s.select_ranges(selections.into_iter().map(|(start, end)| { + snapshot.clip_offset(start, Bias::Left)..snapshot.clip_offset(end, Bias::Right) + })); + }); + } } fn get_uncommitted_diff_for_buffer( diff --git a/crates/editor/src/items.rs b/crates/editor/src/items.rs index 8a15bbb10cc385..7f40092f0b71ff 100644 --- a/crates/editor/src/items.rs +++ b/crates/editor/src/items.rs @@ -1079,6 +1079,7 @@ impl SerializableItem for Editor { cx.new(|cx| { let mut editor = Editor::for_buffer(buffer, Some(project), window, cx); + editor.read_selections_from_db(item_id, workspace_id, window, cx); editor.read_scroll_position_from_db(item_id, workspace_id, window, cx); editor }) @@ -1134,6 +1135,12 @@ impl SerializableItem for Editor { let mut editor = Editor::for_buffer(buffer, Some(project), window, cx); + editor.read_selections_from_db( + item_id, + workspace_id, + window, + cx, + ); editor.read_scroll_position_from_db( item_id, workspace_id, @@ -1152,6 +1159,7 @@ impl SerializableItem for Editor { window.spawn(cx, |mut cx| async move { let editor = open_by_abs_path?.await?.downcast::().with_context(|| format!("Failed to downcast to Editor after opening abs path {abs_path:?}"))?; editor.update_in(&mut cx, |editor, window, cx| { + editor.read_selections_from_db(item_id, workspace_id, window, cx); editor.read_scroll_position_from_db(item_id, workspace_id, window, cx); })?; Ok(editor) diff --git a/crates/editor/src/movement.rs b/crates/editor/src/movement.rs index 556c15cc9b17f7..d070feb262d5c5 100644 --- a/crates/editor/src/movement.rs +++ b/crates/editor/src/movement.rs @@ -1184,6 +1184,7 @@ mod tests { fn init_test(cx: &mut gpui::App) { let settings_store = SettingsStore::test(cx); cx.set_global(settings_store); + workspace::init_settings(cx); theme::init(theme::LoadThemes::JustBase, cx); language::init(cx); crate::init(cx); diff --git a/crates/editor/src/persistence.rs b/crates/editor/src/persistence.rs index 489551241755c3..e8d2ed05d434b6 100644 --- a/crates/editor/src/persistence.rs +++ b/crates/editor/src/persistence.rs @@ -2,6 +2,7 @@ use anyhow::Result; use db::sqlez::bindable::{Bind, Column, StaticColumnCount}; use db::sqlez::statement::Statement; use fs::MTime; +use itertools::Itertools as _; use std::path::PathBuf; use db::sqlez_macros::sql; @@ -134,9 +135,26 @@ define_connection!( ALTER TABLE editors ADD COLUMN mtime_seconds INTEGER DEFAULT NULL; ALTER TABLE editors ADD COLUMN mtime_nanos INTEGER DEFAULT NULL; ), + sql! ( + CREATE TABLE editor_selections ( + item_id INTEGER NOT NULL, + editor_id INTEGER NOT NULL, + workspace_id INTEGER NOT NULL, + start INTEGER NOT NULL, + end INTEGER NOT NULL, + PRIMARY KEY(item_id), + FOREIGN KEY(editor_id, workspace_id) REFERENCES editors(item_id, workspace_id) + ON DELETE CASCADE + ) STRICT; + ), ]; ); +// https://www.sqlite.org/limits.html +// > <..> the maximum value of a host parameter number is SQLITE_MAX_VARIABLE_NUMBER, +// > which defaults to <..> 32766 for SQLite versions after 3.32.0. +const MAX_QUERY_PLACEHOLDERS: usize = 32000; + impl EditorDb { query! { pub fn get_serialized_editor(item_id: ItemId, workspace_id: WorkspaceId) -> Result> { @@ -188,6 +206,68 @@ impl EditorDb { } } + query! { + pub fn get_editor_selections( + editor_id: ItemId, + workspace_id: WorkspaceId + ) -> Result> { + SELECT start, end + FROM editor_selections + WHERE editor_id = ?1 AND workspace_id = ?2 + } + } + + pub async fn save_editor_selections( + &self, + editor_id: ItemId, + workspace_id: WorkspaceId, + selections: Vec<(usize, usize)>, + ) -> Result<()> { + let mut first_selection; + let mut last_selection = 0_usize; + for (count, placeholders) in std::iter::once("(?1, ?2, ?, ?)") + .cycle() + .take(selections.len()) + .chunks(MAX_QUERY_PLACEHOLDERS / 4) + .into_iter() + .map(|chunk| { + let mut count = 0; + let placeholders = chunk + .inspect(|_| { + count += 1; + }) + .join(", "); + (count, placeholders) + }) + .collect::>() + { + first_selection = last_selection; + last_selection = last_selection + count; + let query = format!( + r#" +DELETE FROM editor_selections WHERE editor_id = ?1 AND workspace_id = ?2; + +INSERT INTO editor_selections (editor_id, workspace_id, start, end) +VALUES {placeholders}; +"# + ); + + let selections = selections[first_selection..last_selection].to_vec(); + self.write(move |conn| { + let mut statement = Statement::prepare(conn, query)?; + statement.bind(&editor_id, 1)?; + let mut next_index = statement.bind(&workspace_id, 2)?; + for (start, end) in selections { + next_index = statement.bind(&start, next_index)?; + next_index = statement.bind(&end, next_index)?; + } + statement.exec() + }) + .await?; + } + Ok(()) + } + pub async fn delete_unloaded_items( &self, workspace: WorkspaceId, diff --git a/crates/language_tools/src/lsp_log_tests.rs b/crates/language_tools/src/lsp_log_tests.rs index 5d318d0afadbbe..707d2ca0221983 100644 --- a/crates/language_tools/src/lsp_log_tests.rs +++ b/crates/language_tools/src/lsp_log_tests.rs @@ -109,6 +109,7 @@ fn init_test(cx: &mut gpui::TestAppContext) { cx.update(|cx| { let settings_store = SettingsStore::test(cx); cx.set_global(settings_store); + workspace::init_settings(cx); theme::init(theme::LoadThemes::JustBase, cx); release_channel::init(SemanticVersion::default(), cx); language::init(cx); diff --git a/crates/search/src/buffer_search.rs b/crates/search/src/buffer_search.rs index 5cc644e253477a..3a9a48e0856fcf 100644 --- a/crates/search/src/buffer_search.rs +++ b/crates/search/src/buffer_search.rs @@ -1511,6 +1511,7 @@ mod tests { cx.update(|cx| { let store = settings::SettingsStore::test(cx); cx.set_global(store); + workspace::init_settings(cx); editor::init(cx); language::init(cx); diff --git a/crates/workspace/src/workspace_settings.rs b/crates/workspace/src/workspace_settings.rs index f6d3a176d686d0..575b4ac26166c2 100644 --- a/crates/workspace/src/workspace_settings.rs +++ b/crates/workspace/src/workspace_settings.rs @@ -71,7 +71,7 @@ impl CloseWindowWhenNoItems { } } -#[derive(Copy, Clone, Default, Serialize, Deserialize, JsonSchema)] +#[derive(Copy, Clone, PartialEq, Eq, Default, Serialize, Deserialize, JsonSchema)] #[serde(rename_all = "snake_case")] pub enum RestoreOnStartupBehavior { /// Always start with an empty editor