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