1mod items;
2pub mod pane;
3pub mod pane_group;
4pub mod settings;
5pub mod sidebar;
6
7use anyhow::Result;
8use language::{Buffer, LanguageRegistry};
9use client::{Authenticate, ChannelList, Client, UserStore};
10use gpui::{
11 action, elements::*, json::to_string_pretty, keymap::Binding, platform::CursorStyle,
12 AnyViewHandle, AppContext, ClipboardItem, Entity, ModelHandle, MutableAppContext, PromptLevel,
13 RenderContext, Task, View, ViewContext, ViewHandle, WeakModelHandle,
14};
15use log::error;
16pub use pane::*;
17pub use pane_group::*;
18use postage::{prelude::Stream, watch};
19use project::{Fs, Project, ProjectPath, Worktree};
20pub use settings::Settings;
21use sidebar::{Side, Sidebar, SidebarItemId, ToggleSidebarItem, ToggleSidebarItemFocus};
22use std::{
23 collections::{hash_map::Entry, HashMap},
24 future::Future,
25 path::{Path, PathBuf},
26 sync::Arc,
27};
28
29action!(OpenNew, WorkspaceParams);
30action!(Save);
31action!(DebugElements);
32
33pub fn init(cx: &mut MutableAppContext) {
34 cx.add_action(Workspace::save_active_item);
35 cx.add_action(Workspace::debug_elements);
36 cx.add_action(Workspace::open_new_file);
37 cx.add_action(Workspace::toggle_sidebar_item);
38 cx.add_action(Workspace::toggle_sidebar_item_focus);
39 cx.add_bindings(vec![
40 Binding::new("cmd-s", Save, None),
41 Binding::new("cmd-alt-i", DebugElements, None),
42 Binding::new(
43 "cmd-shift-!",
44 ToggleSidebarItem(SidebarItemId {
45 side: Side::Left,
46 item_index: 0,
47 }),
48 None,
49 ),
50 Binding::new(
51 "cmd-1",
52 ToggleSidebarItemFocus(SidebarItemId {
53 side: Side::Left,
54 item_index: 0,
55 }),
56 None,
57 ),
58 ]);
59 pane::init(cx);
60}
61
62pub trait Item: Entity + Sized {
63 type View: ItemView;
64
65 fn build_view(
66 handle: ModelHandle<Self>,
67 settings: watch::Receiver<Settings>,
68 cx: &mut ViewContext<Self::View>,
69 ) -> Self::View;
70
71 fn project_path(&self) -> Option<ProjectPath>;
72}
73
74pub trait ItemView: View {
75 fn title(&self, cx: &AppContext) -> String;
76 fn project_path(&self, cx: &AppContext) -> Option<ProjectPath>;
77 fn clone_on_split(&self, _: &mut ViewContext<Self>) -> Option<Self>
78 where
79 Self: Sized,
80 {
81 None
82 }
83 fn is_dirty(&self, _: &AppContext) -> bool {
84 false
85 }
86 fn has_conflict(&self, _: &AppContext) -> bool {
87 false
88 }
89 fn save(&mut self, cx: &mut ViewContext<Self>) -> Result<Task<Result<()>>>;
90 fn save_as(
91 &mut self,
92 worktree: ModelHandle<Worktree>,
93 path: &Path,
94 cx: &mut ViewContext<Self>,
95 ) -> Task<anyhow::Result<()>>;
96 fn should_activate_item_on_event(_: &Self::Event) -> bool {
97 false
98 }
99 fn should_close_item_on_event(_: &Self::Event) -> bool {
100 false
101 }
102 fn should_update_tab_on_event(_: &Self::Event) -> bool {
103 false
104 }
105}
106
107pub trait ItemHandle: Send + Sync {
108 fn boxed_clone(&self) -> Box<dyn ItemHandle>;
109 fn downgrade(&self) -> Box<dyn WeakItemHandle>;
110}
111
112pub trait WeakItemHandle {
113 fn add_view(
114 &self,
115 window_id: usize,
116 settings: watch::Receiver<Settings>,
117 cx: &mut MutableAppContext,
118 ) -> Option<Box<dyn ItemViewHandle>>;
119 fn alive(&self, cx: &AppContext) -> bool;
120 fn project_path(&self, cx: &AppContext) -> Option<ProjectPath>;
121}
122
123pub trait ItemViewHandle {
124 fn title(&self, cx: &AppContext) -> String;
125 fn project_path(&self, cx: &AppContext) -> Option<ProjectPath>;
126 fn boxed_clone(&self) -> Box<dyn ItemViewHandle>;
127 fn clone_on_split(&self, cx: &mut MutableAppContext) -> Option<Box<dyn ItemViewHandle>>;
128 fn set_parent_pane(&self, pane: &ViewHandle<Pane>, cx: &mut MutableAppContext);
129 fn id(&self) -> usize;
130 fn to_any(&self) -> AnyViewHandle;
131 fn is_dirty(&self, cx: &AppContext) -> bool;
132 fn has_conflict(&self, cx: &AppContext) -> bool;
133 fn save(&self, cx: &mut MutableAppContext) -> Result<Task<Result<()>>>;
134 fn save_as(
135 &self,
136 worktree: ModelHandle<Worktree>,
137 path: &Path,
138 cx: &mut MutableAppContext,
139 ) -> Task<anyhow::Result<()>>;
140}
141
142impl<T: Item> ItemHandle for ModelHandle<T> {
143 fn boxed_clone(&self) -> Box<dyn ItemHandle> {
144 Box::new(self.clone())
145 }
146
147 fn downgrade(&self) -> Box<dyn WeakItemHandle> {
148 Box::new(self.downgrade())
149 }
150}
151
152impl<T: Item> WeakItemHandle for WeakModelHandle<T> {
153 fn add_view(
154 &self,
155 window_id: usize,
156 settings: watch::Receiver<Settings>,
157 cx: &mut MutableAppContext,
158 ) -> Option<Box<dyn ItemViewHandle>> {
159 if let Some(handle) = self.upgrade(cx.as_ref()) {
160 Some(Box::new(cx.add_view(window_id, |cx| {
161 T::build_view(handle, settings, cx)
162 })))
163 } else {
164 None
165 }
166 }
167
168 fn alive(&self, cx: &AppContext) -> bool {
169 self.upgrade(cx).is_some()
170 }
171
172 fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
173 self.upgrade(cx).and_then(|h| h.read(cx).project_path())
174 }
175}
176
177impl<T: ItemView> ItemViewHandle for ViewHandle<T> {
178 fn title(&self, cx: &AppContext) -> String {
179 self.read(cx).title(cx)
180 }
181
182 fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
183 self.read(cx).project_path(cx)
184 }
185
186 fn boxed_clone(&self) -> Box<dyn ItemViewHandle> {
187 Box::new(self.clone())
188 }
189
190 fn clone_on_split(&self, cx: &mut MutableAppContext) -> Option<Box<dyn ItemViewHandle>> {
191 self.update(cx, |item, cx| {
192 cx.add_option_view(|cx| item.clone_on_split(cx))
193 })
194 .map(|handle| Box::new(handle) as Box<dyn ItemViewHandle>)
195 }
196
197 fn set_parent_pane(&self, pane: &ViewHandle<Pane>, cx: &mut MutableAppContext) {
198 pane.update(cx, |_, cx| {
199 cx.subscribe(self, |pane, item, event, cx| {
200 if T::should_close_item_on_event(event) {
201 pane.close_item(item.id(), cx);
202 return;
203 }
204 if T::should_activate_item_on_event(event) {
205 if let Some(ix) = pane.item_index(&item) {
206 pane.activate_item(ix, cx);
207 pane.activate(cx);
208 }
209 }
210 if T::should_update_tab_on_event(event) {
211 cx.notify()
212 }
213 })
214 .detach();
215 });
216 }
217
218 fn save(&self, cx: &mut MutableAppContext) -> Result<Task<Result<()>>> {
219 self.update(cx, |item, cx| item.save(cx))
220 }
221
222 fn save_as(
223 &self,
224 worktree: ModelHandle<Worktree>,
225 path: &Path,
226 cx: &mut MutableAppContext,
227 ) -> Task<anyhow::Result<()>> {
228 self.update(cx, |item, cx| item.save_as(worktree, path, cx))
229 }
230
231 fn is_dirty(&self, cx: &AppContext) -> bool {
232 self.read(cx).is_dirty(cx)
233 }
234
235 fn has_conflict(&self, cx: &AppContext) -> bool {
236 self.read(cx).has_conflict(cx)
237 }
238
239 fn id(&self) -> usize {
240 self.id()
241 }
242
243 fn to_any(&self) -> AnyViewHandle {
244 self.into()
245 }
246}
247
248impl Clone for Box<dyn ItemViewHandle> {
249 fn clone(&self) -> Box<dyn ItemViewHandle> {
250 self.boxed_clone()
251 }
252}
253
254impl Clone for Box<dyn ItemHandle> {
255 fn clone(&self) -> Box<dyn ItemHandle> {
256 self.boxed_clone()
257 }
258}
259
260#[derive(Clone)]
261pub struct WorkspaceParams {
262 pub client: Arc<Client>,
263 pub fs: Arc<dyn Fs>,
264 pub languages: Arc<LanguageRegistry>,
265 pub settings: watch::Receiver<Settings>,
266 pub user_store: ModelHandle<UserStore>,
267 pub channel_list: ModelHandle<ChannelList>,
268}
269
270impl WorkspaceParams {
271 #[cfg(any(test, feature = "test-support"))]
272 pub fn test(cx: &mut MutableAppContext) -> Self {
273 let mut languages = LanguageRegistry::new();
274 languages.add(Arc::new(language::Language::new(
275 language::LanguageConfig {
276 name: "Rust".to_string(),
277 path_suffixes: vec!["rs".to_string()],
278 ..Default::default()
279 },
280 tree_sitter_rust::language(),
281 )));
282
283 let client = Client::new();
284 let http_client = client::test::FakeHttpClient::new(|_| async move {
285 Ok(client::http::ServerResponse::new(404))
286 });
287 let theme =
288 gpui::fonts::with_font_cache(cx.font_cache().clone(), || theme::Theme::default());
289 let settings = Settings::new("Courier", cx.font_cache(), Arc::new(theme)).unwrap();
290 let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http_client, cx));
291 Self {
292 channel_list: cx
293 .add_model(|cx| ChannelList::new(user_store.clone(), client.clone(), cx)),
294 client,
295 fs: Arc::new(project::FakeFs::new()),
296 languages: Arc::new(languages),
297 settings: watch::channel_with(settings).1,
298 user_store,
299 }
300 }
301}
302
303pub struct Workspace {
304 pub settings: watch::Receiver<Settings>,
305 client: Arc<Client>,
306 user_store: ModelHandle<client::UserStore>,
307 fs: Arc<dyn Fs>,
308 modal: Option<AnyViewHandle>,
309 center: PaneGroup,
310 left_sidebar: Sidebar,
311 right_sidebar: Sidebar,
312 panes: Vec<ViewHandle<Pane>>,
313 active_pane: ViewHandle<Pane>,
314 project: ModelHandle<Project>,
315 items: Vec<Box<dyn WeakItemHandle>>,
316 loading_items: HashMap<
317 ProjectPath,
318 postage::watch::Receiver<Option<Result<Box<dyn ItemHandle>, Arc<anyhow::Error>>>>,
319 >,
320 _observe_current_user: Task<()>,
321}
322
323impl Workspace {
324 pub fn new(params: &WorkspaceParams, cx: &mut ViewContext<Self>) -> Self {
325 let project = cx.add_model(|_| {
326 Project::new(
327 params.languages.clone(),
328 params.client.clone(),
329 params.fs.clone(),
330 )
331 });
332 cx.observe(&project, |_, _, cx| cx.notify()).detach();
333
334 let pane = cx.add_view(|_| Pane::new(params.settings.clone()));
335 let pane_id = pane.id();
336 cx.observe(&pane, move |me, _, cx| {
337 let active_entry = me.active_project_path(cx);
338 me.project
339 .update(cx, |project, cx| project.set_active_path(active_entry, cx));
340 })
341 .detach();
342 cx.subscribe(&pane, move |me, _, event, cx| {
343 me.handle_pane_event(pane_id, event, cx)
344 })
345 .detach();
346 cx.focus(&pane);
347
348 let mut current_user = params.user_store.read(cx).watch_current_user().clone();
349 let mut connection_status = params.client.status().clone();
350 let _observe_current_user = cx.spawn_weak(|this, mut cx| async move {
351 current_user.recv().await;
352 connection_status.recv().await;
353 let mut stream =
354 Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
355
356 while stream.recv().await.is_some() {
357 cx.update(|cx| {
358 if let Some(this) = this.upgrade(&cx) {
359 this.update(cx, |_, cx| cx.notify());
360 }
361 })
362 }
363 });
364
365 Workspace {
366 modal: None,
367 center: PaneGroup::new(pane.id()),
368 panes: vec![pane.clone()],
369 active_pane: pane.clone(),
370 settings: params.settings.clone(),
371 client: params.client.clone(),
372 user_store: params.user_store.clone(),
373 fs: params.fs.clone(),
374 left_sidebar: Sidebar::new(Side::Left),
375 right_sidebar: Sidebar::new(Side::Right),
376 project,
377 items: Default::default(),
378 loading_items: Default::default(),
379 _observe_current_user,
380 }
381 }
382
383 pub fn left_sidebar_mut(&mut self) -> &mut Sidebar {
384 &mut self.left_sidebar
385 }
386
387 pub fn right_sidebar_mut(&mut self) -> &mut Sidebar {
388 &mut self.right_sidebar
389 }
390
391 pub fn project(&self) -> &ModelHandle<Project> {
392 &self.project
393 }
394
395 pub fn worktrees<'a>(&self, cx: &'a AppContext) -> &'a [ModelHandle<Worktree>] {
396 &self.project.read(cx).worktrees()
397 }
398
399 pub fn contains_paths(&self, paths: &[PathBuf], cx: &AppContext) -> bool {
400 paths.iter().all(|path| self.contains_path(&path, cx))
401 }
402
403 pub fn contains_path(&self, path: &Path, cx: &AppContext) -> bool {
404 for worktree in self.worktrees(cx) {
405 let worktree = worktree.read(cx).as_local();
406 if worktree.map_or(false, |w| w.contains_abs_path(path)) {
407 return true;
408 }
409 }
410 false
411 }
412
413 pub fn worktree_scans_complete(&self, cx: &AppContext) -> impl Future<Output = ()> + 'static {
414 let futures = self
415 .worktrees(cx)
416 .iter()
417 .filter_map(|worktree| worktree.read(cx).as_local())
418 .map(|worktree| worktree.scan_complete())
419 .collect::<Vec<_>>();
420 async move {
421 for future in futures {
422 future.await;
423 }
424 }
425 }
426
427 pub fn open_paths(&mut self, abs_paths: &[PathBuf], cx: &mut ViewContext<Self>) -> Task<()> {
428 let entries = abs_paths
429 .iter()
430 .cloned()
431 .map(|path| self.project_path_for_path(&path, cx))
432 .collect::<Vec<_>>();
433
434 let fs = self.fs.clone();
435 let tasks = abs_paths
436 .iter()
437 .cloned()
438 .zip(entries.into_iter())
439 .map(|(abs_path, project_path)| {
440 cx.spawn(|this, mut cx| {
441 let fs = fs.clone();
442 async move {
443 let project_path = project_path.await?;
444 if fs.is_file(&abs_path).await {
445 if let Some(entry) =
446 this.update(&mut cx, |this, cx| this.open_entry(project_path, cx))
447 {
448 entry.await;
449 }
450 }
451 Ok(())
452 }
453 })
454 })
455 .collect::<Vec<Task<Result<()>>>>();
456
457 cx.foreground().spawn(async move {
458 for task in tasks {
459 if let Err(error) = task.await {
460 log::error!("error opening paths {}", error);
461 }
462 }
463 })
464 }
465
466 fn worktree_for_abs_path(
467 &self,
468 abs_path: &Path,
469 cx: &mut ViewContext<Self>,
470 ) -> Task<Result<(ModelHandle<Worktree>, PathBuf)>> {
471 let abs_path: Arc<Path> = Arc::from(abs_path);
472 cx.spawn(|this, mut cx| async move {
473 let mut entry_id = None;
474 this.read_with(&cx, |this, cx| {
475 for tree in this.worktrees(cx) {
476 if let Some(relative_path) = tree
477 .read(cx)
478 .as_local()
479 .and_then(|t| abs_path.strip_prefix(t.abs_path()).ok())
480 {
481 entry_id = Some((tree.clone(), relative_path.into()));
482 break;
483 }
484 }
485 });
486
487 if let Some(entry_id) = entry_id {
488 Ok(entry_id)
489 } else {
490 let worktree = this
491 .update(&mut cx, |this, cx| this.add_worktree(&abs_path, cx))
492 .await?;
493 Ok((worktree, PathBuf::new()))
494 }
495 })
496 }
497
498 fn project_path_for_path(
499 &self,
500 abs_path: &Path,
501 cx: &mut ViewContext<Self>,
502 ) -> Task<Result<ProjectPath>> {
503 let entry = self.worktree_for_abs_path(abs_path, cx);
504 cx.spawn(|_, _| async move {
505 let (worktree, path) = entry.await?;
506 Ok(ProjectPath {
507 worktree_id: worktree.id(),
508 path: path.into(),
509 })
510 })
511 }
512
513 pub fn add_worktree(
514 &self,
515 path: &Path,
516 cx: &mut ViewContext<Self>,
517 ) -> Task<Result<ModelHandle<Worktree>>> {
518 self.project
519 .update(cx, |project, cx| project.add_local_worktree(path, cx))
520 }
521
522 pub fn toggle_modal<V, F>(&mut self, cx: &mut ViewContext<Self>, add_view: F)
523 where
524 V: 'static + View,
525 F: FnOnce(&mut ViewContext<Self>, &mut Self) -> ViewHandle<V>,
526 {
527 if self.modal.as_ref().map_or(false, |modal| modal.is::<V>()) {
528 self.modal.take();
529 cx.focus_self();
530 } else {
531 let modal = add_view(cx, self);
532 cx.focus(&modal);
533 self.modal = Some(modal.into());
534 }
535 cx.notify();
536 }
537
538 pub fn modal(&self) -> Option<&AnyViewHandle> {
539 self.modal.as_ref()
540 }
541
542 pub fn dismiss_modal(&mut self, cx: &mut ViewContext<Self>) {
543 if self.modal.take().is_some() {
544 cx.focus(&self.active_pane);
545 cx.notify();
546 }
547 }
548
549 pub fn open_new_file(&mut self, _: &OpenNew, cx: &mut ViewContext<Self>) {
550 let buffer = cx.add_model(|cx| Buffer::new(0, "", cx));
551 let item_handle = ItemHandle::downgrade(&buffer);
552 let view = item_handle
553 .add_view(cx.window_id(), self.settings.clone(), cx)
554 .unwrap();
555 self.items.push(item_handle);
556 self.active_pane().add_item_view(view, cx.as_mut());
557 }
558
559 #[must_use]
560 pub fn open_entry(
561 &mut self,
562 project_path: ProjectPath,
563 cx: &mut ViewContext<Self>,
564 ) -> Option<Task<()>> {
565 let pane = self.active_pane().clone();
566 if self.activate_or_open_existing_entry(project_path.clone(), &pane, cx) {
567 return None;
568 }
569
570 // let (worktree_id, path) = project_path.clone();
571
572 let worktree = match self
573 .project
574 .read(cx)
575 .worktree_for_id(project_path.worktree_id)
576 {
577 Some(worktree) => worktree,
578 None => {
579 log::error!("worktree {} does not exist", project_path.worktree_id);
580 return None;
581 }
582 };
583
584 if let Entry::Vacant(entry) = self.loading_items.entry(project_path.clone()) {
585 let (mut tx, rx) = postage::watch::channel();
586 entry.insert(rx);
587
588 let project_path = project_path.clone();
589 cx.as_mut()
590 .spawn(|mut cx| async move {
591 let buffer = worktree
592 .update(&mut cx, |worktree, cx| {
593 worktree.open_buffer(project_path.path.as_ref(), cx)
594 })
595 .await;
596 *tx.borrow_mut() = Some(
597 buffer
598 .map(|buffer| Box::new(buffer) as Box<dyn ItemHandle>)
599 .map_err(Arc::new),
600 );
601 })
602 .detach();
603 }
604
605 let pane = pane.downgrade();
606 let settings = self.settings.clone();
607 let mut watch = self.loading_items.get(&project_path).unwrap().clone();
608
609 Some(cx.spawn(|this, mut cx| async move {
610 let load_result = loop {
611 if let Some(load_result) = watch.borrow().as_ref() {
612 break load_result.clone();
613 }
614 watch.recv().await;
615 };
616
617 this.update(&mut cx, |this, cx| {
618 this.loading_items.remove(&project_path);
619 if let Some(pane) = pane.upgrade(&cx) {
620 match load_result {
621 Ok(item) => {
622 // By the time loading finishes, the entry could have been already added
623 // to the pane. If it was, we activate it, otherwise we'll store the
624 // item and add a new view for it.
625 if !this.activate_or_open_existing_entry(project_path, &pane, cx) {
626 let weak_item = item.downgrade();
627 let view = weak_item
628 .add_view(cx.window_id(), settings, cx.as_mut())
629 .unwrap();
630 this.items.push(weak_item);
631 pane.add_item_view(view, cx.as_mut());
632 }
633 }
634 Err(error) => {
635 log::error!("error opening item: {}", error);
636 }
637 }
638 }
639 })
640 }))
641 }
642
643 fn activate_or_open_existing_entry(
644 &mut self,
645 project_path: ProjectPath,
646 pane: &ViewHandle<Pane>,
647 cx: &mut ViewContext<Self>,
648 ) -> bool {
649 // If the pane contains a view for this file, then activate
650 // that item view.
651 if pane.update(cx, |pane, cx| pane.activate_entry(project_path.clone(), cx)) {
652 return true;
653 }
654
655 // Otherwise, if this file is already open somewhere in the workspace,
656 // then add another view for it.
657 let settings = self.settings.clone();
658 let mut view_for_existing_item = None;
659 self.items.retain(|item| {
660 if item.alive(cx.as_ref()) {
661 if view_for_existing_item.is_none()
662 && item
663 .project_path(cx)
664 .map_or(false, |item_project_path| item_project_path == project_path)
665 {
666 view_for_existing_item = Some(
667 item.add_view(cx.window_id(), settings.clone(), cx.as_mut())
668 .unwrap(),
669 );
670 }
671 true
672 } else {
673 false
674 }
675 });
676 if let Some(view) = view_for_existing_item {
677 pane.add_item_view(view, cx.as_mut());
678 true
679 } else {
680 false
681 }
682 }
683
684 pub fn active_item(&self, cx: &ViewContext<Self>) -> Option<Box<dyn ItemViewHandle>> {
685 self.active_pane().read(cx).active_item()
686 }
687
688 fn active_project_path(&self, cx: &ViewContext<Self>) -> Option<ProjectPath> {
689 self.active_item(cx).and_then(|item| item.project_path(cx))
690 }
691
692 pub fn save_active_item(&mut self, _: &Save, cx: &mut ViewContext<Self>) {
693 if let Some(item) = self.active_item(cx) {
694 let handle = cx.handle();
695 if item.project_path(cx.as_ref()).is_none() {
696 let worktree = self.worktrees(cx).first();
697 let start_abs_path = worktree
698 .and_then(|w| w.read(cx).as_local())
699 .map_or(Path::new(""), |w| w.abs_path())
700 .to_path_buf();
701 cx.prompt_for_new_path(&start_abs_path, move |abs_path, cx| {
702 if let Some(abs_path) = abs_path {
703 cx.spawn(|mut cx| async move {
704 let result = match handle
705 .update(&mut cx, |this, cx| {
706 this.worktree_for_abs_path(&abs_path, cx)
707 })
708 .await
709 {
710 Ok((worktree, path)) => {
711 handle
712 .update(&mut cx, |_, cx| {
713 item.save_as(worktree, &path, cx.as_mut())
714 })
715 .await
716 }
717 Err(error) => Err(error),
718 };
719
720 if let Err(error) = result {
721 error!("failed to save item: {:?}, ", error);
722 }
723 })
724 .detach()
725 }
726 });
727 return;
728 } else if item.has_conflict(cx.as_ref()) {
729 const CONFLICT_MESSAGE: &'static str = "This file has changed on disk since you started editing it. Do you want to overwrite it?";
730
731 cx.prompt(
732 PromptLevel::Warning,
733 CONFLICT_MESSAGE,
734 &["Overwrite", "Cancel"],
735 move |answer, cx| {
736 if answer == 0 {
737 cx.spawn(|mut cx| async move {
738 if let Err(error) = cx.update(|cx| item.save(cx)).unwrap().await {
739 error!("failed to save item: {:?}, ", error);
740 }
741 })
742 .detach();
743 }
744 },
745 );
746 } else {
747 cx.spawn(|_, mut cx| async move {
748 if let Err(error) = cx.update(|cx| item.save(cx)).unwrap().await {
749 error!("failed to save item: {:?}, ", error);
750 }
751 })
752 .detach();
753 }
754 }
755 }
756
757 pub fn toggle_sidebar_item(&mut self, action: &ToggleSidebarItem, cx: &mut ViewContext<Self>) {
758 let sidebar = match action.0.side {
759 Side::Left => &mut self.left_sidebar,
760 Side::Right => &mut self.right_sidebar,
761 };
762 sidebar.toggle_item(action.0.item_index);
763 if let Some(active_item) = sidebar.active_item() {
764 cx.focus(active_item);
765 } else {
766 cx.focus_self();
767 }
768 cx.notify();
769 }
770
771 pub fn toggle_sidebar_item_focus(
772 &mut self,
773 action: &ToggleSidebarItemFocus,
774 cx: &mut ViewContext<Self>,
775 ) {
776 let sidebar = match action.0.side {
777 Side::Left => &mut self.left_sidebar,
778 Side::Right => &mut self.right_sidebar,
779 };
780 sidebar.activate_item(action.0.item_index);
781 if let Some(active_item) = sidebar.active_item() {
782 if active_item.is_focused(cx) {
783 cx.focus_self();
784 } else {
785 cx.focus(active_item);
786 }
787 }
788 cx.notify();
789 }
790
791 pub fn debug_elements(&mut self, _: &DebugElements, cx: &mut ViewContext<Self>) {
792 match to_string_pretty(&cx.debug_elements()) {
793 Ok(json) => {
794 let kib = json.len() as f32 / 1024.;
795 cx.as_mut().write_to_clipboard(ClipboardItem::new(json));
796 log::info!(
797 "copied {:.1} KiB of element debug JSON to the clipboard",
798 kib
799 );
800 }
801 Err(error) => {
802 log::error!("error debugging elements: {}", error);
803 }
804 };
805 }
806
807 fn add_pane(&mut self, cx: &mut ViewContext<Self>) -> ViewHandle<Pane> {
808 let pane = cx.add_view(|_| Pane::new(self.settings.clone()));
809 let pane_id = pane.id();
810 cx.observe(&pane, move |me, _, cx| {
811 let active_entry = me.active_project_path(cx);
812 me.project
813 .update(cx, |project, cx| project.set_active_path(active_entry, cx));
814 })
815 .detach();
816 cx.subscribe(&pane, move |me, _, event, cx| {
817 me.handle_pane_event(pane_id, event, cx)
818 })
819 .detach();
820 self.panes.push(pane.clone());
821 self.activate_pane(pane.clone(), cx);
822 pane
823 }
824
825 fn activate_pane(&mut self, pane: ViewHandle<Pane>, cx: &mut ViewContext<Self>) {
826 self.active_pane = pane;
827 cx.focus(&self.active_pane);
828 cx.notify();
829 }
830
831 fn handle_pane_event(
832 &mut self,
833 pane_id: usize,
834 event: &pane::Event,
835 cx: &mut ViewContext<Self>,
836 ) {
837 if let Some(pane) = self.pane(pane_id) {
838 match event {
839 pane::Event::Split(direction) => {
840 self.split_pane(pane, *direction, cx);
841 }
842 pane::Event::Remove => {
843 self.remove_pane(pane, cx);
844 }
845 pane::Event::Activate => {
846 self.activate_pane(pane, cx);
847 }
848 }
849 } else {
850 error!("pane {} not found", pane_id);
851 }
852 }
853
854 fn split_pane(
855 &mut self,
856 pane: ViewHandle<Pane>,
857 direction: SplitDirection,
858 cx: &mut ViewContext<Self>,
859 ) -> ViewHandle<Pane> {
860 let new_pane = self.add_pane(cx);
861 self.activate_pane(new_pane.clone(), cx);
862 if let Some(item) = pane.read(cx).active_item() {
863 if let Some(clone) = item.clone_on_split(cx.as_mut()) {
864 new_pane.add_item_view(clone, cx.as_mut());
865 }
866 }
867 self.center
868 .split(pane.id(), new_pane.id(), direction)
869 .unwrap();
870 cx.notify();
871 new_pane
872 }
873
874 fn remove_pane(&mut self, pane: ViewHandle<Pane>, cx: &mut ViewContext<Self>) {
875 if self.center.remove(pane.id()).unwrap() {
876 self.panes.retain(|p| p != &pane);
877 self.activate_pane(self.panes.last().unwrap().clone(), cx);
878 }
879 }
880
881 fn pane(&self, pane_id: usize) -> Option<ViewHandle<Pane>> {
882 self.panes.iter().find(|pane| pane.id() == pane_id).cloned()
883 }
884
885 pub fn active_pane(&self) -> &ViewHandle<Pane> {
886 &self.active_pane
887 }
888
889 fn render_connection_status(&self) -> Option<ElementBox> {
890 let theme = &self.settings.borrow().theme;
891 match &*self.client.status().borrow() {
892 client::Status::ConnectionError
893 | client::Status::ConnectionLost
894 | client::Status::Reauthenticating
895 | client::Status::Reconnecting { .. }
896 | client::Status::ReconnectionError { .. } => Some(
897 Container::new(
898 Align::new(
899 ConstrainedBox::new(
900 Svg::new("icons/offline-14.svg")
901 .with_color(theme.workspace.titlebar.icon_color)
902 .boxed(),
903 )
904 .with_width(theme.workspace.titlebar.offline_icon.width)
905 .boxed(),
906 )
907 .boxed(),
908 )
909 .with_style(theme.workspace.titlebar.offline_icon.container)
910 .boxed(),
911 ),
912 client::Status::UpgradeRequired => Some(
913 Label::new(
914 "Please update Zed to collaborate".to_string(),
915 theme.workspace.titlebar.outdated_warning.text.clone(),
916 )
917 .contained()
918 .with_style(theme.workspace.titlebar.outdated_warning.container)
919 .aligned()
920 .boxed(),
921 ),
922 _ => None,
923 }
924 }
925
926 fn render_avatar(&self, cx: &mut RenderContext<Self>) -> ElementBox {
927 let theme = &self.settings.borrow().theme;
928 let avatar = if let Some(avatar) = self
929 .user_store
930 .read(cx)
931 .current_user()
932 .and_then(|user| user.avatar.clone())
933 {
934 Image::new(avatar)
935 .with_style(theme.workspace.titlebar.avatar)
936 .boxed()
937 } else {
938 MouseEventHandler::new::<Authenticate, _, _, _>(0, cx, |_, _| {
939 Svg::new("icons/signed-out-12.svg")
940 .with_color(theme.workspace.titlebar.icon_color)
941 .boxed()
942 })
943 .on_click(|cx| cx.dispatch_action(Authenticate))
944 .with_cursor_style(CursorStyle::PointingHand)
945 .boxed()
946 };
947
948 ConstrainedBox::new(
949 Align::new(
950 ConstrainedBox::new(avatar)
951 .with_width(theme.workspace.titlebar.avatar_width)
952 .boxed(),
953 )
954 .boxed(),
955 )
956 .with_width(theme.workspace.right_sidebar.width)
957 .boxed()
958 }
959}
960
961impl Entity for Workspace {
962 type Event = ();
963}
964
965impl View for Workspace {
966 fn ui_name() -> &'static str {
967 "Workspace"
968 }
969
970 fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
971 let settings = self.settings.borrow();
972 let theme = &settings.theme;
973 Container::new(
974 Flex::column()
975 .with_child(
976 ConstrainedBox::new(
977 Container::new(
978 Stack::new()
979 .with_child(
980 Align::new(
981 Label::new(
982 "zed".into(),
983 theme.workspace.titlebar.title.clone(),
984 )
985 .boxed(),
986 )
987 .boxed(),
988 )
989 .with_child(
990 Align::new(
991 Flex::row()
992 .with_children(self.render_connection_status())
993 .with_child(self.render_avatar(cx))
994 .boxed(),
995 )
996 .right()
997 .boxed(),
998 )
999 .boxed(),
1000 )
1001 .with_style(theme.workspace.titlebar.container)
1002 .boxed(),
1003 )
1004 .with_height(32.)
1005 .named("titlebar"),
1006 )
1007 .with_child(
1008 Expanded::new(
1009 1.0,
1010 Stack::new()
1011 .with_child({
1012 let mut content = Flex::row();
1013 content.add_child(self.left_sidebar.render(&settings, cx));
1014 if let Some(element) =
1015 self.left_sidebar.render_active_item(&settings, cx)
1016 {
1017 content.add_child(Flexible::new(0.8, element).boxed());
1018 }
1019 content.add_child(
1020 Expanded::new(1.0, self.center.render(&settings.theme)).boxed(),
1021 );
1022 if let Some(element) =
1023 self.right_sidebar.render_active_item(&settings, cx)
1024 {
1025 content.add_child(Flexible::new(0.8, element).boxed());
1026 }
1027 content.add_child(self.right_sidebar.render(&settings, cx));
1028 content.boxed()
1029 })
1030 .with_children(
1031 self.modal.as_ref().map(|m| ChildView::new(m.id()).boxed()),
1032 )
1033 .boxed(),
1034 )
1035 .boxed(),
1036 )
1037 .boxed(),
1038 )
1039 .with_background_color(settings.theme.workspace.background)
1040 .named("workspace")
1041 }
1042
1043 fn on_focus(&mut self, cx: &mut ViewContext<Self>) {
1044 cx.focus(&self.active_pane);
1045 }
1046}
1047
1048#[cfg(test)]
1049pub trait WorkspaceHandle {
1050 fn file_project_paths(&self, cx: &AppContext) -> Vec<ProjectPath>;
1051}
1052
1053#[cfg(test)]
1054impl WorkspaceHandle for ViewHandle<Workspace> {
1055 fn file_project_paths(&self, cx: &AppContext) -> Vec<ProjectPath> {
1056 self.read(cx)
1057 .worktrees(cx)
1058 .iter()
1059 .flat_map(|worktree| {
1060 let worktree_id = worktree.id();
1061 worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
1062 worktree_id,
1063 path: f.path.clone(),
1064 })
1065 })
1066 .collect::<Vec<_>>()
1067 }
1068}
1069
1070#[cfg(test)]
1071mod tests {
1072 use super::*;
1073 use editor::{Editor, Input};
1074 use serde_json::json;
1075 use std::collections::HashSet;
1076
1077 #[gpui::test]
1078 async fn test_open_entry(mut cx: gpui::TestAppContext) {
1079 let params = cx.update(WorkspaceParams::test);
1080 params
1081 .fs
1082 .as_fake()
1083 .insert_tree(
1084 "/root",
1085 json!({
1086 "a": {
1087 "file1": "contents 1",
1088 "file2": "contents 2",
1089 "file3": "contents 3",
1090 },
1091 }),
1092 )
1093 .await;
1094
1095 let (_, workspace) = cx.add_window(|cx| Workspace::new(¶ms, cx));
1096 workspace
1097 .update(&mut cx, |workspace, cx| {
1098 workspace.add_worktree(Path::new("/root"), cx)
1099 })
1100 .await
1101 .unwrap();
1102
1103 cx.read(|cx| workspace.read(cx).worktree_scans_complete(cx))
1104 .await;
1105 let entries = cx.read(|cx| workspace.file_project_paths(cx));
1106 let file1 = entries[0].clone();
1107 let file2 = entries[1].clone();
1108 let file3 = entries[2].clone();
1109
1110 // Open the first entry
1111 workspace
1112 .update(&mut cx, |w, cx| w.open_entry(file1.clone(), cx))
1113 .unwrap()
1114 .await;
1115 cx.read(|cx| {
1116 let pane = workspace.read(cx).active_pane().read(cx);
1117 assert_eq!(
1118 pane.active_item().unwrap().project_path(cx),
1119 Some(file1.clone())
1120 );
1121 assert_eq!(pane.items().len(), 1);
1122 });
1123
1124 // Open the second entry
1125 workspace
1126 .update(&mut cx, |w, cx| w.open_entry(file2.clone(), cx))
1127 .unwrap()
1128 .await;
1129 cx.read(|cx| {
1130 let pane = workspace.read(cx).active_pane().read(cx);
1131 assert_eq!(
1132 pane.active_item().unwrap().project_path(cx),
1133 Some(file2.clone())
1134 );
1135 assert_eq!(pane.items().len(), 2);
1136 });
1137
1138 // Open the first entry again. The existing pane item is activated.
1139 workspace.update(&mut cx, |w, cx| {
1140 assert!(w.open_entry(file1.clone(), cx).is_none())
1141 });
1142 cx.read(|cx| {
1143 let pane = workspace.read(cx).active_pane().read(cx);
1144 assert_eq!(
1145 pane.active_item().unwrap().project_path(cx),
1146 Some(file1.clone())
1147 );
1148 assert_eq!(pane.items().len(), 2);
1149 });
1150
1151 // Split the pane with the first entry, then open the second entry again.
1152 workspace.update(&mut cx, |w, cx| {
1153 w.split_pane(w.active_pane().clone(), SplitDirection::Right, cx);
1154 assert!(w.open_entry(file2.clone(), cx).is_none());
1155 assert_eq!(
1156 w.active_pane()
1157 .read(cx)
1158 .active_item()
1159 .unwrap()
1160 .project_path(cx.as_ref()),
1161 Some(file2.clone())
1162 );
1163 });
1164
1165 // Open the third entry twice concurrently. Only one pane item is added.
1166 let (t1, t2) = workspace.update(&mut cx, |w, cx| {
1167 (
1168 w.open_entry(file3.clone(), cx).unwrap(),
1169 w.open_entry(file3.clone(), cx).unwrap(),
1170 )
1171 });
1172 t1.await;
1173 t2.await;
1174 cx.read(|cx| {
1175 let pane = workspace.read(cx).active_pane().read(cx);
1176 assert_eq!(
1177 pane.active_item().unwrap().project_path(cx),
1178 Some(file3.clone())
1179 );
1180 let pane_entries = pane
1181 .items()
1182 .iter()
1183 .map(|i| i.project_path(cx).unwrap())
1184 .collect::<Vec<_>>();
1185 assert_eq!(pane_entries, &[file1, file2, file3]);
1186 });
1187 }
1188
1189 #[gpui::test]
1190 async fn test_open_paths(mut cx: gpui::TestAppContext) {
1191 let params = cx.update(WorkspaceParams::test);
1192 let fs = params.fs.as_fake();
1193 fs.insert_dir("/dir1").await.unwrap();
1194 fs.insert_dir("/dir2").await.unwrap();
1195 fs.insert_file("/dir1/a.txt", "".into()).await.unwrap();
1196 fs.insert_file("/dir2/b.txt", "".into()).await.unwrap();
1197
1198 let (_, workspace) = cx.add_window(|cx| Workspace::new(¶ms, cx));
1199 workspace
1200 .update(&mut cx, |workspace, cx| {
1201 workspace.add_worktree("/dir1".as_ref(), cx)
1202 })
1203 .await
1204 .unwrap();
1205 cx.read(|cx| workspace.read(cx).worktree_scans_complete(cx))
1206 .await;
1207
1208 // Open a file within an existing worktree.
1209 cx.update(|cx| {
1210 workspace.update(cx, |view, cx| view.open_paths(&["/dir1/a.txt".into()], cx))
1211 })
1212 .await;
1213 cx.read(|cx| {
1214 assert_eq!(
1215 workspace
1216 .read(cx)
1217 .active_pane()
1218 .read(cx)
1219 .active_item()
1220 .unwrap()
1221 .title(cx),
1222 "a.txt"
1223 );
1224 });
1225
1226 // Open a file outside of any existing worktree.
1227 cx.update(|cx| {
1228 workspace.update(cx, |view, cx| view.open_paths(&["/dir2/b.txt".into()], cx))
1229 })
1230 .await;
1231 cx.read(|cx| {
1232 let worktree_roots = workspace
1233 .read(cx)
1234 .worktrees(cx)
1235 .iter()
1236 .map(|w| w.read(cx).as_local().unwrap().abs_path())
1237 .collect::<HashSet<_>>();
1238 assert_eq!(
1239 worktree_roots,
1240 vec!["/dir1", "/dir2/b.txt"]
1241 .into_iter()
1242 .map(Path::new)
1243 .collect(),
1244 );
1245 assert_eq!(
1246 workspace
1247 .read(cx)
1248 .active_pane()
1249 .read(cx)
1250 .active_item()
1251 .unwrap()
1252 .title(cx),
1253 "b.txt"
1254 );
1255 });
1256 }
1257
1258 #[gpui::test]
1259 async fn test_save_conflicting_item(mut cx: gpui::TestAppContext) {
1260 let params = cx.update(WorkspaceParams::test);
1261 let fs = params.fs.as_fake();
1262 fs.insert_tree("/root", json!({ "a.txt": "" })).await;
1263
1264 let (window_id, workspace) = cx.add_window(|cx| Workspace::new(¶ms, cx));
1265 workspace
1266 .update(&mut cx, |workspace, cx| {
1267 workspace.add_worktree(Path::new("/root"), cx)
1268 })
1269 .await
1270 .unwrap();
1271
1272 // Open a file within an existing worktree.
1273 cx.update(|cx| {
1274 workspace.update(cx, |view, cx| {
1275 view.open_paths(&[PathBuf::from("/root/a.txt")], cx)
1276 })
1277 })
1278 .await;
1279 let editor = cx.read(|cx| {
1280 let pane = workspace.read(cx).active_pane().read(cx);
1281 let item = pane.active_item().unwrap();
1282 item.to_any().downcast::<Editor>().unwrap()
1283 });
1284
1285 cx.update(|cx| editor.update(cx, |editor, cx| editor.handle_input(&Input("x".into()), cx)));
1286 fs.insert_file("/root/a.txt", "changed".to_string())
1287 .await
1288 .unwrap();
1289 editor
1290 .condition(&cx, |editor, cx| editor.has_conflict(cx))
1291 .await;
1292 cx.read(|cx| assert!(editor.is_dirty(cx)));
1293
1294 cx.update(|cx| workspace.update(cx, |w, cx| w.save_active_item(&Save, cx)));
1295 cx.simulate_prompt_answer(window_id, 0);
1296 editor
1297 .condition(&cx, |editor, cx| !editor.is_dirty(cx))
1298 .await;
1299 cx.read(|cx| assert!(!editor.has_conflict(cx)));
1300 }
1301
1302 #[gpui::test]
1303 async fn test_open_and_save_new_file(mut cx: gpui::TestAppContext) {
1304 let params = cx.update(WorkspaceParams::test);
1305 params.fs.as_fake().insert_dir("/root").await.unwrap();
1306 let (_, workspace) = cx.add_window(|cx| Workspace::new(¶ms, cx));
1307 workspace
1308 .update(&mut cx, |workspace, cx| {
1309 workspace.add_worktree(Path::new("/root"), cx)
1310 })
1311 .await
1312 .unwrap();
1313 let worktree = cx.read(|cx| {
1314 workspace
1315 .read(cx)
1316 .worktrees(cx)
1317 .iter()
1318 .next()
1319 .unwrap()
1320 .clone()
1321 });
1322
1323 // Create a new untitled buffer
1324 let editor = workspace.update(&mut cx, |workspace, cx| {
1325 workspace.open_new_file(&OpenNew(params.clone()), cx);
1326 workspace
1327 .active_item(cx)
1328 .unwrap()
1329 .to_any()
1330 .downcast::<Editor>()
1331 .unwrap()
1332 });
1333
1334 editor.update(&mut cx, |editor, cx| {
1335 assert!(!editor.is_dirty(cx.as_ref()));
1336 assert_eq!(editor.title(cx.as_ref()), "untitled");
1337 assert!(editor.language(cx).is_none());
1338 editor.handle_input(&Input("hi".into()), cx);
1339 assert!(editor.is_dirty(cx.as_ref()));
1340 });
1341
1342 // Save the buffer. This prompts for a filename.
1343 workspace.update(&mut cx, |workspace, cx| {
1344 workspace.save_active_item(&Save, cx)
1345 });
1346 cx.simulate_new_path_selection(|parent_dir| {
1347 assert_eq!(parent_dir, Path::new("/root"));
1348 Some(parent_dir.join("the-new-name.rs"))
1349 });
1350 cx.read(|cx| {
1351 assert!(editor.is_dirty(cx));
1352 assert_eq!(editor.title(cx), "untitled");
1353 });
1354
1355 // When the save completes, the buffer's title is updated.
1356 editor
1357 .condition(&cx, |editor, cx| !editor.is_dirty(cx))
1358 .await;
1359 cx.read(|cx| {
1360 assert!(!editor.is_dirty(cx));
1361 assert_eq!(editor.title(cx), "the-new-name.rs");
1362 });
1363 // The language is assigned based on the path
1364 editor.read_with(&cx, |editor, cx| {
1365 assert_eq!(editor.language(cx).unwrap().name(), "Rust")
1366 });
1367
1368 // Edit the file and save it again. This time, there is no filename prompt.
1369 editor.update(&mut cx, |editor, cx| {
1370 editor.handle_input(&Input(" there".into()), cx);
1371 assert_eq!(editor.is_dirty(cx.as_ref()), true);
1372 });
1373 workspace.update(&mut cx, |workspace, cx| {
1374 workspace.save_active_item(&Save, cx)
1375 });
1376 assert!(!cx.did_prompt_for_new_path());
1377 editor
1378 .condition(&cx, |editor, cx| !editor.is_dirty(cx))
1379 .await;
1380 cx.read(|cx| assert_eq!(editor.title(cx), "the-new-name.rs"));
1381
1382 // Open the same newly-created file in another pane item. The new editor should reuse
1383 // the same buffer.
1384 workspace.update(&mut cx, |workspace, cx| {
1385 workspace.open_new_file(&OpenNew(params.clone()), cx);
1386 workspace.split_pane(workspace.active_pane().clone(), SplitDirection::Right, cx);
1387 assert!(workspace
1388 .open_entry(
1389 ProjectPath {
1390 worktree_id: worktree.id(),
1391 path: Path::new("the-new-name.rs").into()
1392 },
1393 cx
1394 )
1395 .is_none());
1396 });
1397 let editor2 = workspace.update(&mut cx, |workspace, cx| {
1398 workspace
1399 .active_item(cx)
1400 .unwrap()
1401 .to_any()
1402 .downcast::<Editor>()
1403 .unwrap()
1404 });
1405 cx.read(|cx| {
1406 assert_eq!(editor2.read(cx).buffer(), editor.read(cx).buffer());
1407 })
1408 }
1409
1410 #[gpui::test]
1411 async fn test_setting_language_when_saving_as_single_file_worktree(
1412 mut cx: gpui::TestAppContext,
1413 ) {
1414 let params = cx.update(WorkspaceParams::test);
1415 params.fs.as_fake().insert_dir("/root").await.unwrap();
1416 let (_, workspace) = cx.add_window(|cx| Workspace::new(¶ms, cx));
1417
1418 // Create a new untitled buffer
1419 let editor = workspace.update(&mut cx, |workspace, cx| {
1420 workspace.open_new_file(&OpenNew(params.clone()), cx);
1421 workspace
1422 .active_item(cx)
1423 .unwrap()
1424 .to_any()
1425 .downcast::<Editor>()
1426 .unwrap()
1427 });
1428
1429 editor.update(&mut cx, |editor, cx| {
1430 assert!(editor.language(cx).is_none());
1431 editor.handle_input(&Input("hi".into()), cx);
1432 assert!(editor.is_dirty(cx.as_ref()));
1433 });
1434
1435 // Save the buffer. This prompts for a filename.
1436 workspace.update(&mut cx, |workspace, cx| {
1437 workspace.save_active_item(&Save, cx)
1438 });
1439 cx.simulate_new_path_selection(|_| Some(PathBuf::from("/root/the-new-name.rs")));
1440
1441 editor
1442 .condition(&cx, |editor, cx| !editor.is_dirty(cx))
1443 .await;
1444
1445 // The language is assigned based on the path
1446 editor.read_with(&cx, |editor, cx| {
1447 assert_eq!(editor.language(cx).unwrap().name(), "Rust")
1448 });
1449 }
1450
1451 #[gpui::test]
1452 async fn test_pane_actions(mut cx: gpui::TestAppContext) {
1453 cx.update(|cx| pane::init(cx));
1454 let params = cx.update(WorkspaceParams::test);
1455 params
1456 .fs
1457 .as_fake()
1458 .insert_tree(
1459 "/root",
1460 json!({
1461 "a": {
1462 "file1": "contents 1",
1463 "file2": "contents 2",
1464 "file3": "contents 3",
1465 },
1466 }),
1467 )
1468 .await;
1469
1470 let (window_id, workspace) = cx.add_window(|cx| Workspace::new(¶ms, cx));
1471 workspace
1472 .update(&mut cx, |workspace, cx| {
1473 workspace.add_worktree(Path::new("/root"), cx)
1474 })
1475 .await
1476 .unwrap();
1477 cx.read(|cx| workspace.read(cx).worktree_scans_complete(cx))
1478 .await;
1479 let entries = cx.read(|cx| workspace.file_project_paths(cx));
1480 let file1 = entries[0].clone();
1481
1482 let pane_1 = cx.read(|cx| workspace.read(cx).active_pane().clone());
1483
1484 workspace
1485 .update(&mut cx, |w, cx| w.open_entry(file1.clone(), cx))
1486 .unwrap()
1487 .await;
1488 cx.read(|cx| {
1489 assert_eq!(
1490 pane_1.read(cx).active_item().unwrap().project_path(cx),
1491 Some(file1.clone())
1492 );
1493 });
1494
1495 cx.dispatch_action(
1496 window_id,
1497 vec![pane_1.id()],
1498 pane::Split(SplitDirection::Right),
1499 );
1500 cx.update(|cx| {
1501 let pane_2 = workspace.read(cx).active_pane().clone();
1502 assert_ne!(pane_1, pane_2);
1503
1504 let pane2_item = pane_2.read(cx).active_item().unwrap();
1505 assert_eq!(pane2_item.project_path(cx.as_ref()), Some(file1.clone()));
1506
1507 cx.dispatch_action(window_id, vec![pane_2.id()], &CloseActiveItem);
1508 let workspace = workspace.read(cx);
1509 assert_eq!(workspace.panes.len(), 1);
1510 assert_eq!(workspace.active_pane(), &pane_1);
1511 });
1512 }
1513}