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