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