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