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 /// Goes through sqlite: serialize -> close -> open new window
858 /// This avoids issues with pending tasks having the wrong window
859 pub fn open_project_group_in_new_window(
860 &mut self,
861 key: &ProjectGroupKey,
862 window: &mut Window,
863 cx: &mut Context<Self>,
864 ) -> Task<Result<()>> {
865 let paths: Vec<PathBuf> = key.path_list().ordered_paths().cloned().collect();
866 if paths.is_empty() {
867 return Task::ready(Ok(()));
868 }
869
870 let app_state = self.workspace().read(cx).app_state().clone();
871
872 let workspaces: Vec<_> = self
873 .workspaces_for_project_group(key, cx)
874 .cloned()
875 .collect();
876 let mut serialization_tasks = Vec::new();
877 for workspace in &workspaces {
878 serialization_tasks.push(
879 workspace.update(cx, |workspace, inner_cx| {
880 workspace.flush_serialization(window, inner_cx)
881 }),
882 );
883 }
884
885 let remove_task = self.remove_project_group(key, window, cx);
886
887 cx.spawn(async move |_this, cx| {
888 futures::future::join_all(serialization_tasks).await;
889
890 let removed = remove_task.await?;
891 if !removed {
892 return Ok(());
893 }
894
895 cx.update(|cx| {
896 Workspace::new_local(
897 paths,
898 app_state,
899 None,
900 None,
901 None,
902 OpenMode::NewWindow,
903 cx,
904 )
905 })
906 .await?;
907
908 Ok(())
909 })
910 }
911
912 /// Finds an existing workspace whose root paths and host exactly match.
913 pub fn workspace_for_paths(
914 &self,
915 path_list: &PathList,
916 host: Option<&RemoteConnectionOptions>,
917 cx: &App,
918 ) -> Option<Entity<Workspace>> {
919 self.workspaces
920 .iter()
921 .find(|ws| {
922 let key = ws.read(cx).project_group_key(cx);
923 key.host().as_ref() == host
924 && PathList::new(&ws.read(cx).root_paths(cx)) == *path_list
925 })
926 .cloned()
927 }
928
929 /// Finds an existing workspace whose paths match, or creates a new one.
930 ///
931 /// For local projects (`host` is `None`), this delegates to
932 /// [`Self::find_or_create_local_workspace`]. For remote projects, it
933 /// tries an exact path match and, if no existing workspace is found,
934 /// calls `connect_remote` to establish a connection and creates a new
935 /// remote workspace.
936 ///
937 /// The `connect_remote` closure is responsible for any user-facing
938 /// connection UI (e.g. password prompts). It receives the connection
939 /// options and should return a [`Task`] that resolves to the
940 /// [`RemoteClient`] session, or `None` if the connection was
941 /// cancelled.
942 pub fn find_or_create_workspace(
943 &mut self,
944 paths: PathList,
945 host: Option<RemoteConnectionOptions>,
946 provisional_project_group_key: Option<ProjectGroupKey>,
947 connect_remote: impl FnOnce(
948 RemoteConnectionOptions,
949 &mut Window,
950 &mut Context<Self>,
951 ) -> Task<Result<Option<Entity<remote::RemoteClient>>>>
952 + 'static,
953 window: &mut Window,
954 cx: &mut Context<Self>,
955 ) -> Task<Result<Entity<Workspace>>> {
956 if let Some(workspace) = self.workspace_for_paths(&paths, host.as_ref(), cx) {
957 self.activate(workspace.clone(), window, cx);
958 return Task::ready(Ok(workspace));
959 }
960
961 let Some(connection_options) = host else {
962 return self.find_or_create_local_workspace(paths, window, cx);
963 };
964
965 let app_state = self.workspace().read(cx).app_state().clone();
966 let window_handle = window.window_handle().downcast::<MultiWorkspace>();
967 let connect_task = connect_remote(connection_options.clone(), window, cx);
968 let paths_vec = paths.paths().to_vec();
969
970 cx.spawn(async move |_this, cx| {
971 let session = connect_task
972 .await?
973 .ok_or_else(|| anyhow::anyhow!("Remote connection was cancelled"))?;
974
975 let new_project = cx.update(|cx| {
976 Project::remote(
977 session,
978 app_state.client.clone(),
979 app_state.node_runtime.clone(),
980 app_state.user_store.clone(),
981 app_state.languages.clone(),
982 app_state.fs.clone(),
983 true,
984 cx,
985 )
986 });
987
988 let window_handle =
989 window_handle.ok_or_else(|| anyhow::anyhow!("Window is not a MultiWorkspace"))?;
990
991 open_remote_project_with_existing_connection(
992 connection_options,
993 new_project,
994 paths_vec,
995 app_state,
996 window_handle,
997 provisional_project_group_key,
998 cx,
999 )
1000 .await?;
1001
1002 window_handle.update(cx, |multi_workspace, window, cx| {
1003 let workspace = multi_workspace.workspace().clone();
1004 multi_workspace.add(workspace.clone(), window, cx);
1005 workspace
1006 })
1007 })
1008 }
1009
1010 /// Finds an existing workspace in this multi-workspace whose paths match,
1011 /// or creates a new one (deserializing its saved state from the database).
1012 /// Never searches other windows or matches workspaces with a superset of
1013 /// the requested paths.
1014 pub fn find_or_create_local_workspace(
1015 &mut self,
1016 path_list: PathList,
1017 window: &mut Window,
1018 cx: &mut Context<Self>,
1019 ) -> Task<Result<Entity<Workspace>>> {
1020 if let Some(workspace) = self.workspace_for_paths(&path_list, None, cx) {
1021 self.activate(workspace.clone(), window, cx);
1022 return Task::ready(Ok(workspace));
1023 }
1024
1025 if let Some(transient) = self.active_workspace.transient_workspace() {
1026 if transient.read(cx).project_group_key(cx).path_list() == &path_list {
1027 return Task::ready(Ok(transient.clone()));
1028 }
1029 }
1030
1031 let paths = path_list.paths().to_vec();
1032 let app_state = self.workspace().read(cx).app_state().clone();
1033 let requesting_window = window.window_handle().downcast::<MultiWorkspace>();
1034
1035 cx.spawn(async move |_this, cx| {
1036 let result = cx
1037 .update(|cx| {
1038 Workspace::new_local(
1039 paths,
1040 app_state,
1041 requesting_window,
1042 None,
1043 None,
1044 OpenMode::Activate,
1045 cx,
1046 )
1047 })
1048 .await?;
1049 Ok(result.workspace)
1050 })
1051 }
1052
1053 pub fn workspace(&self) -> &Entity<Workspace> {
1054 match &self.active_workspace {
1055 ActiveWorkspace::Persistent(index) => &self.workspaces[*index],
1056 ActiveWorkspace::Transient(workspace) => workspace,
1057 }
1058 }
1059
1060 pub fn workspaces(&self) -> impl Iterator<Item = &Entity<Workspace>> {
1061 self.workspaces
1062 .iter()
1063 .chain(self.active_workspace.transient_workspace())
1064 }
1065
1066 /// Adds a workspace to this window as persistent without changing which
1067 /// workspace is active. Unlike `activate()`, this always inserts into the
1068 /// persistent list regardless of sidebar state — it's used for system-
1069 /// initiated additions like deserialization and worktree discovery.
1070 pub fn add(&mut self, workspace: Entity<Workspace>, window: &Window, cx: &mut Context<Self>) {
1071 self.insert_workspace(workspace, window, cx);
1072 }
1073
1074 /// Ensures the workspace is in the multiworkspace and makes it the active one.
1075 pub fn activate(
1076 &mut self,
1077 workspace: Entity<Workspace>,
1078 window: &mut Window,
1079 cx: &mut Context<Self>,
1080 ) {
1081 // Re-activating the current workspace is a no-op.
1082 if self.workspace() == &workspace {
1083 self.focus_active_workspace(window, cx);
1084 return;
1085 }
1086
1087 // Resolve where we're going.
1088 let new_index = if let Some(index) = self.workspaces.iter().position(|w| *w == workspace) {
1089 Some(index)
1090 } else if self.sidebar_open {
1091 Some(self.insert_workspace(workspace.clone(), &*window, cx))
1092 } else {
1093 None
1094 };
1095
1096 // Transition the active workspace.
1097 if let Some(index) = new_index {
1098 if let Some(old) = self.active_workspace.set_persistent(index) {
1099 if self.sidebar_open {
1100 self.promote_transient(old, cx);
1101 } else {
1102 self.detach_workspace(&old, cx);
1103 cx.emit(MultiWorkspaceEvent::WorkspaceRemoved(old.entity_id()));
1104 }
1105 }
1106 } else {
1107 Self::subscribe_to_workspace(&workspace, window, cx);
1108 let weak_self = cx.weak_entity();
1109 workspace.update(cx, |workspace, cx| {
1110 workspace.set_multi_workspace(weak_self, cx);
1111 });
1112 if let Some(old) = self.active_workspace.set_transient(workspace) {
1113 self.detach_workspace(&old, cx);
1114 cx.emit(MultiWorkspaceEvent::WorkspaceRemoved(old.entity_id()));
1115 }
1116 }
1117
1118 cx.emit(MultiWorkspaceEvent::ActiveWorkspaceChanged);
1119 self.serialize(cx);
1120 self.focus_active_workspace(window, cx);
1121 cx.notify();
1122 }
1123
1124 /// Promotes the currently active workspace to persistent if it is
1125 /// transient, so it is retained across workspace switches even when
1126 /// the sidebar is closed. No-op if the workspace is already persistent.
1127 pub fn retain_active_workspace(&mut self, cx: &mut Context<Self>) {
1128 if let ActiveWorkspace::Transient(workspace) = &self.active_workspace {
1129 let workspace = workspace.clone();
1130 let index = self.promote_transient(workspace, cx);
1131 self.active_workspace = ActiveWorkspace::Persistent(index);
1132 self.serialize(cx);
1133 cx.notify();
1134 }
1135 }
1136
1137 /// Promotes a former transient workspace into the persistent list.
1138 /// Returns the index of the newly inserted workspace.
1139 fn promote_transient(&mut self, workspace: Entity<Workspace>, cx: &mut Context<Self>) -> usize {
1140 let project_group_key = self.project_group_key_for_workspace(&workspace, cx);
1141 self.add_project_group_key(project_group_key);
1142 self.workspaces.push(workspace.clone());
1143 cx.emit(MultiWorkspaceEvent::WorkspaceAdded(workspace));
1144 self.workspaces.len() - 1
1145 }
1146
1147 /// Collapses to a single transient workspace, discarding all persistent
1148 /// workspaces. Used when multi-workspace is disabled (e.g. disable_ai).
1149 fn collapse_to_single_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1150 if self.sidebar_open {
1151 self.close_sidebar(window, cx);
1152 }
1153 let active = self.workspace().clone();
1154 for workspace in std::mem::take(&mut self.workspaces) {
1155 if workspace != active {
1156 self.detach_workspace(&workspace, cx);
1157 cx.emit(MultiWorkspaceEvent::WorkspaceRemoved(workspace.entity_id()));
1158 }
1159 }
1160 self.project_group_keys.clear();
1161 self.active_workspace = ActiveWorkspace::Transient(active);
1162 cx.notify();
1163 }
1164
1165 /// Inserts a workspace into the list if not already present. Returns the
1166 /// index of the workspace (existing or newly inserted). Does not change
1167 /// the active workspace index.
1168 fn insert_workspace(
1169 &mut self,
1170 workspace: Entity<Workspace>,
1171 window: &Window,
1172 cx: &mut Context<Self>,
1173 ) -> usize {
1174 if let Some(index) = self.workspaces.iter().position(|w| *w == workspace) {
1175 index
1176 } else {
1177 let project_group_key = self.project_group_key_for_workspace(&workspace, cx);
1178
1179 Self::subscribe_to_workspace(&workspace, window, cx);
1180 self.sync_sidebar_to_workspace(&workspace, cx);
1181 let weak_self = cx.weak_entity();
1182 workspace.update(cx, |workspace, cx| {
1183 workspace.set_multi_workspace(weak_self, cx);
1184 });
1185
1186 self.add_project_group_key(project_group_key);
1187 self.workspaces.push(workspace.clone());
1188 cx.emit(MultiWorkspaceEvent::WorkspaceAdded(workspace));
1189 cx.notify();
1190 self.workspaces.len() - 1
1191 }
1192 }
1193
1194 /// Clears session state and DB binding for a workspace that is being
1195 /// removed or replaced. The DB row is preserved so the workspace still
1196 /// appears in the recent-projects list.
1197 fn detach_workspace(&mut self, workspace: &Entity<Workspace>, cx: &mut Context<Self>) {
1198 workspace.update(cx, |workspace, _cx| {
1199 workspace.session_id.take();
1200 workspace._schedule_serialize_workspace.take();
1201 workspace._serialize_workspace_task.take();
1202 });
1203
1204 if let Some(workspace_id) = workspace.read(cx).database_id() {
1205 let db = crate::persistence::WorkspaceDb::global(cx);
1206 self.pending_removal_tasks.retain(|task| !task.is_ready());
1207 self.pending_removal_tasks
1208 .push(cx.background_spawn(async move {
1209 db.set_session_binding(workspace_id, None, None)
1210 .await
1211 .log_err();
1212 }));
1213 }
1214 }
1215
1216 fn sync_sidebar_to_workspace(&self, workspace: &Entity<Workspace>, cx: &mut Context<Self>) {
1217 if self.sidebar_open() {
1218 let sidebar_focus_handle = self.sidebar.as_ref().map(|s| s.focus_handle(cx));
1219 workspace.update(cx, |workspace, _| {
1220 workspace.set_sidebar_focus_handle(sidebar_focus_handle);
1221 });
1222 }
1223 }
1224
1225 pub(crate) fn serialize(&mut self, cx: &mut Context<Self>) {
1226 self._serialize_task = Some(cx.spawn(async move |this, cx| {
1227 let Some((window_id, state)) = this
1228 .read_with(cx, |this, cx| {
1229 let state = MultiWorkspaceState {
1230 active_workspace_id: this.workspace().read(cx).database_id(),
1231 project_group_keys: this
1232 .project_group_keys()
1233 .cloned()
1234 .map(Into::into)
1235 .collect::<Vec<_>>(),
1236 sidebar_open: this.sidebar_open,
1237 sidebar_state: this.sidebar.as_ref().and_then(|s| s.serialized_state(cx)),
1238 };
1239 (this.window_id, state)
1240 })
1241 .ok()
1242 else {
1243 return;
1244 };
1245 let kvp = cx.update(|cx| db::kvp::KeyValueStore::global(cx));
1246 crate::persistence::write_multi_workspace_state(&kvp, window_id, state).await;
1247 }));
1248 }
1249
1250 /// Returns the in-flight serialization task (if any) so the caller can
1251 /// await it. Used by the quit handler to ensure pending DB writes
1252 /// complete before the process exits.
1253 pub fn flush_serialization(&mut self) -> Task<()> {
1254 self._serialize_task.take().unwrap_or(Task::ready(()))
1255 }
1256
1257 fn app_will_quit(&mut self, _cx: &mut Context<Self>) -> impl Future<Output = ()> + use<> {
1258 let mut tasks: Vec<Task<()>> = Vec::new();
1259 if let Some(task) = self._serialize_task.take() {
1260 tasks.push(task);
1261 }
1262 tasks.extend(std::mem::take(&mut self.pending_removal_tasks));
1263
1264 async move {
1265 futures::future::join_all(tasks).await;
1266 }
1267 }
1268
1269 pub fn focus_active_workspace(&self, window: &mut Window, cx: &mut App) {
1270 // If a dock panel is zoomed, focus it instead of the center pane.
1271 // Otherwise, focusing the center pane triggers dismiss_zoomed_items_to_reveal
1272 // which closes the zoomed dock.
1273 let focus_handle = {
1274 let workspace = self.workspace().read(cx);
1275 let mut target = None;
1276 for dock in workspace.all_docks() {
1277 let dock = dock.read(cx);
1278 if dock.is_open() {
1279 if let Some(panel) = dock.active_panel() {
1280 if panel.is_zoomed(window, cx) {
1281 target = Some(panel.panel_focus_handle(cx));
1282 break;
1283 }
1284 }
1285 }
1286 }
1287 target.unwrap_or_else(|| {
1288 let pane = workspace.active_pane().clone();
1289 pane.read(cx).focus_handle(cx)
1290 })
1291 };
1292 window.focus(&focus_handle, cx);
1293 }
1294
1295 pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
1296 self.workspace().read(cx).panel::<T>(cx)
1297 }
1298
1299 pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
1300 self.workspace().read(cx).active_modal::<V>(cx)
1301 }
1302
1303 pub fn add_panel<T: Panel>(
1304 &mut self,
1305 panel: Entity<T>,
1306 window: &mut Window,
1307 cx: &mut Context<Self>,
1308 ) {
1309 self.workspace().update(cx, |workspace, cx| {
1310 workspace.add_panel(panel, window, cx);
1311 });
1312 }
1313
1314 pub fn focus_panel<T: Panel>(
1315 &mut self,
1316 window: &mut Window,
1317 cx: &mut Context<Self>,
1318 ) -> Option<Entity<T>> {
1319 self.workspace()
1320 .update(cx, |workspace, cx| workspace.focus_panel::<T>(window, cx))
1321 }
1322
1323 // used in a test
1324 pub fn toggle_modal<V: ModalView, B>(
1325 &mut self,
1326 window: &mut Window,
1327 cx: &mut Context<Self>,
1328 build: B,
1329 ) where
1330 B: FnOnce(&mut Window, &mut gpui::Context<V>) -> V,
1331 {
1332 self.workspace().update(cx, |workspace, cx| {
1333 workspace.toggle_modal(window, cx, build);
1334 });
1335 }
1336
1337 pub fn toggle_dock(
1338 &mut self,
1339 dock_side: DockPosition,
1340 window: &mut Window,
1341 cx: &mut Context<Self>,
1342 ) {
1343 self.workspace().update(cx, |workspace, cx| {
1344 workspace.toggle_dock(dock_side, window, cx);
1345 });
1346 }
1347
1348 pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
1349 self.workspace().read(cx).active_item_as::<I>(cx)
1350 }
1351
1352 pub fn items_of_type<'a, T: Item>(
1353 &'a self,
1354 cx: &'a App,
1355 ) -> impl 'a + Iterator<Item = Entity<T>> {
1356 self.workspace().read(cx).items_of_type::<T>(cx)
1357 }
1358
1359 pub fn database_id(&self, cx: &App) -> Option<WorkspaceId> {
1360 self.workspace().read(cx).database_id()
1361 }
1362
1363 pub fn take_pending_removal_tasks(&mut self) -> Vec<Task<()>> {
1364 let tasks: Vec<Task<()>> = std::mem::take(&mut self.pending_removal_tasks)
1365 .into_iter()
1366 .filter(|task| !task.is_ready())
1367 .collect();
1368 tasks
1369 }
1370
1371 #[cfg(any(test, feature = "test-support"))]
1372 pub fn set_random_database_id(&mut self, cx: &mut Context<Self>) {
1373 self.workspace().update(cx, |workspace, _cx| {
1374 workspace.set_random_database_id();
1375 });
1376 }
1377
1378 #[cfg(any(test, feature = "test-support"))]
1379 pub fn test_new(project: Entity<Project>, window: &mut Window, cx: &mut Context<Self>) -> Self {
1380 let workspace = cx.new(|cx| Workspace::test_new(project, window, cx));
1381 Self::new(workspace, window, cx)
1382 }
1383
1384 #[cfg(any(test, feature = "test-support"))]
1385 pub fn test_add_workspace(
1386 &mut self,
1387 project: Entity<Project>,
1388 window: &mut Window,
1389 cx: &mut Context<Self>,
1390 ) -> Entity<Workspace> {
1391 let workspace = cx.new(|cx| Workspace::test_new(project, window, cx));
1392 self.activate(workspace.clone(), window, cx);
1393 workspace
1394 }
1395
1396 #[cfg(any(test, feature = "test-support"))]
1397 pub fn create_test_workspace(
1398 &mut self,
1399 window: &mut Window,
1400 cx: &mut Context<Self>,
1401 ) -> Task<()> {
1402 let app_state = self.workspace().read(cx).app_state().clone();
1403 let project = Project::local(
1404 app_state.client.clone(),
1405 app_state.node_runtime.clone(),
1406 app_state.user_store.clone(),
1407 app_state.languages.clone(),
1408 app_state.fs.clone(),
1409 None,
1410 project::LocalProjectFlags::default(),
1411 cx,
1412 );
1413 let new_workspace = cx.new(|cx| Workspace::new(None, project, app_state, window, cx));
1414 self.activate(new_workspace.clone(), window, cx);
1415
1416 let weak_workspace = new_workspace.downgrade();
1417 let db = crate::persistence::WorkspaceDb::global(cx);
1418 cx.spawn_in(window, async move |this, cx| {
1419 let workspace_id = db.next_id().await.unwrap();
1420 let workspace = weak_workspace.upgrade().unwrap();
1421 let task: Task<()> = this
1422 .update_in(cx, |this, window, cx| {
1423 let session_id = workspace.read(cx).session_id();
1424 let window_id = window.window_handle().window_id().as_u64();
1425 workspace.update(cx, |workspace, _cx| {
1426 workspace.set_database_id(workspace_id);
1427 });
1428 this.serialize(cx);
1429 let db = db.clone();
1430 cx.background_spawn(async move {
1431 db.set_session_binding(workspace_id, session_id, Some(window_id))
1432 .await
1433 .log_err();
1434 })
1435 })
1436 .unwrap();
1437 task.await
1438 })
1439 }
1440
1441 /// Removes one or more workspaces from this multi-workspace.
1442 ///
1443 /// If the active workspace is among those being removed,
1444 /// `fallback_workspace` is called **synchronously before the removal
1445 /// begins** to produce a `Task` that resolves to the workspace that
1446 /// should become active. The fallback must not be one of the
1447 /// workspaces being removed.
1448 ///
1449 /// Returns `true` if any workspaces were actually removed.
1450 pub fn remove(
1451 &mut self,
1452 workspaces: impl IntoIterator<Item = Entity<Workspace>>,
1453 fallback_workspace: impl FnOnce(
1454 &mut Self,
1455 &mut Window,
1456 &mut Context<Self>,
1457 ) -> Task<Result<Entity<Workspace>>>,
1458 window: &mut Window,
1459 cx: &mut Context<Self>,
1460 ) -> Task<Result<bool>> {
1461 let workspaces: Vec<_> = workspaces.into_iter().collect();
1462
1463 if workspaces.is_empty() {
1464 return Task::ready(Ok(false));
1465 }
1466
1467 let removing_active = workspaces.iter().any(|ws| ws == self.workspace());
1468 let original_active = self.workspace().clone();
1469
1470 let fallback_task = removing_active.then(|| fallback_workspace(self, window, cx));
1471
1472 cx.spawn_in(window, async move |this, cx| {
1473 // Prompt each workspace for unsaved changes. If any workspace
1474 // has dirty buffers, save_all_internal will emit Activate to
1475 // bring it into view before showing the save dialog.
1476 for workspace in &workspaces {
1477 let should_continue = workspace
1478 .update_in(cx, |workspace, window, cx| {
1479 workspace.save_all_internal(crate::SaveIntent::Close, window, cx)
1480 })?
1481 .await?;
1482
1483 if !should_continue {
1484 return Ok(false);
1485 }
1486 }
1487
1488 // If we're removing the active workspace, await the
1489 // fallback and switch to it before tearing anything down.
1490 // Otherwise restore the original active workspace in case
1491 // prompting switched away from it.
1492 if let Some(fallback_task) = fallback_task {
1493 let new_active = fallback_task.await?;
1494
1495 this.update_in(cx, |this, window, cx| {
1496 assert!(
1497 !workspaces.contains(&new_active),
1498 "fallback workspace must not be one of the workspaces being removed"
1499 );
1500 this.activate(new_active, window, cx);
1501 })?;
1502 } else {
1503 this.update_in(cx, |this, window, cx| {
1504 if *this.workspace() != original_active {
1505 this.activate(original_active, window, cx);
1506 }
1507 })?;
1508 }
1509
1510 // Actually remove the workspaces.
1511 this.update_in(cx, |this, _, cx| {
1512 // Save a handle to the active workspace so we can restore
1513 // its index after the removals shift the vec around.
1514 let active_workspace = this.workspace().clone();
1515
1516 let mut removed_workspaces: Vec<Entity<Workspace>> = Vec::new();
1517
1518 this.workspaces.retain(|ws| {
1519 if workspaces.contains(ws) {
1520 removed_workspaces.push(ws.clone());
1521 false
1522 } else {
1523 true
1524 }
1525 });
1526
1527 for workspace in &removed_workspaces {
1528 this.detach_workspace(workspace, cx);
1529 cx.emit(MultiWorkspaceEvent::WorkspaceRemoved(workspace.entity_id()));
1530 }
1531
1532 let removed_any = !removed_workspaces.is_empty();
1533
1534 if removed_any {
1535 // Restore the active workspace index after removals.
1536 if let Some(new_index) = this
1537 .workspaces
1538 .iter()
1539 .position(|ws| ws == &active_workspace)
1540 {
1541 this.active_workspace = ActiveWorkspace::Persistent(new_index);
1542 }
1543
1544 this.serialize(cx);
1545 cx.notify();
1546 }
1547
1548 Ok(removed_any)
1549 })?
1550 })
1551 }
1552
1553 pub fn open_project(
1554 &mut self,
1555 paths: Vec<PathBuf>,
1556 open_mode: OpenMode,
1557 window: &mut Window,
1558 cx: &mut Context<Self>,
1559 ) -> Task<Result<Entity<Workspace>>> {
1560 if self.multi_workspace_enabled(cx) {
1561 self.find_or_create_local_workspace(PathList::new(&paths), window, cx)
1562 } else {
1563 let workspace = self.workspace().clone();
1564 cx.spawn_in(window, async move |_this, cx| {
1565 let should_continue = workspace
1566 .update_in(cx, |workspace, window, cx| {
1567 workspace.prepare_to_close(crate::CloseIntent::ReplaceWindow, window, cx)
1568 })?
1569 .await?;
1570 if should_continue {
1571 workspace
1572 .update_in(cx, |workspace, window, cx| {
1573 workspace.open_workspace_for_paths(open_mode, paths, window, cx)
1574 })?
1575 .await
1576 } else {
1577 Ok(workspace)
1578 }
1579 })
1580 }
1581 }
1582}
1583
1584impl Render for MultiWorkspace {
1585 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1586 let multi_workspace_enabled = self.multi_workspace_enabled(cx);
1587 let sidebar_side = self.sidebar_side(cx);
1588 let sidebar_on_right = sidebar_side == SidebarSide::Right;
1589
1590 let sidebar: Option<AnyElement> = if multi_workspace_enabled && self.sidebar_open() {
1591 self.sidebar.as_ref().map(|sidebar_handle| {
1592 let weak = cx.weak_entity();
1593
1594 let sidebar_width = sidebar_handle.width(cx);
1595 let resize_handle = deferred(
1596 div()
1597 .id("sidebar-resize-handle")
1598 .absolute()
1599 .when(!sidebar_on_right, |el| {
1600 el.right(-SIDEBAR_RESIZE_HANDLE_SIZE / 2.)
1601 })
1602 .when(sidebar_on_right, |el| {
1603 el.left(-SIDEBAR_RESIZE_HANDLE_SIZE / 2.)
1604 })
1605 .top(px(0.))
1606 .h_full()
1607 .w(SIDEBAR_RESIZE_HANDLE_SIZE)
1608 .cursor_col_resize()
1609 .on_drag(DraggedSidebar, |dragged, _, _, cx| {
1610 cx.stop_propagation();
1611 cx.new(|_| dragged.clone())
1612 })
1613 .on_mouse_down(MouseButton::Left, |_, _, cx| {
1614 cx.stop_propagation();
1615 })
1616 .on_mouse_up(MouseButton::Left, move |event, _, cx| {
1617 if event.click_count == 2 {
1618 weak.update(cx, |this, cx| {
1619 if let Some(sidebar) = this.sidebar.as_mut() {
1620 sidebar.set_width(None, cx);
1621 }
1622 this.serialize(cx);
1623 })
1624 .ok();
1625 cx.stop_propagation();
1626 } else {
1627 weak.update(cx, |this, cx| {
1628 this.serialize(cx);
1629 })
1630 .ok();
1631 }
1632 })
1633 .occlude(),
1634 );
1635
1636 div()
1637 .id("sidebar-container")
1638 .relative()
1639 .h_full()
1640 .w(sidebar_width)
1641 .flex_shrink_0()
1642 .child(sidebar_handle.to_any())
1643 .child(resize_handle)
1644 .into_any_element()
1645 })
1646 } else {
1647 None
1648 };
1649
1650 let (left_sidebar, right_sidebar) = if sidebar_on_right {
1651 (None, sidebar)
1652 } else {
1653 (sidebar, None)
1654 };
1655
1656 let ui_font = theme_settings::setup_ui_font(window, cx);
1657 let text_color = cx.theme().colors().text;
1658
1659 let workspace = self.workspace().clone();
1660 let workspace_key_context = workspace.update(cx, |workspace, cx| workspace.key_context(cx));
1661 let root = workspace.update(cx, |workspace, cx| workspace.actions(h_flex(), window, cx));
1662
1663 client_side_decorations(
1664 root.key_context(workspace_key_context)
1665 .relative()
1666 .size_full()
1667 .font(ui_font)
1668 .text_color(text_color)
1669 .on_action(cx.listener(Self::close_window))
1670 .when(self.multi_workspace_enabled(cx), |this| {
1671 this.on_action(cx.listener(
1672 |this: &mut Self, _: &ToggleWorkspaceSidebar, window, cx| {
1673 this.toggle_sidebar(window, cx);
1674 },
1675 ))
1676 .on_action(cx.listener(
1677 |this: &mut Self, _: &CloseWorkspaceSidebar, window, cx| {
1678 this.close_sidebar_action(window, cx);
1679 },
1680 ))
1681 .on_action(cx.listener(
1682 |this: &mut Self, _: &FocusWorkspaceSidebar, window, cx| {
1683 this.focus_sidebar(window, cx);
1684 },
1685 ))
1686 .on_action(cx.listener(
1687 |this: &mut Self, action: &ToggleThreadSwitcher, window, cx| {
1688 if let Some(sidebar) = &this.sidebar {
1689 sidebar.toggle_thread_switcher(action.select_last, window, cx);
1690 }
1691 },
1692 ))
1693 .on_action(cx.listener(|this: &mut Self, _: &NextProject, window, cx| {
1694 if let Some(sidebar) = &this.sidebar {
1695 sidebar.cycle_project(true, window, cx);
1696 }
1697 }))
1698 .on_action(
1699 cx.listener(|this: &mut Self, _: &PreviousProject, window, cx| {
1700 if let Some(sidebar) = &this.sidebar {
1701 sidebar.cycle_project(false, window, cx);
1702 }
1703 }),
1704 )
1705 .on_action(cx.listener(|this: &mut Self, _: &NextThread, window, cx| {
1706 if let Some(sidebar) = &this.sidebar {
1707 sidebar.cycle_thread(true, window, cx);
1708 }
1709 }))
1710 .on_action(cx.listener(
1711 |this: &mut Self, _: &PreviousThread, window, cx| {
1712 if let Some(sidebar) = &this.sidebar {
1713 sidebar.cycle_thread(false, window, cx);
1714 }
1715 },
1716 ))
1717 })
1718 .when(
1719 self.sidebar_open() && self.multi_workspace_enabled(cx),
1720 |this| {
1721 this.on_drag_move(cx.listener(
1722 move |this: &mut Self,
1723 e: &DragMoveEvent<DraggedSidebar>,
1724 window,
1725 cx| {
1726 if let Some(sidebar) = &this.sidebar {
1727 let new_width = if sidebar_on_right {
1728 window.bounds().size.width - e.event.position.x
1729 } else {
1730 e.event.position.x
1731 };
1732 sidebar.set_width(Some(new_width), cx);
1733 }
1734 },
1735 ))
1736 },
1737 )
1738 .children(left_sidebar)
1739 .child(
1740 div()
1741 .flex()
1742 .flex_1()
1743 .size_full()
1744 .overflow_hidden()
1745 .child(self.workspace().clone()),
1746 )
1747 .children(right_sidebar)
1748 .child(self.workspace().read(cx).modal_layer.clone())
1749 .children(self.sidebar_overlay.as_ref().map(|view| {
1750 deferred(div().absolute().size_full().inset_0().occlude().child(
1751 v_flex().h(px(0.0)).top_20().items_center().child(
1752 h_flex().occlude().child(view.clone()).on_mouse_down(
1753 MouseButton::Left,
1754 |_, _, cx| {
1755 cx.stop_propagation();
1756 },
1757 ),
1758 ),
1759 ))
1760 .with_priority(2)
1761 })),
1762 window,
1763 cx,
1764 Tiling {
1765 left: !sidebar_on_right && multi_workspace_enabled && self.sidebar_open(),
1766 right: sidebar_on_right && multi_workspace_enabled && self.sidebar_open(),
1767 ..Tiling::default()
1768 },
1769 )
1770 }
1771}