Skip to content

armgit / zed

Public Imported from GitHub
0

Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.

workspace: Persist recent navigation history across sessions (#55034)

Anıl Zeybek09adbb01f6ed
diff --git a/crates/editor/src/editor.rs b/crates/editor/src/editor.rs
index f5b485141af..d92b05775eb 100644
--- a/crates/editor/src/editor.rs
+++ b/crates/editor/src/editor.rs
@@ -2076,7 +2076,12 @@ impl Editor {
}
}
- project::Event::EntryRenamed(transaction, project_path, abs_path) => {
+ project::Event::EntryRenamed {
+ transaction,
+ new_project_path,
+ new_abs_path,
+ ..
+ } => {
let Some(workspace) = editor.workspace() else {
return;
};
@@ -2095,8 +2100,8 @@ impl Editor {
p.update(cx, |pane, _| {
pane.nav_history_mut().rename_item(
entity_id,
- project_path.clone(),
- abs_path.clone().into(),
+ new_project_path.clone(),
+ new_abs_path.clone().into(),
);
})
});
diff --git a/crates/file_finder/src/file_finder.rs b/crates/file_finder/src/file_finder.rs
index 77b6a3fb591..2bc51326b50 100644
--- a/crates/file_finder/src/file_finder.rs
+++ b/crates/file_finder/src/file_finder.rs
@@ -48,8 +48,8 @@ use util::{
rel_path::RelPath,
};
use workspace::{
- ModalView, OpenChannelNotesById, OpenOptions, OpenVisible, SplitDirection, Workspace,
- item::PreviewTabsSettings, notifications::NotifyResultExt, pane,
+ MAX_RECENT_SELECTIONS, ModalView, OpenChannelNotesById, OpenOptions, OpenVisible,
+ SplitDirection, Workspace, item::PreviewTabsSettings, notifications::NotifyResultExt, pane,
};
use zed_actions::search::ToggleIncludeIgnored;
@@ -851,7 +851,6 @@ impl FoundPath {
}
}
-const MAX_RECENT_SELECTIONS: usize = 20;
const SEARCH_DEBOUNCE: Duration = Duration::from_millis(100);
const WORKTREE_UPDATE_REFRESH_DEBOUNCE: Duration = Duration::from_millis(200);
diff --git a/crates/project/src/project.rs b/crates/project/src/project.rs
index c1a8cb5f3c6..3a6e053740b 100644
--- a/crates/project/src/project.rs
+++ b/crates/project/src/project.rs
@@ -421,7 +421,12 @@ pub enum Event {
RevealInProjectPanel(ProjectEntryId),
SnippetEdit(BufferId, Vec<(lsp::Range, Snippet)>),
ExpandedAllForEntry(WorktreeId, ProjectEntryId),
- EntryRenamed(ProjectTransaction, ProjectPath, PathBuf),
+ EntryRenamed {
+ transaction: ProjectTransaction,
+ new_project_path: ProjectPath,
+ old_abs_path: PathBuf,
+ new_abs_path: PathBuf,
+ },
WorkspaceEditApplied(ProjectTransaction),
AgentLocationChanged,
BufferEdited {
@@ -2672,11 +2677,12 @@ impl Project {
project
.update(cx, |_, cx| {
- cx.emit(Event::EntryRenamed(
+ cx.emit(Event::EntryRenamed {
transaction,
- new_path.clone(),
- new_abs_path.clone(),
- ));
+ new_project_path: new_path.clone(),
+ old_abs_path: old_abs_path.clone(),
+ new_abs_path: new_abs_path.clone(),
+ });
})
.ok();
diff --git a/crates/workspace/src/persistence.rs b/crates/workspace/src/persistence.rs
index f08aaba6c48..d352a92c235 100644
--- a/crates/workspace/src/persistence.rs
+++ b/crates/workspace/src/persistence.rs
@@ -1051,6 +1051,17 @@ impl Domain for WorkspaceDb {
sql!(
ALTER TABLE bookmarks ADD COLUMN label TEXT NOT NULL DEFAULT "";
),
+ sql!(
+ CREATE TABLE recent_navigation_history (
+ workspace_id INTEGER NOT NULL,
+ path BLOB NOT NULL,
+ position INTEGER NOT NULL,
+ PRIMARY KEY (workspace_id, path),
+ FOREIGN KEY(workspace_id) REFERENCES workspaces(workspace_id)
+ ON DELETE CASCADE
+ ON UPDATE CASCADE
+ ) STRICT;
+ ),
];
// Allow recovering from bad migration that was initially shipped to nightly
@@ -1202,6 +1213,7 @@ impl WorkspaceDb {
breakpoints: self.breakpoints(workspace_id),
window_id,
user_toolchains: self.user_toolchains(workspace_id, remote_connection_id),
+ recent_navigation_history: self.recent_navigation_history(workspace_id),
})
}
@@ -1306,9 +1318,23 @@ impl WorkspaceDb {
breakpoints: self.breakpoints(workspace_id),
window_id,
user_toolchains: self.user_toolchains(workspace_id, remote_connection_id),
+ recent_navigation_history: self.recent_navigation_history(workspace_id),
})
}
+ fn recent_navigation_history(&self, workspace_id: WorkspaceId) -> Vec<PathBuf> {
+ self.select_bound(sql!(
+ SELECT path
+ FROM recent_navigation_history
+ WHERE workspace_id = ?
+ ORDER BY position
+ ))
+ .and_then(|mut statement| statement(workspace_id))
+ .context("Loading recent navigation history")
+ .log_err()
+ .unwrap_or_default()
+ }
+
fn bookmarks(&self, workspace_id: WorkspaceId) -> BTreeMap<Arc<Path>, Vec<SerializedBookmark>> {
let bookmarks: Result<Vec<(PathBuf, Bookmark)>> = self
.select_bound(sql! {
@@ -1635,6 +1661,20 @@ impl WorkspaceDb {
prepared_query(args).context("Updating workspace")?;
+ conn.exec_bound(sql!(
+ DELETE FROM recent_navigation_history WHERE workspace_id = ?;
+ ))?(workspace.id)
+ .context("Clearing recent navigation history")?;
+
+ let mut insert_recent_path = conn.exec_bound(sql!(
+ INSERT INTO recent_navigation_history(workspace_id, path, position)
+ VALUES (?, ?, ?);
+ ))?;
+ for (position, path) in workspace.recent_navigation_history.iter().enumerate() {
+ insert_recent_path((workspace.id, path.as_path(), position))
+ .context("Inserting recent navigation history")?;
+ }
+
// Save center pane group
Self::save_pane_group(conn, workspace.id, &workspace.center_group, None)
.context("save pane group in save workspace")?;
@@ -2971,6 +3011,7 @@ mod tests {
session_id: None,
window_id: None,
user_toolchains: Default::default(),
+ recent_navigation_history: Default::default(),
};
db.save_workspace(workspace.clone()).await;
@@ -3094,6 +3135,7 @@ mod tests {
session_id: None,
window_id: None,
user_toolchains: Default::default(),
+ recent_navigation_history: Default::default(),
};
db.save_workspace(workspace.clone()).await;
@@ -3130,6 +3172,7 @@ mod tests {
session_id: None,
window_id: None,
user_toolchains: Default::default(),
+ recent_navigation_history: Default::default(),
};
db.save_workspace(workspace_without_breakpoint.clone())
@@ -3230,6 +3273,7 @@ mod tests {
session_id: None,
window_id: None,
user_toolchains: Default::default(),
+ recent_navigation_history: Default::default(),
};
let workspace_2 = SerializedWorkspace {
@@ -3247,6 +3291,7 @@ mod tests {
session_id: None,
window_id: None,
user_toolchains: Default::default(),
+ recent_navigation_history: Default::default(),
};
db.save_workspace(workspace_1.clone()).await;
@@ -3356,6 +3401,9 @@ mod tests {
session_id: None,
window_id: Some(999),
user_toolchains: Default::default(),
+ recent_navigation_history: (0..20)
+ .map(|index| PathBuf::from(format!("/tmp2/src/{index}.rs")))
+ .collect(),
};
db.save_workspace(workspace.clone()).await;
@@ -3369,6 +3417,9 @@ mod tests {
let round_trip_workspace = db.workspace_for_roots(&["/tmp", "/tmp2"]);
assert_eq!(workspace, round_trip_workspace.unwrap());
+
+ assert!(db.delete_workspace_by_id(workspace.id).await.is_ok());
+ assert!(db.recent_navigation_history(workspace.id).is_empty());
}
#[gpui::test]
@@ -3392,6 +3443,7 @@ mod tests {
session_id: None,
window_id: Some(1),
user_toolchains: Default::default(),
+ recent_navigation_history: Default::default(),
};
let mut workspace_2 = SerializedWorkspace {
@@ -3409,6 +3461,7 @@ mod tests {
session_id: None,
window_id: Some(2),
user_toolchains: Default::default(),
+ recent_navigation_history: Default::default(),
};
db.save_workspace(workspace_1.clone()).await;
@@ -3453,6 +3506,7 @@ mod tests {
session_id: None,
window_id: Some(3),
user_toolchains: Default::default(),
+ recent_navigation_history: Default::default(),
};
db.save_workspace(workspace_3.clone()).await;
@@ -3493,6 +3547,7 @@ mod tests {
session_id: Some("session-id-1".to_owned()),
window_id: Some(10),
user_toolchains: Default::default(),
+ recent_navigation_history: Default::default(),
};
let workspace_2 = SerializedWorkspace {
@@ -3510,6 +3565,7 @@ mod tests {
session_id: Some("session-id-1".to_owned()),
window_id: Some(20),
user_toolchains: Default::default(),
+ recent_navigation_history: Default::default(),
};
let workspace_3 = SerializedWorkspace {
@@ -3527,6 +3583,7 @@ mod tests {
session_id: Some("session-id-2".to_owned()),
window_id: Some(30),
user_toolchains: Default::default(),
+ recent_navigation_history: Default::default(),
};
let workspace_4 = SerializedWorkspace {
@@ -3544,6 +3601,7 @@ mod tests {
session_id: None,
window_id: None,
user_toolchains: Default::default(),
+ recent_navigation_history: Default::default(),
};
let connection_id = db
@@ -3572,6 +3630,7 @@ mod tests {
session_id: Some("session-id-2".to_owned()),
window_id: Some(50),
user_toolchains: Default::default(),
+ recent_navigation_history: Default::default(),
};
let workspace_6 = SerializedWorkspace {
@@ -3589,6 +3648,7 @@ mod tests {
session_id: Some("session-id-3".to_owned()),
window_id: Some(60),
user_toolchains: Default::default(),
+ recent_navigation_history: Default::default(),
};
db.save_workspace(workspace_1.clone()).await;
@@ -3648,6 +3708,7 @@ mod tests {
session_id: None,
window_id: None,
user_toolchains: Default::default(),
+ recent_navigation_history: Default::default(),
}
}
@@ -3691,6 +3752,7 @@ mod tests {
breakpoints: Default::default(),
window_id: Some(window_id),
user_toolchains: Default::default(),
+ recent_navigation_history: Default::default(),
})
.collect::<Vec<_>>();
@@ -3790,6 +3852,7 @@ mod tests {
session_id: session_id.map(|s| s.to_owned()),
window_id: Some(id),
user_toolchains: Default::default(),
+ recent_navigation_history: Default::default(),
}
}
@@ -3814,6 +3877,7 @@ mod tests {
session_id: None,
window_id: Some(id),
user_toolchains: Default::default(),
+ recent_navigation_history: Default::default(),
}
}
@@ -4072,6 +4136,7 @@ mod tests {
breakpoints: Default::default(),
window_id: Some(window_id),
user_toolchains: Default::default(),
+ recent_navigation_history: Default::default(),
})
.collect::<Vec<_>>();
@@ -4435,6 +4500,7 @@ mod tests {
session_id: None,
window_id: None,
user_toolchains: Default::default(),
+ recent_navigation_history: Default::default(),
};
// Save the workspace (this creates the record with empty paths)
@@ -4513,6 +4579,7 @@ mod tests {
breakpoints: Default::default(),
window_id: Some(*window_id),
user_toolchains: Default::default(),
+ recent_navigation_history: Default::default(),
})
.await;
}
@@ -4800,6 +4867,7 @@ mod tests {
breakpoints: Default::default(),
window_id: Some(99),
user_toolchains: Default::default(),
+ recent_navigation_history: Default::default(),
})
.await;
@@ -4897,6 +4965,7 @@ mod tests {
breakpoints: Default::default(),
window_id: Some(window_id_val),
user_toolchains: Default::default(),
+ recent_navigation_history: Default::default(),
})
.await;
@@ -4915,6 +4984,7 @@ mod tests {
breakpoints: Default::default(),
window_id: Some(window_id_val),
user_toolchains: Default::default(),
+ recent_navigation_history: Default::default(),
})
.await;
@@ -4995,6 +5065,7 @@ mod tests {
breakpoints: Default::default(),
window_id: Some(88),
user_toolchains: Default::default(),
+ recent_navigation_history: Default::default(),
})
.await;
cx.run_until_parked();
diff --git a/crates/workspace/src/persistence/model.rs b/crates/workspace/src/persistence/model.rs
index 03e0e055f71..b56279a8b0c 100644
--- a/crates/workspace/src/persistence/model.rs
+++ b/crates/workspace/src/persistence/model.rs
@@ -146,6 +146,7 @@ pub(crate) struct SerializedWorkspace {
pub(crate) bookmarks: BTreeMap<Arc<Path>, Vec<SerializedBookmark>>,
pub(crate) breakpoints: BTreeMap<Arc<Path>, Vec<SourceBreakpoint>>,
pub(crate) user_toolchains: BTreeMap<ToolchainScope, IndexSet<Toolchain>>,
+ pub(crate) recent_navigation_history: Vec<PathBuf>,
pub(crate) window_id: Option<u64>,
}
diff --git a/crates/workspace/src/workspace.rs b/crates/workspace/src/workspace.rs
index c9942cebbb1..d28dbfae090 100644
--- a/crates/workspace/src/workspace.rs
+++ b/crates/workspace/src/workspace.rs
@@ -171,6 +171,7 @@ use crate::{
};
pub const SERIALIZATION_THROTTLE_TIME: Duration = Duration::from_millis(200);
+pub const MAX_RECENT_SELECTIONS: usize = 20;
static ZED_WINDOW_SIZE: LazyLock<Option<Size<Pixels>>> = LazyLock::new(|| {
env::var("ZED_WINDOW_SIZE")
@@ -1439,6 +1440,9 @@ pub struct Workspace {
active_workspace_id: Option<Rc<Cell<EntityId>>>,
active_worktree_creation: ActiveWorktreeCreation,
deferred_save_items: Vec<Box<dyn WeakItemHandle>>,
+ persisted_recent_navigation_history: Vec<PathBuf>,
+ last_active_project_path: Option<ProjectPath>,
+ restoring_workspace: bool,
}
impl EventEmitter<Event> for Workspace {}
@@ -1564,6 +1568,16 @@ impl Workspace {
this.serialize_workspace(window, cx);
}
+ project::Event::EntryRenamed {
+ old_abs_path,
+ new_abs_path,
+ ..
+ } => {
+ if this.rename_persisted_navigation_history_paths(old_abs_path, new_abs_path) {
+ this.serialize_workspace(window, cx);
+ }
+ }
+
project::Event::DisconnectedFromHost => {
this.update_window_edited(window, cx);
let leaders_to_unfollow =
@@ -1894,6 +1908,9 @@ impl Workspace {
open_in_dev_container: false,
_dev_container_task: None,
deferred_save_items: Vec::new(),
+ persisted_recent_navigation_history: Vec::new(),
+ last_active_project_path: None,
+ restoring_workspace: false,
}
}
@@ -2743,7 +2760,7 @@ impl Workspace {
}
}
- history
+ let mut recent_history = history
.into_iter()
.sorted_by_key(|(_, (_, order))| *order)
.map(|(project_path, (fs_path, _))| (project_path, fs_path))
@@ -2760,6 +2777,23 @@ impl Workspace {
latest_project_path_opened.is_none_or(|path| path == history_path)
})
+ .collect::<Vec<_>>();
+
+ let mut seen_paths = recent_history
+ .iter()
+ .map(|(project_path, _)| project_path.clone())
+ .collect::<HashSet<_>>();
+ let project = self.project.read(cx);
+ for abs_path in &self.persisted_recent_navigation_history {
+ let Some(project_path) = project.project_path_for_absolute_path(abs_path, cx) else {
+ continue;
+ };
+ if seen_paths.insert(project_path.clone()) {
+ recent_history.push((project_path, Some(abs_path.clone())));
+ }
+ }
+
+ recent_history.into_iter()
}
pub fn recent_navigation_history(
@@ -2772,10 +2806,61 @@ impl Workspace {
.collect()
}
- pub fn clear_navigation_history(&mut self, _window: &mut Window, cx: &mut Context<Workspace>) {
+ pub fn clear_navigation_history(&mut self, window: &mut Window, cx: &mut Context<Workspace>) {
for pane in &self.panes {
pane.update(cx, |pane, cx| pane.nav_history_mut().clear(cx));
}
+ self.persisted_recent_navigation_history.clear();
+ self.last_active_project_path = None;
+ self.serialize_workspace(window, cx);
+ }
+
+ fn rename_persisted_navigation_history_paths(
+ &mut self,
+ old_path: &Path,
+ new_path: &Path,
+ ) -> bool {
+ let mut changed = false;
+ for path in &mut self.persisted_recent_navigation_history {
+ let Ok(suffix) = path.strip_prefix(old_path) else {
+ continue;
+ };
+ let renamed_path = new_path.join(suffix);
+ if *path != renamed_path {
+ *path = renamed_path;
+ changed = true;
+ }
+ }
+
+ if changed {
+ let mut seen_paths = HashSet::default();
+ self.persisted_recent_navigation_history
+ .retain(|path| seen_paths.insert(path.clone()));
+ }
+ changed
+ }
+
+ fn remember_navigation_history_path(&mut self, project_path: &ProjectPath, cx: &App) -> bool {
+ if self.restoring_workspace {
+ return false;
+ }
+ let Some(absolute_path) = self.project.read(cx).absolute_path(project_path, cx) else {
+ return false;
+ };
+
+ self.last_active_project_path = Some(project_path.clone());
+
+ if self.persisted_recent_navigation_history.first() == Some(&absolute_path) {
+ return false;
+ }
+
+ self.persisted_recent_navigation_history
+ .retain(|path| path != &absolute_path);
+ self.persisted_recent_navigation_history
+ .insert(0, absolute_path);
+ self.persisted_recent_navigation_history
+ .truncate(MAX_RECENT_SELECTIONS);
+ true
}
fn navigate_history(
@@ -6177,6 +6262,8 @@ impl Workspace {
) {
cx.emit(Event::ActiveItemChanged);
let active_entry = self.active_project_path(cx);
+ let active_project_path_changed =
+ self.last_active_project_path.as_ref() != active_entry.as_ref();
self.project.update(cx, |project, cx| {
project.set_active_path(active_entry.clone(), cx)
});
@@ -6188,6 +6275,16 @@ impl Workspace {
});
}
+ if active_project_path_changed {
+ match active_entry.as_ref() {
+ None => self.last_active_project_path = None,
+ Some(path) if self.remember_navigation_history_path(path, cx) => {
+ self.serialize_workspace(window, cx);
+ }
+ Some(_) => {}
+ }
+ }
+
self.update_window_title(window, cx);
}
@@ -7158,6 +7255,7 @@ impl Workspace {
let docks = build_serialized_docks(self, window, cx);
let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
let identity_paths_hint = self.project_group_key(cx).path_list().clone();
+ let recent_navigation_history = self.persisted_recent_navigation_history.clone();
let serialized_workspace = SerializedWorkspace {
id: database_id,
@@ -7174,6 +7272,7 @@ impl Workspace {
breakpoints,
window_id: Some(window.window_handle().window_id().as_u64()),
user_toolchains,
+ recent_navigation_history,
};
let db = WorkspaceDb::global(cx);
@@ -7302,6 +7401,11 @@ impl Workspace {
cx: &mut Context<Workspace>,
) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
cx.spawn_in(window, async move |workspace, cx| {
+ let recent_navigation_history = serialized_workspace.recent_navigation_history.clone();
+ workspace.update(cx, |workspace, _| {
+ workspace.persisted_recent_navigation_history = recent_navigation_history;
+ workspace.restoring_workspace = true;
+ })?;
let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
let mut center_group = None;
@@ -7377,6 +7481,7 @@ impl Workspace {
});
}
+ workspace.restoring_workspace = false;
cx.notify();
})?;
@@ -13173,6 +13278,37 @@ mod tests {
});
}
+ #[gpui::test]
+ async fn test_clear_navigation_history_clears_persisted_recent_paths(
+ cx: &mut gpui::TestAppContext,
+ ) {
+ init_test(cx);
+
+ let fs = FakeFs::new(cx.executor());
+ fs.insert_tree(path!("/src"), json!({ "a.txt": "" })).await;
+ let project = Project::test(fs, [path!("/src").as_ref()], cx).await;
+ let (workspace, cx) =
+ cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
+
+ workspace.update(cx, |workspace, cx| {
+ workspace
+ .persisted_recent_navigation_history
+ .push(PathBuf::from(path!("/src/a.txt")));
+ workspace.last_active_project_path = Some(ProjectPath {
+ worktree_id: WorktreeId::from_usize(1),
+ path: rel_path("a.txt").into(),
+ });
+ assert_eq!(workspace.recent_navigation_history(None, cx).len(), 1);
+ });
+
+ workspace.update_in(cx, |workspace, window, cx| {
+ workspace.clear_navigation_history(window, cx);
+ assert!(workspace.persisted_recent_navigation_history.is_empty());
+ assert!(workspace.last_active_project_path.is_none());
+ assert!(workspace.recent_navigation_history(None, cx).is_empty());
+ });
+ }
+
#[gpui::test]
async fn test_activate_last_pane(cx: &mut gpui::TestAppContext) {
init_test(cx);
@@ -17950,6 +18086,315 @@ mod tests {
assert_eq!(path, None);
}
+ #[gpui::test]
+ async fn test_recent_navigation_history_includes_persisted_paths(
+ cx: &mut gpui::TestAppContext,
+ ) {
+ init_test(cx);
+
+ let fs = FakeFs::new(cx.executor());
+ fs.insert_tree(
+ path!("/project"),
+ json!({
+ "a.rs": "",
+ "b.rs": "",
+ }),
+ )
+ .await;
+
+ let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
+ let (workspace, cx) =
+ cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
+ let worktree_id = project.update(cx, |project, cx| {
+ project.worktrees(cx).next().unwrap().read(cx).id()
+ });
+
+ let item_a = cx.new(|cx| {
+ TestItem::new(cx).with_project_items(&[TestProjectItem::new_in_worktree(
+ 1,
+ "a.rs",
+ worktree_id,
+ cx,
+ )])
+ });
+ workspace.update_in(cx, |workspace, window, cx| {
+ workspace.add_item_to_active_pane(Box::new(item_a), None, true, window, cx);
+ });
+
+ assert_eq!(
+ workspace.read_with(cx, |workspace, _| {
+ workspace.persisted_recent_navigation_history.clone()
+ }),
+ vec![PathBuf::from(path!("/project/a.rs"))]
+ );
+
+ workspace.update(cx, |workspace, _| {
+ workspace.persisted_recent_navigation_history = vec![
+ PathBuf::from(path!("/project/b.rs")),
+ PathBuf::from(path!("/project/a.rs")),
+ PathBuf::from(path!("/outside/z.rs")),
+ ];
+ });
+
+ let history = workspace.read_with(cx, |workspace, cx| {
+ workspace
+ .recent_navigation_history_iter(cx)
+ .map(|(project_path, _)| {
+ <RelPath as AsRef<Path>>::as_ref(&project_path.path).to_path_buf()
+ })
+ .collect::<Vec<_>>()
+ });
+
+ assert_eq!(history, vec![PathBuf::from("a.rs"), PathBuf::from("b.rs")]);
+ }
+
+ #[gpui::test]
+ async fn test_active_project_path_changes_are_persisted(cx: &mut gpui::TestAppContext) {
+ init_test(cx);
+ cx.update(register_serializable_item::<TestItem>);
+
+ let fs = FakeFs::new(cx.executor());
+ fs.insert_tree(
+ path!("/project"),
+ json!({
+ "a.rs": "",
+ "b.rs": "",
+ }),
+ )
+ .await;
+ let project = Project::test(fs, [path!("/project").as_ref()], cx).await;
+ let (workspace, cx) =
+ cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
+ let worktree_id = project.update(cx, |project, cx| {
+ project.worktrees(cx).next().unwrap().read(cx).id()
+ });
+ let path_b = ProjectPath {
+ worktree_id,
+ path: rel_path("b.rs").into(),
+ };
+
+ let database = cx.update(|_, cx| WorkspaceDb::global(cx));
+ let workspace_id = database.next_id().await.unwrap();
+ workspace.update(cx, |workspace, _| workspace.set_database_id(workspace_id));
+
+ let project_item =
+ cx.update(|_, cx| TestProjectItem::new_in_worktree(1, "a.rs", worktree_id, cx));
+ let item =
+ cx.new(|cx| TestItem::new(cx).with_project_items(std::slice::from_ref(&project_item)));
+ workspace.update_in(cx, |workspace, window, cx| {
+ workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
+ });
+
+ cx.executor().advance_clock(SERIALIZATION_THROTTLE_TIME);
+ cx.run_until_parked();
+ assert_eq!(
+ database
+ .workspace_for_id(workspace_id)
+ .unwrap()
+ .recent_navigation_history,
+ vec![PathBuf::from(path!("/project/a.rs"))]
+ );
+ assert!(workspace.read_with(cx, |workspace, _| {
+ workspace.last_active_project_path.is_some()
+ }));
+
+ workspace.update_in(cx, |workspace, window, cx| {
+ workspace.clear_navigation_history(window, cx);
+ assert!(workspace.persisted_recent_navigation_history.is_empty());
+ assert!(workspace.last_active_project_path.is_none());
+ });
+ item.update(cx, |_, cx| {
+ cx.emit(ItemEvent::UpdateBreadcrumbs);
+ });
+ assert_eq!(
+ workspace.read_with(cx, |workspace, _| {
+ workspace.persisted_recent_navigation_history.clone()
+ }),
+ vec![PathBuf::from(path!("/project/a.rs"))]
+ );
+
+ project_item.update(cx, |project_item, _| {
+ project_item.project_path = Some(path_b.clone());
+ });
+ item.update(cx, |_, cx| {
+ cx.emit(ItemEvent::UpdateBreadcrumbs);
+ });
+ assert_eq!(
+ workspace.read_with(cx, |workspace, _| {
+ workspace.persisted_recent_navigation_history.clone()
+ }),
+ vec![
+ PathBuf::from(path!("/project/b.rs")),
+ PathBuf::from(path!("/project/a.rs")),
+ ]
+ );
+
+ cx.executor().advance_clock(SERIALIZATION_THROTTLE_TIME);
+ cx.run_until_parked();
+ let serialized_workspace = database.workspace_for_id(workspace_id).unwrap();
+ assert_eq!(
+ serialized_workspace.recent_navigation_history,
+ vec![
+ PathBuf::from(path!("/project/b.rs")),
+ PathBuf::from(path!("/project/a.rs")),
+ ]
+ );
+
+ assert!(workspace.read_with(cx, |workspace, _| {
+ workspace._schedule_serialize_workspace.is_none()
+ }));
+ item.update(cx, |_, cx| {
+ cx.emit(ItemEvent::UpdateBreadcrumbs);
+ });
+ assert!(workspace.read_with(cx, |workspace, _| {
+ workspace._schedule_serialize_workspace.is_none()
+ }));
+
+ workspace.update(cx, |workspace, _| {
+ workspace.persisted_recent_navigation_history.clear();
+ });
+ workspace
+ .update_in(cx, |_, window, cx| {
+ Workspace::load_workspace(serialized_workspace, Vec::new(), window, cx)
+ })
+ .await
+ .unwrap();
+ assert_eq!(
+ workspace.read_with(cx, |workspace, _| {
+ workspace.persisted_recent_navigation_history.clone()
+ }),
+ vec![
+ PathBuf::from(path!("/project/b.rs")),
+ PathBuf::from(path!("/project/a.rs")),
+ ]
+ );
+ }
+
+ #[gpui::test]
+ async fn test_persisted_recent_navigation_history_is_bounded_mru(
+ cx: &mut gpui::TestAppContext,
+ ) {
+ init_test(cx);
+
+ let fs = FakeFs::new(cx.executor());
+ fs.insert_tree(path!("/project"), json!({})).await;
+ let project = Project::test(fs, [path!("/project").as_ref()], cx).await;
+ let (workspace, cx) =
+ cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
+ let worktree_id = project.update(cx, |project, cx| {
+ project.worktrees(cx).next().unwrap().read(cx).id()
+ });
+ for index in 0..=MAX_RECENT_SELECTIONS {
+ workspace.update(cx, |workspace, cx| {
+ assert!(workspace.remember_navigation_history_path(
+ &ProjectPath {
+ worktree_id,
+ path: rel_path(&format!("{index}.rs")).into(),
+ },
+ cx,
+ ));
+ });
+ }
+
+ let expected = (1..=MAX_RECENT_SELECTIONS)
+ .rev()
+ .map(|index| PathBuf::from(path!("/project")).join(format!("{index}.rs")))
+ .collect::<Vec<_>>();
+ assert_eq!(
+ workspace.read_with(cx, |workspace, _| {
+ workspace.persisted_recent_navigation_history.clone()
+ }),
+ expected
+ );
+
+ workspace.update(cx, |workspace, cx| {
+ assert!(workspace.remember_navigation_history_path(
+ &ProjectPath {
+ worktree_id,
+ path: rel_path("10.rs").into(),
+ },
+ cx,
+ ));
+ });
+ let history = workspace.read_with(cx, |workspace, _| {
+ workspace.persisted_recent_navigation_history.clone()
+ });
+ assert_eq!(history.len(), MAX_RECENT_SELECTIONS);
+ assert_eq!(
+ history.first(),
+ Some(&PathBuf::from(path!("/project/10.rs")))
+ );
+ assert_eq!(
+ history
+ .iter()
+ .filter(|path| *path == path!("/project/10.rs"))
+ .count(),
+ 1
+ );
+ }
+
+ #[gpui::test]
+ async fn test_project_rename_updates_persisted_navigation_history(
+ cx: &mut gpui::TestAppContext,
+ ) {
+ init_test(cx);
+
+ let fs = FakeFs::new(cx.executor());
+ fs.insert_tree(
+ path!("/project"),
+ json!({
+ "dir": { "a.rs": "" },
+ "other.rs": "",
+ }),
+ )
+ .await;
+ let project = Project::test(fs, [path!("/project").as_ref()], cx).await;
+ let (workspace, cx) =
+ cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
+ let (worktree_id, directory_entry_id) = project.update(cx, |project, cx| {
+ let worktree_id = project.worktrees(cx).next().unwrap().read(cx).id();
+ let directory_path = ProjectPath {
+ worktree_id,
+ path: rel_path("dir").into(),
+ };
+ let entry_id = project.entry_for_path(&directory_path, cx).unwrap().id;
+ (worktree_id, entry_id)
+ });
+
+ workspace.update(cx, |workspace, _| {
+ workspace.persisted_recent_navigation_history = vec![
+ PathBuf::from(path!("/project/other.rs")),
+ PathBuf::from(path!("/project/dir/a.rs")),
+ PathBuf::from(path!("/project/renamed/a.rs")),
+ ];
+ });
+
+ project
+ .update(cx, |project, cx| {
+ project.rename_entry(
+ directory_entry_id,
+ ProjectPath {
+ worktree_id,
+ path: rel_path("renamed").into(),
+ },
+ cx,
+ )
+ })
+ .await
+ .unwrap();
+ cx.run_until_parked();
+
+ assert_eq!(
+ workspace.read_with(cx, |workspace, _| {
+ workspace.persisted_recent_navigation_history.clone()
+ }),
+ vec![
+ PathBuf::from(path!("/project/other.rs")),
+ PathBuf::from(path!("/project/renamed/a.rs")),
+ ]
+ );
+ }
+
#[gpui::test]
async fn test_open_url_or_file_routes_urls(cx: &mut TestAppContext) {
init_test(cx);