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