Show navigation history in the file finder modal

co-authored-by: Max <max@zed.dev>
This commit is contained in:
Kirill Bulatov 2023-05-17 17:35:06 +03:00
parent 711d2c6fe7
commit 201d513c50
8 changed files with 162 additions and 165 deletions

1
Cargo.lock generated
View file

@ -8676,6 +8676,7 @@ dependencies = [
"gpui", "gpui",
"indoc", "indoc",
"install_cli", "install_cli",
"itertools",
"language", "language",
"lazy_static", "lazy_static",
"log", "log",

View file

@ -25,10 +25,11 @@ pub struct FileFinderDelegate {
latest_search_id: usize, latest_search_id: usize,
latest_search_did_cancel: bool, latest_search_did_cancel: bool,
latest_search_query: Option<PathLikeWithPosition<FileSearchQuery>>, latest_search_query: Option<PathLikeWithPosition<FileSearchQuery>>,
relative_to: Option<Arc<Path>>, currently_opened_path: Option<ProjectPath>,
matches: Vec<PathMatch>, matches: Vec<PathMatch>,
selected: Option<(usize, Arc<Path>)>, selected: Option<(usize, Arc<Path>)>,
cancel_flag: Arc<AtomicBool>, cancel_flag: Arc<AtomicBool>,
history_items: Vec<ProjectPath>,
} }
actions!(file_finder, [Toggle]); actions!(file_finder, [Toggle]);
@ -38,17 +39,26 @@ pub fn init(cx: &mut AppContext) {
FileFinder::init(cx); FileFinder::init(cx);
} }
const MAX_RECENT_SELECTIONS: usize = 20;
fn toggle_file_finder(workspace: &mut Workspace, _: &Toggle, cx: &mut ViewContext<Workspace>) { fn toggle_file_finder(workspace: &mut Workspace, _: &Toggle, cx: &mut ViewContext<Workspace>) {
workspace.toggle_modal(cx, |workspace, cx| { workspace.toggle_modal(cx, |workspace, cx| {
let relative_to = workspace let history_items = workspace.recent_navigation_history(Some(MAX_RECENT_SELECTIONS), cx);
let currently_opened_path = workspace
.active_item(cx) .active_item(cx)
.and_then(|item| item.project_path(cx)) .and_then(|item| item.project_path(cx));
.map(|project_path| project_path.path.clone());
let project = workspace.project().clone(); let project = workspace.project().clone();
let workspace = cx.handle().downgrade(); let workspace = cx.handle().downgrade();
let finder = cx.add_view(|cx| { let finder = cx.add_view(|cx| {
Picker::new( Picker::new(
FileFinderDelegate::new(workspace, project, relative_to, cx), FileFinderDelegate::new(
workspace,
project,
currently_opened_path,
history_items,
cx,
),
cx, cx,
) )
}); });
@ -106,7 +116,8 @@ impl FileFinderDelegate {
pub fn new( pub fn new(
workspace: WeakViewHandle<Workspace>, workspace: WeakViewHandle<Workspace>,
project: ModelHandle<Project>, project: ModelHandle<Project>,
relative_to: Option<Arc<Path>>, currently_opened_path: Option<ProjectPath>,
history_items: Vec<ProjectPath>,
cx: &mut ViewContext<FileFinder>, cx: &mut ViewContext<FileFinder>,
) -> Self { ) -> Self {
cx.observe(&project, |picker, _, cx| { cx.observe(&project, |picker, _, cx| {
@ -120,10 +131,11 @@ impl FileFinderDelegate {
latest_search_id: 0, latest_search_id: 0,
latest_search_did_cancel: false, latest_search_did_cancel: false,
latest_search_query: None, latest_search_query: None,
relative_to, currently_opened_path,
matches: Vec::new(), matches: Vec::new(),
selected: None, selected: None,
cancel_flag: Arc::new(AtomicBool::new(false)), cancel_flag: Arc::new(AtomicBool::new(false)),
history_items,
} }
} }
@ -132,7 +144,10 @@ impl FileFinderDelegate {
query: PathLikeWithPosition<FileSearchQuery>, query: PathLikeWithPosition<FileSearchQuery>,
cx: &mut ViewContext<FileFinder>, cx: &mut ViewContext<FileFinder>,
) -> Task<()> { ) -> Task<()> {
let relative_to = self.relative_to.clone(); let relative_to = self
.currently_opened_path
.as_ref()
.map(|project_path| Arc::clone(&project_path.path));
let worktrees = self let worktrees = self
.project .project
.read(cx) .read(cx)
@ -239,12 +254,22 @@ impl PickerDelegate for FileFinderDelegate {
if raw_query.is_empty() { if raw_query.is_empty() {
self.latest_search_id = post_inc(&mut self.search_count); self.latest_search_id = post_inc(&mut self.search_count);
self.matches.clear(); self.matches.clear();
self.matches = self self.matches = self
.project .currently_opened_path
.read(cx) .iter() // if exists, bubble the currently opened path to the top
.search_panel_state() .chain(self.history_items.iter().filter(|history_item| {
.recent_selections() Some(*history_item) != self.currently_opened_path.as_ref()
.cloned() }))
.enumerate()
.map(|(i, history_item)| PathMatch {
score: i as f64,
positions: Vec::new(),
worktree_id: history_item.worktree_id.0,
path: Arc::clone(&history_item.path),
path_prefix: "".into(),
distance_to_relative_ancestor: usize::MAX,
})
.collect(); .collect();
cx.notify(); cx.notify();
Task::ready(()) Task::ready(())
@ -268,10 +293,6 @@ impl PickerDelegate for FileFinderDelegate {
fn confirm(&mut self, cx: &mut ViewContext<FileFinder>) { fn confirm(&mut self, cx: &mut ViewContext<FileFinder>) {
if let Some(m) = self.matches.get(self.selected_index()) { if let Some(m) = self.matches.get(self.selected_index()) {
if let Some(workspace) = self.workspace.upgrade(cx) { if let Some(workspace) = self.workspace.upgrade(cx) {
self.project.update(cx, |project, _cx| {
project.update_search_panel_state().add_selection(m.clone())
});
let project_path = ProjectPath { let project_path = ProjectPath {
worktree_id: WorktreeId::from_usize(m.worktree_id), worktree_id: WorktreeId::from_usize(m.worktree_id),
path: m.path.clone(), path: m.path.clone(),
@ -613,6 +634,7 @@ mod tests {
workspace.downgrade(), workspace.downgrade(),
workspace.read(cx).project().clone(), workspace.read(cx).project().clone(),
None, None,
Vec::new(),
cx, cx,
), ),
cx, cx,
@ -697,6 +719,7 @@ mod tests {
workspace.downgrade(), workspace.downgrade(),
workspace.read(cx).project().clone(), workspace.read(cx).project().clone(),
None, None,
Vec::new(),
cx, cx,
), ),
cx, cx,
@ -732,6 +755,7 @@ mod tests {
workspace.downgrade(), workspace.downgrade(),
workspace.read(cx).project().clone(), workspace.read(cx).project().clone(),
None, None,
Vec::new(),
cx, cx,
), ),
cx, cx,
@ -797,6 +821,7 @@ mod tests {
workspace.downgrade(), workspace.downgrade(),
workspace.read(cx).project().clone(), workspace.read(cx).project().clone(),
None, None,
Vec::new(),
cx, cx,
), ),
cx, cx,
@ -846,13 +871,17 @@ mod tests {
// When workspace has an active item, sort items which are closer to that item // When workspace has an active item, sort items which are closer to that item
// first when they have the same name. In this case, b.txt is closer to dir2's a.txt // first when they have the same name. In this case, b.txt is closer to dir2's a.txt
// so that one should be sorted earlier // so that one should be sorted earlier
let b_path = Some(Arc::from(Path::new("/root/dir2/b.txt"))); let b_path = Some(ProjectPath {
worktree_id: WorktreeId(workspace.id()),
path: Arc::from(Path::new("/root/dir2/b.txt")),
});
let (_, finder) = cx.add_window(|cx| { let (_, finder) = cx.add_window(|cx| {
Picker::new( Picker::new(
FileFinderDelegate::new( FileFinderDelegate::new(
workspace.downgrade(), workspace.downgrade(),
workspace.read(cx).project().clone(), workspace.read(cx).project().clone(),
b_path, b_path,
Vec::new(),
cx, cx,
), ),
cx, cx,
@ -897,6 +926,7 @@ mod tests {
workspace.downgrade(), workspace.downgrade(),
workspace.read(cx).project().clone(), workspace.read(cx).project().clone(),
None, None,
Vec::new(),
cx, cx,
), ),
cx, cx,
@ -913,97 +943,6 @@ mod tests {
}); });
} }
#[gpui::test]
async fn test_query_history(cx: &mut gpui::TestAppContext) {
let app_state = init_test(cx);
app_state
.fs
.as_fake()
.insert_tree(
"/src",
json!({
"test": {
"first.rs": "// First Rust file",
"second.rs": "// Second Rust file",
"third.rs": "// Third Rust file",
}
}),
)
.await;
let project = Project::test(app_state.fs.clone(), ["/src".as_ref()], cx).await;
let (window_id, workspace) = cx.add_window(|cx| Workspace::test_new(project, cx));
cx.dispatch_action(window_id, Toggle);
let finder = cx.read(|cx| workspace.read(cx).modal::<FileFinder>().unwrap());
finder
.update(cx, |finder, cx| {
finder.delegate_mut().update_matches("fir".to_string(), cx)
})
.await;
cx.dispatch_action(window_id, SelectNext);
cx.dispatch_action(window_id, Confirm);
cx.dispatch_action(window_id, Toggle);
let finder = cx.read(|cx| workspace.read(cx).modal::<FileFinder>().unwrap());
finder
.update(cx, |finder, cx| {
finder.delegate_mut().update_matches("sec".to_string(), cx)
})
.await;
cx.dispatch_action(window_id, SelectNext);
cx.dispatch_action(window_id, Confirm);
finder.read_with(cx, |finder, cx| {
let recent_query_paths = finder
.delegate()
.project
.read(cx)
.search_panel_state()
.recent_selections()
.map(|query| query.path.to_path_buf())
.collect::<Vec<_>>();
assert_eq!(
vec![
Path::new("test/second.rs").to_path_buf(),
Path::new("test/first.rs").to_path_buf(),
],
recent_query_paths,
"Two finder queries should produce only two recent queries. Second query should be more recent (first)"
)
});
cx.dispatch_action(window_id, Toggle);
let finder = cx.read(|cx| workspace.read(cx).modal::<FileFinder>().unwrap());
finder
.update(cx, |finder, cx| {
finder.delegate_mut().update_matches("fir".to_string(), cx)
})
.await;
cx.dispatch_action(window_id, SelectNext);
cx.dispatch_action(window_id, Confirm);
finder.read_with(cx, |finder, cx| {
let recent_query_paths = finder
.delegate()
.project
.read(cx)
.search_panel_state()
.recent_selections()
.map(|query| query.path.to_path_buf())
.collect::<Vec<_>>();
assert_eq!(
vec![
Path::new("test/first.rs").to_path_buf(),
Path::new("test/second.rs").to_path_buf(),
],
recent_query_paths,
"Three finder queries on two different files should produce only two recent queries. First query should be more recent (first), since got queried again"
)
});
}
fn init_test(cx: &mut TestAppContext) -> Arc<AppState> { fn init_test(cx: &mut TestAppContext) -> Arc<AppState> {
cx.foreground().forbid_parking(); cx.foreground().forbid_parking();
cx.update(|cx| { cx.update(|cx| {

View file

@ -12,14 +12,13 @@ mod project_tests;
use anyhow::{anyhow, Context, Result}; use anyhow::{anyhow, Context, Result};
use client::{proto, Client, TypedEnvelope, UserStore}; use client::{proto, Client, TypedEnvelope, UserStore};
use clock::ReplicaId; use clock::ReplicaId;
use collections::{hash_map, BTreeMap, HashMap, HashSet, VecDeque}; use collections::{hash_map, BTreeMap, HashMap, HashSet};
use copilot::Copilot; use copilot::Copilot;
use futures::{ use futures::{
channel::mpsc::{self, UnboundedReceiver}, channel::mpsc::{self, UnboundedReceiver},
future::{try_join_all, Shared}, future::{try_join_all, Shared},
AsyncWriteExt, Future, FutureExt, StreamExt, TryFutureExt, AsyncWriteExt, Future, FutureExt, StreamExt, TryFutureExt,
}; };
use fuzzy::PathMatch;
use gpui::{ use gpui::{
AnyModelHandle, AppContext, AsyncAppContext, BorrowAppContext, Entity, ModelContext, AnyModelHandle, AppContext, AsyncAppContext, BorrowAppContext, Entity, ModelContext,
ModelHandle, Task, WeakModelHandle, ModelHandle, Task, WeakModelHandle,
@ -136,7 +135,6 @@ pub struct Project {
_maintain_workspace_config: Task<()>, _maintain_workspace_config: Task<()>,
terminals: Terminals, terminals: Terminals,
copilot_enabled: bool, copilot_enabled: bool,
search_panel_state: SearchPanelState,
} }
struct LspBufferSnapshot { struct LspBufferSnapshot {
@ -390,42 +388,6 @@ impl FormatTrigger {
} }
} }
const MAX_RECENT_SELECTIONS: usize = 20;
#[derive(Debug, Default)]
pub struct SearchPanelState {
recent_selections: VecDeque<PathMatch>,
}
impl SearchPanelState {
pub fn recent_selections(&self) -> impl Iterator<Item = &PathMatch> {
self.recent_selections.iter().rev()
}
pub fn add_selection(&mut self, mut new_selection: PathMatch) {
let old_len = self.recent_selections.len();
// remove `new_selection` element, if it's in the list
self.recent_selections.retain(|old_selection| {
old_selection.worktree_id != new_selection.worktree_id
|| old_selection.path != new_selection.path
});
// if `new_selection` was not present and we're adding a new element,
// ensure we do not exceed max allowed elements
if self.recent_selections.len() == old_len {
if self.recent_selections.len() >= MAX_RECENT_SELECTIONS {
self.recent_selections.pop_front();
}
}
// do not highlight query matches in the selection
new_selection.positions.clear();
// always re-add the element even if it exists to the back
// this way, it gets to the top as the most recently selected element
self.recent_selections.push_back(new_selection);
}
}
impl Project { impl Project {
pub fn init_settings(cx: &mut AppContext) { pub fn init_settings(cx: &mut AppContext) {
settings::register::<ProjectSettings>(cx); settings::register::<ProjectSettings>(cx);
@ -525,7 +487,6 @@ impl Project {
local_handles: Vec::new(), local_handles: Vec::new(),
}, },
copilot_enabled: Copilot::global(cx).is_some(), copilot_enabled: Copilot::global(cx).is_some(),
search_panel_state: SearchPanelState::default(),
} }
}) })
} }
@ -616,7 +577,6 @@ impl Project {
local_handles: Vec::new(), local_handles: Vec::new(),
}, },
copilot_enabled: Copilot::global(cx).is_some(), copilot_enabled: Copilot::global(cx).is_some(),
search_panel_state: SearchPanelState::default(),
}; };
for worktree in worktrees { for worktree in worktrees {
let _ = this.add_worktree(&worktree, cx); let _ = this.add_worktree(&worktree, cx);
@ -6475,14 +6435,6 @@ impl Project {
}) })
} }
pub fn search_panel_state(&self) -> &SearchPanelState {
&self.search_panel_state
}
pub fn update_search_panel_state(&mut self) -> &mut SearchPanelState {
&mut self.search_panel_state
}
fn primary_language_servers_for_buffer( fn primary_language_servers_for_buffer(
&self, &self,
buffer: &Buffer, buffer: &Buffer,

View file

@ -58,7 +58,7 @@ use sum_tree::{Bias, Edit, SeekTarget, SumTree, TreeMap, TreeSet};
use util::{paths::HOME, ResultExt, TakeUntilExt, TryFutureExt}; use util::{paths::HOME, ResultExt, TakeUntilExt, TryFutureExt};
#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash, PartialOrd, Ord)] #[derive(Copy, Clone, PartialEq, Eq, Debug, Hash, PartialOrd, Ord)]
pub struct WorktreeId(usize); pub struct WorktreeId(pub usize);
pub enum Worktree { pub enum Worktree {
Local(LocalWorktree), Local(LocalWorktree),

View file

@ -38,6 +38,7 @@ theme = { path = "../theme" }
util = { path = "../util" } util = { path = "../util" }
async-recursion = "1.0.0" async-recursion = "1.0.0"
itertools = "0.10"
bincode = "1.2.1" bincode = "1.2.1"
anyhow.workspace = true anyhow.workspace = true
futures.workspace = true futures.workspace = true

View file

@ -12,6 +12,7 @@ use gpui::{
platform::{CursorStyle, MouseButton}, platform::{CursorStyle, MouseButton},
AnyElement, AppContext, Border, Element, SizeConstraint, ViewContext, ViewHandle, AnyElement, AppContext, Border, Element, SizeConstraint, ViewContext, ViewHandle,
}; };
use std::sync::{atomic::AtomicUsize, Arc};
use theme::Theme; use theme::Theme;
pub use toggle_dock_button::ToggleDockButton; pub use toggle_dock_button::ToggleDockButton;
@ -170,13 +171,21 @@ impl Dock {
pub fn new( pub fn new(
default_item_factory: DockDefaultItemFactory, default_item_factory: DockDefaultItemFactory,
background_actions: BackgroundActions, background_actions: BackgroundActions,
pane_history_timestamp: Arc<AtomicUsize>,
cx: &mut ViewContext<Workspace>, cx: &mut ViewContext<Workspace>,
) -> Self { ) -> Self {
let position = let position =
DockPosition::Hidden(settings::get::<WorkspaceSettings>(cx).default_dock_anchor); DockPosition::Hidden(settings::get::<WorkspaceSettings>(cx).default_dock_anchor);
let workspace = cx.weak_handle(); let workspace = cx.weak_handle();
let pane = let pane = cx.add_view(|cx| {
cx.add_view(|cx| Pane::new(workspace, Some(position.anchor()), background_actions, cx)); Pane::new(
workspace,
Some(position.anchor()),
background_actions,
pane_history_timestamp,
cx,
)
});
pane.update(cx, |pane, cx| { pane.update(cx, |pane, cx| {
pane.set_active(false, cx); pane.set_active(false, cx);
}); });

View file

@ -30,7 +30,17 @@ use gpui::{
}; };
use project::{Project, ProjectEntryId, ProjectPath}; use project::{Project, ProjectEntryId, ProjectPath};
use serde::Deserialize; use serde::Deserialize;
use std::{any::Any, cell::RefCell, cmp, mem, path::Path, rc::Rc}; use std::{
any::Any,
cell::RefCell,
cmp, mem,
path::Path,
rc::Rc,
sync::{
atomic::{AtomicUsize, Ordering},
Arc,
},
};
use theme::Theme; use theme::Theme;
use util::ResultExt; use util::ResultExt;
@ -159,6 +169,8 @@ pub struct ItemNavHistory {
item: Rc<dyn WeakItemHandle>, item: Rc<dyn WeakItemHandle>,
} }
pub struct PaneNavHistory(Rc<RefCell<NavHistory>>);
struct NavHistory { struct NavHistory {
mode: NavigationMode, mode: NavigationMode,
backward_stack: VecDeque<NavigationEntry>, backward_stack: VecDeque<NavigationEntry>,
@ -166,6 +178,7 @@ struct NavHistory {
closed_stack: VecDeque<NavigationEntry>, closed_stack: VecDeque<NavigationEntry>,
paths_by_item: HashMap<usize, ProjectPath>, paths_by_item: HashMap<usize, ProjectPath>,
pane: WeakViewHandle<Pane>, pane: WeakViewHandle<Pane>,
next_timestamp: Arc<AtomicUsize>,
} }
#[derive(Copy, Clone)] #[derive(Copy, Clone)]
@ -187,6 +200,7 @@ impl Default for NavigationMode {
pub struct NavigationEntry { pub struct NavigationEntry {
pub item: Rc<dyn WeakItemHandle>, pub item: Rc<dyn WeakItemHandle>,
pub data: Option<Box<dyn Any>>, pub data: Option<Box<dyn Any>>,
pub timestamp: usize,
} }
struct DraggedItem { struct DraggedItem {
@ -226,6 +240,7 @@ impl Pane {
workspace: WeakViewHandle<Workspace>, workspace: WeakViewHandle<Workspace>,
docked: Option<DockAnchor>, docked: Option<DockAnchor>,
background_actions: BackgroundActions, background_actions: BackgroundActions,
next_timestamp: Arc<AtomicUsize>,
cx: &mut ViewContext<Self>, cx: &mut ViewContext<Self>,
) -> Self { ) -> Self {
let pane_view_id = cx.view_id(); let pane_view_id = cx.view_id();
@ -249,6 +264,7 @@ impl Pane {
closed_stack: Default::default(), closed_stack: Default::default(),
paths_by_item: Default::default(), paths_by_item: Default::default(),
pane: handle.clone(), pane: handle.clone(),
next_timestamp,
})), })),
toolbar: cx.add_view(|_| Toolbar::new(handle)), toolbar: cx.add_view(|_| Toolbar::new(handle)),
tab_bar_context_menu: TabBarContextMenu { tab_bar_context_menu: TabBarContextMenu {
@ -292,6 +308,10 @@ impl Pane {
} }
} }
pub fn nav_history(&self) -> PaneNavHistory {
PaneNavHistory(self.nav_history.clone())
}
pub fn go_back( pub fn go_back(
workspace: &mut Workspace, workspace: &mut Workspace,
pane: Option<WeakViewHandle<Pane>>, pane: Option<WeakViewHandle<Pane>>,
@ -1942,6 +1962,7 @@ impl NavHistory {
self.backward_stack.push_back(NavigationEntry { self.backward_stack.push_back(NavigationEntry {
item, item,
data: data.map(|data| Box::new(data) as Box<dyn Any>), data: data.map(|data| Box::new(data) as Box<dyn Any>),
timestamp: self.next_timestamp.fetch_add(1, Ordering::SeqCst),
}); });
self.forward_stack.clear(); self.forward_stack.clear();
} }
@ -1952,6 +1973,7 @@ impl NavHistory {
self.forward_stack.push_back(NavigationEntry { self.forward_stack.push_back(NavigationEntry {
item, item,
data: data.map(|data| Box::new(data) as Box<dyn Any>), data: data.map(|data| Box::new(data) as Box<dyn Any>),
timestamp: self.next_timestamp.fetch_add(1, Ordering::SeqCst),
}); });
} }
NavigationMode::GoingForward => { NavigationMode::GoingForward => {
@ -1961,6 +1983,7 @@ impl NavHistory {
self.backward_stack.push_back(NavigationEntry { self.backward_stack.push_back(NavigationEntry {
item, item,
data: data.map(|data| Box::new(data) as Box<dyn Any>), data: data.map(|data| Box::new(data) as Box<dyn Any>),
timestamp: self.next_timestamp.fetch_add(1, Ordering::SeqCst),
}); });
} }
NavigationMode::ClosingItem => { NavigationMode::ClosingItem => {
@ -1970,6 +1993,7 @@ impl NavHistory {
self.closed_stack.push_back(NavigationEntry { self.closed_stack.push_back(NavigationEntry {
item, item,
data: data.map(|data| Box::new(data) as Box<dyn Any>), data: data.map(|data| Box::new(data) as Box<dyn Any>),
timestamp: self.next_timestamp.fetch_add(1, Ordering::SeqCst),
}); });
} }
} }
@ -1985,6 +2009,31 @@ impl NavHistory {
} }
} }
impl PaneNavHistory {
pub fn for_each_entry(
&self,
cx: &AppContext,
mut f: impl FnMut(&NavigationEntry, ProjectPath),
) {
let borrowed_history = self.0.borrow();
borrowed_history
.forward_stack
.iter()
.chain(borrowed_history.backward_stack.iter())
.chain(borrowed_history.closed_stack.iter())
.for_each(|entry| {
if let Some(path) = borrowed_history.paths_by_item.get(&entry.item.id()) {
f(entry, path.clone());
} else if let Some(item) = entry.item.upgrade(cx) {
let path = item.project_path(cx);
if let Some(path) = path {
f(entry, path);
}
}
})
}
}
pub struct PaneBackdrop<V: View> { pub struct PaneBackdrop<V: View> {
child_view: usize, child_view: usize,
child: AnyElement<V>, child: AnyElement<V>,

View file

@ -47,6 +47,7 @@ use gpui::{
WindowContext, WindowContext,
}; };
use item::{FollowableItem, FollowableItemHandle, Item, ItemHandle, ProjectItem}; use item::{FollowableItem, FollowableItemHandle, Item, ItemHandle, ProjectItem};
use itertools::Itertools;
use language::{LanguageRegistry, Rope}; use language::{LanguageRegistry, Rope};
use std::{ use std::{
any::TypeId, any::TypeId,
@ -55,7 +56,7 @@ use std::{
future::Future, future::Future,
path::{Path, PathBuf}, path::{Path, PathBuf},
str, str,
sync::Arc, sync::{atomic::AtomicUsize, Arc},
time::Duration, time::Duration,
}; };
@ -481,6 +482,7 @@ pub struct Workspace {
_window_subscriptions: [Subscription; 3], _window_subscriptions: [Subscription; 3],
_apply_leader_updates: Task<Result<()>>, _apply_leader_updates: Task<Result<()>>,
_observe_current_user: Task<Result<()>>, _observe_current_user: Task<Result<()>>,
pane_history_timestamp: Arc<AtomicUsize>,
} }
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
@ -542,15 +544,24 @@ impl Workspace {
.detach(); .detach();
let weak_handle = cx.weak_handle(); let weak_handle = cx.weak_handle();
let pane_history_timestamp = Arc::new(AtomicUsize::new(0));
let center_pane = cx let center_pane = cx.add_view(|cx| {
.add_view(|cx| Pane::new(weak_handle.clone(), None, app_state.background_actions, cx)); Pane::new(
weak_handle.clone(),
None,
app_state.background_actions,
pane_history_timestamp.clone(),
cx,
)
});
cx.subscribe(&center_pane, Self::handle_pane_event).detach(); cx.subscribe(&center_pane, Self::handle_pane_event).detach();
cx.focus(&center_pane); cx.focus(&center_pane);
cx.emit(Event::PaneAdded(center_pane.clone())); cx.emit(Event::PaneAdded(center_pane.clone()));
let dock = Dock::new( let dock = Dock::new(
app_state.dock_default_item_factory, app_state.dock_default_item_factory,
app_state.background_actions, app_state.background_actions,
pane_history_timestamp.clone(),
cx, cx,
); );
let dock_pane = dock.pane().clone(); let dock_pane = dock.pane().clone();
@ -665,6 +676,7 @@ impl Workspace {
_apply_leader_updates, _apply_leader_updates,
leader_updates_tx, leader_updates_tx,
_window_subscriptions: subscriptions, _window_subscriptions: subscriptions,
pane_history_timestamp,
}; };
this.project_remote_id_changed(project.read(cx).remote_id(), cx); this.project_remote_id_changed(project.read(cx).remote_id(), cx);
cx.defer(|this, cx| this.update_window_title(cx)); cx.defer(|this, cx| this.update_window_title(cx));
@ -825,6 +837,39 @@ impl Workspace {
&self.project &self.project
} }
pub fn recent_navigation_history(
&self,
limit: Option<usize>,
cx: &AppContext,
) -> Vec<ProjectPath> {
let mut history: HashMap<ProjectPath, usize> = HashMap::default();
for pane in &self.panes {
let pane = pane.read(cx);
pane.nav_history()
.for_each_entry(cx, |entry, project_path| {
let timestamp = entry.timestamp;
match history.entry(project_path) {
hash_map::Entry::Occupied(mut entry) => {
if &timestamp > entry.get() {
entry.insert(timestamp);
}
}
hash_map::Entry::Vacant(entry) => {
entry.insert(timestamp);
}
}
});
}
history
.into_iter()
.sorted_by_key(|(_, timestamp)| *timestamp)
.map(|(project_path, _)| project_path)
.rev()
.take(limit.unwrap_or(usize::MAX))
.collect()
}
pub fn client(&self) -> &Client { pub fn client(&self) -> &Client {
&self.app_state.client &self.app_state.client
} }
@ -1386,6 +1431,7 @@ impl Workspace {
self.weak_handle(), self.weak_handle(),
None, None,
self.app_state.background_actions, self.app_state.background_actions,
self.pane_history_timestamp.clone(),
cx, cx,
) )
}); });