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::test());
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, |_, project, cx| {
580 if project.read(cx).is_read_only() {
581 cx.blur();
582 }
583 cx.notify()
584 })
585 .detach();
586
587 let pane = cx.add_view(|_| Pane::new(params.settings.clone()));
588 let pane_id = pane.id();
589 cx.observe(&pane, move |me, _, cx| {
590 let active_entry = me.active_project_path(cx);
591 me.project
592 .update(cx, |project, cx| project.set_active_path(active_entry, cx));
593 })
594 .detach();
595 cx.subscribe(&pane, move |me, _, event, cx| {
596 me.handle_pane_event(pane_id, event, cx)
597 })
598 .detach();
599 cx.focus(&pane);
600
601 let status_bar = cx.add_view(|cx| StatusBar::new(&pane, params.settings.clone(), cx));
602 let mut current_user = params.user_store.read(cx).watch_current_user().clone();
603 let mut connection_status = params.client.status().clone();
604 let _observe_current_user = cx.spawn_weak(|this, mut cx| async move {
605 current_user.recv().await;
606 connection_status.recv().await;
607 let mut stream =
608 Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
609
610 while stream.recv().await.is_some() {
611 cx.update(|cx| {
612 if let Some(this) = this.upgrade(cx) {
613 this.update(cx, |_, cx| cx.notify());
614 }
615 })
616 }
617 });
618
619 Workspace {
620 modal: None,
621 weak_self: cx.weak_handle(),
622 center: PaneGroup::new(pane.clone()),
623 panes: vec![pane.clone()],
624 active_pane: pane.clone(),
625 status_bar,
626 settings: params.settings.clone(),
627 client: params.client.clone(),
628 user_store: params.user_store.clone(),
629 fs: params.fs.clone(),
630 left_sidebar: Sidebar::new(Side::Left),
631 right_sidebar: Sidebar::new(Side::Right),
632 project: params.project.clone(),
633 path_openers: params.path_openers.clone(),
634 items: Default::default(),
635 _observe_current_user,
636 }
637 }
638
639 pub fn weak_handle(&self) -> WeakViewHandle<Self> {
640 self.weak_self.clone()
641 }
642
643 pub fn settings(&self) -> watch::Receiver<Settings> {
644 self.settings.clone()
645 }
646
647 pub fn left_sidebar_mut(&mut self) -> &mut Sidebar {
648 &mut self.left_sidebar
649 }
650
651 pub fn right_sidebar_mut(&mut self) -> &mut Sidebar {
652 &mut self.right_sidebar
653 }
654
655 pub fn status_bar(&self) -> &ViewHandle<StatusBar> {
656 &self.status_bar
657 }
658
659 pub fn project(&self) -> &ModelHandle<Project> {
660 &self.project
661 }
662
663 pub fn worktrees<'a>(
664 &self,
665 cx: &'a AppContext,
666 ) -> impl 'a + Iterator<Item = ModelHandle<Worktree>> {
667 self.project.read(cx).worktrees(cx)
668 }
669
670 pub fn contains_paths(&self, paths: &[PathBuf], cx: &AppContext) -> bool {
671 paths.iter().all(|path| self.contains_path(&path, cx))
672 }
673
674 pub fn contains_path(&self, path: &Path, cx: &AppContext) -> bool {
675 for worktree in self.worktrees(cx) {
676 let worktree = worktree.read(cx).as_local();
677 if worktree.map_or(false, |w| w.contains_abs_path(path)) {
678 return true;
679 }
680 }
681 false
682 }
683
684 pub fn worktree_scans_complete(&self, cx: &AppContext) -> impl Future<Output = ()> + 'static {
685 let futures = self
686 .worktrees(cx)
687 .filter_map(|worktree| worktree.read(cx).as_local())
688 .map(|worktree| worktree.scan_complete())
689 .collect::<Vec<_>>();
690 async move {
691 for future in futures {
692 future.await;
693 }
694 }
695 }
696
697 pub fn open_paths(
698 &mut self,
699 abs_paths: &[PathBuf],
700 cx: &mut ViewContext<Self>,
701 ) -> Task<Vec<Option<Result<Box<dyn ItemViewHandle>, Arc<anyhow::Error>>>>> {
702 let entries = abs_paths
703 .iter()
704 .cloned()
705 .map(|path| self.project_path_for_path(&path, cx))
706 .collect::<Vec<_>>();
707
708 let fs = self.fs.clone();
709 let tasks = abs_paths
710 .iter()
711 .cloned()
712 .zip(entries.into_iter())
713 .map(|(abs_path, project_path)| {
714 cx.spawn(|this, mut cx| {
715 let fs = fs.clone();
716 async move {
717 let project_path = project_path.await.ok()?;
718 if fs.is_file(&abs_path).await {
719 Some(
720 this.update(&mut cx, |this, cx| this.open_path(project_path, cx))
721 .await,
722 )
723 } else {
724 None
725 }
726 }
727 })
728 })
729 .collect::<Vec<_>>();
730
731 cx.foreground().spawn(async move {
732 let mut items = Vec::new();
733 for task in tasks {
734 items.push(task.await);
735 }
736 items
737 })
738 }
739
740 fn project_path_for_path(
741 &self,
742 abs_path: &Path,
743 cx: &mut ViewContext<Self>,
744 ) -> Task<Result<ProjectPath>> {
745 let entry = self.project().update(cx, |project, cx| {
746 project.find_or_create_local_worktree(abs_path, true, cx)
747 });
748 cx.spawn(|_, cx| async move {
749 let (worktree, path) = entry.await?;
750 Ok(ProjectPath {
751 worktree_id: worktree.read_with(&cx, |t, _| t.id()),
752 path: path.into(),
753 })
754 })
755 }
756
757 // Returns the model that was toggled closed if it was open
758 pub fn toggle_modal<V, F>(
759 &mut self,
760 cx: &mut ViewContext<Self>,
761 add_view: F,
762 ) -> Option<ViewHandle<V>>
763 where
764 V: 'static + View,
765 F: FnOnce(&mut ViewContext<Self>, &mut Self) -> ViewHandle<V>,
766 {
767 cx.notify();
768 // Whatever modal was visible is getting clobbered. If its the same type as V, then return
769 // it. Otherwise, create a new modal and set it as active.
770 let already_open_modal = self.modal.take().and_then(|modal| modal.downcast::<V>());
771 if let Some(already_open_modal) = already_open_modal {
772 cx.focus_self();
773 Some(already_open_modal)
774 } else {
775 let modal = add_view(cx, self);
776 cx.focus(&modal);
777 self.modal = Some(modal.into());
778 None
779 }
780 }
781
782 pub fn modal(&self) -> Option<&AnyViewHandle> {
783 self.modal.as_ref()
784 }
785
786 pub fn dismiss_modal(&mut self, cx: &mut ViewContext<Self>) {
787 if self.modal.take().is_some() {
788 cx.focus(&self.active_pane);
789 cx.notify();
790 }
791 }
792
793 pub fn open_path(
794 &mut self,
795 path: ProjectPath,
796 cx: &mut ViewContext<Self>,
797 ) -> Task<Result<Box<dyn ItemViewHandle>, Arc<anyhow::Error>>> {
798 let load_task = self.load_path(path, cx);
799 let pane = self.active_pane().clone().downgrade();
800 cx.spawn(|this, mut cx| async move {
801 let item = load_task.await?;
802 this.update(&mut cx, |this, cx| {
803 let pane = pane
804 .upgrade(cx)
805 .ok_or_else(|| anyhow!("could not upgrade pane reference"))?;
806 Ok(this.open_item_in_pane(item, &pane, cx))
807 })
808 })
809 }
810
811 pub fn load_path(
812 &mut self,
813 path: ProjectPath,
814 cx: &mut ViewContext<Self>,
815 ) -> Task<Result<Box<dyn ItemHandle>>> {
816 if let Some(existing_item) = self.item_for_path(&path, cx) {
817 return Task::ready(Ok(existing_item));
818 }
819
820 let project_path = path.clone();
821 let path_openers = self.path_openers.clone();
822 self.project.update(cx, |project, cx| {
823 for opener in path_openers.iter() {
824 if let Some(task) = opener.open(project, project_path.clone(), cx) {
825 return task;
826 }
827 }
828 Task::ready(Err(anyhow!("no opener found for path {:?}", project_path)))
829 })
830 }
831
832 fn item_for_path(&self, path: &ProjectPath, cx: &AppContext) -> Option<Box<dyn ItemHandle>> {
833 self.items
834 .values()
835 .filter_map(|i| i.upgrade(cx))
836 .find(|i| i.project_path(cx).as_ref() == Some(path))
837 }
838
839 pub fn item_of_type<T: Item>(&self, cx: &AppContext) -> Option<ModelHandle<T>> {
840 self.items
841 .values()
842 .find_map(|i| i.upgrade(cx).and_then(|i| i.to_any().downcast()))
843 }
844
845 pub fn items_of_type<'a, T: Item>(
846 &'a self,
847 cx: &'a AppContext,
848 ) -> impl 'a + Iterator<Item = ModelHandle<T>> {
849 self.items
850 .values()
851 .filter_map(|i| i.upgrade(cx).and_then(|i| i.to_any().downcast()))
852 }
853
854 pub fn active_item(&self, cx: &AppContext) -> Option<Box<dyn ItemViewHandle>> {
855 self.active_pane().read(cx).active_item()
856 }
857
858 fn active_project_path(&self, cx: &ViewContext<Self>) -> Option<ProjectPath> {
859 self.active_item(cx).and_then(|item| item.project_path(cx))
860 }
861
862 pub fn save_active_item(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<()>> {
863 let project = self.project.clone();
864 if let Some(item) = self.active_item(cx) {
865 if item.can_save(cx) {
866 if item.has_conflict(cx.as_ref()) {
867 const CONFLICT_MESSAGE: &'static str = "This file has changed on disk since you started editing it. Do you want to overwrite it?";
868
869 let mut answer = cx.prompt(
870 PromptLevel::Warning,
871 CONFLICT_MESSAGE,
872 &["Overwrite", "Cancel"],
873 );
874 cx.spawn(|_, mut cx| async move {
875 let answer = answer.recv().await;
876 if answer == Some(0) {
877 cx.update(|cx| item.save(project, cx)).await?;
878 }
879 Ok(())
880 })
881 } else {
882 item.save(project, cx)
883 }
884 } else if item.can_save_as(cx) {
885 let worktree = self.worktrees(cx).next();
886 let start_abs_path = worktree
887 .and_then(|w| w.read(cx).as_local())
888 .map_or(Path::new(""), |w| w.abs_path())
889 .to_path_buf();
890 let mut abs_path = cx.prompt_for_new_path(&start_abs_path);
891 cx.spawn(|_, mut cx| async move {
892 if let Some(abs_path) = abs_path.recv().await.flatten() {
893 cx.update(|cx| item.save_as(project, abs_path, cx)).await?;
894 }
895 Ok(())
896 })
897 } else {
898 Task::ready(Ok(()))
899 }
900 } else {
901 Task::ready(Ok(()))
902 }
903 }
904
905 pub fn toggle_sidebar_item(&mut self, action: &ToggleSidebarItem, cx: &mut ViewContext<Self>) {
906 let sidebar = match action.0.side {
907 Side::Left => &mut self.left_sidebar,
908 Side::Right => &mut self.right_sidebar,
909 };
910 sidebar.toggle_item(action.0.item_index);
911 if let Some(active_item) = sidebar.active_item() {
912 cx.focus(active_item);
913 } else {
914 cx.focus_self();
915 }
916 cx.notify();
917 }
918
919 pub fn toggle_sidebar_item_focus(
920 &mut self,
921 action: &ToggleSidebarItemFocus,
922 cx: &mut ViewContext<Self>,
923 ) {
924 let sidebar = match action.0.side {
925 Side::Left => &mut self.left_sidebar,
926 Side::Right => &mut self.right_sidebar,
927 };
928 sidebar.activate_item(action.0.item_index);
929 if let Some(active_item) = sidebar.active_item() {
930 if active_item.is_focused(cx) {
931 cx.focus_self();
932 } else {
933 cx.focus(active_item);
934 }
935 }
936 cx.notify();
937 }
938
939 pub fn debug_elements(&mut self, _: &DebugElements, cx: &mut ViewContext<Self>) {
940 match to_string_pretty(&cx.debug_elements()) {
941 Ok(json) => {
942 let kib = json.len() as f32 / 1024.;
943 cx.as_mut().write_to_clipboard(ClipboardItem::new(json));
944 log::info!(
945 "copied {:.1} KiB of element debug JSON to the clipboard",
946 kib
947 );
948 }
949 Err(error) => {
950 log::error!("error debugging elements: {}", error);
951 }
952 };
953 }
954
955 fn add_pane(&mut self, cx: &mut ViewContext<Self>) -> ViewHandle<Pane> {
956 let pane = cx.add_view(|_| Pane::new(self.settings.clone()));
957 let pane_id = pane.id();
958 cx.observe(&pane, move |me, _, cx| {
959 let active_entry = me.active_project_path(cx);
960 me.project
961 .update(cx, |project, cx| project.set_active_path(active_entry, cx));
962 })
963 .detach();
964 cx.subscribe(&pane, move |me, _, event, cx| {
965 me.handle_pane_event(pane_id, event, cx)
966 })
967 .detach();
968 self.panes.push(pane.clone());
969 self.activate_pane(pane.clone(), cx);
970 pane
971 }
972
973 pub fn open_item<T>(
974 &mut self,
975 item_handle: T,
976 cx: &mut ViewContext<Self>,
977 ) -> Box<dyn ItemViewHandle>
978 where
979 T: 'static + ItemHandle,
980 {
981 self.open_item_in_pane(item_handle, &self.active_pane().clone(), cx)
982 }
983
984 pub fn open_item_in_pane<T>(
985 &mut self,
986 item_handle: T,
987 pane: &ViewHandle<Pane>,
988 cx: &mut ViewContext<Self>,
989 ) -> Box<dyn ItemViewHandle>
990 where
991 T: 'static + ItemHandle,
992 {
993 self.items
994 .insert(Reverse(item_handle.id()), item_handle.downgrade());
995 pane.update(cx, |pane, cx| pane.open_item(item_handle, self, cx))
996 }
997
998 pub fn activate_pane_for_item(
999 &mut self,
1000 item: &dyn ItemHandle,
1001 cx: &mut ViewContext<Self>,
1002 ) -> bool {
1003 let pane = self.panes.iter().find_map(|pane| {
1004 if pane.read(cx).contains_item(item) {
1005 Some(pane.clone())
1006 } else {
1007 None
1008 }
1009 });
1010 if let Some(pane) = pane {
1011 self.activate_pane(pane.clone(), cx);
1012 true
1013 } else {
1014 false
1015 }
1016 }
1017
1018 pub fn activate_item(&mut self, item: &dyn ItemHandle, cx: &mut ViewContext<Self>) -> bool {
1019 let result = self.panes.iter().find_map(|pane| {
1020 if let Some(ix) = pane.read(cx).index_for_item(item) {
1021 Some((pane.clone(), ix))
1022 } else {
1023 None
1024 }
1025 });
1026 if let Some((pane, ix)) = result {
1027 self.activate_pane(pane.clone(), cx);
1028 pane.update(cx, |pane, cx| pane.activate_item(ix, cx));
1029 true
1030 } else {
1031 false
1032 }
1033 }
1034
1035 pub fn activate_next_pane(&mut self, cx: &mut ViewContext<Self>) {
1036 let ix = self
1037 .panes
1038 .iter()
1039 .position(|pane| pane == &self.active_pane)
1040 .unwrap();
1041 let next_ix = (ix + 1) % self.panes.len();
1042 self.activate_pane(self.panes[next_ix].clone(), cx);
1043 }
1044
1045 fn activate_pane(&mut self, pane: ViewHandle<Pane>, cx: &mut ViewContext<Self>) {
1046 if self.active_pane != pane {
1047 self.active_pane = pane;
1048 self.status_bar.update(cx, |status_bar, cx| {
1049 status_bar.set_active_pane(&self.active_pane, cx);
1050 });
1051 cx.focus(&self.active_pane);
1052 cx.notify();
1053 }
1054 }
1055
1056 fn handle_pane_event(
1057 &mut self,
1058 pane_id: usize,
1059 event: &pane::Event,
1060 cx: &mut ViewContext<Self>,
1061 ) {
1062 if let Some(pane) = self.pane(pane_id) {
1063 match event {
1064 pane::Event::Split(direction) => {
1065 self.split_pane(pane, *direction, cx);
1066 }
1067 pane::Event::Remove => {
1068 self.remove_pane(pane, cx);
1069 }
1070 pane::Event::Activate => {
1071 self.activate_pane(pane, cx);
1072 }
1073 }
1074 } else {
1075 error!("pane {} not found", pane_id);
1076 }
1077 }
1078
1079 pub fn split_pane(
1080 &mut self,
1081 pane: ViewHandle<Pane>,
1082 direction: SplitDirection,
1083 cx: &mut ViewContext<Self>,
1084 ) -> ViewHandle<Pane> {
1085 let new_pane = self.add_pane(cx);
1086 self.activate_pane(new_pane.clone(), cx);
1087 if let Some(item) = pane.read(cx).active_item() {
1088 let nav_history = new_pane.read(cx).nav_history().clone();
1089 if let Some(clone) = item.clone_on_split(nav_history, cx.as_mut()) {
1090 let item = clone.item(cx).downgrade();
1091 self.items.insert(Reverse(item.id()), item);
1092 new_pane.update(cx, |new_pane, cx| new_pane.add_item_view(clone, cx));
1093 }
1094 }
1095 self.center.split(&pane, &new_pane, direction).unwrap();
1096 cx.notify();
1097 new_pane
1098 }
1099
1100 fn remove_pane(&mut self, pane: ViewHandle<Pane>, cx: &mut ViewContext<Self>) {
1101 if self.center.remove(&pane).unwrap() {
1102 self.panes.retain(|p| p != &pane);
1103 self.activate_pane(self.panes.last().unwrap().clone(), cx);
1104 }
1105 }
1106
1107 pub fn panes(&self) -> &[ViewHandle<Pane>] {
1108 &self.panes
1109 }
1110
1111 fn pane(&self, pane_id: usize) -> Option<ViewHandle<Pane>> {
1112 self.panes.iter().find(|pane| pane.id() == pane_id).cloned()
1113 }
1114
1115 pub fn active_pane(&self) -> &ViewHandle<Pane> {
1116 &self.active_pane
1117 }
1118
1119 fn toggle_share(&mut self, _: &ToggleShare, cx: &mut ViewContext<Self>) {
1120 self.project.update(cx, |project, cx| {
1121 if project.is_local() {
1122 if project.is_shared() {
1123 project.unshare(cx).detach();
1124 } else {
1125 project.share(cx).detach();
1126 }
1127 }
1128 });
1129 }
1130
1131 fn render_connection_status(&self) -> Option<ElementBox> {
1132 let theme = &self.settings.borrow().theme;
1133 match &*self.client.status().borrow() {
1134 client::Status::ConnectionError
1135 | client::Status::ConnectionLost
1136 | client::Status::Reauthenticating
1137 | client::Status::Reconnecting { .. }
1138 | client::Status::ReconnectionError { .. } => Some(
1139 Container::new(
1140 Align::new(
1141 ConstrainedBox::new(
1142 Svg::new("icons/offline-14.svg")
1143 .with_color(theme.workspace.titlebar.offline_icon.color)
1144 .boxed(),
1145 )
1146 .with_width(theme.workspace.titlebar.offline_icon.width)
1147 .boxed(),
1148 )
1149 .boxed(),
1150 )
1151 .with_style(theme.workspace.titlebar.offline_icon.container)
1152 .boxed(),
1153 ),
1154 client::Status::UpgradeRequired => Some(
1155 Label::new(
1156 "Please update Zed to collaborate".to_string(),
1157 theme.workspace.titlebar.outdated_warning.text.clone(),
1158 )
1159 .contained()
1160 .with_style(theme.workspace.titlebar.outdated_warning.container)
1161 .aligned()
1162 .boxed(),
1163 ),
1164 _ => None,
1165 }
1166 }
1167
1168 fn render_titlebar(&self, theme: &Theme, cx: &mut RenderContext<Self>) -> ElementBox {
1169 ConstrainedBox::new(
1170 Container::new(
1171 Stack::new()
1172 .with_child(
1173 Align::new(
1174 Label::new("zed".into(), theme.workspace.titlebar.title.clone())
1175 .boxed(),
1176 )
1177 .boxed(),
1178 )
1179 .with_child(
1180 Align::new(
1181 Flex::row()
1182 .with_children(self.render_share_icon(theme, cx))
1183 .with_children(self.render_collaborators(theme, cx))
1184 .with_child(self.render_current_user(
1185 self.user_store.read(cx).current_user().as_ref(),
1186 self.project.read(cx).replica_id(),
1187 theme,
1188 cx,
1189 ))
1190 .with_children(self.render_connection_status())
1191 .boxed(),
1192 )
1193 .right()
1194 .boxed(),
1195 )
1196 .boxed(),
1197 )
1198 .with_style(theme.workspace.titlebar.container)
1199 .boxed(),
1200 )
1201 .with_height(theme.workspace.titlebar.height)
1202 .named("titlebar")
1203 }
1204
1205 fn render_collaborators(&self, theme: &Theme, cx: &mut RenderContext<Self>) -> Vec<ElementBox> {
1206 let mut collaborators = self
1207 .project
1208 .read(cx)
1209 .collaborators()
1210 .values()
1211 .cloned()
1212 .collect::<Vec<_>>();
1213 collaborators.sort_unstable_by_key(|collaborator| collaborator.replica_id);
1214 collaborators
1215 .into_iter()
1216 .filter_map(|collaborator| {
1217 Some(self.render_avatar(
1218 collaborator.user.avatar.clone()?,
1219 collaborator.replica_id,
1220 theme,
1221 ))
1222 })
1223 .collect()
1224 }
1225
1226 fn render_current_user(
1227 &self,
1228 user: Option<&Arc<User>>,
1229 replica_id: ReplicaId,
1230 theme: &Theme,
1231 cx: &mut RenderContext<Self>,
1232 ) -> ElementBox {
1233 if let Some(avatar) = user.and_then(|user| user.avatar.clone()) {
1234 self.render_avatar(avatar, replica_id, theme)
1235 } else {
1236 MouseEventHandler::new::<Authenticate, _, _>(0, cx, |state, _| {
1237 let style = if state.hovered {
1238 &theme.workspace.titlebar.hovered_sign_in_prompt
1239 } else {
1240 &theme.workspace.titlebar.sign_in_prompt
1241 };
1242 Label::new("Sign in".to_string(), style.text.clone())
1243 .contained()
1244 .with_style(style.container)
1245 .boxed()
1246 })
1247 .on_click(|cx| cx.dispatch_action(Authenticate))
1248 .with_cursor_style(CursorStyle::PointingHand)
1249 .aligned()
1250 .boxed()
1251 }
1252 }
1253
1254 fn render_avatar(
1255 &self,
1256 avatar: Arc<ImageData>,
1257 replica_id: ReplicaId,
1258 theme: &Theme,
1259 ) -> ElementBox {
1260 ConstrainedBox::new(
1261 Stack::new()
1262 .with_child(
1263 ConstrainedBox::new(
1264 Image::new(avatar)
1265 .with_style(theme.workspace.titlebar.avatar)
1266 .boxed(),
1267 )
1268 .with_width(theme.workspace.titlebar.avatar_width)
1269 .aligned()
1270 .boxed(),
1271 )
1272 .with_child(
1273 AvatarRibbon::new(theme.editor.replica_selection_style(replica_id).cursor)
1274 .constrained()
1275 .with_width(theme.workspace.titlebar.avatar_ribbon.width)
1276 .with_height(theme.workspace.titlebar.avatar_ribbon.height)
1277 .aligned()
1278 .bottom()
1279 .boxed(),
1280 )
1281 .boxed(),
1282 )
1283 .with_width(theme.workspace.right_sidebar.width)
1284 .boxed()
1285 }
1286
1287 fn render_share_icon(&self, theme: &Theme, cx: &mut RenderContext<Self>) -> Option<ElementBox> {
1288 if self.project().read(cx).is_local() && self.client.user_id().is_some() {
1289 enum Share {}
1290
1291 let color = if self.project().read(cx).is_shared() {
1292 theme.workspace.titlebar.share_icon_active_color
1293 } else {
1294 theme.workspace.titlebar.share_icon_color
1295 };
1296 Some(
1297 MouseEventHandler::new::<Share, _, _>(0, cx, |_, _| {
1298 Align::new(
1299 ConstrainedBox::new(
1300 Svg::new("icons/broadcast-24.svg").with_color(color).boxed(),
1301 )
1302 .with_width(24.)
1303 .boxed(),
1304 )
1305 .boxed()
1306 })
1307 .with_cursor_style(CursorStyle::PointingHand)
1308 .on_click(|cx| cx.dispatch_action(ToggleShare))
1309 .boxed(),
1310 )
1311 } else {
1312 None
1313 }
1314 }
1315
1316 fn render_disconnected_overlay(&self, cx: &AppContext) -> Option<ElementBox> {
1317 if self.project.read(cx).is_read_only() {
1318 let theme = &self.settings.borrow().theme;
1319 Some(
1320 EventHandler::new(
1321 Label::new(
1322 "Your connection to the remote project has been lost.".to_string(),
1323 theme.workspace.disconnected_overlay.text.clone(),
1324 )
1325 .aligned()
1326 .contained()
1327 .with_style(theme.workspace.disconnected_overlay.container)
1328 .boxed(),
1329 )
1330 .capture(|_, _, _| true)
1331 .boxed(),
1332 )
1333 } else {
1334 None
1335 }
1336 }
1337}
1338
1339impl Entity for Workspace {
1340 type Event = ();
1341}
1342
1343impl View for Workspace {
1344 fn ui_name() -> &'static str {
1345 "Workspace"
1346 }
1347
1348 fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
1349 let settings = self.settings.borrow();
1350 let theme = &settings.theme;
1351 Stack::new()
1352 .with_child(
1353 Flex::column()
1354 .with_child(self.render_titlebar(&theme, cx))
1355 .with_child(
1356 Stack::new()
1357 .with_child({
1358 let mut content = Flex::row();
1359 content.add_child(self.left_sidebar.render(&settings, cx));
1360 if let Some(element) =
1361 self.left_sidebar.render_active_item(&settings, cx)
1362 {
1363 content.add_child(Flexible::new(0.8, false, element).boxed());
1364 }
1365 content.add_child(
1366 Flex::column()
1367 .with_child(
1368 Flexible::new(
1369 1.,
1370 true,
1371 self.center.render(&settings.theme),
1372 )
1373 .boxed(),
1374 )
1375 .with_child(ChildView::new(&self.status_bar).boxed())
1376 .flexible(1., true)
1377 .boxed(),
1378 );
1379 if let Some(element) =
1380 self.right_sidebar.render_active_item(&settings, cx)
1381 {
1382 content.add_child(Flexible::new(0.8, false, element).boxed());
1383 }
1384 content.add_child(self.right_sidebar.render(&settings, cx));
1385 content.boxed()
1386 })
1387 .with_children(self.modal.as_ref().map(|m| ChildView::new(m).boxed()))
1388 .flexible(1.0, true)
1389 .boxed(),
1390 )
1391 .contained()
1392 .with_background_color(settings.theme.workspace.background)
1393 .boxed(),
1394 )
1395 .with_children(self.render_disconnected_overlay(cx))
1396 .named("workspace")
1397 }
1398
1399 fn on_focus(&mut self, cx: &mut ViewContext<Self>) {
1400 cx.focus(&self.active_pane);
1401 }
1402}
1403
1404pub trait WorkspaceHandle {
1405 fn file_project_paths(&self, cx: &AppContext) -> Vec<ProjectPath>;
1406}
1407
1408impl WorkspaceHandle for ViewHandle<Workspace> {
1409 fn file_project_paths(&self, cx: &AppContext) -> Vec<ProjectPath> {
1410 self.read(cx)
1411 .worktrees(cx)
1412 .flat_map(|worktree| {
1413 let worktree_id = worktree.read(cx).id();
1414 worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
1415 worktree_id,
1416 path: f.path.clone(),
1417 })
1418 })
1419 .collect::<Vec<_>>()
1420 }
1421}
1422
1423pub struct AvatarRibbon {
1424 color: Color,
1425}
1426
1427impl AvatarRibbon {
1428 pub fn new(color: Color) -> AvatarRibbon {
1429 AvatarRibbon { color }
1430 }
1431}
1432
1433impl Element for AvatarRibbon {
1434 type LayoutState = ();
1435
1436 type PaintState = ();
1437
1438 fn layout(
1439 &mut self,
1440 constraint: gpui::SizeConstraint,
1441 _: &mut gpui::LayoutContext,
1442 ) -> (gpui::geometry::vector::Vector2F, Self::LayoutState) {
1443 (constraint.max, ())
1444 }
1445
1446 fn paint(
1447 &mut self,
1448 bounds: gpui::geometry::rect::RectF,
1449 _: gpui::geometry::rect::RectF,
1450 _: &mut Self::LayoutState,
1451 cx: &mut gpui::PaintContext,
1452 ) -> Self::PaintState {
1453 let mut path = PathBuilder::new();
1454 path.reset(bounds.lower_left());
1455 path.curve_to(
1456 bounds.origin() + vec2f(bounds.height(), 0.),
1457 bounds.origin(),
1458 );
1459 path.line_to(bounds.upper_right() - vec2f(bounds.height(), 0.));
1460 path.curve_to(bounds.lower_right(), bounds.upper_right());
1461 path.line_to(bounds.lower_left());
1462 cx.scene.push_path(path.build(self.color, None));
1463 }
1464
1465 fn dispatch_event(
1466 &mut self,
1467 _: &gpui::Event,
1468 _: gpui::geometry::rect::RectF,
1469 _: &mut Self::LayoutState,
1470 _: &mut Self::PaintState,
1471 _: &mut gpui::EventContext,
1472 ) -> bool {
1473 false
1474 }
1475
1476 fn debug(
1477 &self,
1478 bounds: gpui::geometry::rect::RectF,
1479 _: &Self::LayoutState,
1480 _: &Self::PaintState,
1481 _: &gpui::DebugContext,
1482 ) -> gpui::json::Value {
1483 json::json!({
1484 "type": "AvatarRibbon",
1485 "bounds": bounds.to_json(),
1486 "color": self.color.to_json(),
1487 })
1488 }
1489}
1490
1491impl std::fmt::Debug for OpenParams {
1492 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1493 f.debug_struct("OpenParams")
1494 .field("paths", &self.paths)
1495 .finish()
1496 }
1497}
1498
1499fn open(action: &Open, cx: &mut MutableAppContext) {
1500 let app_state = action.0.clone();
1501 let mut paths = cx.prompt_for_paths(PathPromptOptions {
1502 files: true,
1503 directories: true,
1504 multiple: true,
1505 });
1506 cx.spawn(|mut cx| async move {
1507 if let Some(paths) = paths.recv().await.flatten() {
1508 cx.update(|cx| cx.dispatch_global_action(OpenPaths(OpenParams { paths, app_state })));
1509 }
1510 })
1511 .detach();
1512}
1513
1514pub fn open_paths(
1515 abs_paths: &[PathBuf],
1516 app_state: &Arc<AppState>,
1517 cx: &mut MutableAppContext,
1518) -> Task<ViewHandle<Workspace>> {
1519 log::info!("open paths {:?}", abs_paths);
1520
1521 // Open paths in existing workspace if possible
1522 let mut existing = None;
1523 for window_id in cx.window_ids().collect::<Vec<_>>() {
1524 if let Some(workspace_handle) = cx.root_view::<Workspace>(window_id) {
1525 if workspace_handle.update(cx, |workspace, cx| {
1526 if workspace.contains_paths(abs_paths, cx.as_ref()) {
1527 cx.activate_window(window_id);
1528 existing = Some(workspace_handle.clone());
1529 true
1530 } else {
1531 false
1532 }
1533 }) {
1534 break;
1535 }
1536 }
1537 }
1538
1539 let workspace = existing.unwrap_or_else(|| {
1540 cx.add_window((app_state.build_window_options)(), |cx| {
1541 let project = Project::local(
1542 app_state.client.clone(),
1543 app_state.user_store.clone(),
1544 app_state.languages.clone(),
1545 app_state.fs.clone(),
1546 cx,
1547 );
1548 (app_state.build_workspace)(project, &app_state, cx)
1549 })
1550 .1
1551 });
1552
1553 let task = workspace.update(cx, |workspace, cx| workspace.open_paths(abs_paths, cx));
1554 cx.spawn(|_| async move {
1555 task.await;
1556 workspace
1557 })
1558}
1559
1560pub fn join_project(
1561 project_id: u64,
1562 app_state: &Arc<AppState>,
1563 cx: &mut MutableAppContext,
1564) -> Task<Result<ViewHandle<Workspace>>> {
1565 for window_id in cx.window_ids().collect::<Vec<_>>() {
1566 if let Some(workspace) = cx.root_view::<Workspace>(window_id) {
1567 if workspace.read(cx).project().read(cx).remote_id() == Some(project_id) {
1568 return Task::ready(Ok(workspace));
1569 }
1570 }
1571 }
1572
1573 let app_state = app_state.clone();
1574 cx.spawn(|mut cx| async move {
1575 let project = Project::remote(
1576 project_id,
1577 app_state.client.clone(),
1578 app_state.user_store.clone(),
1579 app_state.languages.clone(),
1580 app_state.fs.clone(),
1581 &mut cx,
1582 )
1583 .await?;
1584 let (_, workspace) = cx.update(|cx| {
1585 cx.add_window((app_state.build_window_options)(), |cx| {
1586 (app_state.build_workspace)(project, &app_state, cx)
1587 })
1588 });
1589 Ok(workspace)
1590 })
1591}
1592
1593fn open_new(app_state: &Arc<AppState>, cx: &mut MutableAppContext) {
1594 let (window_id, workspace) = cx.add_window((app_state.build_window_options)(), |cx| {
1595 let project = Project::local(
1596 app_state.client.clone(),
1597 app_state.user_store.clone(),
1598 app_state.languages.clone(),
1599 app_state.fs.clone(),
1600 cx,
1601 );
1602 (app_state.build_workspace)(project, &app_state, cx)
1603 });
1604 cx.dispatch_action(window_id, vec![workspace.id()], &OpenNew(app_state.clone()));
1605}