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