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