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