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