1pub mod lsp_status;
2pub mod menu;
3pub mod pane;
4pub mod pane_group;
5pub mod sidebar;
6mod status_bar;
7mod toolbar;
8
9use anyhow::{anyhow, Context, Result};
10use client::{
11 proto, Authenticate, ChannelList, Client, PeerId, Subscription, TypedEnvelope, User, UserStore,
12};
13use clock::ReplicaId;
14use collections::{hash_map, HashMap, HashSet};
15use gpui::{
16 actions,
17 color::Color,
18 elements::*,
19 geometry::{rect::RectF, vector::vec2f, PathBuilder},
20 impl_internal_actions,
21 json::{self, ToJson},
22 platform::{CursorStyle, WindowOptions},
23 AnyModelHandle, AnyViewHandle, AppContext, AsyncAppContext, Border, Entity, ImageData,
24 ModelHandle, MutableAppContext, PathPromptOptions, PromptLevel, RenderContext, Task, View,
25 ViewContext, ViewHandle, WeakViewHandle,
26};
27use language::LanguageRegistry;
28use log::error;
29pub use pane::*;
30pub use pane_group::*;
31use postage::prelude::Stream;
32use project::{fs, Fs, Project, ProjectEntryId, ProjectPath, Worktree};
33use settings::Settings;
34use sidebar::{Side, Sidebar, ToggleSidebarItem, ToggleSidebarItemFocus};
35use status_bar::StatusBar;
36pub use status_bar::StatusItemView;
37use std::{
38 any::{Any, TypeId},
39 cell::RefCell,
40 fmt,
41 future::Future,
42 path::{Path, PathBuf},
43 rc::Rc,
44 sync::{
45 atomic::{AtomicBool, Ordering::SeqCst},
46 Arc,
47 },
48};
49use theme::{Theme, ThemeRegistry};
50pub use toolbar::{ToolbarItemLocation, ToolbarItemView};
51use util::ResultExt;
52
53type ProjectItemBuilders = HashMap<
54 TypeId,
55 fn(usize, ModelHandle<Project>, AnyModelHandle, &mut MutableAppContext) -> Box<dyn ItemHandle>,
56>;
57
58type FollowableItemBuilder = fn(
59 ViewHandle<Pane>,
60 ModelHandle<Project>,
61 &mut Option<proto::view::Variant>,
62 &mut MutableAppContext,
63) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>>;
64type FollowableItemBuilders = HashMap<
65 TypeId,
66 (
67 FollowableItemBuilder,
68 fn(AnyViewHandle) -> Box<dyn FollowableItemHandle>,
69 ),
70>;
71
72actions!(
73 workspace,
74 [
75 ToggleShare,
76 Unfollow,
77 Save,
78 ActivatePreviousPane,
79 ActivateNextPane,
80 FollowNextCollaborator,
81 ]
82);
83
84#[derive(Clone)]
85pub struct Open(pub Arc<AppState>);
86
87#[derive(Clone)]
88pub struct OpenNew(pub Arc<AppState>);
89
90#[derive(Clone)]
91pub struct OpenPaths {
92 pub paths: Vec<PathBuf>,
93 pub app_state: Arc<AppState>,
94}
95
96#[derive(Clone)]
97pub struct ToggleFollow(pub PeerId);
98
99#[derive(Clone)]
100pub struct JoinProject {
101 pub project_id: u64,
102 pub app_state: Arc<AppState>,
103}
104
105impl_internal_actions!(
106 workspace,
107 [Open, OpenNew, OpenPaths, ToggleFollow, JoinProject]
108);
109
110pub fn init(client: &Arc<Client>, cx: &mut MutableAppContext) {
111 pane::init(cx);
112
113 cx.add_global_action(open);
114 cx.add_global_action(move |action: &OpenPaths, cx: &mut MutableAppContext| {
115 open_paths(&action.paths, &action.app_state, cx).detach();
116 });
117 cx.add_global_action(move |action: &OpenNew, cx: &mut MutableAppContext| {
118 open_new(&action.0, cx)
119 });
120 cx.add_global_action(move |action: &JoinProject, cx: &mut MutableAppContext| {
121 join_project(action.project_id, &action.app_state, cx).detach();
122 });
123
124 cx.add_action(Workspace::toggle_share);
125 cx.add_async_action(Workspace::toggle_follow);
126 cx.add_async_action(Workspace::follow_next_collaborator);
127 cx.add_action(
128 |workspace: &mut Workspace, _: &Unfollow, cx: &mut ViewContext<Workspace>| {
129 let pane = workspace.active_pane().clone();
130 workspace.unfollow(&pane, cx);
131 },
132 );
133 cx.add_action(
134 |workspace: &mut Workspace, _: &Save, cx: &mut ViewContext<Workspace>| {
135 workspace.save_active_item(cx).detach_and_log_err(cx);
136 },
137 );
138 cx.add_action(Workspace::toggle_sidebar_item);
139 cx.add_action(Workspace::toggle_sidebar_item_focus);
140 cx.add_action(|workspace: &mut Workspace, _: &ActivatePreviousPane, cx| {
141 workspace.activate_previous_pane(cx)
142 });
143 cx.add_action(|workspace: &mut Workspace, _: &ActivateNextPane, cx| {
144 workspace.activate_next_pane(cx)
145 });
146
147 client.add_view_request_handler(Workspace::handle_follow);
148 client.add_view_message_handler(Workspace::handle_unfollow);
149 client.add_view_message_handler(Workspace::handle_update_followers);
150}
151
152pub fn register_project_item<I: ProjectItem>(cx: &mut MutableAppContext) {
153 cx.update_default_global(|builders: &mut ProjectItemBuilders, _| {
154 builders.insert(TypeId::of::<I::Item>(), |window_id, project, model, cx| {
155 let item = model.downcast::<I::Item>().unwrap();
156 Box::new(cx.add_view(window_id, |cx| I::for_project_item(project, item, cx)))
157 });
158 });
159}
160
161pub fn register_followable_item<I: FollowableItem>(cx: &mut MutableAppContext) {
162 cx.update_default_global(|builders: &mut FollowableItemBuilders, _| {
163 builders.insert(
164 TypeId::of::<I>(),
165 (
166 |pane, project, state, cx| {
167 I::from_state_proto(pane, project, state, cx).map(|task| {
168 cx.foreground()
169 .spawn(async move { Ok(Box::new(task.await?) as Box<_>) })
170 })
171 },
172 |this| Box::new(this.downcast::<I>().unwrap()),
173 ),
174 );
175 });
176}
177
178pub struct AppState {
179 pub languages: Arc<LanguageRegistry>,
180 pub themes: Arc<ThemeRegistry>,
181 pub client: Arc<client::Client>,
182 pub user_store: ModelHandle<client::UserStore>,
183 pub fs: Arc<dyn fs::Fs>,
184 pub channel_list: ModelHandle<client::ChannelList>,
185 pub build_window_options: &'static dyn Fn() -> WindowOptions<'static>,
186 pub build_workspace: &'static dyn Fn(
187 ModelHandle<Project>,
188 &Arc<AppState>,
189 &mut ViewContext<Workspace>,
190 ) -> Workspace,
191}
192
193pub trait Item: View {
194 fn deactivated(&mut self, _: &mut ViewContext<Self>) {}
195 fn navigate(&mut self, _: Box<dyn Any>, _: &mut ViewContext<Self>) -> bool {
196 false
197 }
198 fn tab_content(&self, style: &theme::Tab, cx: &AppContext) -> ElementBox;
199 fn project_path(&self, cx: &AppContext) -> Option<ProjectPath>;
200 fn project_entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId>;
201 fn set_nav_history(&mut self, _: ItemNavHistory, _: &mut ViewContext<Self>);
202 fn clone_on_split(&self, _: &mut ViewContext<Self>) -> Option<Self>
203 where
204 Self: Sized,
205 {
206 None
207 }
208 fn is_dirty(&self, _: &AppContext) -> bool {
209 false
210 }
211 fn has_conflict(&self, _: &AppContext) -> bool {
212 false
213 }
214 fn can_save(&self, cx: &AppContext) -> bool;
215 fn save(
216 &mut self,
217 project: ModelHandle<Project>,
218 cx: &mut ViewContext<Self>,
219 ) -> Task<Result<()>>;
220 fn can_save_as(&self, cx: &AppContext) -> bool;
221 fn save_as(
222 &mut self,
223 project: ModelHandle<Project>,
224 abs_path: PathBuf,
225 cx: &mut ViewContext<Self>,
226 ) -> Task<Result<()>>;
227 fn reload(
228 &mut self,
229 project: ModelHandle<Project>,
230 cx: &mut ViewContext<Self>,
231 ) -> Task<Result<()>>;
232 fn should_activate_item_on_event(_: &Self::Event) -> bool {
233 false
234 }
235 fn should_close_item_on_event(_: &Self::Event) -> bool {
236 false
237 }
238 fn should_update_tab_on_event(_: &Self::Event) -> bool {
239 false
240 }
241 fn act_as_type(
242 &self,
243 type_id: TypeId,
244 self_handle: &ViewHandle<Self>,
245 _: &AppContext,
246 ) -> Option<AnyViewHandle> {
247 if TypeId::of::<Self>() == type_id {
248 Some(self_handle.into())
249 } else {
250 None
251 }
252 }
253}
254
255pub trait ProjectItem: Item {
256 type Item: project::Item;
257
258 fn for_project_item(
259 project: ModelHandle<Project>,
260 item: ModelHandle<Self::Item>,
261 cx: &mut ViewContext<Self>,
262 ) -> Self;
263}
264
265pub trait FollowableItem: Item {
266 fn to_state_proto(&self, cx: &AppContext) -> Option<proto::view::Variant>;
267 fn from_state_proto(
268 pane: ViewHandle<Pane>,
269 project: ModelHandle<Project>,
270 state: &mut Option<proto::view::Variant>,
271 cx: &mut MutableAppContext,
272 ) -> Option<Task<Result<ViewHandle<Self>>>>;
273 fn add_event_to_update_proto(
274 &self,
275 event: &Self::Event,
276 update: &mut Option<proto::update_view::Variant>,
277 cx: &AppContext,
278 ) -> bool;
279 fn apply_update_proto(
280 &mut self,
281 message: proto::update_view::Variant,
282 cx: &mut ViewContext<Self>,
283 ) -> Result<()>;
284
285 fn set_leader_replica_id(&mut self, leader_replica_id: Option<u16>, cx: &mut ViewContext<Self>);
286 fn should_unfollow_on_event(event: &Self::Event, cx: &AppContext) -> bool;
287}
288
289pub trait FollowableItemHandle: ItemHandle {
290 fn set_leader_replica_id(&self, leader_replica_id: Option<u16>, cx: &mut MutableAppContext);
291 fn to_state_proto(&self, cx: &AppContext) -> Option<proto::view::Variant>;
292 fn add_event_to_update_proto(
293 &self,
294 event: &dyn Any,
295 update: &mut Option<proto::update_view::Variant>,
296 cx: &AppContext,
297 ) -> bool;
298 fn apply_update_proto(
299 &self,
300 message: proto::update_view::Variant,
301 cx: &mut MutableAppContext,
302 ) -> Result<()>;
303 fn should_unfollow_on_event(&self, event: &dyn Any, cx: &AppContext) -> bool;
304}
305
306impl<T: FollowableItem> FollowableItemHandle for ViewHandle<T> {
307 fn set_leader_replica_id(&self, leader_replica_id: Option<u16>, cx: &mut MutableAppContext) {
308 self.update(cx, |this, cx| {
309 this.set_leader_replica_id(leader_replica_id, cx)
310 })
311 }
312
313 fn to_state_proto(&self, cx: &AppContext) -> Option<proto::view::Variant> {
314 self.read(cx).to_state_proto(cx)
315 }
316
317 fn add_event_to_update_proto(
318 &self,
319 event: &dyn Any,
320 update: &mut Option<proto::update_view::Variant>,
321 cx: &AppContext,
322 ) -> bool {
323 if let Some(event) = event.downcast_ref() {
324 self.read(cx).add_event_to_update_proto(event, update, cx)
325 } else {
326 false
327 }
328 }
329
330 fn apply_update_proto(
331 &self,
332 message: proto::update_view::Variant,
333 cx: &mut MutableAppContext,
334 ) -> Result<()> {
335 self.update(cx, |this, cx| this.apply_update_proto(message, cx))
336 }
337
338 fn should_unfollow_on_event(&self, event: &dyn Any, cx: &AppContext) -> bool {
339 if let Some(event) = event.downcast_ref() {
340 T::should_unfollow_on_event(event, cx)
341 } else {
342 false
343 }
344 }
345}
346
347pub trait ItemHandle: 'static + fmt::Debug {
348 fn tab_content(&self, style: &theme::Tab, cx: &AppContext) -> ElementBox;
349 fn project_path(&self, cx: &AppContext) -> Option<ProjectPath>;
350 fn project_entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId>;
351 fn boxed_clone(&self) -> Box<dyn ItemHandle>;
352 fn set_nav_history(&self, nav_history: Rc<RefCell<NavHistory>>, cx: &mut MutableAppContext);
353 fn clone_on_split(&self, cx: &mut MutableAppContext) -> Option<Box<dyn ItemHandle>>;
354 fn added_to_pane(
355 &self,
356 workspace: &mut Workspace,
357 pane: ViewHandle<Pane>,
358 cx: &mut ViewContext<Workspace>,
359 );
360 fn deactivated(&self, cx: &mut MutableAppContext);
361 fn navigate(&self, data: Box<dyn Any>, cx: &mut MutableAppContext) -> bool;
362 fn id(&self) -> usize;
363 fn to_any(&self) -> AnyViewHandle;
364 fn is_dirty(&self, cx: &AppContext) -> bool;
365 fn has_conflict(&self, cx: &AppContext) -> bool;
366 fn can_save(&self, cx: &AppContext) -> bool;
367 fn can_save_as(&self, cx: &AppContext) -> bool;
368 fn save(&self, project: ModelHandle<Project>, cx: &mut MutableAppContext) -> Task<Result<()>>;
369 fn save_as(
370 &self,
371 project: ModelHandle<Project>,
372 abs_path: PathBuf,
373 cx: &mut MutableAppContext,
374 ) -> Task<Result<()>>;
375 fn reload(&self, project: ModelHandle<Project>, cx: &mut MutableAppContext)
376 -> Task<Result<()>>;
377 fn act_as_type(&self, type_id: TypeId, cx: &AppContext) -> Option<AnyViewHandle>;
378 fn to_followable_item_handle(&self, cx: &AppContext) -> Option<Box<dyn FollowableItemHandle>>;
379 fn on_release(
380 &self,
381 cx: &mut MutableAppContext,
382 callback: Box<dyn FnOnce(&mut MutableAppContext)>,
383 ) -> gpui::Subscription;
384}
385
386pub trait WeakItemHandle {
387 fn id(&self) -> usize;
388 fn upgrade(&self, cx: &AppContext) -> Option<Box<dyn ItemHandle>>;
389}
390
391impl dyn ItemHandle {
392 pub fn downcast<T: View>(&self) -> Option<ViewHandle<T>> {
393 self.to_any().downcast()
394 }
395
396 pub fn act_as<T: View>(&self, cx: &AppContext) -> Option<ViewHandle<T>> {
397 self.act_as_type(TypeId::of::<T>(), cx)
398 .and_then(|t| t.downcast())
399 }
400}
401
402impl<T: Item> ItemHandle for ViewHandle<T> {
403 fn tab_content(&self, style: &theme::Tab, cx: &AppContext) -> ElementBox {
404 self.read(cx).tab_content(style, cx)
405 }
406
407 fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
408 self.read(cx).project_path(cx)
409 }
410
411 fn project_entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId> {
412 self.read(cx).project_entry_id(cx)
413 }
414
415 fn boxed_clone(&self) -> Box<dyn ItemHandle> {
416 Box::new(self.clone())
417 }
418
419 fn set_nav_history(&self, nav_history: Rc<RefCell<NavHistory>>, cx: &mut MutableAppContext) {
420 self.update(cx, |item, cx| {
421 item.set_nav_history(ItemNavHistory::new(nav_history, &cx.handle()), cx);
422 })
423 }
424
425 fn clone_on_split(&self, cx: &mut MutableAppContext) -> Option<Box<dyn ItemHandle>> {
426 self.update(cx, |item, cx| {
427 cx.add_option_view(|cx| item.clone_on_split(cx))
428 })
429 .map(|handle| Box::new(handle) as Box<dyn ItemHandle>)
430 }
431
432 fn added_to_pane(
433 &self,
434 workspace: &mut Workspace,
435 pane: ViewHandle<Pane>,
436 cx: &mut ViewContext<Workspace>,
437 ) {
438 if let Some(followed_item) = self.to_followable_item_handle(cx) {
439 if let Some(message) = followed_item.to_state_proto(cx) {
440 workspace.update_followers(
441 proto::update_followers::Variant::CreateView(proto::View {
442 id: followed_item.id() as u64,
443 variant: Some(message),
444 leader_id: workspace.leader_for_pane(&pane).map(|id| id.0),
445 }),
446 cx,
447 );
448 }
449 }
450
451 let pending_update = Rc::new(RefCell::new(None));
452 let pending_update_scheduled = Rc::new(AtomicBool::new(false));
453 let pane = pane.downgrade();
454 cx.subscribe(self, move |workspace, item, event, cx| {
455 let pane = if let Some(pane) = pane.upgrade(cx) {
456 pane
457 } else {
458 log::error!("unexpected item event after pane was dropped");
459 return;
460 };
461
462 if let Some(item) = item.to_followable_item_handle(cx) {
463 let leader_id = workspace.leader_for_pane(&pane);
464
465 if leader_id.is_some() && item.should_unfollow_on_event(event, cx) {
466 workspace.unfollow(&pane, cx);
467 }
468
469 if item.add_event_to_update_proto(event, &mut *pending_update.borrow_mut(), cx)
470 && !pending_update_scheduled.load(SeqCst)
471 {
472 pending_update_scheduled.store(true, SeqCst);
473 cx.after_window_update({
474 let pending_update = pending_update.clone();
475 let pending_update_scheduled = pending_update_scheduled.clone();
476 move |this, cx| {
477 pending_update_scheduled.store(false, SeqCst);
478 this.update_followers(
479 proto::update_followers::Variant::UpdateView(proto::UpdateView {
480 id: item.id() as u64,
481 variant: pending_update.borrow_mut().take(),
482 leader_id: leader_id.map(|id| id.0),
483 }),
484 cx,
485 );
486 }
487 });
488 }
489 }
490
491 if T::should_close_item_on_event(event) {
492 Pane::close_item(workspace, pane, item.id(), cx).detach_and_log_err(cx);
493 return;
494 }
495
496 if T::should_activate_item_on_event(event) {
497 pane.update(cx, |pane, cx| {
498 if let Some(ix) = pane.index_for_item(&item) {
499 pane.activate_item(ix, true, cx);
500 pane.activate(cx);
501 }
502 });
503 }
504
505 if T::should_update_tab_on_event(event) {
506 pane.update(cx, |_, cx| cx.notify());
507 }
508 })
509 .detach();
510 }
511
512 fn deactivated(&self, cx: &mut MutableAppContext) {
513 self.update(cx, |this, cx| this.deactivated(cx));
514 }
515
516 fn navigate(&self, data: Box<dyn Any>, cx: &mut MutableAppContext) -> bool {
517 self.update(cx, |this, cx| this.navigate(data, cx))
518 }
519
520 fn id(&self) -> usize {
521 self.id()
522 }
523
524 fn to_any(&self) -> AnyViewHandle {
525 self.into()
526 }
527
528 fn is_dirty(&self, cx: &AppContext) -> bool {
529 self.read(cx).is_dirty(cx)
530 }
531
532 fn has_conflict(&self, cx: &AppContext) -> bool {
533 self.read(cx).has_conflict(cx)
534 }
535
536 fn can_save(&self, cx: &AppContext) -> bool {
537 self.read(cx).can_save(cx)
538 }
539
540 fn can_save_as(&self, cx: &AppContext) -> bool {
541 self.read(cx).can_save_as(cx)
542 }
543
544 fn save(&self, project: ModelHandle<Project>, cx: &mut MutableAppContext) -> Task<Result<()>> {
545 self.update(cx, |item, cx| item.save(project, cx))
546 }
547
548 fn save_as(
549 &self,
550 project: ModelHandle<Project>,
551 abs_path: PathBuf,
552 cx: &mut MutableAppContext,
553 ) -> Task<anyhow::Result<()>> {
554 self.update(cx, |item, cx| item.save_as(project, abs_path, cx))
555 }
556
557 fn reload(
558 &self,
559 project: ModelHandle<Project>,
560 cx: &mut MutableAppContext,
561 ) -> Task<Result<()>> {
562 self.update(cx, |item, cx| item.reload(project, cx))
563 }
564
565 fn act_as_type(&self, type_id: TypeId, cx: &AppContext) -> Option<AnyViewHandle> {
566 self.read(cx).act_as_type(type_id, self, cx)
567 }
568
569 fn to_followable_item_handle(&self, cx: &AppContext) -> Option<Box<dyn FollowableItemHandle>> {
570 if cx.has_global::<FollowableItemBuilders>() {
571 let builders = cx.global::<FollowableItemBuilders>();
572 let item = self.to_any();
573 Some(builders.get(&item.view_type())?.1(item))
574 } else {
575 None
576 }
577 }
578
579 fn on_release(
580 &self,
581 cx: &mut MutableAppContext,
582 callback: Box<dyn FnOnce(&mut MutableAppContext)>,
583 ) -> gpui::Subscription {
584 cx.observe_release(self, move |_, cx| callback(cx))
585 }
586}
587
588impl Into<AnyViewHandle> for Box<dyn ItemHandle> {
589 fn into(self) -> AnyViewHandle {
590 self.to_any()
591 }
592}
593
594impl Clone for Box<dyn ItemHandle> {
595 fn clone(&self) -> Box<dyn ItemHandle> {
596 self.boxed_clone()
597 }
598}
599
600impl<T: Item> WeakItemHandle for WeakViewHandle<T> {
601 fn id(&self) -> usize {
602 self.id()
603 }
604
605 fn upgrade(&self, cx: &AppContext) -> Option<Box<dyn ItemHandle>> {
606 self.upgrade(cx).map(|v| Box::new(v) as Box<dyn ItemHandle>)
607 }
608}
609
610#[derive(Clone)]
611pub struct WorkspaceParams {
612 pub project: ModelHandle<Project>,
613 pub client: Arc<Client>,
614 pub fs: Arc<dyn Fs>,
615 pub languages: Arc<LanguageRegistry>,
616 pub themes: Arc<ThemeRegistry>,
617 pub user_store: ModelHandle<UserStore>,
618 pub channel_list: ModelHandle<ChannelList>,
619}
620
621impl WorkspaceParams {
622 #[cfg(any(test, feature = "test-support"))]
623 pub fn test(cx: &mut MutableAppContext) -> Self {
624 let settings = Settings::test(cx);
625 cx.set_global(settings);
626
627 let fs = project::FakeFs::new(cx.background().clone());
628 let languages = Arc::new(LanguageRegistry::test());
629 let http_client = client::test::FakeHttpClient::new(|_| async move {
630 Ok(client::http::ServerResponse::new(404))
631 });
632 let client = Client::new(http_client.clone());
633 let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http_client, cx));
634 let project = Project::local(
635 client.clone(),
636 user_store.clone(),
637 languages.clone(),
638 fs.clone(),
639 cx,
640 );
641 Self {
642 project,
643 channel_list: cx
644 .add_model(|cx| ChannelList::new(user_store.clone(), client.clone(), cx)),
645 client,
646 themes: ThemeRegistry::new((), cx.font_cache().clone()),
647 fs,
648 languages,
649 user_store,
650 }
651 }
652
653 #[cfg(any(test, feature = "test-support"))]
654 pub fn local(app_state: &Arc<AppState>, cx: &mut MutableAppContext) -> Self {
655 Self {
656 project: Project::local(
657 app_state.client.clone(),
658 app_state.user_store.clone(),
659 app_state.languages.clone(),
660 app_state.fs.clone(),
661 cx,
662 ),
663 client: app_state.client.clone(),
664 fs: app_state.fs.clone(),
665 themes: app_state.themes.clone(),
666 languages: app_state.languages.clone(),
667 user_store: app_state.user_store.clone(),
668 channel_list: app_state.channel_list.clone(),
669 }
670 }
671}
672
673pub enum Event {
674 PaneAdded(ViewHandle<Pane>),
675}
676
677pub struct Workspace {
678 weak_self: WeakViewHandle<Self>,
679 client: Arc<Client>,
680 user_store: ModelHandle<client::UserStore>,
681 remote_entity_subscription: Option<Subscription>,
682 fs: Arc<dyn Fs>,
683 themes: Arc<ThemeRegistry>,
684 modal: Option<AnyViewHandle>,
685 center: PaneGroup,
686 left_sidebar: Sidebar,
687 right_sidebar: Sidebar,
688 panes: Vec<ViewHandle<Pane>>,
689 active_pane: ViewHandle<Pane>,
690 status_bar: ViewHandle<StatusBar>,
691 project: ModelHandle<Project>,
692 leader_state: LeaderState,
693 follower_states_by_leader: FollowerStatesByLeader,
694 last_leaders_by_pane: HashMap<WeakViewHandle<Pane>, PeerId>,
695 _observe_current_user: Task<()>,
696}
697
698#[derive(Default)]
699struct LeaderState {
700 followers: HashSet<PeerId>,
701}
702
703type FollowerStatesByLeader = HashMap<PeerId, HashMap<ViewHandle<Pane>, FollowerState>>;
704
705#[derive(Default)]
706struct FollowerState {
707 active_view_id: Option<u64>,
708 items_by_leader_view_id: HashMap<u64, FollowerItem>,
709}
710
711#[derive(Debug)]
712enum FollowerItem {
713 Loading(Vec<proto::update_view::Variant>),
714 Loaded(Box<dyn FollowableItemHandle>),
715}
716
717impl Workspace {
718 pub fn new(params: &WorkspaceParams, cx: &mut ViewContext<Self>) -> Self {
719 cx.observe(¶ms.project, |_, project, cx| {
720 if project.read(cx).is_read_only() {
721 cx.blur();
722 }
723 cx.notify()
724 })
725 .detach();
726
727 cx.subscribe(¶ms.project, move |this, project, event, cx| {
728 match event {
729 project::Event::RemoteIdChanged(remote_id) => {
730 this.project_remote_id_changed(*remote_id, cx);
731 }
732 project::Event::CollaboratorLeft(peer_id) => {
733 this.collaborator_left(*peer_id, cx);
734 }
735 _ => {}
736 }
737 if project.read(cx).is_read_only() {
738 cx.blur();
739 }
740 cx.notify()
741 })
742 .detach();
743
744 let pane = cx.add_view(|cx| Pane::new(cx));
745 let pane_id = pane.id();
746 cx.observe(&pane, move |me, _, cx| {
747 let active_entry = me.active_project_path(cx);
748 me.project
749 .update(cx, |project, cx| project.set_active_path(active_entry, cx));
750 })
751 .detach();
752 cx.subscribe(&pane, move |me, _, event, cx| {
753 me.handle_pane_event(pane_id, event, cx)
754 })
755 .detach();
756 cx.focus(&pane);
757 cx.emit(Event::PaneAdded(pane.clone()));
758
759 let status_bar = cx.add_view(|cx| StatusBar::new(&pane, cx));
760 let mut current_user = params.user_store.read(cx).watch_current_user().clone();
761 let mut connection_status = params.client.status().clone();
762 let _observe_current_user = cx.spawn_weak(|this, mut cx| async move {
763 current_user.recv().await;
764 connection_status.recv().await;
765 let mut stream =
766 Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
767
768 while stream.recv().await.is_some() {
769 cx.update(|cx| {
770 if let Some(this) = this.upgrade(cx) {
771 this.update(cx, |_, cx| cx.notify());
772 }
773 })
774 }
775 });
776
777 let weak_self = cx.weak_handle();
778
779 cx.emit_global(WorkspaceCreated(weak_self.clone()));
780
781 let mut this = Workspace {
782 modal: None,
783 weak_self,
784 center: PaneGroup::new(pane.clone()),
785 panes: vec![pane.clone()],
786 active_pane: pane.clone(),
787 status_bar,
788 client: params.client.clone(),
789 remote_entity_subscription: None,
790 user_store: params.user_store.clone(),
791 fs: params.fs.clone(),
792 themes: params.themes.clone(),
793 left_sidebar: Sidebar::new(Side::Left),
794 right_sidebar: Sidebar::new(Side::Right),
795 project: params.project.clone(),
796 leader_state: Default::default(),
797 follower_states_by_leader: Default::default(),
798 last_leaders_by_pane: Default::default(),
799 _observe_current_user,
800 };
801 this.project_remote_id_changed(this.project.read(cx).remote_id(), cx);
802 this
803 }
804
805 pub fn weak_handle(&self) -> WeakViewHandle<Self> {
806 self.weak_self.clone()
807 }
808
809 pub fn left_sidebar_mut(&mut self) -> &mut Sidebar {
810 &mut self.left_sidebar
811 }
812
813 pub fn right_sidebar_mut(&mut self) -> &mut Sidebar {
814 &mut self.right_sidebar
815 }
816
817 pub fn status_bar(&self) -> &ViewHandle<StatusBar> {
818 &self.status_bar
819 }
820
821 pub fn project(&self) -> &ModelHandle<Project> {
822 &self.project
823 }
824
825 pub fn themes(&self) -> Arc<ThemeRegistry> {
826 self.themes.clone()
827 }
828
829 pub fn worktrees<'a>(
830 &self,
831 cx: &'a AppContext,
832 ) -> impl 'a + Iterator<Item = ModelHandle<Worktree>> {
833 self.project.read(cx).worktrees(cx)
834 }
835
836 pub fn contains_paths(&self, paths: &[PathBuf], cx: &AppContext) -> bool {
837 paths.iter().all(|path| self.contains_path(&path, cx))
838 }
839
840 pub fn contains_path(&self, path: &Path, cx: &AppContext) -> bool {
841 for worktree in self.worktrees(cx) {
842 let worktree = worktree.read(cx).as_local();
843 if worktree.map_or(false, |w| w.contains_abs_path(path)) {
844 return true;
845 }
846 }
847 false
848 }
849
850 pub fn worktree_scans_complete(&self, cx: &AppContext) -> impl Future<Output = ()> + 'static {
851 let futures = self
852 .worktrees(cx)
853 .filter_map(|worktree| worktree.read(cx).as_local())
854 .map(|worktree| worktree.scan_complete())
855 .collect::<Vec<_>>();
856 async move {
857 for future in futures {
858 future.await;
859 }
860 }
861 }
862
863 pub fn open_paths(
864 &mut self,
865 abs_paths: &[PathBuf],
866 cx: &mut ViewContext<Self>,
867 ) -> Task<Vec<Option<Result<Box<dyn ItemHandle>, Arc<anyhow::Error>>>>> {
868 let entries = abs_paths
869 .iter()
870 .cloned()
871 .map(|path| self.project_path_for_path(&path, cx))
872 .collect::<Vec<_>>();
873
874 let fs = self.fs.clone();
875 let tasks = abs_paths
876 .iter()
877 .cloned()
878 .zip(entries.into_iter())
879 .map(|(abs_path, project_path)| {
880 cx.spawn(|this, mut cx| {
881 let fs = fs.clone();
882 async move {
883 let project_path = project_path.await.ok()?;
884 if fs.is_file(&abs_path).await {
885 Some(
886 this.update(&mut cx, |this, cx| this.open_path(project_path, cx))
887 .await,
888 )
889 } else {
890 None
891 }
892 }
893 })
894 })
895 .collect::<Vec<_>>();
896
897 cx.foreground().spawn(async move {
898 let mut items = Vec::new();
899 for task in tasks {
900 items.push(task.await);
901 }
902 items
903 })
904 }
905
906 fn project_path_for_path(
907 &self,
908 abs_path: &Path,
909 cx: &mut ViewContext<Self>,
910 ) -> Task<Result<ProjectPath>> {
911 let entry = self.project().update(cx, |project, cx| {
912 project.find_or_create_local_worktree(abs_path, true, cx)
913 });
914 cx.spawn(|_, cx| async move {
915 let (worktree, path) = entry.await?;
916 Ok(ProjectPath {
917 worktree_id: worktree.read_with(&cx, |t, _| t.id()),
918 path: path.into(),
919 })
920 })
921 }
922
923 // Returns the model that was toggled closed if it was open
924 pub fn toggle_modal<V, F>(
925 &mut self,
926 cx: &mut ViewContext<Self>,
927 add_view: F,
928 ) -> Option<ViewHandle<V>>
929 where
930 V: 'static + View,
931 F: FnOnce(&mut ViewContext<Self>, &mut Self) -> ViewHandle<V>,
932 {
933 cx.notify();
934 // Whatever modal was visible is getting clobbered. If its the same type as V, then return
935 // it. Otherwise, create a new modal and set it as active.
936 let already_open_modal = self.modal.take().and_then(|modal| modal.downcast::<V>());
937 if let Some(already_open_modal) = already_open_modal {
938 cx.focus_self();
939 Some(already_open_modal)
940 } else {
941 let modal = add_view(cx, self);
942 cx.focus(&modal);
943 self.modal = Some(modal.into());
944 None
945 }
946 }
947
948 pub fn modal(&self) -> Option<&AnyViewHandle> {
949 self.modal.as_ref()
950 }
951
952 pub fn dismiss_modal(&mut self, cx: &mut ViewContext<Self>) {
953 if self.modal.take().is_some() {
954 cx.focus(&self.active_pane);
955 cx.notify();
956 }
957 }
958
959 pub fn items<'a>(
960 &'a self,
961 cx: &'a AppContext,
962 ) -> impl 'a + Iterator<Item = &Box<dyn ItemHandle>> {
963 self.panes.iter().flat_map(|pane| pane.read(cx).items())
964 }
965
966 pub fn item_of_type<T: Item>(&self, cx: &AppContext) -> Option<ViewHandle<T>> {
967 self.items_of_type(cx).max_by_key(|item| item.id())
968 }
969
970 pub fn items_of_type<'a, T: Item>(
971 &'a self,
972 cx: &'a AppContext,
973 ) -> impl 'a + Iterator<Item = ViewHandle<T>> {
974 self.panes
975 .iter()
976 .flat_map(|pane| pane.read(cx).items_of_type())
977 }
978
979 pub fn active_item(&self, cx: &AppContext) -> Option<Box<dyn ItemHandle>> {
980 self.active_pane().read(cx).active_item()
981 }
982
983 fn active_project_path(&self, cx: &ViewContext<Self>) -> Option<ProjectPath> {
984 self.active_item(cx).and_then(|item| item.project_path(cx))
985 }
986
987 pub fn save_active_item(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<()>> {
988 let project = self.project.clone();
989 if let Some(item) = self.active_item(cx) {
990 if item.can_save(cx) {
991 if item.has_conflict(cx.as_ref()) {
992 const CONFLICT_MESSAGE: &'static str = "This file has changed on disk since you started editing it. Do you want to overwrite it?";
993
994 let mut answer = cx.prompt(
995 PromptLevel::Warning,
996 CONFLICT_MESSAGE,
997 &["Overwrite", "Cancel"],
998 );
999 cx.spawn(|_, mut cx| async move {
1000 let answer = answer.recv().await;
1001 if answer == Some(0) {
1002 cx.update(|cx| item.save(project, cx)).await?;
1003 }
1004 Ok(())
1005 })
1006 } else {
1007 item.save(project, cx)
1008 }
1009 } else if item.can_save_as(cx) {
1010 let worktree = self.worktrees(cx).next();
1011 let start_abs_path = worktree
1012 .and_then(|w| w.read(cx).as_local())
1013 .map_or(Path::new(""), |w| w.abs_path())
1014 .to_path_buf();
1015 let mut abs_path = cx.prompt_for_new_path(&start_abs_path);
1016 cx.spawn(|_, mut cx| async move {
1017 if let Some(abs_path) = abs_path.recv().await.flatten() {
1018 cx.update(|cx| item.save_as(project, abs_path, cx)).await?;
1019 }
1020 Ok(())
1021 })
1022 } else {
1023 Task::ready(Ok(()))
1024 }
1025 } else {
1026 Task::ready(Ok(()))
1027 }
1028 }
1029
1030 pub fn toggle_sidebar_item(&mut self, action: &ToggleSidebarItem, cx: &mut ViewContext<Self>) {
1031 let sidebar = match action.0.side {
1032 Side::Left => &mut self.left_sidebar,
1033 Side::Right => &mut self.right_sidebar,
1034 };
1035 sidebar.toggle_item(action.0.item_index);
1036 if let Some(active_item) = sidebar.active_item() {
1037 cx.focus(active_item);
1038 } else {
1039 cx.focus_self();
1040 }
1041 cx.notify();
1042 }
1043
1044 pub fn toggle_sidebar_item_focus(
1045 &mut self,
1046 action: &ToggleSidebarItemFocus,
1047 cx: &mut ViewContext<Self>,
1048 ) {
1049 let sidebar = match action.0.side {
1050 Side::Left => &mut self.left_sidebar,
1051 Side::Right => &mut self.right_sidebar,
1052 };
1053 sidebar.activate_item(action.0.item_index);
1054 if let Some(active_item) = sidebar.active_item() {
1055 if active_item.is_focused(cx) {
1056 cx.focus_self();
1057 } else {
1058 cx.focus(active_item);
1059 }
1060 }
1061 cx.notify();
1062 }
1063
1064 fn add_pane(&mut self, cx: &mut ViewContext<Self>) -> ViewHandle<Pane> {
1065 let pane = cx.add_view(|cx| Pane::new(cx));
1066 let pane_id = pane.id();
1067 cx.observe(&pane, move |me, _, cx| {
1068 let active_entry = me.active_project_path(cx);
1069 me.project
1070 .update(cx, |project, cx| project.set_active_path(active_entry, cx));
1071 })
1072 .detach();
1073 cx.subscribe(&pane, move |me, _, event, cx| {
1074 me.handle_pane_event(pane_id, event, cx)
1075 })
1076 .detach();
1077 self.panes.push(pane.clone());
1078 self.activate_pane(pane.clone(), cx);
1079 cx.emit(Event::PaneAdded(pane.clone()));
1080 pane
1081 }
1082
1083 pub fn add_item(&mut self, item: Box<dyn ItemHandle>, cx: &mut ViewContext<Self>) {
1084 let pane = self.active_pane().clone();
1085 Pane::add_item(self, pane, item, true, cx);
1086 }
1087
1088 pub fn open_path(
1089 &mut self,
1090 path: impl Into<ProjectPath>,
1091 cx: &mut ViewContext<Self>,
1092 ) -> Task<Result<Box<dyn ItemHandle>, Arc<anyhow::Error>>> {
1093 let pane = self.active_pane().downgrade();
1094 let task = self.load_path(path.into(), cx);
1095 cx.spawn(|this, mut cx| async move {
1096 let (project_entry_id, build_item) = task.await?;
1097 let pane = pane
1098 .upgrade(&cx)
1099 .ok_or_else(|| anyhow!("pane was closed"))?;
1100 this.update(&mut cx, |this, cx| {
1101 Ok(Pane::open_item(
1102 this,
1103 pane,
1104 project_entry_id,
1105 cx,
1106 build_item,
1107 ))
1108 })
1109 })
1110 }
1111
1112 pub(crate) fn load_path(
1113 &mut self,
1114 path: ProjectPath,
1115 cx: &mut ViewContext<Self>,
1116 ) -> Task<
1117 Result<(
1118 ProjectEntryId,
1119 impl 'static + FnOnce(&mut MutableAppContext) -> Box<dyn ItemHandle>,
1120 )>,
1121 > {
1122 let project = self.project().clone();
1123 let project_item = project.update(cx, |project, cx| project.open_path(path, cx));
1124 let window_id = cx.window_id();
1125 cx.as_mut().spawn(|mut cx| async move {
1126 let (project_entry_id, project_item) = project_item.await?;
1127 let build_item = cx.update(|cx| {
1128 cx.default_global::<ProjectItemBuilders>()
1129 .get(&project_item.model_type())
1130 .ok_or_else(|| anyhow!("no item builder for project item"))
1131 .cloned()
1132 })?;
1133 let build_item =
1134 move |cx: &mut MutableAppContext| build_item(window_id, project, project_item, cx);
1135 Ok((project_entry_id, build_item))
1136 })
1137 }
1138
1139 pub fn open_project_item<T>(
1140 &mut self,
1141 project_item: ModelHandle<T::Item>,
1142 cx: &mut ViewContext<Self>,
1143 ) -> ViewHandle<T>
1144 where
1145 T: ProjectItem,
1146 {
1147 use project::Item as _;
1148
1149 let entry_id = project_item.read(cx).entry_id(cx);
1150 if let Some(item) = entry_id
1151 .and_then(|entry_id| self.active_pane().read(cx).item_for_entry(entry_id, cx))
1152 .and_then(|item| item.downcast())
1153 {
1154 self.activate_item(&item, cx);
1155 return item;
1156 }
1157
1158 let item = cx.add_view(|cx| T::for_project_item(self.project().clone(), project_item, cx));
1159 self.add_item(Box::new(item.clone()), cx);
1160 item
1161 }
1162
1163 pub fn activate_item(&mut self, item: &dyn ItemHandle, cx: &mut ViewContext<Self>) -> bool {
1164 let result = self.panes.iter().find_map(|pane| {
1165 if let Some(ix) = pane.read(cx).index_for_item(item) {
1166 Some((pane.clone(), ix))
1167 } else {
1168 None
1169 }
1170 });
1171 if let Some((pane, ix)) = result {
1172 self.activate_pane(pane.clone(), cx);
1173 pane.update(cx, |pane, cx| pane.activate_item(ix, true, cx));
1174 true
1175 } else {
1176 false
1177 }
1178 }
1179
1180 pub fn activate_next_pane(&mut self, cx: &mut ViewContext<Self>) {
1181 let next_pane = {
1182 let panes = self.center.panes();
1183 let ix = panes
1184 .iter()
1185 .position(|pane| **pane == self.active_pane)
1186 .unwrap();
1187 let next_ix = (ix + 1) % panes.len();
1188 panes[next_ix].clone()
1189 };
1190 self.activate_pane(next_pane, cx);
1191 }
1192
1193 pub fn activate_previous_pane(&mut self, cx: &mut ViewContext<Self>) {
1194 let prev_pane = {
1195 let panes = self.center.panes();
1196 let ix = panes
1197 .iter()
1198 .position(|pane| **pane == self.active_pane)
1199 .unwrap();
1200 let prev_ix = if ix == 0 { panes.len() - 1 } else { ix - 1 };
1201 panes[prev_ix].clone()
1202 };
1203 self.activate_pane(prev_pane, cx);
1204 }
1205
1206 fn activate_pane(&mut self, pane: ViewHandle<Pane>, cx: &mut ViewContext<Self>) {
1207 if self.active_pane != pane {
1208 self.active_pane = pane.clone();
1209 self.status_bar.update(cx, |status_bar, cx| {
1210 status_bar.set_active_pane(&self.active_pane, cx);
1211 });
1212 cx.focus(&self.active_pane);
1213 cx.notify();
1214 }
1215
1216 self.update_followers(
1217 proto::update_followers::Variant::UpdateActiveView(proto::UpdateActiveView {
1218 id: self.active_item(cx).map(|item| item.id() as u64),
1219 leader_id: self.leader_for_pane(&pane).map(|id| id.0),
1220 }),
1221 cx,
1222 );
1223 }
1224
1225 fn handle_pane_event(
1226 &mut self,
1227 pane_id: usize,
1228 event: &pane::Event,
1229 cx: &mut ViewContext<Self>,
1230 ) {
1231 if let Some(pane) = self.pane(pane_id) {
1232 match event {
1233 pane::Event::Split(direction) => {
1234 self.split_pane(pane, *direction, cx);
1235 }
1236 pane::Event::Remove => {
1237 self.remove_pane(pane, cx);
1238 }
1239 pane::Event::Activate => {
1240 self.activate_pane(pane, cx);
1241 }
1242 pane::Event::ActivateItem { local } => {
1243 if *local {
1244 self.unfollow(&pane, cx);
1245 }
1246 }
1247 }
1248 } else {
1249 error!("pane {} not found", pane_id);
1250 }
1251 }
1252
1253 pub fn split_pane(
1254 &mut self,
1255 pane: ViewHandle<Pane>,
1256 direction: SplitDirection,
1257 cx: &mut ViewContext<Self>,
1258 ) -> ViewHandle<Pane> {
1259 let new_pane = self.add_pane(cx);
1260 self.activate_pane(new_pane.clone(), cx);
1261 if let Some(item) = pane.read(cx).active_item() {
1262 if let Some(clone) = item.clone_on_split(cx.as_mut()) {
1263 Pane::add_item(self, new_pane.clone(), clone, true, cx);
1264 }
1265 }
1266 self.center.split(&pane, &new_pane, direction).unwrap();
1267 cx.notify();
1268 new_pane
1269 }
1270
1271 fn remove_pane(&mut self, pane: ViewHandle<Pane>, cx: &mut ViewContext<Self>) {
1272 if self.center.remove(&pane).unwrap() {
1273 self.panes.retain(|p| p != &pane);
1274 self.activate_pane(self.panes.last().unwrap().clone(), cx);
1275 self.unfollow(&pane, cx);
1276 self.last_leaders_by_pane.remove(&pane.downgrade());
1277 cx.notify();
1278 }
1279 }
1280
1281 pub fn panes(&self) -> &[ViewHandle<Pane>] {
1282 &self.panes
1283 }
1284
1285 fn pane(&self, pane_id: usize) -> Option<ViewHandle<Pane>> {
1286 self.panes.iter().find(|pane| pane.id() == pane_id).cloned()
1287 }
1288
1289 pub fn active_pane(&self) -> &ViewHandle<Pane> {
1290 &self.active_pane
1291 }
1292
1293 fn toggle_share(&mut self, _: &ToggleShare, cx: &mut ViewContext<Self>) {
1294 self.project.update(cx, |project, cx| {
1295 if project.is_local() {
1296 if project.is_shared() {
1297 project.unshare(cx);
1298 } else {
1299 project.share(cx).detach();
1300 }
1301 }
1302 });
1303 }
1304
1305 fn project_remote_id_changed(&mut self, remote_id: Option<u64>, cx: &mut ViewContext<Self>) {
1306 if let Some(remote_id) = remote_id {
1307 self.remote_entity_subscription =
1308 Some(self.client.add_view_for_remote_entity(remote_id, cx));
1309 } else {
1310 self.remote_entity_subscription.take();
1311 }
1312 }
1313
1314 fn collaborator_left(&mut self, peer_id: PeerId, cx: &mut ViewContext<Self>) {
1315 self.leader_state.followers.remove(&peer_id);
1316 if let Some(states_by_pane) = self.follower_states_by_leader.remove(&peer_id) {
1317 for state in states_by_pane.into_values() {
1318 for item in state.items_by_leader_view_id.into_values() {
1319 if let FollowerItem::Loaded(item) = item {
1320 item.set_leader_replica_id(None, cx);
1321 }
1322 }
1323 }
1324 }
1325 cx.notify();
1326 }
1327
1328 pub fn toggle_follow(
1329 &mut self,
1330 ToggleFollow(leader_id): &ToggleFollow,
1331 cx: &mut ViewContext<Self>,
1332 ) -> Option<Task<Result<()>>> {
1333 let leader_id = *leader_id;
1334 let pane = self.active_pane().clone();
1335
1336 if let Some(prev_leader_id) = self.unfollow(&pane, cx) {
1337 if leader_id == prev_leader_id {
1338 return None;
1339 }
1340 }
1341
1342 self.last_leaders_by_pane
1343 .insert(pane.downgrade(), leader_id);
1344 self.follower_states_by_leader
1345 .entry(leader_id)
1346 .or_default()
1347 .insert(pane.clone(), Default::default());
1348 cx.notify();
1349
1350 let project_id = self.project.read(cx).remote_id()?;
1351 let request = self.client.request(proto::Follow {
1352 project_id,
1353 leader_id: leader_id.0,
1354 });
1355 Some(cx.spawn_weak(|this, mut cx| async move {
1356 let response = request.await?;
1357 if let Some(this) = this.upgrade(&cx) {
1358 this.update(&mut cx, |this, _| {
1359 let state = this
1360 .follower_states_by_leader
1361 .get_mut(&leader_id)
1362 .and_then(|states_by_pane| states_by_pane.get_mut(&pane))
1363 .ok_or_else(|| anyhow!("following interrupted"))?;
1364 state.active_view_id = response.active_view_id;
1365 Ok::<_, anyhow::Error>(())
1366 })?;
1367 Self::add_views_from_leader(this, leader_id, vec![pane], response.views, &mut cx)
1368 .await?;
1369 }
1370 Ok(())
1371 }))
1372 }
1373
1374 pub fn follow_next_collaborator(
1375 &mut self,
1376 _: &FollowNextCollaborator,
1377 cx: &mut ViewContext<Self>,
1378 ) -> Option<Task<Result<()>>> {
1379 let collaborators = self.project.read(cx).collaborators();
1380 let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
1381 let mut collaborators = collaborators.keys().copied();
1382 while let Some(peer_id) = collaborators.next() {
1383 if peer_id == leader_id {
1384 break;
1385 }
1386 }
1387 collaborators.next()
1388 } else if let Some(last_leader_id) =
1389 self.last_leaders_by_pane.get(&self.active_pane.downgrade())
1390 {
1391 if collaborators.contains_key(last_leader_id) {
1392 Some(*last_leader_id)
1393 } else {
1394 None
1395 }
1396 } else {
1397 None
1398 };
1399
1400 next_leader_id
1401 .or_else(|| collaborators.keys().copied().next())
1402 .and_then(|leader_id| self.toggle_follow(&ToggleFollow(leader_id), cx))
1403 }
1404
1405 pub fn unfollow(
1406 &mut self,
1407 pane: &ViewHandle<Pane>,
1408 cx: &mut ViewContext<Self>,
1409 ) -> Option<PeerId> {
1410 for (leader_id, states_by_pane) in &mut self.follower_states_by_leader {
1411 let leader_id = *leader_id;
1412 if let Some(state) = states_by_pane.remove(&pane) {
1413 for (_, item) in state.items_by_leader_view_id {
1414 if let FollowerItem::Loaded(item) = item {
1415 item.set_leader_replica_id(None, cx);
1416 }
1417 }
1418
1419 if states_by_pane.is_empty() {
1420 self.follower_states_by_leader.remove(&leader_id);
1421 if let Some(project_id) = self.project.read(cx).remote_id() {
1422 self.client
1423 .send(proto::Unfollow {
1424 project_id,
1425 leader_id: leader_id.0,
1426 })
1427 .log_err();
1428 }
1429 }
1430
1431 cx.notify();
1432 return Some(leader_id);
1433 }
1434 }
1435 None
1436 }
1437
1438 fn render_connection_status(&self, cx: &mut RenderContext<Self>) -> Option<ElementBox> {
1439 let theme = &cx.global::<Settings>().theme;
1440 match &*self.client.status().borrow() {
1441 client::Status::ConnectionError
1442 | client::Status::ConnectionLost
1443 | client::Status::Reauthenticating
1444 | client::Status::Reconnecting { .. }
1445 | client::Status::ReconnectionError { .. } => Some(
1446 Container::new(
1447 Align::new(
1448 ConstrainedBox::new(
1449 Svg::new("icons/offline-14.svg")
1450 .with_color(theme.workspace.titlebar.offline_icon.color)
1451 .boxed(),
1452 )
1453 .with_width(theme.workspace.titlebar.offline_icon.width)
1454 .boxed(),
1455 )
1456 .boxed(),
1457 )
1458 .with_style(theme.workspace.titlebar.offline_icon.container)
1459 .boxed(),
1460 ),
1461 client::Status::UpgradeRequired => Some(
1462 Label::new(
1463 "Please update Zed to collaborate".to_string(),
1464 theme.workspace.titlebar.outdated_warning.text.clone(),
1465 )
1466 .contained()
1467 .with_style(theme.workspace.titlebar.outdated_warning.container)
1468 .aligned()
1469 .boxed(),
1470 ),
1471 _ => None,
1472 }
1473 }
1474
1475 fn render_titlebar(&self, theme: &Theme, cx: &mut RenderContext<Self>) -> ElementBox {
1476 ConstrainedBox::new(
1477 Container::new(
1478 Stack::new()
1479 .with_child(
1480 Align::new(
1481 Label::new("zed".into(), theme.workspace.titlebar.title.clone())
1482 .boxed(),
1483 )
1484 .boxed(),
1485 )
1486 .with_child(
1487 Align::new(
1488 Flex::row()
1489 .with_children(self.render_share_icon(theme, cx))
1490 .with_children(self.render_collaborators(theme, cx))
1491 .with_child(self.render_current_user(
1492 self.user_store.read(cx).current_user().as_ref(),
1493 self.project.read(cx).replica_id(),
1494 theme,
1495 cx,
1496 ))
1497 .with_children(self.render_connection_status(cx))
1498 .boxed(),
1499 )
1500 .right()
1501 .boxed(),
1502 )
1503 .boxed(),
1504 )
1505 .with_style(theme.workspace.titlebar.container)
1506 .boxed(),
1507 )
1508 .with_height(theme.workspace.titlebar.height)
1509 .named("titlebar")
1510 }
1511
1512 fn render_collaborators(&self, theme: &Theme, cx: &mut RenderContext<Self>) -> Vec<ElementBox> {
1513 let mut collaborators = self
1514 .project
1515 .read(cx)
1516 .collaborators()
1517 .values()
1518 .cloned()
1519 .collect::<Vec<_>>();
1520 collaborators.sort_unstable_by_key(|collaborator| collaborator.replica_id);
1521 collaborators
1522 .into_iter()
1523 .filter_map(|collaborator| {
1524 Some(self.render_avatar(
1525 collaborator.user.avatar.clone()?,
1526 collaborator.replica_id,
1527 Some(collaborator.peer_id),
1528 theme,
1529 cx,
1530 ))
1531 })
1532 .collect()
1533 }
1534
1535 fn render_current_user(
1536 &self,
1537 user: Option<&Arc<User>>,
1538 replica_id: ReplicaId,
1539 theme: &Theme,
1540 cx: &mut RenderContext<Self>,
1541 ) -> ElementBox {
1542 if let Some(avatar) = user.and_then(|user| user.avatar.clone()) {
1543 self.render_avatar(avatar, replica_id, None, theme, cx)
1544 } else {
1545 MouseEventHandler::new::<Authenticate, _, _>(0, cx, |state, _| {
1546 let style = if state.hovered {
1547 &theme.workspace.titlebar.hovered_sign_in_prompt
1548 } else {
1549 &theme.workspace.titlebar.sign_in_prompt
1550 };
1551 Label::new("Sign in".to_string(), style.text.clone())
1552 .contained()
1553 .with_style(style.container)
1554 .boxed()
1555 })
1556 .on_click(|cx| cx.dispatch_action(Authenticate))
1557 .with_cursor_style(CursorStyle::PointingHand)
1558 .aligned()
1559 .boxed()
1560 }
1561 }
1562
1563 fn render_avatar(
1564 &self,
1565 avatar: Arc<ImageData>,
1566 replica_id: ReplicaId,
1567 peer_id: Option<PeerId>,
1568 theme: &Theme,
1569 cx: &mut RenderContext<Self>,
1570 ) -> ElementBox {
1571 let replica_color = theme.editor.replica_selection_style(replica_id).cursor;
1572 let is_followed = peer_id.map_or(false, |peer_id| {
1573 self.follower_states_by_leader.contains_key(&peer_id)
1574 });
1575 let mut avatar_style = theme.workspace.titlebar.avatar;
1576 if is_followed {
1577 avatar_style.border = Border::all(1.0, replica_color);
1578 }
1579 let content = Stack::new()
1580 .with_child(
1581 Image::new(avatar)
1582 .with_style(avatar_style)
1583 .constrained()
1584 .with_width(theme.workspace.titlebar.avatar_width)
1585 .aligned()
1586 .boxed(),
1587 )
1588 .with_child(
1589 AvatarRibbon::new(replica_color)
1590 .constrained()
1591 .with_width(theme.workspace.titlebar.avatar_ribbon.width)
1592 .with_height(theme.workspace.titlebar.avatar_ribbon.height)
1593 .aligned()
1594 .bottom()
1595 .boxed(),
1596 )
1597 .constrained()
1598 .with_width(theme.workspace.right_sidebar.width)
1599 .boxed();
1600
1601 if let Some(peer_id) = peer_id {
1602 MouseEventHandler::new::<ToggleFollow, _, _>(replica_id.into(), cx, move |_, _| content)
1603 .with_cursor_style(CursorStyle::PointingHand)
1604 .on_click(move |cx| cx.dispatch_action(ToggleFollow(peer_id)))
1605 .boxed()
1606 } else {
1607 content
1608 }
1609 }
1610
1611 fn render_share_icon(&self, theme: &Theme, cx: &mut RenderContext<Self>) -> Option<ElementBox> {
1612 if self.project().read(cx).is_local() && self.client.user_id().is_some() {
1613 let color = if self.project().read(cx).is_shared() {
1614 theme.workspace.titlebar.share_icon_active_color
1615 } else {
1616 theme.workspace.titlebar.share_icon_color
1617 };
1618 Some(
1619 MouseEventHandler::new::<ToggleShare, _, _>(0, cx, |_, _| {
1620 Align::new(
1621 Svg::new("icons/broadcast-24.svg")
1622 .with_color(color)
1623 .constrained()
1624 .with_width(24.)
1625 .boxed(),
1626 )
1627 .boxed()
1628 })
1629 .with_cursor_style(CursorStyle::PointingHand)
1630 .on_click(|cx| cx.dispatch_action(ToggleShare))
1631 .boxed(),
1632 )
1633 } else {
1634 None
1635 }
1636 }
1637
1638 fn render_disconnected_overlay(&self, cx: &AppContext) -> Option<ElementBox> {
1639 if self.project.read(cx).is_read_only() {
1640 let theme = &cx.global::<Settings>().theme;
1641 Some(
1642 EventHandler::new(
1643 Label::new(
1644 "Your connection to the remote project has been lost.".to_string(),
1645 theme.workspace.disconnected_overlay.text.clone(),
1646 )
1647 .aligned()
1648 .contained()
1649 .with_style(theme.workspace.disconnected_overlay.container)
1650 .boxed(),
1651 )
1652 .capture(|_, _, _| true)
1653 .boxed(),
1654 )
1655 } else {
1656 None
1657 }
1658 }
1659
1660 // RPC handlers
1661
1662 async fn handle_follow(
1663 this: ViewHandle<Self>,
1664 envelope: TypedEnvelope<proto::Follow>,
1665 _: Arc<Client>,
1666 mut cx: AsyncAppContext,
1667 ) -> Result<proto::FollowResponse> {
1668 this.update(&mut cx, |this, cx| {
1669 this.leader_state
1670 .followers
1671 .insert(envelope.original_sender_id()?);
1672
1673 let active_view_id = this
1674 .active_item(cx)
1675 .and_then(|i| i.to_followable_item_handle(cx))
1676 .map(|i| i.id() as u64);
1677 Ok(proto::FollowResponse {
1678 active_view_id,
1679 views: this
1680 .panes()
1681 .iter()
1682 .flat_map(|pane| {
1683 let leader_id = this.leader_for_pane(pane).map(|id| id.0);
1684 pane.read(cx).items().filter_map({
1685 let cx = &cx;
1686 move |item| {
1687 let id = item.id() as u64;
1688 let item = item.to_followable_item_handle(cx)?;
1689 let variant = item.to_state_proto(cx)?;
1690 Some(proto::View {
1691 id,
1692 leader_id,
1693 variant: Some(variant),
1694 })
1695 }
1696 })
1697 })
1698 .collect(),
1699 })
1700 })
1701 }
1702
1703 async fn handle_unfollow(
1704 this: ViewHandle<Self>,
1705 envelope: TypedEnvelope<proto::Unfollow>,
1706 _: Arc<Client>,
1707 mut cx: AsyncAppContext,
1708 ) -> Result<()> {
1709 this.update(&mut cx, |this, _| {
1710 this.leader_state
1711 .followers
1712 .remove(&envelope.original_sender_id()?);
1713 Ok(())
1714 })
1715 }
1716
1717 async fn handle_update_followers(
1718 this: ViewHandle<Self>,
1719 envelope: TypedEnvelope<proto::UpdateFollowers>,
1720 _: Arc<Client>,
1721 mut cx: AsyncAppContext,
1722 ) -> Result<()> {
1723 let leader_id = envelope.original_sender_id()?;
1724 match envelope
1725 .payload
1726 .variant
1727 .ok_or_else(|| anyhow!("invalid update"))?
1728 {
1729 proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
1730 this.update(&mut cx, |this, cx| {
1731 this.update_leader_state(leader_id, cx, |state, _| {
1732 state.active_view_id = update_active_view.id;
1733 });
1734 Ok::<_, anyhow::Error>(())
1735 })
1736 }
1737 proto::update_followers::Variant::UpdateView(update_view) => {
1738 this.update(&mut cx, |this, cx| {
1739 let variant = update_view
1740 .variant
1741 .ok_or_else(|| anyhow!("missing update view variant"))?;
1742 this.update_leader_state(leader_id, cx, |state, cx| {
1743 let variant = variant.clone();
1744 match state
1745 .items_by_leader_view_id
1746 .entry(update_view.id)
1747 .or_insert(FollowerItem::Loading(Vec::new()))
1748 {
1749 FollowerItem::Loaded(item) => {
1750 item.apply_update_proto(variant, cx).log_err();
1751 }
1752 FollowerItem::Loading(updates) => updates.push(variant),
1753 }
1754 });
1755 Ok(())
1756 })
1757 }
1758 proto::update_followers::Variant::CreateView(view) => {
1759 let panes = this.read_with(&cx, |this, _| {
1760 this.follower_states_by_leader
1761 .get(&leader_id)
1762 .into_iter()
1763 .flat_map(|states_by_pane| states_by_pane.keys())
1764 .cloned()
1765 .collect()
1766 });
1767 Self::add_views_from_leader(this.clone(), leader_id, panes, vec![view], &mut cx)
1768 .await?;
1769 Ok(())
1770 }
1771 }
1772 .log_err();
1773
1774 Ok(())
1775 }
1776
1777 async fn add_views_from_leader(
1778 this: ViewHandle<Self>,
1779 leader_id: PeerId,
1780 panes: Vec<ViewHandle<Pane>>,
1781 views: Vec<proto::View>,
1782 cx: &mut AsyncAppContext,
1783 ) -> Result<()> {
1784 let project = this.read_with(cx, |this, _| this.project.clone());
1785 let replica_id = project
1786 .read_with(cx, |project, _| {
1787 project
1788 .collaborators()
1789 .get(&leader_id)
1790 .map(|c| c.replica_id)
1791 })
1792 .ok_or_else(|| anyhow!("no such collaborator {}", leader_id))?;
1793
1794 let item_builders = cx.update(|cx| {
1795 cx.default_global::<FollowableItemBuilders>()
1796 .values()
1797 .map(|b| b.0)
1798 .collect::<Vec<_>>()
1799 .clone()
1800 });
1801
1802 let mut item_tasks_by_pane = HashMap::default();
1803 for pane in panes {
1804 let mut item_tasks = Vec::new();
1805 let mut leader_view_ids = Vec::new();
1806 for view in &views {
1807 let mut variant = view.variant.clone();
1808 if variant.is_none() {
1809 Err(anyhow!("missing variant"))?;
1810 }
1811 for build_item in &item_builders {
1812 let task =
1813 cx.update(|cx| build_item(pane.clone(), project.clone(), &mut variant, cx));
1814 if let Some(task) = task {
1815 item_tasks.push(task);
1816 leader_view_ids.push(view.id);
1817 break;
1818 } else {
1819 assert!(variant.is_some());
1820 }
1821 }
1822 }
1823
1824 item_tasks_by_pane.insert(pane, (item_tasks, leader_view_ids));
1825 }
1826
1827 for (pane, (item_tasks, leader_view_ids)) in item_tasks_by_pane {
1828 let items = futures::future::try_join_all(item_tasks).await?;
1829 this.update(cx, |this, cx| {
1830 let state = this
1831 .follower_states_by_leader
1832 .get_mut(&leader_id)?
1833 .get_mut(&pane)?;
1834
1835 for (id, item) in leader_view_ids.into_iter().zip(items) {
1836 item.set_leader_replica_id(Some(replica_id), cx);
1837 match state.items_by_leader_view_id.entry(id) {
1838 hash_map::Entry::Occupied(e) => {
1839 let e = e.into_mut();
1840 if let FollowerItem::Loading(updates) = e {
1841 for update in updates.drain(..) {
1842 item.apply_update_proto(update, cx)
1843 .context("failed to apply view update")
1844 .log_err();
1845 }
1846 }
1847 *e = FollowerItem::Loaded(item);
1848 }
1849 hash_map::Entry::Vacant(e) => {
1850 e.insert(FollowerItem::Loaded(item));
1851 }
1852 }
1853 }
1854
1855 Some(())
1856 });
1857 }
1858 this.update(cx, |this, cx| this.leader_updated(leader_id, cx));
1859
1860 Ok(())
1861 }
1862
1863 fn update_followers(
1864 &self,
1865 update: proto::update_followers::Variant,
1866 cx: &AppContext,
1867 ) -> Option<()> {
1868 let project_id = self.project.read(cx).remote_id()?;
1869 if !self.leader_state.followers.is_empty() {
1870 self.client
1871 .send(proto::UpdateFollowers {
1872 project_id,
1873 follower_ids: self.leader_state.followers.iter().map(|f| f.0).collect(),
1874 variant: Some(update),
1875 })
1876 .log_err();
1877 }
1878 None
1879 }
1880
1881 pub fn leader_for_pane(&self, pane: &ViewHandle<Pane>) -> Option<PeerId> {
1882 self.follower_states_by_leader
1883 .iter()
1884 .find_map(|(leader_id, state)| {
1885 if state.contains_key(pane) {
1886 Some(*leader_id)
1887 } else {
1888 None
1889 }
1890 })
1891 }
1892
1893 fn update_leader_state(
1894 &mut self,
1895 leader_id: PeerId,
1896 cx: &mut ViewContext<Self>,
1897 mut update_fn: impl FnMut(&mut FollowerState, &mut ViewContext<Self>),
1898 ) {
1899 for (_, state) in self
1900 .follower_states_by_leader
1901 .get_mut(&leader_id)
1902 .into_iter()
1903 .flatten()
1904 {
1905 update_fn(state, cx);
1906 }
1907 self.leader_updated(leader_id, cx);
1908 }
1909
1910 fn leader_updated(&mut self, leader_id: PeerId, cx: &mut ViewContext<Self>) -> Option<()> {
1911 let mut items_to_add = Vec::new();
1912 for (pane, state) in self.follower_states_by_leader.get(&leader_id)? {
1913 if let Some(active_item) = state
1914 .active_view_id
1915 .and_then(|id| state.items_by_leader_view_id.get(&id))
1916 {
1917 if let FollowerItem::Loaded(item) = active_item {
1918 items_to_add.push((pane.clone(), item.boxed_clone()));
1919 }
1920 }
1921 }
1922
1923 for (pane, item) in items_to_add {
1924 Pane::add_item(self, pane.clone(), item.boxed_clone(), false, cx);
1925 if pane == self.active_pane {
1926 pane.update(cx, |pane, cx| pane.focus_active_item(cx));
1927 }
1928 cx.notify();
1929 }
1930 None
1931 }
1932}
1933
1934impl Entity for Workspace {
1935 type Event = Event;
1936}
1937
1938impl View for Workspace {
1939 fn ui_name() -> &'static str {
1940 "Workspace"
1941 }
1942
1943 fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
1944 let theme = cx.global::<Settings>().theme.clone();
1945 Stack::new()
1946 .with_child(
1947 Flex::column()
1948 .with_child(self.render_titlebar(&theme, cx))
1949 .with_child(
1950 Stack::new()
1951 .with_child({
1952 let mut content = Flex::row();
1953 content.add_child(self.left_sidebar.render(&theme, cx));
1954 if let Some(element) =
1955 self.left_sidebar.render_active_item(&theme, cx)
1956 {
1957 content
1958 .add_child(FlexItem::new(element).flex(0.8, false).boxed());
1959 }
1960 content.add_child(
1961 Flex::column()
1962 .with_child(
1963 FlexItem::new(self.center.render(
1964 &theme,
1965 &self.follower_states_by_leader,
1966 self.project.read(cx).collaborators(),
1967 ))
1968 .flex(1., true)
1969 .boxed(),
1970 )
1971 .with_child(ChildView::new(&self.status_bar).boxed())
1972 .flex(1., true)
1973 .boxed(),
1974 );
1975 if let Some(element) =
1976 self.right_sidebar.render_active_item(&theme, cx)
1977 {
1978 content
1979 .add_child(FlexItem::new(element).flex(0.8, false).boxed());
1980 }
1981 content.add_child(self.right_sidebar.render(&theme, cx));
1982 content.boxed()
1983 })
1984 .with_children(self.modal.as_ref().map(|m| ChildView::new(m).boxed()))
1985 .flex(1.0, true)
1986 .boxed(),
1987 )
1988 .contained()
1989 .with_background_color(theme.workspace.background)
1990 .boxed(),
1991 )
1992 .with_children(self.render_disconnected_overlay(cx))
1993 .named("workspace")
1994 }
1995
1996 fn on_focus(&mut self, cx: &mut ViewContext<Self>) {
1997 cx.focus(&self.active_pane);
1998 }
1999}
2000
2001pub trait WorkspaceHandle {
2002 fn file_project_paths(&self, cx: &AppContext) -> Vec<ProjectPath>;
2003}
2004
2005impl WorkspaceHandle for ViewHandle<Workspace> {
2006 fn file_project_paths(&self, cx: &AppContext) -> Vec<ProjectPath> {
2007 self.read(cx)
2008 .worktrees(cx)
2009 .flat_map(|worktree| {
2010 let worktree_id = worktree.read(cx).id();
2011 worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
2012 worktree_id,
2013 path: f.path.clone(),
2014 })
2015 })
2016 .collect::<Vec<_>>()
2017 }
2018}
2019
2020pub struct AvatarRibbon {
2021 color: Color,
2022}
2023
2024impl AvatarRibbon {
2025 pub fn new(color: Color) -> AvatarRibbon {
2026 AvatarRibbon { color }
2027 }
2028}
2029
2030impl Element for AvatarRibbon {
2031 type LayoutState = ();
2032
2033 type PaintState = ();
2034
2035 fn layout(
2036 &mut self,
2037 constraint: gpui::SizeConstraint,
2038 _: &mut gpui::LayoutContext,
2039 ) -> (gpui::geometry::vector::Vector2F, Self::LayoutState) {
2040 (constraint.max, ())
2041 }
2042
2043 fn paint(
2044 &mut self,
2045 bounds: gpui::geometry::rect::RectF,
2046 _: gpui::geometry::rect::RectF,
2047 _: &mut Self::LayoutState,
2048 cx: &mut gpui::PaintContext,
2049 ) -> Self::PaintState {
2050 let mut path = PathBuilder::new();
2051 path.reset(bounds.lower_left());
2052 path.curve_to(
2053 bounds.origin() + vec2f(bounds.height(), 0.),
2054 bounds.origin(),
2055 );
2056 path.line_to(bounds.upper_right() - vec2f(bounds.height(), 0.));
2057 path.curve_to(bounds.lower_right(), bounds.upper_right());
2058 path.line_to(bounds.lower_left());
2059 cx.scene.push_path(path.build(self.color, None));
2060 }
2061
2062 fn dispatch_event(
2063 &mut self,
2064 _: &gpui::Event,
2065 _: RectF,
2066 _: RectF,
2067 _: &mut Self::LayoutState,
2068 _: &mut Self::PaintState,
2069 _: &mut gpui::EventContext,
2070 ) -> bool {
2071 false
2072 }
2073
2074 fn debug(
2075 &self,
2076 bounds: gpui::geometry::rect::RectF,
2077 _: &Self::LayoutState,
2078 _: &Self::PaintState,
2079 _: &gpui::DebugContext,
2080 ) -> gpui::json::Value {
2081 json::json!({
2082 "type": "AvatarRibbon",
2083 "bounds": bounds.to_json(),
2084 "color": self.color.to_json(),
2085 })
2086 }
2087}
2088
2089impl std::fmt::Debug for OpenPaths {
2090 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2091 f.debug_struct("OpenPaths")
2092 .field("paths", &self.paths)
2093 .finish()
2094 }
2095}
2096
2097fn open(action: &Open, cx: &mut MutableAppContext) {
2098 let app_state = action.0.clone();
2099 let mut paths = cx.prompt_for_paths(PathPromptOptions {
2100 files: true,
2101 directories: true,
2102 multiple: true,
2103 });
2104 cx.spawn(|mut cx| async move {
2105 if let Some(paths) = paths.recv().await.flatten() {
2106 cx.update(|cx| cx.dispatch_global_action(OpenPaths { paths, app_state }));
2107 }
2108 })
2109 .detach();
2110}
2111
2112pub struct WorkspaceCreated(WeakViewHandle<Workspace>);
2113
2114pub fn open_paths(
2115 abs_paths: &[PathBuf],
2116 app_state: &Arc<AppState>,
2117 cx: &mut MutableAppContext,
2118) -> Task<(
2119 ViewHandle<Workspace>,
2120 Vec<Option<Result<Box<dyn ItemHandle>, Arc<anyhow::Error>>>>,
2121)> {
2122 log::info!("open paths {:?}", abs_paths);
2123
2124 // Open paths in existing workspace if possible
2125 let mut existing = None;
2126 for window_id in cx.window_ids().collect::<Vec<_>>() {
2127 if let Some(workspace_handle) = cx.root_view::<Workspace>(window_id) {
2128 if workspace_handle.update(cx, |workspace, cx| {
2129 if workspace.contains_paths(abs_paths, cx.as_ref()) {
2130 cx.activate_window(window_id);
2131 existing = Some(workspace_handle.clone());
2132 true
2133 } else {
2134 false
2135 }
2136 }) {
2137 break;
2138 }
2139 }
2140 }
2141
2142 let workspace = existing.unwrap_or_else(|| {
2143 cx.add_window((app_state.build_window_options)(), |cx| {
2144 let project = Project::local(
2145 app_state.client.clone(),
2146 app_state.user_store.clone(),
2147 app_state.languages.clone(),
2148 app_state.fs.clone(),
2149 cx,
2150 );
2151 (app_state.build_workspace)(project, &app_state, cx)
2152 })
2153 .1
2154 });
2155
2156 let task = workspace.update(cx, |workspace, cx| workspace.open_paths(abs_paths, cx));
2157 cx.spawn(|_| async move {
2158 let items = task.await;
2159 (workspace, items)
2160 })
2161}
2162
2163pub fn join_project(
2164 project_id: u64,
2165 app_state: &Arc<AppState>,
2166 cx: &mut MutableAppContext,
2167) -> Task<Result<ViewHandle<Workspace>>> {
2168 for window_id in cx.window_ids().collect::<Vec<_>>() {
2169 if let Some(workspace) = cx.root_view::<Workspace>(window_id) {
2170 if workspace.read(cx).project().read(cx).remote_id() == Some(project_id) {
2171 return Task::ready(Ok(workspace));
2172 }
2173 }
2174 }
2175
2176 let app_state = app_state.clone();
2177 cx.spawn(|mut cx| async move {
2178 let project = Project::remote(
2179 project_id,
2180 app_state.client.clone(),
2181 app_state.user_store.clone(),
2182 app_state.languages.clone(),
2183 app_state.fs.clone(),
2184 &mut cx,
2185 )
2186 .await?;
2187 Ok(cx.update(|cx| {
2188 cx.add_window((app_state.build_window_options)(), |cx| {
2189 (app_state.build_workspace)(project, &app_state, cx)
2190 })
2191 .1
2192 }))
2193 })
2194}
2195
2196fn open_new(app_state: &Arc<AppState>, cx: &mut MutableAppContext) {
2197 let (window_id, workspace) = cx.add_window((app_state.build_window_options)(), |cx| {
2198 let project = Project::local(
2199 app_state.client.clone(),
2200 app_state.user_store.clone(),
2201 app_state.languages.clone(),
2202 app_state.fs.clone(),
2203 cx,
2204 );
2205 (app_state.build_workspace)(project, &app_state, cx)
2206 });
2207 cx.dispatch_action(window_id, vec![workspace.id()], &OpenNew(app_state.clone()));
2208}