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