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 }
1093 }
1094
1095 pub fn panes(&self) -> &[ViewHandle<Pane>] {
1096 &self.panes
1097 }
1098
1099 fn pane(&self, pane_id: usize) -> Option<ViewHandle<Pane>> {
1100 self.panes.iter().find(|pane| pane.id() == pane_id).cloned()
1101 }
1102
1103 pub fn active_pane(&self) -> &ViewHandle<Pane> {
1104 &self.active_pane
1105 }
1106
1107 fn toggle_share(&mut self, _: &ToggleShare, cx: &mut ViewContext<Self>) {
1108 self.project.update(cx, |project, cx| {
1109 if project.is_local() {
1110 if project.is_shared() {
1111 project.unshare(cx).detach();
1112 } else {
1113 project.share(cx).detach();
1114 }
1115 }
1116 });
1117 }
1118
1119 fn render_connection_status(&self, cx: &mut RenderContext<Self>) -> Option<ElementBox> {
1120 let theme = &cx.app_state::<Settings>().theme;
1121 match &*self.client.status().borrow() {
1122 client::Status::ConnectionError
1123 | client::Status::ConnectionLost
1124 | client::Status::Reauthenticating
1125 | client::Status::Reconnecting { .. }
1126 | client::Status::ReconnectionError { .. } => Some(
1127 Container::new(
1128 Align::new(
1129 ConstrainedBox::new(
1130 Svg::new("icons/offline-14.svg")
1131 .with_color(theme.workspace.titlebar.offline_icon.color)
1132 .boxed(),
1133 )
1134 .with_width(theme.workspace.titlebar.offline_icon.width)
1135 .boxed(),
1136 )
1137 .boxed(),
1138 )
1139 .with_style(theme.workspace.titlebar.offline_icon.container)
1140 .boxed(),
1141 ),
1142 client::Status::UpgradeRequired => Some(
1143 Label::new(
1144 "Please update Zed to collaborate".to_string(),
1145 theme.workspace.titlebar.outdated_warning.text.clone(),
1146 )
1147 .contained()
1148 .with_style(theme.workspace.titlebar.outdated_warning.container)
1149 .aligned()
1150 .boxed(),
1151 ),
1152 _ => None,
1153 }
1154 }
1155
1156 fn render_titlebar(&self, theme: &Theme, cx: &mut RenderContext<Self>) -> ElementBox {
1157 ConstrainedBox::new(
1158 Container::new(
1159 Stack::new()
1160 .with_child(
1161 Align::new(
1162 Label::new("zed".into(), theme.workspace.titlebar.title.clone())
1163 .boxed(),
1164 )
1165 .boxed(),
1166 )
1167 .with_child(
1168 Align::new(
1169 Flex::row()
1170 .with_children(self.render_share_icon(theme, cx))
1171 .with_children(self.render_collaborators(theme, cx))
1172 .with_child(self.render_current_user(
1173 self.user_store.read(cx).current_user().as_ref(),
1174 self.project.read(cx).replica_id(),
1175 theme,
1176 cx,
1177 ))
1178 .with_children(self.render_connection_status(cx))
1179 .boxed(),
1180 )
1181 .right()
1182 .boxed(),
1183 )
1184 .boxed(),
1185 )
1186 .with_style(theme.workspace.titlebar.container)
1187 .boxed(),
1188 )
1189 .with_height(theme.workspace.titlebar.height)
1190 .named("titlebar")
1191 }
1192
1193 fn render_collaborators(&self, theme: &Theme, cx: &mut RenderContext<Self>) -> Vec<ElementBox> {
1194 let mut collaborators = self
1195 .project
1196 .read(cx)
1197 .collaborators()
1198 .values()
1199 .cloned()
1200 .collect::<Vec<_>>();
1201 collaborators.sort_unstable_by_key(|collaborator| collaborator.replica_id);
1202 collaborators
1203 .into_iter()
1204 .filter_map(|collaborator| {
1205 Some(self.render_avatar(
1206 collaborator.user.avatar.clone()?,
1207 collaborator.replica_id,
1208 theme,
1209 ))
1210 })
1211 .collect()
1212 }
1213
1214 fn render_current_user(
1215 &self,
1216 user: Option<&Arc<User>>,
1217 replica_id: ReplicaId,
1218 theme: &Theme,
1219 cx: &mut RenderContext<Self>,
1220 ) -> ElementBox {
1221 if let Some(avatar) = user.and_then(|user| user.avatar.clone()) {
1222 self.render_avatar(avatar, replica_id, theme)
1223 } else {
1224 MouseEventHandler::new::<Authenticate, _, _>(0, cx, |state, _| {
1225 let style = if state.hovered {
1226 &theme.workspace.titlebar.hovered_sign_in_prompt
1227 } else {
1228 &theme.workspace.titlebar.sign_in_prompt
1229 };
1230 Label::new("Sign in".to_string(), style.text.clone())
1231 .contained()
1232 .with_style(style.container)
1233 .boxed()
1234 })
1235 .on_click(|cx| cx.dispatch_action(Authenticate))
1236 .with_cursor_style(CursorStyle::PointingHand)
1237 .aligned()
1238 .boxed()
1239 }
1240 }
1241
1242 fn render_avatar(
1243 &self,
1244 avatar: Arc<ImageData>,
1245 replica_id: ReplicaId,
1246 theme: &Theme,
1247 ) -> ElementBox {
1248 ConstrainedBox::new(
1249 Stack::new()
1250 .with_child(
1251 ConstrainedBox::new(
1252 Image::new(avatar)
1253 .with_style(theme.workspace.titlebar.avatar)
1254 .boxed(),
1255 )
1256 .with_width(theme.workspace.titlebar.avatar_width)
1257 .aligned()
1258 .boxed(),
1259 )
1260 .with_child(
1261 AvatarRibbon::new(theme.editor.replica_selection_style(replica_id).cursor)
1262 .constrained()
1263 .with_width(theme.workspace.titlebar.avatar_ribbon.width)
1264 .with_height(theme.workspace.titlebar.avatar_ribbon.height)
1265 .aligned()
1266 .bottom()
1267 .boxed(),
1268 )
1269 .boxed(),
1270 )
1271 .with_width(theme.workspace.right_sidebar.width)
1272 .boxed()
1273 }
1274
1275 fn render_share_icon(&self, theme: &Theme, cx: &mut RenderContext<Self>) -> Option<ElementBox> {
1276 if self.project().read(cx).is_local() && self.client.user_id().is_some() {
1277 enum Share {}
1278
1279 let color = if self.project().read(cx).is_shared() {
1280 theme.workspace.titlebar.share_icon_active_color
1281 } else {
1282 theme.workspace.titlebar.share_icon_color
1283 };
1284 Some(
1285 MouseEventHandler::new::<Share, _, _>(0, cx, |_, _| {
1286 Align::new(
1287 ConstrainedBox::new(
1288 Svg::new("icons/broadcast-24.svg").with_color(color).boxed(),
1289 )
1290 .with_width(24.)
1291 .boxed(),
1292 )
1293 .boxed()
1294 })
1295 .with_cursor_style(CursorStyle::PointingHand)
1296 .on_click(|cx| cx.dispatch_action(ToggleShare))
1297 .boxed(),
1298 )
1299 } else {
1300 None
1301 }
1302 }
1303
1304 fn render_disconnected_overlay(&self, cx: &AppContext) -> Option<ElementBox> {
1305 if self.project.read(cx).is_read_only() {
1306 let theme = &cx.app_state::<Settings>().theme;
1307 Some(
1308 EventHandler::new(
1309 Label::new(
1310 "Your connection to the remote project has been lost.".to_string(),
1311 theme.workspace.disconnected_overlay.text.clone(),
1312 )
1313 .aligned()
1314 .contained()
1315 .with_style(theme.workspace.disconnected_overlay.container)
1316 .boxed(),
1317 )
1318 .capture(|_, _, _| true)
1319 .boxed(),
1320 )
1321 } else {
1322 None
1323 }
1324 }
1325}
1326
1327impl Entity for Workspace {
1328 type Event = ();
1329}
1330
1331impl View for Workspace {
1332 fn ui_name() -> &'static str {
1333 "Workspace"
1334 }
1335
1336 fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
1337 let theme = cx.app_state::<Settings>().theme.clone();
1338 Stack::new()
1339 .with_child(
1340 Flex::column()
1341 .with_child(self.render_titlebar(&theme, cx))
1342 .with_child(
1343 Stack::new()
1344 .with_child({
1345 let mut content = Flex::row();
1346 content.add_child(self.left_sidebar.render(&theme, cx));
1347 if let Some(element) =
1348 self.left_sidebar.render_active_item(&theme, cx)
1349 {
1350 content.add_child(Flexible::new(0.8, false, element).boxed());
1351 }
1352 content.add_child(
1353 Flex::column()
1354 .with_child(
1355 Flexible::new(1., true, self.center.render(&theme))
1356 .boxed(),
1357 )
1358 .with_child(ChildView::new(&self.status_bar).boxed())
1359 .flexible(1., true)
1360 .boxed(),
1361 );
1362 if let Some(element) =
1363 self.right_sidebar.render_active_item(&theme, cx)
1364 {
1365 content.add_child(Flexible::new(0.8, false, element).boxed());
1366 }
1367 content.add_child(self.right_sidebar.render(&theme, cx));
1368 content.boxed()
1369 })
1370 .with_children(self.modal.as_ref().map(|m| ChildView::new(m).boxed()))
1371 .flexible(1.0, true)
1372 .boxed(),
1373 )
1374 .contained()
1375 .with_background_color(theme.workspace.background)
1376 .boxed(),
1377 )
1378 .with_children(self.render_disconnected_overlay(cx))
1379 .named("workspace")
1380 }
1381
1382 fn on_focus(&mut self, cx: &mut ViewContext<Self>) {
1383 cx.focus(&self.active_pane);
1384 }
1385}
1386
1387pub trait WorkspaceHandle {
1388 fn file_project_paths(&self, cx: &AppContext) -> Vec<ProjectPath>;
1389}
1390
1391impl WorkspaceHandle for ViewHandle<Workspace> {
1392 fn file_project_paths(&self, cx: &AppContext) -> Vec<ProjectPath> {
1393 self.read(cx)
1394 .worktrees(cx)
1395 .flat_map(|worktree| {
1396 let worktree_id = worktree.read(cx).id();
1397 worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
1398 worktree_id,
1399 path: f.path.clone(),
1400 })
1401 })
1402 .collect::<Vec<_>>()
1403 }
1404}
1405
1406pub struct AvatarRibbon {
1407 color: Color,
1408}
1409
1410impl AvatarRibbon {
1411 pub fn new(color: Color) -> AvatarRibbon {
1412 AvatarRibbon { color }
1413 }
1414}
1415
1416impl Element for AvatarRibbon {
1417 type LayoutState = ();
1418
1419 type PaintState = ();
1420
1421 fn layout(
1422 &mut self,
1423 constraint: gpui::SizeConstraint,
1424 _: &mut gpui::LayoutContext,
1425 ) -> (gpui::geometry::vector::Vector2F, Self::LayoutState) {
1426 (constraint.max, ())
1427 }
1428
1429 fn paint(
1430 &mut self,
1431 bounds: gpui::geometry::rect::RectF,
1432 _: gpui::geometry::rect::RectF,
1433 _: &mut Self::LayoutState,
1434 cx: &mut gpui::PaintContext,
1435 ) -> Self::PaintState {
1436 let mut path = PathBuilder::new();
1437 path.reset(bounds.lower_left());
1438 path.curve_to(
1439 bounds.origin() + vec2f(bounds.height(), 0.),
1440 bounds.origin(),
1441 );
1442 path.line_to(bounds.upper_right() - vec2f(bounds.height(), 0.));
1443 path.curve_to(bounds.lower_right(), bounds.upper_right());
1444 path.line_to(bounds.lower_left());
1445 cx.scene.push_path(path.build(self.color, None));
1446 }
1447
1448 fn dispatch_event(
1449 &mut self,
1450 _: &gpui::Event,
1451 _: gpui::geometry::rect::RectF,
1452 _: &mut Self::LayoutState,
1453 _: &mut Self::PaintState,
1454 _: &mut gpui::EventContext,
1455 ) -> bool {
1456 false
1457 }
1458
1459 fn debug(
1460 &self,
1461 bounds: gpui::geometry::rect::RectF,
1462 _: &Self::LayoutState,
1463 _: &Self::PaintState,
1464 _: &gpui::DebugContext,
1465 ) -> gpui::json::Value {
1466 json::json!({
1467 "type": "AvatarRibbon",
1468 "bounds": bounds.to_json(),
1469 "color": self.color.to_json(),
1470 })
1471 }
1472}
1473
1474impl std::fmt::Debug for OpenParams {
1475 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1476 f.debug_struct("OpenParams")
1477 .field("paths", &self.paths)
1478 .finish()
1479 }
1480}
1481
1482fn open(action: &Open, cx: &mut MutableAppContext) {
1483 let app_state = action.0.clone();
1484 let mut paths = cx.prompt_for_paths(PathPromptOptions {
1485 files: true,
1486 directories: true,
1487 multiple: true,
1488 });
1489 cx.spawn(|mut cx| async move {
1490 if let Some(paths) = paths.recv().await.flatten() {
1491 cx.update(|cx| cx.dispatch_global_action(OpenPaths(OpenParams { paths, app_state })));
1492 }
1493 })
1494 .detach();
1495}
1496
1497pub struct WorkspaceCreated(WeakViewHandle<Workspace>);
1498
1499pub fn open_paths(
1500 abs_paths: &[PathBuf],
1501 app_state: &Arc<AppState>,
1502 cx: &mut MutableAppContext,
1503) -> Task<ViewHandle<Workspace>> {
1504 log::info!("open paths {:?}", abs_paths);
1505
1506 // Open paths in existing workspace if possible
1507 let mut existing = None;
1508 for window_id in cx.window_ids().collect::<Vec<_>>() {
1509 if let Some(workspace_handle) = cx.root_view::<Workspace>(window_id) {
1510 if workspace_handle.update(cx, |workspace, cx| {
1511 if workspace.contains_paths(abs_paths, cx.as_ref()) {
1512 cx.activate_window(window_id);
1513 existing = Some(workspace_handle.clone());
1514 true
1515 } else {
1516 false
1517 }
1518 }) {
1519 break;
1520 }
1521 }
1522 }
1523
1524 let workspace = existing.unwrap_or_else(|| {
1525 let (_, workspace) = cx.add_window((app_state.build_window_options)(), |cx| {
1526 let project = Project::local(
1527 app_state.client.clone(),
1528 app_state.user_store.clone(),
1529 app_state.languages.clone(),
1530 app_state.fs.clone(),
1531 cx,
1532 );
1533 (app_state.build_workspace)(project, &app_state, cx)
1534 });
1535 cx.emit_global(WorkspaceCreated(workspace.downgrade()));
1536 workspace
1537 });
1538
1539 let task = workspace.update(cx, |workspace, cx| workspace.open_paths(abs_paths, cx));
1540 cx.spawn(|_| async move {
1541 task.await;
1542 workspace
1543 })
1544}
1545
1546pub fn join_project(
1547 project_id: u64,
1548 app_state: &Arc<AppState>,
1549 cx: &mut MutableAppContext,
1550) -> Task<Result<ViewHandle<Workspace>>> {
1551 for window_id in cx.window_ids().collect::<Vec<_>>() {
1552 if let Some(workspace) = cx.root_view::<Workspace>(window_id) {
1553 if workspace.read(cx).project().read(cx).remote_id() == Some(project_id) {
1554 return Task::ready(Ok(workspace));
1555 }
1556 }
1557 }
1558
1559 let app_state = app_state.clone();
1560 cx.spawn(|mut cx| async move {
1561 let project = Project::remote(
1562 project_id,
1563 app_state.client.clone(),
1564 app_state.user_store.clone(),
1565 app_state.languages.clone(),
1566 app_state.fs.clone(),
1567 &mut cx,
1568 )
1569 .await?;
1570 Ok(cx.update(|cx| {
1571 let (_, workspace) = cx.add_window((app_state.build_window_options)(), |cx| {
1572 (app_state.build_workspace)(project, &app_state, cx)
1573 });
1574 cx.emit_global(WorkspaceCreated(workspace.downgrade()));
1575 workspace
1576 }))
1577 })
1578}
1579
1580fn open_new(app_state: &Arc<AppState>, cx: &mut MutableAppContext) {
1581 let (window_id, workspace) = cx.add_window((app_state.build_window_options)(), |cx| {
1582 let project = Project::local(
1583 app_state.client.clone(),
1584 app_state.user_store.clone(),
1585 app_state.languages.clone(),
1586 app_state.fs.clone(),
1587 cx,
1588 );
1589 (app_state.build_workspace)(project, &app_state, cx)
1590 });
1591 cx.emit_global(WorkspaceCreated(workspace.downgrade()));
1592 cx.dispatch_action(window_id, vec![workspace.id()], &OpenNew(app_state.clone()));
1593}