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
This commit is contained in:
parent
b34037876e
commit
80458ffb96
8 changed files with 159 additions and 5 deletions
|
@ -2778,6 +2778,7 @@ pub mod tests {
|
||||||
fn init_test(cx: &mut App, f: impl Fn(&mut AllLanguageSettingsContent)) {
|
fn init_test(cx: &mut App, f: impl Fn(&mut AllLanguageSettingsContent)) {
|
||||||
let settings = SettingsStore::test(cx);
|
let settings = SettingsStore::test(cx);
|
||||||
cx.set_global(settings);
|
cx.set_global(settings);
|
||||||
|
workspace::init_settings(cx);
|
||||||
language::init(cx);
|
language::init(cx);
|
||||||
crate::init(cx);
|
crate::init(cx);
|
||||||
Project::init_settings(cx);
|
Project::init_settings(cx);
|
||||||
|
|
|
@ -106,6 +106,7 @@ use language::{
|
||||||
use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
|
use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
|
||||||
use linked_editing_ranges::refresh_linked_ranges;
|
use linked_editing_ranges::refresh_linked_ranges;
|
||||||
use mouse_context_menu::MouseContextMenu;
|
use mouse_context_menu::MouseContextMenu;
|
||||||
|
use persistence::DB;
|
||||||
pub use proposed_changes_editor::{
|
pub use proposed_changes_editor::{
|
||||||
ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
|
ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
|
||||||
};
|
};
|
||||||
|
@ -171,8 +172,14 @@ use ui::{
|
||||||
Tooltip,
|
Tooltip,
|
||||||
};
|
};
|
||||||
use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
|
use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
|
||||||
use workspace::item::{ItemHandle, PreviewTabsSettings};
|
use workspace::{
|
||||||
use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
|
item::{ItemHandle, PreviewTabsSettings},
|
||||||
|
ItemId, RestoreOnStartupBehavior,
|
||||||
|
};
|
||||||
|
use workspace::{
|
||||||
|
notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt},
|
||||||
|
WorkspaceSettings,
|
||||||
|
};
|
||||||
use workspace::{
|
use workspace::{
|
||||||
searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
|
searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
|
||||||
};
|
};
|
||||||
|
@ -763,6 +770,7 @@ pub struct Editor {
|
||||||
selection_mark_mode: bool,
|
selection_mark_mode: bool,
|
||||||
toggle_fold_multiple_buffers: Task<()>,
|
toggle_fold_multiple_buffers: Task<()>,
|
||||||
_scroll_cursor_center_top_bottom_task: Task<()>,
|
_scroll_cursor_center_top_bottom_task: Task<()>,
|
||||||
|
serialize_selections: Task<()>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
|
#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
|
||||||
|
@ -1475,6 +1483,7 @@ impl Editor {
|
||||||
_scroll_cursor_center_top_bottom_task: Task::ready(()),
|
_scroll_cursor_center_top_bottom_task: Task::ready(()),
|
||||||
selection_mark_mode: false,
|
selection_mark_mode: false,
|
||||||
toggle_fold_multiple_buffers: Task::ready(()),
|
toggle_fold_multiple_buffers: Task::ready(()),
|
||||||
|
serialize_selections: Task::ready(()),
|
||||||
text_style_refinement: None,
|
text_style_refinement: None,
|
||||||
load_diff_task: load_uncommitted_diff,
|
load_diff_task: load_uncommitted_diff,
|
||||||
};
|
};
|
||||||
|
@ -2181,9 +2190,37 @@ impl Editor {
|
||||||
self.blink_manager.update(cx, BlinkManager::pause_blinking);
|
self.blink_manager.update(cx, BlinkManager::pause_blinking);
|
||||||
cx.emit(EditorEvent::SelectionsChanged { local });
|
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)
|
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();
|
cx.notify();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -2197,7 +2234,7 @@ impl Editor {
|
||||||
self.change_selections_inner(autoscroll, true, window, cx, change)
|
self.change_selections_inner(autoscroll, true, window, cx, change)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn change_selections_inner<R>(
|
fn change_selections_inner<R>(
|
||||||
&mut self,
|
&mut self,
|
||||||
autoscroll: Option<Autoscroll>,
|
autoscroll: Option<Autoscroll>,
|
||||||
request_completions: bool,
|
request_completions: bool,
|
||||||
|
@ -14982,6 +15019,31 @@ impl Editor {
|
||||||
pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
|
pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
|
||||||
self.load_diff_task.clone()
|
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(
|
fn get_uncommitted_diff_for_buffer(
|
||||||
|
|
|
@ -1079,6 +1079,7 @@ impl SerializableItem for Editor {
|
||||||
cx.new(|cx| {
|
cx.new(|cx| {
|
||||||
let mut editor = Editor::for_buffer(buffer, Some(project), window, 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.read_scroll_position_from_db(item_id, workspace_id, window, cx);
|
||||||
editor
|
editor
|
||||||
})
|
})
|
||||||
|
@ -1134,6 +1135,12 @@ impl SerializableItem for Editor {
|
||||||
let mut editor =
|
let mut editor =
|
||||||
Editor::for_buffer(buffer, Some(project), window, cx);
|
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(
|
editor.read_scroll_position_from_db(
|
||||||
item_id,
|
item_id,
|
||||||
workspace_id,
|
workspace_id,
|
||||||
|
@ -1152,6 +1159,7 @@ impl SerializableItem for Editor {
|
||||||
window.spawn(cx, |mut cx| async move {
|
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:?}"))?;
|
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.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);
|
editor.read_scroll_position_from_db(item_id, workspace_id, window, cx);
|
||||||
})?;
|
})?;
|
||||||
Ok(editor)
|
Ok(editor)
|
||||||
|
|
|
@ -1184,6 +1184,7 @@ mod tests {
|
||||||
fn init_test(cx: &mut gpui::App) {
|
fn init_test(cx: &mut gpui::App) {
|
||||||
let settings_store = SettingsStore::test(cx);
|
let settings_store = SettingsStore::test(cx);
|
||||||
cx.set_global(settings_store);
|
cx.set_global(settings_store);
|
||||||
|
workspace::init_settings(cx);
|
||||||
theme::init(theme::LoadThemes::JustBase, cx);
|
theme::init(theme::LoadThemes::JustBase, cx);
|
||||||
language::init(cx);
|
language::init(cx);
|
||||||
crate::init(cx);
|
crate::init(cx);
|
||||||
|
|
|
@ -2,6 +2,7 @@ use anyhow::Result;
|
||||||
use db::sqlez::bindable::{Bind, Column, StaticColumnCount};
|
use db::sqlez::bindable::{Bind, Column, StaticColumnCount};
|
||||||
use db::sqlez::statement::Statement;
|
use db::sqlez::statement::Statement;
|
||||||
use fs::MTime;
|
use fs::MTime;
|
||||||
|
use itertools::Itertools as _;
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
|
|
||||||
use db::sqlez_macros::sql;
|
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_seconds INTEGER DEFAULT NULL;
|
||||||
ALTER TABLE editors ADD COLUMN mtime_nanos 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 {
|
impl EditorDb {
|
||||||
query! {
|
query! {
|
||||||
pub fn get_serialized_editor(item_id: ItemId, workspace_id: WorkspaceId) -> Result<Option<SerializedEditor>> {
|
pub fn get_serialized_editor(item_id: ItemId, workspace_id: WorkspaceId) -> Result<Option<SerializedEditor>> {
|
||||||
|
@ -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(
|
pub async fn delete_unloaded_items(
|
||||||
&self,
|
&self,
|
||||||
workspace: WorkspaceId,
|
workspace: WorkspaceId,
|
||||||
|
|
|
@ -109,6 +109,7 @@ fn init_test(cx: &mut gpui::TestAppContext) {
|
||||||
cx.update(|cx| {
|
cx.update(|cx| {
|
||||||
let settings_store = SettingsStore::test(cx);
|
let settings_store = SettingsStore::test(cx);
|
||||||
cx.set_global(settings_store);
|
cx.set_global(settings_store);
|
||||||
|
workspace::init_settings(cx);
|
||||||
theme::init(theme::LoadThemes::JustBase, cx);
|
theme::init(theme::LoadThemes::JustBase, cx);
|
||||||
release_channel::init(SemanticVersion::default(), cx);
|
release_channel::init(SemanticVersion::default(), cx);
|
||||||
language::init(cx);
|
language::init(cx);
|
||||||
|
|
|
@ -1511,6 +1511,7 @@ mod tests {
|
||||||
cx.update(|cx| {
|
cx.update(|cx| {
|
||||||
let store = settings::SettingsStore::test(cx);
|
let store = settings::SettingsStore::test(cx);
|
||||||
cx.set_global(store);
|
cx.set_global(store);
|
||||||
|
workspace::init_settings(cx);
|
||||||
editor::init(cx);
|
editor::init(cx);
|
||||||
|
|
||||||
language::init(cx);
|
language::init(cx);
|
||||||
|
|
|
@ -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")]
|
#[serde(rename_all = "snake_case")]
|
||||||
pub enum RestoreOnStartupBehavior {
|
pub enum RestoreOnStartupBehavior {
|
||||||
/// Always start with an empty editor
|
/// Always start with an empty editor
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue