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