1use anyhow::Result;
2use gpui::PathPromptOptions;
3use gpui::{
4 AnyView, App, Context, DragMoveEvent, Entity, EntityId, EventEmitter, FocusHandle, Focusable,
5 ManagedView, MouseButton, Pixels, Render, Subscription, Task, Tiling, Window, WindowId,
6 actions, deferred, px,
7};
8use project::{DirectoryLister, DisableAiSettings, Project, ProjectGroupKey};
9use remote::RemoteConnectionOptions;
10use settings::Settings;
11pub use settings::SidebarSide;
12use std::collections::{HashMap, HashSet};
13use std::future::Future;
14use std::path::Path;
15use std::path::PathBuf;
16use ui::prelude::*;
17use util::ResultExt;
18use util::path_list::PathList;
19use zed_actions::agents_sidebar::ToggleThreadSwitcher;
20
21use agent_settings::AgentSettings;
22use settings::SidebarDockPosition;
23use ui::{ContextMenu, right_click_menu};
24
25const SIDEBAR_RESIZE_HANDLE_SIZE: Pixels = px(6.0);
26
27use crate::open_remote_project_with_existing_connection;
28use crate::{
29 CloseIntent, CloseWindow, DockPosition, Event as WorkspaceEvent, Item, ModalView, OpenMode,
30 Panel, Workspace, WorkspaceId, client_side_decorations,
31 persistence::model::MultiWorkspaceState,
32};
33
34actions!(
35 multi_workspace,
36 [
37 /// Toggles the workspace switcher sidebar.
38 ToggleWorkspaceSidebar,
39 /// Closes the workspace sidebar.
40 CloseWorkspaceSidebar,
41 /// Moves focus to or from the workspace sidebar without closing it.
42 FocusWorkspaceSidebar,
43 /// Activates the next project in the sidebar.
44 NextProject,
45 /// Activates the previous project in the sidebar.
46 PreviousProject,
47 /// Activates the next thread in sidebar order.
48 NextThread,
49 /// Activates the previous thread in sidebar order.
50 PreviousThread,
51 /// Expands the thread list for the current project to show more threads.
52 ShowMoreThreads,
53 /// Collapses the thread list for the current project to show fewer threads.
54 ShowFewerThreads,
55 /// Creates a new thread in the current workspace.
56 NewThread,
57 ]
58);
59
60#[derive(Default)]
61pub struct SidebarRenderState {
62 pub open: bool,
63 pub side: SidebarSide,
64}
65
66pub fn sidebar_side_context_menu(
67 id: impl Into<ElementId>,
68 cx: &App,
69) -> ui::RightClickMenu<ContextMenu> {
70 let current_position = AgentSettings::get_global(cx).sidebar_side;
71 right_click_menu(id).menu(move |window, cx| {
72 let fs = <dyn fs::Fs>::global(cx);
73 ContextMenu::build(window, cx, move |mut menu, _, _cx| {
74 let positions: [(SidebarDockPosition, &str); 2] = [
75 (SidebarDockPosition::Left, "Left"),
76 (SidebarDockPosition::Right, "Right"),
77 ];
78 for (position, label) in positions {
79 let fs = fs.clone();
80 menu = menu.toggleable_entry(
81 label,
82 position == current_position,
83 IconPosition::Start,
84 None,
85 move |_window, cx| {
86 settings::update_settings_file(fs.clone(), cx, move |settings, _cx| {
87 settings
88 .agent
89 .get_or_insert_default()
90 .set_sidebar_side(position);
91 });
92 },
93 );
94 }
95 menu
96 })
97 })
98}
99
100pub enum MultiWorkspaceEvent {
101 ActiveWorkspaceChanged,
102 WorkspaceAdded(Entity<Workspace>),
103 WorkspaceRemoved(EntityId),
104}
105
106pub enum SidebarEvent {
107 SerializeNeeded,
108}
109
110pub trait Sidebar: Focusable + Render + EventEmitter<SidebarEvent> + Sized {
111 fn width(&self, cx: &App) -> Pixels;
112 fn set_width(&mut self, width: Option<Pixels>, cx: &mut Context<Self>);
113 fn has_notifications(&self, cx: &App) -> bool;
114 fn side(&self, _cx: &App) -> SidebarSide;
115
116 fn is_threads_list_view_active(&self) -> bool {
117 true
118 }
119 /// Makes focus reset back to the search editor upon toggling the sidebar from outside
120 fn prepare_for_focus(&mut self, _window: &mut Window, _cx: &mut Context<Self>) {}
121 /// Opens or cycles the thread switcher popup.
122 fn toggle_thread_switcher(
123 &mut self,
124 _select_last: bool,
125 _window: &mut Window,
126 _cx: &mut Context<Self>,
127 ) {
128 }
129
130 /// Activates the next or previous project.
131 fn cycle_project(&mut self, _forward: bool, _window: &mut Window, _cx: &mut Context<Self>) {}
132
133 /// Activates the next or previous thread in sidebar order.
134 fn cycle_thread(&mut self, _forward: bool, _window: &mut Window, _cx: &mut Context<Self>) {}
135
136 /// Return an opaque JSON blob of sidebar-specific state to persist.
137 fn serialized_state(&self, _cx: &App) -> Option<String> {
138 None
139 }
140
141 /// Restore sidebar state from a previously-serialized blob.
142 fn restore_serialized_state(
143 &mut self,
144 _state: &str,
145 _window: &mut Window,
146 _cx: &mut Context<Self>,
147 ) {
148 }
149}
150
151pub trait SidebarHandle: 'static + Send + Sync {
152 fn width(&self, cx: &App) -> Pixels;
153 fn set_width(&self, width: Option<Pixels>, cx: &mut App);
154 fn focus_handle(&self, cx: &App) -> FocusHandle;
155 fn focus(&self, window: &mut Window, cx: &mut App);
156 fn prepare_for_focus(&self, window: &mut Window, cx: &mut App);
157 fn has_notifications(&self, cx: &App) -> bool;
158 fn to_any(&self) -> AnyView;
159 fn entity_id(&self) -> EntityId;
160 fn toggle_thread_switcher(&self, select_last: bool, window: &mut Window, cx: &mut App);
161 fn cycle_project(&self, forward: bool, window: &mut Window, cx: &mut App);
162 fn cycle_thread(&self, forward: bool, window: &mut Window, cx: &mut App);
163
164 fn is_threads_list_view_active(&self, cx: &App) -> bool;
165
166 fn side(&self, cx: &App) -> SidebarSide;
167 fn serialized_state(&self, cx: &App) -> Option<String>;
168 fn restore_serialized_state(&self, state: &str, window: &mut Window, cx: &mut App);
169}
170
171#[derive(Clone)]
172pub struct DraggedSidebar;
173
174impl Render for DraggedSidebar {
175 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
176 gpui::Empty
177 }
178}
179
180impl<T: Sidebar> SidebarHandle for Entity<T> {
181 fn width(&self, cx: &App) -> Pixels {
182 self.read(cx).width(cx)
183 }
184
185 fn set_width(&self, width: Option<Pixels>, cx: &mut App) {
186 self.update(cx, |this, cx| this.set_width(width, cx))
187 }
188
189 fn focus_handle(&self, cx: &App) -> FocusHandle {
190 self.read(cx).focus_handle(cx)
191 }
192
193 fn focus(&self, window: &mut Window, cx: &mut App) {
194 let handle = self.read(cx).focus_handle(cx);
195 window.focus(&handle, cx);
196 }
197
198 fn prepare_for_focus(&self, window: &mut Window, cx: &mut App) {
199 self.update(cx, |this, cx| this.prepare_for_focus(window, cx));
200 }
201
202 fn has_notifications(&self, cx: &App) -> bool {
203 self.read(cx).has_notifications(cx)
204 }
205
206 fn to_any(&self) -> AnyView {
207 self.clone().into()
208 }
209
210 fn entity_id(&self) -> EntityId {
211 Entity::entity_id(self)
212 }
213
214 fn toggle_thread_switcher(&self, select_last: bool, window: &mut Window, cx: &mut App) {
215 let entity = self.clone();
216 window.defer(cx, move |window, cx| {
217 entity.update(cx, |this, cx| {
218 this.toggle_thread_switcher(select_last, window, cx);
219 });
220 });
221 }
222
223 fn cycle_project(&self, forward: bool, window: &mut Window, cx: &mut App) {
224 let entity = self.clone();
225 window.defer(cx, move |window, cx| {
226 entity.update(cx, |this, cx| {
227 this.cycle_project(forward, window, cx);
228 });
229 });
230 }
231
232 fn cycle_thread(&self, forward: bool, window: &mut Window, cx: &mut App) {
233 let entity = self.clone();
234 window.defer(cx, move |window, cx| {
235 entity.update(cx, |this, cx| {
236 this.cycle_thread(forward, window, cx);
237 });
238 });
239 }
240
241 fn is_threads_list_view_active(&self, cx: &App) -> bool {
242 self.read(cx).is_threads_list_view_active()
243 }
244
245 fn side(&self, cx: &App) -> SidebarSide {
246 self.read(cx).side(cx)
247 }
248
249 fn serialized_state(&self, cx: &App) -> Option<String> {
250 self.read(cx).serialized_state(cx)
251 }
252
253 fn restore_serialized_state(&self, state: &str, window: &mut Window, cx: &mut App) {
254 self.update(cx, |this, cx| {
255 this.restore_serialized_state(state, window, cx)
256 })
257 }
258}
259
260/// Tracks which workspace the user is currently looking at.
261///
262/// `Persistent` workspaces live in the `workspaces` vec and are shown in the
263/// sidebar. `Transient` workspaces exist outside the vec and are discarded
264/// when the user switches away.
265enum ActiveWorkspace {
266 /// A persistent workspace, identified by index into the `workspaces` vec.
267 Persistent(usize),
268 /// A workspace not in the `workspaces` vec that will be discarded on
269 /// switch or promoted to persistent when the sidebar is opened.
270 Transient(Entity<Workspace>),
271}
272
273impl ActiveWorkspace {
274 fn transient_workspace(&self) -> Option<&Entity<Workspace>> {
275 match self {
276 Self::Transient(workspace) => Some(workspace),
277 Self::Persistent(_) => None,
278 }
279 }
280
281 /// Sets the active workspace to transient, returning the previous
282 /// transient workspace (if any).
283 fn set_transient(&mut self, workspace: Entity<Workspace>) -> Option<Entity<Workspace>> {
284 match std::mem::replace(self, Self::Transient(workspace)) {
285 Self::Transient(old) => Some(old),
286 Self::Persistent(_) => None,
287 }
288 }
289
290 /// Sets the active workspace to persistent at the given index,
291 /// returning the previous transient workspace (if any).
292 fn set_persistent(&mut self, index: usize) -> Option<Entity<Workspace>> {
293 match std::mem::replace(self, Self::Persistent(index)) {
294 Self::Transient(workspace) => Some(workspace),
295 Self::Persistent(_) => None,
296 }
297 }
298}
299
300pub struct MultiWorkspace {
301 window_id: WindowId,
302 workspaces: Vec<Entity<Workspace>>,
303 active_workspace: ActiveWorkspace,
304 project_group_keys: Vec<ProjectGroupKey>,
305 provisional_project_group_keys: HashMap<EntityId, ProjectGroupKey>,
306 sidebar: Option<Box<dyn SidebarHandle>>,
307 sidebar_open: bool,
308 sidebar_overlay: Option<AnyView>,
309 pending_removal_tasks: Vec<Task<()>>,
310 _serialize_task: Option<Task<()>>,
311 _subscriptions: Vec<Subscription>,
312 previous_focus_handle: Option<FocusHandle>,
313}
314
315impl EventEmitter<MultiWorkspaceEvent> for MultiWorkspace {}
316
317impl MultiWorkspace {
318 pub fn sidebar_side(&self, cx: &App) -> SidebarSide {
319 self.sidebar
320 .as_ref()
321 .map_or(SidebarSide::Left, |s| s.side(cx))
322 }
323
324 pub fn sidebar_render_state(&self, cx: &App) -> SidebarRenderState {
325 SidebarRenderState {
326 open: self.sidebar_open() && self.multi_workspace_enabled(cx),
327 side: self.sidebar_side(cx),
328 }
329 }
330
331 pub fn new(workspace: Entity<Workspace>, window: &mut Window, cx: &mut Context<Self>) -> Self {
332 let release_subscription = cx.on_release(|this: &mut MultiWorkspace, _cx| {
333 if let Some(task) = this._serialize_task.take() {
334 task.detach();
335 }
336 for task in std::mem::take(&mut this.pending_removal_tasks) {
337 task.detach();
338 }
339 });
340 let quit_subscription = cx.on_app_quit(Self::app_will_quit);
341 let settings_subscription = cx.observe_global_in::<settings::SettingsStore>(window, {
342 let mut previous_disable_ai = DisableAiSettings::get_global(cx).disable_ai;
343 move |this, window, cx| {
344 if DisableAiSettings::get_global(cx).disable_ai != previous_disable_ai {
345 this.collapse_to_single_workspace(window, cx);
346 previous_disable_ai = DisableAiSettings::get_global(cx).disable_ai;
347 }
348 }
349 });
350 Self::subscribe_to_workspace(&workspace, window, cx);
351 let weak_self = cx.weak_entity();
352 workspace.update(cx, |workspace, cx| {
353 workspace.set_multi_workspace(weak_self, cx);
354 });
355 Self {
356 window_id: window.window_handle().window_id(),
357 project_group_keys: Vec::new(),
358 provisional_project_group_keys: HashMap::default(),
359 workspaces: Vec::new(),
360 active_workspace: ActiveWorkspace::Transient(workspace),
361 sidebar: None,
362 sidebar_open: false,
363 sidebar_overlay: None,
364 pending_removal_tasks: Vec::new(),
365 _serialize_task: None,
366 _subscriptions: vec![
367 release_subscription,
368 quit_subscription,
369 settings_subscription,
370 ],
371 previous_focus_handle: None,
372 }
373 }
374
375 pub fn register_sidebar<T: Sidebar>(&mut self, sidebar: Entity<T>, cx: &mut Context<Self>) {
376 self._subscriptions
377 .push(cx.observe(&sidebar, |_this, _, cx| {
378 cx.notify();
379 }));
380 self._subscriptions
381 .push(cx.subscribe(&sidebar, |this, _, event, cx| match event {
382 SidebarEvent::SerializeNeeded => {
383 this.serialize(cx);
384 }
385 }));
386 self.sidebar = Some(Box::new(sidebar));
387 }
388
389 pub fn sidebar(&self) -> Option<&dyn SidebarHandle> {
390 self.sidebar.as_deref()
391 }
392
393 pub fn set_sidebar_overlay(&mut self, overlay: Option<AnyView>, cx: &mut Context<Self>) {
394 self.sidebar_overlay = overlay;
395 cx.notify();
396 }
397
398 pub fn sidebar_open(&self) -> bool {
399 self.sidebar_open
400 }
401
402 pub fn sidebar_has_notifications(&self, cx: &App) -> bool {
403 self.sidebar
404 .as_ref()
405 .map_or(false, |s| s.has_notifications(cx))
406 }
407
408 pub fn is_threads_list_view_active(&self, cx: &App) -> bool {
409 self.sidebar
410 .as_ref()
411 .map_or(false, |s| s.is_threads_list_view_active(cx))
412 }
413
414 pub fn multi_workspace_enabled(&self, cx: &App) -> bool {
415 !DisableAiSettings::get_global(cx).disable_ai
416 }
417
418 pub fn toggle_sidebar(&mut self, window: &mut Window, cx: &mut Context<Self>) {
419 if !self.multi_workspace_enabled(cx) {
420 return;
421 }
422
423 if self.sidebar_open() {
424 self.close_sidebar(window, cx);
425 } else {
426 self.previous_focus_handle = window.focused(cx);
427 self.open_sidebar(cx);
428 if let Some(sidebar) = &self.sidebar {
429 sidebar.prepare_for_focus(window, cx);
430 sidebar.focus(window, cx);
431 }
432 }
433 }
434
435 pub fn close_sidebar_action(&mut self, window: &mut Window, cx: &mut Context<Self>) {
436 if !self.multi_workspace_enabled(cx) {
437 return;
438 }
439
440 if self.sidebar_open() {
441 self.close_sidebar(window, cx);
442 }
443 }
444
445 pub fn focus_sidebar(&mut self, window: &mut Window, cx: &mut Context<Self>) {
446 if !self.multi_workspace_enabled(cx) {
447 return;
448 }
449
450 if self.sidebar_open() {
451 let sidebar_is_focused = self
452 .sidebar
453 .as_ref()
454 .is_some_and(|s| s.focus_handle(cx).contains_focused(window, cx));
455
456 if sidebar_is_focused {
457 self.restore_previous_focus(false, window, cx);
458 } else {
459 self.previous_focus_handle = window.focused(cx);
460 if let Some(sidebar) = &self.sidebar {
461 sidebar.prepare_for_focus(window, cx);
462 sidebar.focus(window, cx);
463 }
464 }
465 } else {
466 self.previous_focus_handle = window.focused(cx);
467 self.open_sidebar(cx);
468 if let Some(sidebar) = &self.sidebar {
469 sidebar.prepare_for_focus(window, cx);
470 sidebar.focus(window, cx);
471 }
472 }
473 }
474
475 pub fn open_sidebar(&mut self, cx: &mut Context<Self>) {
476 self.sidebar_open = true;
477 if let ActiveWorkspace::Transient(workspace) = &self.active_workspace {
478 let workspace = workspace.clone();
479 let index = self.promote_transient(workspace, cx);
480 self.active_workspace = ActiveWorkspace::Persistent(index);
481 }
482 let sidebar_focus_handle = self.sidebar.as_ref().map(|s| s.focus_handle(cx));
483 for workspace in self.workspaces.iter() {
484 workspace.update(cx, |workspace, _cx| {
485 workspace.set_sidebar_focus_handle(sidebar_focus_handle.clone());
486 });
487 }
488 self.serialize(cx);
489 cx.notify();
490 }
491
492 pub fn close_sidebar(&mut self, window: &mut Window, cx: &mut Context<Self>) {
493 self.sidebar_open = false;
494 for workspace in self.workspaces.iter() {
495 workspace.update(cx, |workspace, _cx| {
496 workspace.set_sidebar_focus_handle(None);
497 });
498 }
499 let sidebar_has_focus = self
500 .sidebar
501 .as_ref()
502 .is_some_and(|s| s.focus_handle(cx).contains_focused(window, cx));
503 if sidebar_has_focus {
504 self.restore_previous_focus(true, window, cx);
505 } else {
506 self.previous_focus_handle.take();
507 }
508 self.serialize(cx);
509 cx.notify();
510 }
511
512 fn restore_previous_focus(&mut self, clear: bool, window: &mut Window, cx: &mut Context<Self>) {
513 let focus_handle = if clear {
514 self.previous_focus_handle.take()
515 } else {
516 self.previous_focus_handle.clone()
517 };
518
519 if let Some(previous_focus) = focus_handle {
520 previous_focus.focus(window, cx);
521 } else {
522 let pane = self.workspace().read(cx).active_pane().clone();
523 window.focus(&pane.read(cx).focus_handle(cx), cx);
524 }
525 }
526
527 pub fn close_window(&mut self, _: &CloseWindow, window: &mut Window, cx: &mut Context<Self>) {
528 cx.spawn_in(window, async move |this, cx| {
529 let workspaces = this.update(cx, |multi_workspace, _cx| {
530 multi_workspace.workspaces().cloned().collect::<Vec<_>>()
531 })?;
532
533 for workspace in workspaces {
534 let should_continue = workspace
535 .update_in(cx, |workspace, window, cx| {
536 workspace.prepare_to_close(CloseIntent::CloseWindow, window, cx)
537 })?
538 .await?;
539 if !should_continue {
540 return anyhow::Ok(());
541 }
542 }
543
544 cx.update(|window, _cx| {
545 window.remove_window();
546 })?;
547
548 anyhow::Ok(())
549 })
550 .detach_and_log_err(cx);
551 }
552
553 fn subscribe_to_workspace(
554 workspace: &Entity<Workspace>,
555 window: &Window,
556 cx: &mut Context<Self>,
557 ) {
558 let project = workspace.read(cx).project().clone();
559 cx.subscribe_in(&project, window, {
560 let workspace = workspace.downgrade();
561 move |this, _project, event, _window, cx| match event {
562 project::Event::WorktreeAdded(_) | project::Event::WorktreeRemoved(_) => {
563 if let Some(workspace) = workspace.upgrade() {
564 this.add_project_group_key(workspace.read(cx).project_group_key(cx));
565 }
566 }
567 project::Event::WorktreeUpdatedRootRepoCommonDir(_) => {
568 if let Some(workspace) = workspace.upgrade() {
569 this.maybe_clear_provisional_project_group_key(&workspace, cx);
570 this.add_project_group_key(
571 this.project_group_key_for_workspace(&workspace, cx),
572 );
573 this.remove_stale_project_group_keys(cx);
574 cx.notify();
575 }
576 }
577 _ => {}
578 }
579 })
580 .detach();
581
582 cx.subscribe_in(workspace, window, |this, workspace, event, window, cx| {
583 if let WorkspaceEvent::Activate = event {
584 this.activate(workspace.clone(), window, cx);
585 }
586 })
587 .detach();
588 }
589
590 pub fn add_project_group_key(&mut self, project_group_key: ProjectGroupKey) {
591 if project_group_key.path_list().paths().is_empty() {
592 return;
593 }
594 if self.project_group_keys.contains(&project_group_key) {
595 return;
596 }
597 // Store newest first so the vec is in "most recently added"
598 self.project_group_keys.insert(0, project_group_key);
599 }
600
601 pub fn set_provisional_project_group_key(
602 &mut self,
603 workspace: &Entity<Workspace>,
604 project_group_key: ProjectGroupKey,
605 ) {
606 self.provisional_project_group_keys
607 .insert(workspace.entity_id(), project_group_key.clone());
608 self.add_project_group_key(project_group_key);
609 }
610
611 pub fn project_group_key_for_workspace(
612 &self,
613 workspace: &Entity<Workspace>,
614 cx: &App,
615 ) -> ProjectGroupKey {
616 self.provisional_project_group_keys
617 .get(&workspace.entity_id())
618 .cloned()
619 .unwrap_or_else(|| workspace.read(cx).project_group_key(cx))
620 }
621
622 fn maybe_clear_provisional_project_group_key(
623 &mut self,
624 workspace: &Entity<Workspace>,
625 cx: &App,
626 ) {
627 let live_key = workspace.read(cx).project_group_key(cx);
628 if self
629 .provisional_project_group_keys
630 .get(&workspace.entity_id())
631 .is_some_and(|key| *key == live_key)
632 {
633 self.provisional_project_group_keys
634 .remove(&workspace.entity_id());
635 }
636 }
637
638 fn remove_stale_project_group_keys(&mut self, cx: &App) {
639 let workspace_keys: HashSet<ProjectGroupKey> = self
640 .workspaces
641 .iter()
642 .map(|workspace| self.project_group_key_for_workspace(workspace, cx))
643 .collect();
644 self.project_group_keys
645 .retain(|key| workspace_keys.contains(key));
646 }
647
648 pub fn restore_project_group_keys(&mut self, keys: Vec<ProjectGroupKey>) {
649 let mut restored: Vec<ProjectGroupKey> = Vec::with_capacity(keys.len());
650 for key in keys {
651 if key.path_list().paths().is_empty() {
652 continue;
653 }
654 if !restored.contains(&key) {
655 restored.push(key);
656 }
657 }
658 for existing_key in &self.project_group_keys {
659 if !restored.contains(existing_key) {
660 restored.push(existing_key.clone());
661 }
662 }
663 self.project_group_keys = restored;
664 }
665
666 pub fn project_group_keys(&self) -> impl Iterator<Item = &ProjectGroupKey> {
667 self.project_group_keys.iter()
668 }
669
670 /// Returns the project groups, ordered by most recently added.
671 pub fn project_groups(
672 &self,
673 cx: &App,
674 ) -> impl Iterator<Item = (ProjectGroupKey, Vec<Entity<Workspace>>)> {
675 let mut groups = self
676 .project_group_keys
677 .iter()
678 .map(|key| (key.clone(), Vec::new()))
679 .collect::<Vec<_>>();
680 for workspace in &self.workspaces {
681 let key = self.project_group_key_for_workspace(workspace, cx);
682 if let Some((_, workspaces)) = groups.iter_mut().find(|(k, _)| k == &key) {
683 workspaces.push(workspace.clone());
684 }
685 }
686 groups.into_iter()
687 }
688
689 pub fn workspaces_for_project_group(
690 &self,
691 project_group_key: &ProjectGroupKey,
692 cx: &App,
693 ) -> impl Iterator<Item = &Entity<Workspace>> {
694 self.workspaces.iter().filter(move |workspace| {
695 self.project_group_key_for_workspace(workspace, cx) == *project_group_key
696 })
697 }
698
699 pub fn remove_folder_from_project_group(
700 &mut self,
701 project_group_key: &ProjectGroupKey,
702 path: &Path,
703 cx: &mut Context<Self>,
704 ) {
705 let new_path_list = project_group_key.path_list().without_path(path);
706 if new_path_list.is_empty() {
707 return;
708 }
709
710 let new_key = ProjectGroupKey::new(project_group_key.host(), new_path_list);
711
712 let workspaces: Vec<_> = self
713 .workspaces_for_project_group(project_group_key, cx)
714 .cloned()
715 .collect();
716
717 self.add_project_group_key(new_key);
718
719 for workspace in workspaces {
720 let project = workspace.read(cx).project().clone();
721 project.update(cx, |project, cx| {
722 project.remove_worktree_for_main_worktree_path(path, cx);
723 });
724 }
725
726 self.serialize(cx);
727 cx.notify();
728 }
729
730 pub fn prompt_to_add_folders_to_project_group(
731 &mut self,
732 key: &ProjectGroupKey,
733 window: &mut Window,
734 cx: &mut Context<Self>,
735 ) {
736 let paths = self.workspace().update(cx, |workspace, cx| {
737 workspace.prompt_for_open_path(
738 PathPromptOptions {
739 files: false,
740 directories: true,
741 multiple: true,
742 prompt: None,
743 },
744 DirectoryLister::Project(workspace.project().clone()),
745 window,
746 cx,
747 )
748 });
749
750 let key = key.clone();
751 cx.spawn_in(window, async move |this, cx| {
752 if let Some(new_paths) = paths.await.ok().flatten() {
753 if !new_paths.is_empty() {
754 this.update(cx, |multi_workspace, cx| {
755 multi_workspace.add_folders_to_project_group(&key, new_paths, cx);
756 })?;
757 }
758 }
759 anyhow::Ok(())
760 })
761 .detach_and_log_err(cx);
762 }
763
764 pub fn add_folders_to_project_group(
765 &mut self,
766 project_group_key: &ProjectGroupKey,
767 new_paths: Vec<PathBuf>,
768 cx: &mut Context<Self>,
769 ) {
770 let mut all_paths: Vec<PathBuf> = project_group_key.path_list().paths().to_vec();
771 all_paths.extend(new_paths.iter().cloned());
772 let new_path_list = PathList::new(&all_paths);
773 let new_key = ProjectGroupKey::new(project_group_key.host(), new_path_list);
774
775 let workspaces: Vec<_> = self
776 .workspaces_for_project_group(project_group_key, cx)
777 .cloned()
778 .collect();
779
780 self.add_project_group_key(new_key);
781
782 for workspace in workspaces {
783 let project = workspace.read(cx).project().clone();
784 for path in &new_paths {
785 project
786 .update(cx, |project, cx| {
787 project.find_or_create_worktree(path, true, cx)
788 })
789 .detach_and_log_err(cx);
790 }
791 }
792
793 self.serialize(cx);
794 cx.notify();
795 }
796
797 pub fn remove_project_group(
798 &mut self,
799 key: &ProjectGroupKey,
800 window: &mut Window,
801 cx: &mut Context<Self>,
802 ) -> Task<Result<bool>> {
803 let workspaces: Vec<_> = self
804 .workspaces_for_project_group(key, cx)
805 .cloned()
806 .collect();
807
808 // Compute the neighbor while the key is still in the list.
809 let neighbor_key = {
810 let pos = self.project_group_keys.iter().position(|k| k == key);
811 pos.and_then(|pos| {
812 // Keys are in display order, so pos+1 is below
813 // and pos-1 is above. Try below first.
814 self.project_group_keys.get(pos + 1).or_else(|| {
815 pos.checked_sub(1)
816 .and_then(|i| self.project_group_keys.get(i))
817 })
818 })
819 .cloned()
820 };
821
822 // Now remove the key.
823 self.project_group_keys.retain(|k| k != key);
824
825 self.remove(
826 workspaces,
827 move |this, window, cx| {
828 if let Some(neighbor_key) = neighbor_key {
829 return this.find_or_create_local_workspace(
830 neighbor_key.path_list().clone(),
831 window,
832 cx,
833 );
834 }
835
836 // No other project groups remain — create an empty workspace.
837 let app_state = this.workspace().read(cx).app_state().clone();
838 let project = Project::local(
839 app_state.client.clone(),
840 app_state.node_runtime.clone(),
841 app_state.user_store.clone(),
842 app_state.languages.clone(),
843 app_state.fs.clone(),
844 None,
845 project::LocalProjectFlags::default(),
846 cx,
847 );
848 let new_workspace =
849 cx.new(|cx| Workspace::new(None, project, app_state, window, cx));
850 Task::ready(Ok(new_workspace))
851 },
852 window,
853 cx,
854 )
855 }
856
857 /// Finds an existing workspace whose root paths and host exactly match.
858 pub fn workspace_for_paths(
859 &self,
860 path_list: &PathList,
861 host: Option<&RemoteConnectionOptions>,
862 cx: &App,
863 ) -> Option<Entity<Workspace>> {
864 self.workspaces
865 .iter()
866 .find(|ws| {
867 let key = ws.read(cx).project_group_key(cx);
868 key.host().as_ref() == host
869 && PathList::new(&ws.read(cx).root_paths(cx)) == *path_list
870 })
871 .cloned()
872 }
873
874 /// Finds an existing workspace whose paths match, or creates a new one.
875 ///
876 /// For local projects (`host` is `None`), this delegates to
877 /// [`Self::find_or_create_local_workspace`]. For remote projects, it
878 /// tries an exact path match and, if no existing workspace is found,
879 /// calls `connect_remote` to establish a connection and creates a new
880 /// remote workspace.
881 ///
882 /// The `connect_remote` closure is responsible for any user-facing
883 /// connection UI (e.g. password prompts). It receives the connection
884 /// options and should return a [`Task`] that resolves to the
885 /// [`RemoteClient`] session, or `None` if the connection was
886 /// cancelled.
887 pub fn find_or_create_workspace(
888 &mut self,
889 paths: PathList,
890 host: Option<RemoteConnectionOptions>,
891 provisional_project_group_key: Option<ProjectGroupKey>,
892 connect_remote: impl FnOnce(
893 RemoteConnectionOptions,
894 &mut Window,
895 &mut Context<Self>,
896 ) -> Task<Result<Option<Entity<remote::RemoteClient>>>>
897 + 'static,
898 window: &mut Window,
899 cx: &mut Context<Self>,
900 ) -> Task<Result<Entity<Workspace>>> {
901 if let Some(workspace) = self.workspace_for_paths(&paths, host.as_ref(), cx) {
902 self.activate(workspace.clone(), window, cx);
903 return Task::ready(Ok(workspace));
904 }
905
906 let Some(connection_options) = host else {
907 return self.find_or_create_local_workspace(paths, window, cx);
908 };
909
910 let app_state = self.workspace().read(cx).app_state().clone();
911 let window_handle = window.window_handle().downcast::<MultiWorkspace>();
912 let connect_task = connect_remote(connection_options.clone(), window, cx);
913 let paths_vec = paths.paths().to_vec();
914
915 cx.spawn(async move |_this, cx| {
916 let session = connect_task
917 .await?
918 .ok_or_else(|| anyhow::anyhow!("Remote connection was cancelled"))?;
919
920 let new_project = cx.update(|cx| {
921 Project::remote(
922 session,
923 app_state.client.clone(),
924 app_state.node_runtime.clone(),
925 app_state.user_store.clone(),
926 app_state.languages.clone(),
927 app_state.fs.clone(),
928 true,
929 cx,
930 )
931 });
932
933 let window_handle =
934 window_handle.ok_or_else(|| anyhow::anyhow!("Window is not a MultiWorkspace"))?;
935
936 open_remote_project_with_existing_connection(
937 connection_options,
938 new_project,
939 paths_vec,
940 app_state,
941 window_handle,
942 provisional_project_group_key,
943 cx,
944 )
945 .await?;
946
947 window_handle.update(cx, |multi_workspace, window, cx| {
948 let workspace = multi_workspace.workspace().clone();
949 multi_workspace.add(workspace.clone(), window, cx);
950 workspace
951 })
952 })
953 }
954
955 /// Finds an existing workspace in this multi-workspace whose paths match,
956 /// or creates a new one (deserializing its saved state from the database).
957 /// Never searches other windows or matches workspaces with a superset of
958 /// the requested paths.
959 pub fn find_or_create_local_workspace(
960 &mut self,
961 path_list: PathList,
962 window: &mut Window,
963 cx: &mut Context<Self>,
964 ) -> Task<Result<Entity<Workspace>>> {
965 if let Some(workspace) = self.workspace_for_paths(&path_list, None, cx) {
966 self.activate(workspace.clone(), window, cx);
967 return Task::ready(Ok(workspace));
968 }
969
970 if let Some(transient) = self.active_workspace.transient_workspace() {
971 if transient.read(cx).project_group_key(cx).path_list() == &path_list {
972 return Task::ready(Ok(transient.clone()));
973 }
974 }
975
976 let paths = path_list.paths().to_vec();
977 let app_state = self.workspace().read(cx).app_state().clone();
978 let requesting_window = window.window_handle().downcast::<MultiWorkspace>();
979
980 cx.spawn(async move |_this, cx| {
981 let result = cx
982 .update(|cx| {
983 Workspace::new_local(
984 paths,
985 app_state,
986 requesting_window,
987 None,
988 None,
989 OpenMode::Activate,
990 cx,
991 )
992 })
993 .await?;
994 Ok(result.workspace)
995 })
996 }
997
998 pub fn workspace(&self) -> &Entity<Workspace> {
999 match &self.active_workspace {
1000 ActiveWorkspace::Persistent(index) => &self.workspaces[*index],
1001 ActiveWorkspace::Transient(workspace) => workspace,
1002 }
1003 }
1004
1005 pub fn workspaces(&self) -> impl Iterator<Item = &Entity<Workspace>> {
1006 self.workspaces
1007 .iter()
1008 .chain(self.active_workspace.transient_workspace())
1009 }
1010
1011 /// Adds a workspace to this window as persistent without changing which
1012 /// workspace is active. Unlike `activate()`, this always inserts into the
1013 /// persistent list regardless of sidebar state — it's used for system-
1014 /// initiated additions like deserialization and worktree discovery.
1015 pub fn add(&mut self, workspace: Entity<Workspace>, window: &Window, cx: &mut Context<Self>) {
1016 self.insert_workspace(workspace, window, cx);
1017 }
1018
1019 /// Ensures the workspace is in the multiworkspace and makes it the active one.
1020 pub fn activate(
1021 &mut self,
1022 workspace: Entity<Workspace>,
1023 window: &mut Window,
1024 cx: &mut Context<Self>,
1025 ) {
1026 // Re-activating the current workspace is a no-op.
1027 if self.workspace() == &workspace {
1028 self.focus_active_workspace(window, cx);
1029 return;
1030 }
1031
1032 // Resolve where we're going.
1033 let new_index = if let Some(index) = self.workspaces.iter().position(|w| *w == workspace) {
1034 Some(index)
1035 } else if self.sidebar_open {
1036 Some(self.insert_workspace(workspace.clone(), &*window, cx))
1037 } else {
1038 None
1039 };
1040
1041 // Transition the active workspace.
1042 if let Some(index) = new_index {
1043 if let Some(old) = self.active_workspace.set_persistent(index) {
1044 if self.sidebar_open {
1045 self.promote_transient(old, cx);
1046 } else {
1047 self.detach_workspace(&old, cx);
1048 cx.emit(MultiWorkspaceEvent::WorkspaceRemoved(old.entity_id()));
1049 }
1050 }
1051 } else {
1052 Self::subscribe_to_workspace(&workspace, window, cx);
1053 let weak_self = cx.weak_entity();
1054 workspace.update(cx, |workspace, cx| {
1055 workspace.set_multi_workspace(weak_self, cx);
1056 });
1057 if let Some(old) = self.active_workspace.set_transient(workspace) {
1058 self.detach_workspace(&old, cx);
1059 cx.emit(MultiWorkspaceEvent::WorkspaceRemoved(old.entity_id()));
1060 }
1061 }
1062
1063 cx.emit(MultiWorkspaceEvent::ActiveWorkspaceChanged);
1064 self.serialize(cx);
1065 self.focus_active_workspace(window, cx);
1066 cx.notify();
1067 }
1068
1069 /// Promotes the currently active workspace to persistent if it is
1070 /// transient, so it is retained across workspace switches even when
1071 /// the sidebar is closed. No-op if the workspace is already persistent.
1072 pub fn retain_active_workspace(&mut self, cx: &mut Context<Self>) {
1073 if let ActiveWorkspace::Transient(workspace) = &self.active_workspace {
1074 let workspace = workspace.clone();
1075 let index = self.promote_transient(workspace, cx);
1076 self.active_workspace = ActiveWorkspace::Persistent(index);
1077 self.serialize(cx);
1078 cx.notify();
1079 }
1080 }
1081
1082 /// Promotes a former transient workspace into the persistent list.
1083 /// Returns the index of the newly inserted workspace.
1084 fn promote_transient(&mut self, workspace: Entity<Workspace>, cx: &mut Context<Self>) -> usize {
1085 let project_group_key = self.project_group_key_for_workspace(&workspace, cx);
1086 self.add_project_group_key(project_group_key);
1087 self.workspaces.push(workspace.clone());
1088 cx.emit(MultiWorkspaceEvent::WorkspaceAdded(workspace));
1089 self.workspaces.len() - 1
1090 }
1091
1092 /// Collapses to a single transient workspace, discarding all persistent
1093 /// workspaces. Used when multi-workspace is disabled (e.g. disable_ai).
1094 fn collapse_to_single_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1095 if self.sidebar_open {
1096 self.close_sidebar(window, cx);
1097 }
1098 let active = self.workspace().clone();
1099 for workspace in std::mem::take(&mut self.workspaces) {
1100 if workspace != active {
1101 self.detach_workspace(&workspace, cx);
1102 cx.emit(MultiWorkspaceEvent::WorkspaceRemoved(workspace.entity_id()));
1103 }
1104 }
1105 self.project_group_keys.clear();
1106 self.active_workspace = ActiveWorkspace::Transient(active);
1107 cx.notify();
1108 }
1109
1110 /// Inserts a workspace into the list if not already present. Returns the
1111 /// index of the workspace (existing or newly inserted). Does not change
1112 /// the active workspace index.
1113 fn insert_workspace(
1114 &mut self,
1115 workspace: Entity<Workspace>,
1116 window: &Window,
1117 cx: &mut Context<Self>,
1118 ) -> usize {
1119 if let Some(index) = self.workspaces.iter().position(|w| *w == workspace) {
1120 index
1121 } else {
1122 let project_group_key = self.project_group_key_for_workspace(&workspace, cx);
1123
1124 Self::subscribe_to_workspace(&workspace, window, cx);
1125 self.sync_sidebar_to_workspace(&workspace, cx);
1126 let weak_self = cx.weak_entity();
1127 workspace.update(cx, |workspace, cx| {
1128 workspace.set_multi_workspace(weak_self, cx);
1129 });
1130
1131 self.add_project_group_key(project_group_key);
1132 self.workspaces.push(workspace.clone());
1133 cx.emit(MultiWorkspaceEvent::WorkspaceAdded(workspace));
1134 cx.notify();
1135 self.workspaces.len() - 1
1136 }
1137 }
1138
1139 /// Clears session state and DB binding for a workspace that is being
1140 /// removed or replaced. The DB row is preserved so the workspace still
1141 /// appears in the recent-projects list.
1142 fn detach_workspace(&mut self, workspace: &Entity<Workspace>, cx: &mut Context<Self>) {
1143 workspace.update(cx, |workspace, _cx| {
1144 workspace.session_id.take();
1145 workspace._schedule_serialize_workspace.take();
1146 workspace._serialize_workspace_task.take();
1147 });
1148
1149 if let Some(workspace_id) = workspace.read(cx).database_id() {
1150 let db = crate::persistence::WorkspaceDb::global(cx);
1151 self.pending_removal_tasks.retain(|task| !task.is_ready());
1152 self.pending_removal_tasks
1153 .push(cx.background_spawn(async move {
1154 db.set_session_binding(workspace_id, None, None)
1155 .await
1156 .log_err();
1157 }));
1158 }
1159 }
1160
1161 fn sync_sidebar_to_workspace(&self, workspace: &Entity<Workspace>, cx: &mut Context<Self>) {
1162 if self.sidebar_open() {
1163 let sidebar_focus_handle = self.sidebar.as_ref().map(|s| s.focus_handle(cx));
1164 workspace.update(cx, |workspace, _| {
1165 workspace.set_sidebar_focus_handle(sidebar_focus_handle);
1166 });
1167 }
1168 }
1169
1170 pub(crate) fn serialize(&mut self, cx: &mut Context<Self>) {
1171 self._serialize_task = Some(cx.spawn(async move |this, cx| {
1172 let Some((window_id, state)) = this
1173 .read_with(cx, |this, cx| {
1174 let state = MultiWorkspaceState {
1175 active_workspace_id: this.workspace().read(cx).database_id(),
1176 project_group_keys: this
1177 .project_group_keys()
1178 .cloned()
1179 .map(Into::into)
1180 .collect::<Vec<_>>(),
1181 sidebar_open: this.sidebar_open,
1182 sidebar_state: this.sidebar.as_ref().and_then(|s| s.serialized_state(cx)),
1183 };
1184 (this.window_id, state)
1185 })
1186 .ok()
1187 else {
1188 return;
1189 };
1190 let kvp = cx.update(|cx| db::kvp::KeyValueStore::global(cx));
1191 crate::persistence::write_multi_workspace_state(&kvp, window_id, state).await;
1192 }));
1193 }
1194
1195 /// Returns the in-flight serialization task (if any) so the caller can
1196 /// await it. Used by the quit handler to ensure pending DB writes
1197 /// complete before the process exits.
1198 pub fn flush_serialization(&mut self) -> Task<()> {
1199 self._serialize_task.take().unwrap_or(Task::ready(()))
1200 }
1201
1202 fn app_will_quit(&mut self, _cx: &mut Context<Self>) -> impl Future<Output = ()> + use<> {
1203 let mut tasks: Vec<Task<()>> = Vec::new();
1204 if let Some(task) = self._serialize_task.take() {
1205 tasks.push(task);
1206 }
1207 tasks.extend(std::mem::take(&mut self.pending_removal_tasks));
1208
1209 async move {
1210 futures::future::join_all(tasks).await;
1211 }
1212 }
1213
1214 pub fn focus_active_workspace(&self, window: &mut Window, cx: &mut App) {
1215 // If a dock panel is zoomed, focus it instead of the center pane.
1216 // Otherwise, focusing the center pane triggers dismiss_zoomed_items_to_reveal
1217 // which closes the zoomed dock.
1218 let focus_handle = {
1219 let workspace = self.workspace().read(cx);
1220 let mut target = None;
1221 for dock in workspace.all_docks() {
1222 let dock = dock.read(cx);
1223 if dock.is_open() {
1224 if let Some(panel) = dock.active_panel() {
1225 if panel.is_zoomed(window, cx) {
1226 target = Some(panel.panel_focus_handle(cx));
1227 break;
1228 }
1229 }
1230 }
1231 }
1232 target.unwrap_or_else(|| {
1233 let pane = workspace.active_pane().clone();
1234 pane.read(cx).focus_handle(cx)
1235 })
1236 };
1237 window.focus(&focus_handle, cx);
1238 }
1239
1240 pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
1241 self.workspace().read(cx).panel::<T>(cx)
1242 }
1243
1244 pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
1245 self.workspace().read(cx).active_modal::<V>(cx)
1246 }
1247
1248 pub fn add_panel<T: Panel>(
1249 &mut self,
1250 panel: Entity<T>,
1251 window: &mut Window,
1252 cx: &mut Context<Self>,
1253 ) {
1254 self.workspace().update(cx, |workspace, cx| {
1255 workspace.add_panel(panel, window, cx);
1256 });
1257 }
1258
1259 pub fn focus_panel<T: Panel>(
1260 &mut self,
1261 window: &mut Window,
1262 cx: &mut Context<Self>,
1263 ) -> Option<Entity<T>> {
1264 self.workspace()
1265 .update(cx, |workspace, cx| workspace.focus_panel::<T>(window, cx))
1266 }
1267
1268 // used in a test
1269 pub fn toggle_modal<V: ModalView, B>(
1270 &mut self,
1271 window: &mut Window,
1272 cx: &mut Context<Self>,
1273 build: B,
1274 ) where
1275 B: FnOnce(&mut Window, &mut gpui::Context<V>) -> V,
1276 {
1277 self.workspace().update(cx, |workspace, cx| {
1278 workspace.toggle_modal(window, cx, build);
1279 });
1280 }
1281
1282 pub fn toggle_dock(
1283 &mut self,
1284 dock_side: DockPosition,
1285 window: &mut Window,
1286 cx: &mut Context<Self>,
1287 ) {
1288 self.workspace().update(cx, |workspace, cx| {
1289 workspace.toggle_dock(dock_side, window, cx);
1290 });
1291 }
1292
1293 pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
1294 self.workspace().read(cx).active_item_as::<I>(cx)
1295 }
1296
1297 pub fn items_of_type<'a, T: Item>(
1298 &'a self,
1299 cx: &'a App,
1300 ) -> impl 'a + Iterator<Item = Entity<T>> {
1301 self.workspace().read(cx).items_of_type::<T>(cx)
1302 }
1303
1304 pub fn database_id(&self, cx: &App) -> Option<WorkspaceId> {
1305 self.workspace().read(cx).database_id()
1306 }
1307
1308 pub fn take_pending_removal_tasks(&mut self) -> Vec<Task<()>> {
1309 let tasks: Vec<Task<()>> = std::mem::take(&mut self.pending_removal_tasks)
1310 .into_iter()
1311 .filter(|task| !task.is_ready())
1312 .collect();
1313 tasks
1314 }
1315
1316 #[cfg(any(test, feature = "test-support"))]
1317 pub fn set_random_database_id(&mut self, cx: &mut Context<Self>) {
1318 self.workspace().update(cx, |workspace, _cx| {
1319 workspace.set_random_database_id();
1320 });
1321 }
1322
1323 #[cfg(any(test, feature = "test-support"))]
1324 pub fn test_new(project: Entity<Project>, window: &mut Window, cx: &mut Context<Self>) -> Self {
1325 let workspace = cx.new(|cx| Workspace::test_new(project, window, cx));
1326 Self::new(workspace, window, cx)
1327 }
1328
1329 #[cfg(any(test, feature = "test-support"))]
1330 pub fn test_add_workspace(
1331 &mut self,
1332 project: Entity<Project>,
1333 window: &mut Window,
1334 cx: &mut Context<Self>,
1335 ) -> Entity<Workspace> {
1336 let workspace = cx.new(|cx| Workspace::test_new(project, window, cx));
1337 self.activate(workspace.clone(), window, cx);
1338 workspace
1339 }
1340
1341 #[cfg(any(test, feature = "test-support"))]
1342 pub fn create_test_workspace(
1343 &mut self,
1344 window: &mut Window,
1345 cx: &mut Context<Self>,
1346 ) -> Task<()> {
1347 let app_state = self.workspace().read(cx).app_state().clone();
1348 let project = Project::local(
1349 app_state.client.clone(),
1350 app_state.node_runtime.clone(),
1351 app_state.user_store.clone(),
1352 app_state.languages.clone(),
1353 app_state.fs.clone(),
1354 None,
1355 project::LocalProjectFlags::default(),
1356 cx,
1357 );
1358 let new_workspace = cx.new(|cx| Workspace::new(None, project, app_state, window, cx));
1359 self.activate(new_workspace.clone(), window, cx);
1360
1361 let weak_workspace = new_workspace.downgrade();
1362 let db = crate::persistence::WorkspaceDb::global(cx);
1363 cx.spawn_in(window, async move |this, cx| {
1364 let workspace_id = db.next_id().await.unwrap();
1365 let workspace = weak_workspace.upgrade().unwrap();
1366 let task: Task<()> = this
1367 .update_in(cx, |this, window, cx| {
1368 let session_id = workspace.read(cx).session_id();
1369 let window_id = window.window_handle().window_id().as_u64();
1370 workspace.update(cx, |workspace, _cx| {
1371 workspace.set_database_id(workspace_id);
1372 });
1373 this.serialize(cx);
1374 let db = db.clone();
1375 cx.background_spawn(async move {
1376 db.set_session_binding(workspace_id, session_id, Some(window_id))
1377 .await
1378 .log_err();
1379 })
1380 })
1381 .unwrap();
1382 task.await
1383 })
1384 }
1385
1386 /// Removes one or more workspaces from this multi-workspace.
1387 ///
1388 /// If the active workspace is among those being removed,
1389 /// `fallback_workspace` is called **synchronously before the removal
1390 /// begins** to produce a `Task` that resolves to the workspace that
1391 /// should become active. The fallback must not be one of the
1392 /// workspaces being removed.
1393 ///
1394 /// Returns `true` if any workspaces were actually removed.
1395 pub fn remove(
1396 &mut self,
1397 workspaces: impl IntoIterator<Item = Entity<Workspace>>,
1398 fallback_workspace: impl FnOnce(
1399 &mut Self,
1400 &mut Window,
1401 &mut Context<Self>,
1402 ) -> Task<Result<Entity<Workspace>>>,
1403 window: &mut Window,
1404 cx: &mut Context<Self>,
1405 ) -> Task<Result<bool>> {
1406 let workspaces: Vec<_> = workspaces.into_iter().collect();
1407
1408 if workspaces.is_empty() {
1409 return Task::ready(Ok(false));
1410 }
1411
1412 let removing_active = workspaces.iter().any(|ws| ws == self.workspace());
1413 let original_active = self.workspace().clone();
1414
1415 let fallback_task = removing_active.then(|| fallback_workspace(self, window, cx));
1416
1417 cx.spawn_in(window, async move |this, cx| {
1418 // Prompt each workspace for unsaved changes. If any workspace
1419 // has dirty buffers, save_all_internal will emit Activate to
1420 // bring it into view before showing the save dialog.
1421 for workspace in &workspaces {
1422 let should_continue = workspace
1423 .update_in(cx, |workspace, window, cx| {
1424 workspace.save_all_internal(crate::SaveIntent::Close, window, cx)
1425 })?
1426 .await?;
1427
1428 if !should_continue {
1429 return Ok(false);
1430 }
1431 }
1432
1433 // If we're removing the active workspace, await the
1434 // fallback and switch to it before tearing anything down.
1435 // Otherwise restore the original active workspace in case
1436 // prompting switched away from it.
1437 if let Some(fallback_task) = fallback_task {
1438 let new_active = fallback_task.await?;
1439
1440 this.update_in(cx, |this, window, cx| {
1441 assert!(
1442 !workspaces.contains(&new_active),
1443 "fallback workspace must not be one of the workspaces being removed"
1444 );
1445 this.activate(new_active, window, cx);
1446 })?;
1447 } else {
1448 this.update_in(cx, |this, window, cx| {
1449 if *this.workspace() != original_active {
1450 this.activate(original_active, window, cx);
1451 }
1452 })?;
1453 }
1454
1455 // Actually remove the workspaces.
1456 this.update_in(cx, |this, _, cx| {
1457 // Save a handle to the active workspace so we can restore
1458 // its index after the removals shift the vec around.
1459 let active_workspace = this.workspace().clone();
1460
1461 let mut removed_workspaces: Vec<Entity<Workspace>> = Vec::new();
1462
1463 this.workspaces.retain(|ws| {
1464 if workspaces.contains(ws) {
1465 removed_workspaces.push(ws.clone());
1466 false
1467 } else {
1468 true
1469 }
1470 });
1471
1472 for workspace in &removed_workspaces {
1473 this.detach_workspace(workspace, cx);
1474 cx.emit(MultiWorkspaceEvent::WorkspaceRemoved(workspace.entity_id()));
1475 }
1476
1477 let removed_any = !removed_workspaces.is_empty();
1478
1479 if removed_any {
1480 // Restore the active workspace index after removals.
1481 if let Some(new_index) = this
1482 .workspaces
1483 .iter()
1484 .position(|ws| ws == &active_workspace)
1485 {
1486 this.active_workspace = ActiveWorkspace::Persistent(new_index);
1487 }
1488
1489 this.serialize(cx);
1490 cx.notify();
1491 }
1492
1493 Ok(removed_any)
1494 })?
1495 })
1496 }
1497
1498 pub fn open_project(
1499 &mut self,
1500 paths: Vec<PathBuf>,
1501 open_mode: OpenMode,
1502 window: &mut Window,
1503 cx: &mut Context<Self>,
1504 ) -> Task<Result<Entity<Workspace>>> {
1505 if self.multi_workspace_enabled(cx) {
1506 self.find_or_create_local_workspace(PathList::new(&paths), window, cx)
1507 } else {
1508 let workspace = self.workspace().clone();
1509 cx.spawn_in(window, async move |_this, cx| {
1510 let should_continue = workspace
1511 .update_in(cx, |workspace, window, cx| {
1512 workspace.prepare_to_close(crate::CloseIntent::ReplaceWindow, window, cx)
1513 })?
1514 .await?;
1515 if should_continue {
1516 workspace
1517 .update_in(cx, |workspace, window, cx| {
1518 workspace.open_workspace_for_paths(open_mode, paths, window, cx)
1519 })?
1520 .await
1521 } else {
1522 Ok(workspace)
1523 }
1524 })
1525 }
1526 }
1527}
1528
1529impl Render for MultiWorkspace {
1530 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1531 let multi_workspace_enabled = self.multi_workspace_enabled(cx);
1532 let sidebar_side = self.sidebar_side(cx);
1533 let sidebar_on_right = sidebar_side == SidebarSide::Right;
1534
1535 let sidebar: Option<AnyElement> = if multi_workspace_enabled && self.sidebar_open() {
1536 self.sidebar.as_ref().map(|sidebar_handle| {
1537 let weak = cx.weak_entity();
1538
1539 let sidebar_width = sidebar_handle.width(cx);
1540 let resize_handle = deferred(
1541 div()
1542 .id("sidebar-resize-handle")
1543 .absolute()
1544 .when(!sidebar_on_right, |el| {
1545 el.right(-SIDEBAR_RESIZE_HANDLE_SIZE / 2.)
1546 })
1547 .when(sidebar_on_right, |el| {
1548 el.left(-SIDEBAR_RESIZE_HANDLE_SIZE / 2.)
1549 })
1550 .top(px(0.))
1551 .h_full()
1552 .w(SIDEBAR_RESIZE_HANDLE_SIZE)
1553 .cursor_col_resize()
1554 .on_drag(DraggedSidebar, |dragged, _, _, cx| {
1555 cx.stop_propagation();
1556 cx.new(|_| dragged.clone())
1557 })
1558 .on_mouse_down(MouseButton::Left, |_, _, cx| {
1559 cx.stop_propagation();
1560 })
1561 .on_mouse_up(MouseButton::Left, move |event, _, cx| {
1562 if event.click_count == 2 {
1563 weak.update(cx, |this, cx| {
1564 if let Some(sidebar) = this.sidebar.as_mut() {
1565 sidebar.set_width(None, cx);
1566 }
1567 this.serialize(cx);
1568 })
1569 .ok();
1570 cx.stop_propagation();
1571 } else {
1572 weak.update(cx, |this, cx| {
1573 this.serialize(cx);
1574 })
1575 .ok();
1576 }
1577 })
1578 .occlude(),
1579 );
1580
1581 div()
1582 .id("sidebar-container")
1583 .relative()
1584 .h_full()
1585 .w(sidebar_width)
1586 .flex_shrink_0()
1587 .child(sidebar_handle.to_any())
1588 .child(resize_handle)
1589 .into_any_element()
1590 })
1591 } else {
1592 None
1593 };
1594
1595 let (left_sidebar, right_sidebar) = if sidebar_on_right {
1596 (None, sidebar)
1597 } else {
1598 (sidebar, None)
1599 };
1600
1601 let ui_font = theme_settings::setup_ui_font(window, cx);
1602 let text_color = cx.theme().colors().text;
1603
1604 let workspace = self.workspace().clone();
1605 let workspace_key_context = workspace.update(cx, |workspace, cx| workspace.key_context(cx));
1606 let root = workspace.update(cx, |workspace, cx| workspace.actions(h_flex(), window, cx));
1607
1608 client_side_decorations(
1609 root.key_context(workspace_key_context)
1610 .relative()
1611 .size_full()
1612 .font(ui_font)
1613 .text_color(text_color)
1614 .on_action(cx.listener(Self::close_window))
1615 .when(self.multi_workspace_enabled(cx), |this| {
1616 this.on_action(cx.listener(
1617 |this: &mut Self, _: &ToggleWorkspaceSidebar, window, cx| {
1618 this.toggle_sidebar(window, cx);
1619 },
1620 ))
1621 .on_action(cx.listener(
1622 |this: &mut Self, _: &CloseWorkspaceSidebar, window, cx| {
1623 this.close_sidebar_action(window, cx);
1624 },
1625 ))
1626 .on_action(cx.listener(
1627 |this: &mut Self, _: &FocusWorkspaceSidebar, window, cx| {
1628 this.focus_sidebar(window, cx);
1629 },
1630 ))
1631 .on_action(cx.listener(
1632 |this: &mut Self, action: &ToggleThreadSwitcher, window, cx| {
1633 if let Some(sidebar) = &this.sidebar {
1634 sidebar.toggle_thread_switcher(action.select_last, window, cx);
1635 }
1636 },
1637 ))
1638 .on_action(cx.listener(|this: &mut Self, _: &NextProject, window, cx| {
1639 if let Some(sidebar) = &this.sidebar {
1640 sidebar.cycle_project(true, window, cx);
1641 }
1642 }))
1643 .on_action(
1644 cx.listener(|this: &mut Self, _: &PreviousProject, window, cx| {
1645 if let Some(sidebar) = &this.sidebar {
1646 sidebar.cycle_project(false, window, cx);
1647 }
1648 }),
1649 )
1650 .on_action(cx.listener(|this: &mut Self, _: &NextThread, window, cx| {
1651 if let Some(sidebar) = &this.sidebar {
1652 sidebar.cycle_thread(true, window, cx);
1653 }
1654 }))
1655 .on_action(cx.listener(
1656 |this: &mut Self, _: &PreviousThread, window, cx| {
1657 if let Some(sidebar) = &this.sidebar {
1658 sidebar.cycle_thread(false, window, cx);
1659 }
1660 },
1661 ))
1662 })
1663 .when(
1664 self.sidebar_open() && self.multi_workspace_enabled(cx),
1665 |this| {
1666 this.on_drag_move(cx.listener(
1667 move |this: &mut Self,
1668 e: &DragMoveEvent<DraggedSidebar>,
1669 window,
1670 cx| {
1671 if let Some(sidebar) = &this.sidebar {
1672 let new_width = if sidebar_on_right {
1673 window.bounds().size.width - e.event.position.x
1674 } else {
1675 e.event.position.x
1676 };
1677 sidebar.set_width(Some(new_width), cx);
1678 }
1679 },
1680 ))
1681 },
1682 )
1683 .children(left_sidebar)
1684 .child(
1685 div()
1686 .flex()
1687 .flex_1()
1688 .size_full()
1689 .overflow_hidden()
1690 .child(self.workspace().clone()),
1691 )
1692 .children(right_sidebar)
1693 .child(self.workspace().read(cx).modal_layer.clone())
1694 .children(self.sidebar_overlay.as_ref().map(|view| {
1695 deferred(div().absolute().size_full().inset_0().occlude().child(
1696 v_flex().h(px(0.0)).top_20().items_center().child(
1697 h_flex().occlude().child(view.clone()).on_mouse_down(
1698 MouseButton::Left,
1699 |_, _, cx| {
1700 cx.stop_propagation();
1701 },
1702 ),
1703 ),
1704 ))
1705 .with_priority(2)
1706 })),
1707 window,
1708 cx,
1709 Tiling {
1710 left: !sidebar_on_right && multi_workspace_enabled && self.sidebar_open(),
1711 right: sidebar_on_right && multi_workspace_enabled && self.sidebar_open(),
1712 ..Tiling::default()
1713 },
1714 )
1715 }
1716}