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