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