Skip to content

Commit

Permalink
Persist selections for editors (#25083)
Browse files Browse the repository at this point in the history
Part of #7371
Closes #12853

Release Notes:

- Started to persist latest selections for editors, to restore those on
restart
  • Loading branch information
SomeoneToIgnore authored Feb 18, 2025
1 parent b340378 commit 80458ff
Show file tree
Hide file tree
Showing 8 changed files with 159 additions and 5 deletions.
1 change: 1 addition & 0 deletions crates/editor/src/display_map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
70 changes: 66 additions & 4 deletions crates/editor/src/editor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
};
Expand Down Expand Up @@ -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,
};
Expand Down Expand Up @@ -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)]
Expand Down Expand Up @@ -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,
};
Expand Down Expand Up @@ -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();
}

Expand All @@ -2197,7 +2234,7 @@ impl Editor {
self.change_selections_inner(autoscroll, true, window, cx, change)
}

pub fn change_selections_inner<R>(
fn change_selections_inner<R>(
&mut self,
autoscroll: Option<Autoscroll>,
request_completions: bool,
Expand Down Expand Up @@ -14982,6 +15019,31 @@ impl Editor {
pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
self.load_diff_task.clone()
}

fn read_selections_from_db(
&mut self,
item_id: u64,
workspace_id: WorkspaceId,
window: &mut Window,
cx: &mut Context<Editor>,
) {
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(
Expand Down
8 changes: 8 additions & 0 deletions crates/editor/src/items.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
})
Expand Down Expand Up @@ -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,
Expand All @@ -1152,6 +1159,7 @@ impl SerializableItem for Editor {
window.spawn(cx, |mut cx| async move {
let editor = open_by_abs_path?.await?.downcast::<Editor>().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)
Expand Down
1 change: 1 addition & 0 deletions crates/editor/src/movement.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
80 changes: 80 additions & 0 deletions crates/editor/src/persistence.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<Option<SerializedEditor>> {
Expand Down Expand Up @@ -188,6 +206,68 @@ impl EditorDb {
}
}

query! {
pub fn get_editor_selections(
editor_id: ItemId,
workspace_id: WorkspaceId
) -> Result<Vec<(usize, usize)>> {
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::<Vec<_>>()
{
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,
Expand Down
1 change: 1 addition & 0 deletions crates/language_tools/src/lsp_log_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
1 change: 1 addition & 0 deletions crates/search/src/buffer_search.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
2 changes: 1 addition & 1 deletion crates/workspace/src/workspace_settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 80458ff

Please sign in to comment.