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