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