1use anyhow::Result;
2use feature_flags::{AgentV2FeatureFlag, FeatureFlagAppExt};
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::DisableAiSettings;
9#[cfg(any(test, feature = "test-support"))]
10use project::Project;
11use remote::RemoteConnectionOptions;
12use settings::Settings;
13pub use settings::SidebarSide;
14use std::future::Future;
15use std::path::PathBuf;
16use std::sync::Arc;
17use ui::prelude::*;
18use util::{ResultExt, path_list::PathList};
19use zed_actions::agents_sidebar::{MoveWorkspaceToNewWindow, 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::{
28 CloseIntent, CloseWindow, DockPosition, Event as WorkspaceEvent, Item, ModalView, OpenMode,
29 Panel, Workspace, WorkspaceId, client_side_decorations,
30};
31
32actions!(
33 multi_workspace,
34 [
35 /// Toggles the workspace switcher sidebar.
36 ToggleWorkspaceSidebar,
37 /// Closes the workspace sidebar.
38 CloseWorkspaceSidebar,
39 /// Moves focus to or from the workspace sidebar without closing it.
40 FocusWorkspaceSidebar,
41 /// Switches to the next workspace.
42 NextWorkspace,
43 /// Switches to the previous workspace.
44 PreviousWorkspace,
45 ]
46);
47
48#[derive(Default)]
49pub struct SidebarRenderState {
50 pub open: bool,
51 pub side: SidebarSide,
52}
53
54pub fn sidebar_side_context_menu(
55 id: impl Into<ElementId>,
56 cx: &App,
57) -> ui::RightClickMenu<ContextMenu> {
58 let current_position = AgentSettings::get_global(cx).sidebar_side;
59 right_click_menu(id).menu(move |window, cx| {
60 let fs = <dyn fs::Fs>::global(cx);
61 ContextMenu::build(window, cx, move |mut menu, _, _cx| {
62 let positions: [(SidebarDockPosition, &str); 2] = [
63 (SidebarDockPosition::Left, "Left"),
64 (SidebarDockPosition::Right, "Right"),
65 ];
66 for (position, label) in positions {
67 let fs = fs.clone();
68 menu = menu.toggleable_entry(
69 label,
70 position == current_position,
71 IconPosition::Start,
72 None,
73 move |_window, cx| {
74 settings::update_settings_file(fs.clone(), cx, move |settings, _cx| {
75 settings
76 .agent
77 .get_or_insert_default()
78 .set_sidebar_side(position);
79 });
80 },
81 );
82 }
83 menu
84 })
85 })
86}
87
88pub enum MultiWorkspaceEvent {
89 ActiveWorkspaceChanged,
90 WorkspaceAdded(Entity<Workspace>),
91 WorkspaceRemoved(EntityId),
92}
93
94pub enum SidebarEvent {
95 SerializeNeeded,
96}
97
98pub trait Sidebar: Focusable + Render + EventEmitter<SidebarEvent> + Sized {
99 fn width(&self, cx: &App) -> Pixels;
100 fn set_width(&mut self, width: Option<Pixels>, cx: &mut Context<Self>);
101 fn has_notifications(&self, cx: &App) -> bool;
102 fn side(&self, _cx: &App) -> SidebarSide;
103
104 fn is_threads_list_view_active(&self) -> bool {
105 true
106 }
107 /// Makes focus reset back to the search editor upon toggling the sidebar from outside
108 fn prepare_for_focus(&mut self, _window: &mut Window, _cx: &mut Context<Self>) {}
109 /// Opens or cycles the thread switcher popup.
110 fn toggle_thread_switcher(
111 &mut self,
112 _select_last: bool,
113 _window: &mut Window,
114 _cx: &mut Context<Self>,
115 ) {
116 }
117
118 /// Return an opaque JSON blob of sidebar-specific state to persist.
119 fn serialized_state(&self, _cx: &App) -> Option<String> {
120 None
121 }
122
123 /// Restore sidebar state from a previously-serialized blob.
124 fn restore_serialized_state(
125 &mut self,
126 _state: &str,
127 _window: &mut Window,
128 _cx: &mut Context<Self>,
129 ) {
130 }
131}
132
133pub trait SidebarHandle: 'static + Send + Sync {
134 fn width(&self, cx: &App) -> Pixels;
135 fn set_width(&self, width: Option<Pixels>, cx: &mut App);
136 fn focus_handle(&self, cx: &App) -> FocusHandle;
137 fn focus(&self, window: &mut Window, cx: &mut App);
138 fn prepare_for_focus(&self, window: &mut Window, cx: &mut App);
139 fn has_notifications(&self, cx: &App) -> bool;
140 fn to_any(&self) -> AnyView;
141 fn entity_id(&self) -> EntityId;
142 fn toggle_thread_switcher(&self, select_last: bool, window: &mut Window, cx: &mut App);
143
144 fn is_threads_list_view_active(&self, cx: &App) -> bool;
145
146 fn side(&self, cx: &App) -> SidebarSide;
147 fn serialized_state(&self, cx: &App) -> Option<String>;
148 fn restore_serialized_state(&self, state: &str, window: &mut Window, cx: &mut App);
149}
150
151#[derive(Clone)]
152pub struct DraggedSidebar;
153
154impl Render for DraggedSidebar {
155 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
156 gpui::Empty
157 }
158}
159
160impl<T: Sidebar> SidebarHandle for Entity<T> {
161 fn width(&self, cx: &App) -> Pixels {
162 self.read(cx).width(cx)
163 }
164
165 fn set_width(&self, width: Option<Pixels>, cx: &mut App) {
166 self.update(cx, |this, cx| this.set_width(width, cx))
167 }
168
169 fn focus_handle(&self, cx: &App) -> FocusHandle {
170 self.read(cx).focus_handle(cx)
171 }
172
173 fn focus(&self, window: &mut Window, cx: &mut App) {
174 let handle = self.read(cx).focus_handle(cx);
175 window.focus(&handle, cx);
176 }
177
178 fn prepare_for_focus(&self, window: &mut Window, cx: &mut App) {
179 self.update(cx, |this, cx| this.prepare_for_focus(window, cx));
180 }
181
182 fn has_notifications(&self, cx: &App) -> bool {
183 self.read(cx).has_notifications(cx)
184 }
185
186 fn to_any(&self) -> AnyView {
187 self.clone().into()
188 }
189
190 fn entity_id(&self) -> EntityId {
191 Entity::entity_id(self)
192 }
193
194 fn toggle_thread_switcher(&self, select_last: bool, window: &mut Window, cx: &mut App) {
195 let entity = self.clone();
196 window.defer(cx, move |window, cx| {
197 entity.update(cx, |this, cx| {
198 this.toggle_thread_switcher(select_last, window, cx);
199 });
200 });
201 }
202
203 fn is_threads_list_view_active(&self, cx: &App) -> bool {
204 self.read(cx).is_threads_list_view_active()
205 }
206
207 fn side(&self, cx: &App) -> SidebarSide {
208 self.read(cx).side(cx)
209 }
210
211 fn serialized_state(&self, cx: &App) -> Option<String> {
212 self.read(cx).serialized_state(cx)
213 }
214
215 fn restore_serialized_state(&self, state: &str, window: &mut Window, cx: &mut App) {
216 self.update(cx, |this, cx| {
217 this.restore_serialized_state(state, window, cx)
218 })
219 }
220}
221
222pub struct MultiWorkspace {
223 window_id: WindowId,
224 workspaces: Vec<Entity<Workspace>>,
225 active_workspace_index: usize,
226 sidebar: Option<Box<dyn SidebarHandle>>,
227 sidebar_open: bool,
228 sidebar_overlay: Option<AnyView>,
229 pending_removal_tasks: Vec<Task<()>>,
230 _serialize_task: Option<Task<()>>,
231 _subscriptions: Vec<Subscription>,
232}
233
234#[derive(Clone, PartialEq, Eq, Debug)]
235pub struct ProjectGroupKey {
236 pub host: Option<RemoteConnectionOptions>,
237 pub main_worktree_paths: PathList,
238}
239
240impl ProjectGroupKey {
241 pub fn display_name(&self) -> SharedString {
242 let mut names = Vec::with_capacity(self.main_worktree_paths.paths().len());
243 for abs_path in self.main_worktree_paths.paths() {
244 if let Some(name) = abs_path.file_name() {
245 names.push(name.to_string_lossy().to_string());
246 }
247 }
248 if names.is_empty() {
249 "Empty Workspace".into()
250 } else {
251 names.join(", ").into()
252 }
253 }
254}
255
256impl EventEmitter<MultiWorkspaceEvent> for MultiWorkspace {}
257
258impl MultiWorkspace {
259 pub fn sidebar_side(&self, cx: &App) -> SidebarSide {
260 self.sidebar
261 .as_ref()
262 .map_or(SidebarSide::Left, |s| s.side(cx))
263 }
264
265 pub fn sidebar_render_state(&self, cx: &App) -> SidebarRenderState {
266 SidebarRenderState {
267 open: self.sidebar_open() && self.multi_workspace_enabled(cx),
268 side: self.sidebar_side(cx),
269 }
270 }
271
272 pub fn new(workspace: Entity<Workspace>, window: &mut Window, cx: &mut Context<Self>) -> Self {
273 let release_subscription = cx.on_release(|this: &mut MultiWorkspace, _cx| {
274 if let Some(task) = this._serialize_task.take() {
275 task.detach();
276 }
277 for task in std::mem::take(&mut this.pending_removal_tasks) {
278 task.detach();
279 }
280 });
281 let quit_subscription = cx.on_app_quit(Self::app_will_quit);
282 let settings_subscription =
283 cx.observe_global_in::<settings::SettingsStore>(window, |this, window, cx| {
284 if DisableAiSettings::get_global(cx).disable_ai && this.sidebar_open {
285 this.close_sidebar(window, cx);
286 }
287 });
288 Self::subscribe_to_workspace(&workspace, window, cx);
289 let weak_self = cx.weak_entity();
290 workspace.update(cx, |workspace, cx| {
291 workspace.set_multi_workspace(weak_self, cx);
292 });
293 Self {
294 window_id: window.window_handle().window_id(),
295 workspaces: vec![workspace],
296 active_workspace_index: 0,
297 sidebar: None,
298 sidebar_open: false,
299 sidebar_overlay: None,
300 pending_removal_tasks: Vec::new(),
301 _serialize_task: None,
302 _subscriptions: vec![
303 release_subscription,
304 quit_subscription,
305 settings_subscription,
306 ],
307 }
308 }
309
310 pub fn register_sidebar<T: Sidebar>(&mut self, sidebar: Entity<T>, cx: &mut Context<Self>) {
311 self._subscriptions
312 .push(cx.observe(&sidebar, |_this, _, cx| {
313 cx.notify();
314 }));
315 self._subscriptions
316 .push(cx.subscribe(&sidebar, |this, _, event, cx| match event {
317 SidebarEvent::SerializeNeeded => {
318 this.serialize(cx);
319 }
320 }));
321 self.sidebar = Some(Box::new(sidebar));
322 }
323
324 pub fn sidebar(&self) -> Option<&dyn SidebarHandle> {
325 self.sidebar.as_deref()
326 }
327
328 pub fn set_sidebar_overlay(&mut self, overlay: Option<AnyView>, cx: &mut Context<Self>) {
329 self.sidebar_overlay = overlay;
330 cx.notify();
331 }
332
333 pub fn sidebar_open(&self) -> bool {
334 self.sidebar_open
335 }
336
337 pub fn sidebar_has_notifications(&self, cx: &App) -> bool {
338 self.sidebar
339 .as_ref()
340 .map_or(false, |s| s.has_notifications(cx))
341 }
342
343 pub fn is_threads_list_view_active(&self, cx: &App) -> bool {
344 self.sidebar
345 .as_ref()
346 .map_or(false, |s| s.is_threads_list_view_active(cx))
347 }
348
349 pub fn multi_workspace_enabled(&self, cx: &App) -> bool {
350 cx.has_flag::<AgentV2FeatureFlag>() && !DisableAiSettings::get_global(cx).disable_ai
351 }
352
353 pub fn toggle_sidebar(&mut self, window: &mut Window, cx: &mut Context<Self>) {
354 if !self.multi_workspace_enabled(cx) {
355 return;
356 }
357
358 if self.sidebar_open {
359 self.close_sidebar(window, cx);
360 } else {
361 self.open_sidebar(cx);
362 if let Some(sidebar) = &self.sidebar {
363 sidebar.prepare_for_focus(window, cx);
364 sidebar.focus(window, cx);
365 }
366 }
367 }
368
369 pub fn close_sidebar_action(&mut self, window: &mut Window, cx: &mut Context<Self>) {
370 if !self.multi_workspace_enabled(cx) {
371 return;
372 }
373
374 if self.sidebar_open {
375 self.close_sidebar(window, cx);
376 }
377 }
378
379 pub fn focus_sidebar(&mut self, window: &mut Window, cx: &mut Context<Self>) {
380 if !self.multi_workspace_enabled(cx) {
381 return;
382 }
383
384 if self.sidebar_open {
385 let sidebar_is_focused = self
386 .sidebar
387 .as_ref()
388 .is_some_and(|s| s.focus_handle(cx).contains_focused(window, cx));
389
390 if sidebar_is_focused {
391 let pane = self.workspace().read(cx).active_pane().clone();
392 let pane_focus = pane.read(cx).focus_handle(cx);
393 window.focus(&pane_focus, cx);
394 } else if let Some(sidebar) = &self.sidebar {
395 sidebar.prepare_for_focus(window, cx);
396 sidebar.focus(window, cx);
397 }
398 } else {
399 self.open_sidebar(cx);
400 if let Some(sidebar) = &self.sidebar {
401 sidebar.prepare_for_focus(window, cx);
402 sidebar.focus(window, cx);
403 }
404 }
405 }
406
407 pub fn open_sidebar(&mut self, cx: &mut Context<Self>) {
408 self.sidebar_open = true;
409 let sidebar_focus_handle = self.sidebar.as_ref().map(|s| s.focus_handle(cx));
410 for workspace in &self.workspaces {
411 workspace.update(cx, |workspace, _cx| {
412 workspace.set_sidebar_focus_handle(sidebar_focus_handle.clone());
413 });
414 }
415 self.serialize(cx);
416 cx.notify();
417 }
418
419 pub fn close_sidebar(&mut self, window: &mut Window, cx: &mut Context<Self>) {
420 self.sidebar_open = false;
421 for workspace in &self.workspaces {
422 workspace.update(cx, |workspace, _cx| {
423 workspace.set_sidebar_focus_handle(None);
424 });
425 }
426 let pane = self.workspace().read(cx).active_pane().clone();
427 let pane_focus = pane.read(cx).focus_handle(cx);
428 window.focus(&pane_focus, cx);
429 self.serialize(cx);
430 cx.notify();
431 }
432
433 pub fn close_window(&mut self, _: &CloseWindow, window: &mut Window, cx: &mut Context<Self>) {
434 cx.spawn_in(window, async move |this, cx| {
435 let workspaces = this.update(cx, |multi_workspace, _cx| {
436 multi_workspace.workspaces().to_vec()
437 })?;
438
439 for workspace in workspaces {
440 let should_continue = workspace
441 .update_in(cx, |workspace, window, cx| {
442 workspace.prepare_to_close(CloseIntent::CloseWindow, window, cx)
443 })?
444 .await?;
445 if !should_continue {
446 return anyhow::Ok(());
447 }
448 }
449
450 cx.update(|window, _cx| {
451 window.remove_window();
452 })?;
453
454 anyhow::Ok(())
455 })
456 .detach_and_log_err(cx);
457 }
458
459 fn subscribe_to_workspace(
460 workspace: &Entity<Workspace>,
461 window: &Window,
462 cx: &mut Context<Self>,
463 ) {
464 cx.subscribe_in(workspace, window, |this, workspace, event, window, cx| {
465 if let WorkspaceEvent::Activate = event {
466 this.activate(workspace.clone(), window, cx);
467 }
468 })
469 .detach();
470 }
471
472 pub fn workspace(&self) -> &Entity<Workspace> {
473 &self.workspaces[self.active_workspace_index]
474 }
475
476 pub fn workspaces(&self) -> &[Entity<Workspace>] {
477 &self.workspaces
478 }
479
480 pub fn project_group_keys(&self, cx: &App) -> impl Iterator<Item = ProjectGroupKey> {
481 let mut keys = Vec::new();
482 for workspace in &self.workspaces {
483 let key = workspace.read(cx).project_group_key(cx);
484 keys.push(key);
485 }
486 keys.into_iter()
487 }
488
489 pub fn active_workspace_index(&self) -> usize {
490 self.active_workspace_index
491 }
492
493 /// Adds a workspace to this window without changing which workspace is
494 /// active.
495 pub fn add(&mut self, workspace: Entity<Workspace>, window: &Window, cx: &mut Context<Self>) {
496 if !self.multi_workspace_enabled(cx) {
497 self.set_single_workspace(workspace, cx);
498 return;
499 }
500
501 self.insert_workspace(workspace, window, cx);
502 }
503
504 /// Ensures the workspace is in the multiworkspace and makes it the active one.
505 pub fn activate(
506 &mut self,
507 workspace: Entity<Workspace>,
508 window: &mut Window,
509 cx: &mut Context<Self>,
510 ) {
511 if !self.multi_workspace_enabled(cx) {
512 self.set_single_workspace(workspace, cx);
513 return;
514 }
515
516 let index = self.insert_workspace(workspace, &*window, cx);
517 let changed = self.active_workspace_index != index;
518 self.active_workspace_index = index;
519 if changed {
520 cx.emit(MultiWorkspaceEvent::ActiveWorkspaceChanged);
521 self.serialize(cx);
522 }
523 self.focus_active_workspace(window, cx);
524 cx.notify();
525 }
526
527 /// Replaces the currently active workspace with a new one. If the
528 /// workspace is already in the list, this just switches to it.
529 pub fn replace(
530 &mut self,
531 workspace: Entity<Workspace>,
532 window: &Window,
533 cx: &mut Context<Self>,
534 ) {
535 if !self.multi_workspace_enabled(cx) {
536 self.set_single_workspace(workspace, cx);
537 return;
538 }
539
540 if let Some(index) = self.workspaces.iter().position(|w| *w == workspace) {
541 let changed = self.active_workspace_index != index;
542 self.active_workspace_index = index;
543 if changed {
544 cx.emit(MultiWorkspaceEvent::ActiveWorkspaceChanged);
545 self.serialize(cx);
546 }
547 cx.notify();
548 return;
549 }
550
551 let old_workspace = std::mem::replace(
552 &mut self.workspaces[self.active_workspace_index],
553 workspace.clone(),
554 );
555
556 let old_entity_id = old_workspace.entity_id();
557 self.detach_workspace(&old_workspace, cx);
558
559 Self::subscribe_to_workspace(&workspace, window, cx);
560 self.sync_sidebar_to_workspace(&workspace, cx);
561
562 cx.emit(MultiWorkspaceEvent::WorkspaceRemoved(old_entity_id));
563 cx.emit(MultiWorkspaceEvent::WorkspaceAdded(workspace));
564 cx.emit(MultiWorkspaceEvent::ActiveWorkspaceChanged);
565 self.serialize(cx);
566 cx.notify();
567 }
568
569 fn set_single_workspace(&mut self, workspace: Entity<Workspace>, cx: &mut Context<Self>) {
570 self.workspaces[0] = workspace;
571 self.active_workspace_index = 0;
572 cx.emit(MultiWorkspaceEvent::ActiveWorkspaceChanged);
573 cx.notify();
574 }
575
576 /// Inserts a workspace into the list if not already present. Returns the
577 /// index of the workspace (existing or newly inserted). Does not change
578 /// the active workspace index.
579 fn insert_workspace(
580 &mut self,
581 workspace: Entity<Workspace>,
582 window: &Window,
583 cx: &mut Context<Self>,
584 ) -> usize {
585 if let Some(index) = self.workspaces.iter().position(|w| *w == workspace) {
586 index
587 } else {
588 Self::subscribe_to_workspace(&workspace, window, cx);
589 self.sync_sidebar_to_workspace(&workspace, cx);
590 let weak_self = cx.weak_entity();
591 workspace.update(cx, |workspace, cx| {
592 workspace.set_multi_workspace(weak_self, cx);
593 });
594 self.workspaces.push(workspace.clone());
595 cx.emit(MultiWorkspaceEvent::WorkspaceAdded(workspace));
596 cx.notify();
597 self.workspaces.len() - 1
598 }
599 }
600
601 /// Clears session state and DB binding for a workspace that is being
602 /// removed or replaced. The DB row is preserved so the workspace still
603 /// appears in the recent-projects list.
604 fn detach_workspace(&mut self, workspace: &Entity<Workspace>, cx: &mut Context<Self>) {
605 workspace.update(cx, |workspace, _cx| {
606 workspace.session_id.take();
607 workspace._schedule_serialize_workspace.take();
608 workspace._serialize_workspace_task.take();
609 });
610
611 if let Some(workspace_id) = workspace.read(cx).database_id() {
612 let db = crate::persistence::WorkspaceDb::global(cx);
613 self.pending_removal_tasks.retain(|task| !task.is_ready());
614 self.pending_removal_tasks
615 .push(cx.background_spawn(async move {
616 db.set_session_binding(workspace_id, None, None)
617 .await
618 .log_err();
619 }));
620 }
621 }
622
623 fn sync_sidebar_to_workspace(&self, workspace: &Entity<Workspace>, cx: &mut Context<Self>) {
624 if self.sidebar_open {
625 let sidebar_focus_handle = self.sidebar.as_ref().map(|s| s.focus_handle(cx));
626 workspace.update(cx, |workspace, _| {
627 workspace.set_sidebar_focus_handle(sidebar_focus_handle);
628 });
629 }
630 }
631
632 fn cycle_workspace(&mut self, delta: isize, window: &mut Window, cx: &mut Context<Self>) {
633 let count = self.workspaces.len() as isize;
634 if count <= 1 {
635 return;
636 }
637 let current = self.active_workspace_index as isize;
638 let next = ((current + delta).rem_euclid(count)) as usize;
639 let workspace = self.workspaces[next].clone();
640 self.activate(workspace, window, cx);
641 }
642
643 fn next_workspace(&mut self, _: &NextWorkspace, window: &mut Window, cx: &mut Context<Self>) {
644 self.cycle_workspace(1, window, cx);
645 }
646
647 fn previous_workspace(
648 &mut self,
649 _: &PreviousWorkspace,
650 window: &mut Window,
651 cx: &mut Context<Self>,
652 ) {
653 self.cycle_workspace(-1, window, cx);
654 }
655
656 pub(crate) fn serialize(&mut self, cx: &mut Context<Self>) {
657 self._serialize_task = Some(cx.spawn(async move |this, cx| {
658 let Some((window_id, state)) = this
659 .read_with(cx, |this, cx| {
660 let state = crate::persistence::model::MultiWorkspaceState {
661 active_workspace_id: this.workspace().read(cx).database_id(),
662 sidebar_open: this.sidebar_open,
663 sidebar_state: this.sidebar.as_ref().and_then(|s| s.serialized_state(cx)),
664 };
665 (this.window_id, state)
666 })
667 .ok()
668 else {
669 return;
670 };
671 let kvp = cx.update(|cx| db::kvp::KeyValueStore::global(cx));
672 crate::persistence::write_multi_workspace_state(&kvp, window_id, state).await;
673 }));
674 }
675
676 /// Returns the in-flight serialization task (if any) so the caller can
677 /// await it. Used by the quit handler to ensure pending DB writes
678 /// complete before the process exits.
679 pub fn flush_serialization(&mut self) -> Task<()> {
680 self._serialize_task.take().unwrap_or(Task::ready(()))
681 }
682
683 fn app_will_quit(&mut self, _cx: &mut Context<Self>) -> impl Future<Output = ()> + use<> {
684 let mut tasks: Vec<Task<()>> = Vec::new();
685 if let Some(task) = self._serialize_task.take() {
686 tasks.push(task);
687 }
688 tasks.extend(std::mem::take(&mut self.pending_removal_tasks));
689
690 async move {
691 futures::future::join_all(tasks).await;
692 }
693 }
694
695 pub fn focus_active_workspace(&self, window: &mut Window, cx: &mut App) {
696 // If a dock panel is zoomed, focus it instead of the center pane.
697 // Otherwise, focusing the center pane triggers dismiss_zoomed_items_to_reveal
698 // which closes the zoomed dock.
699 let focus_handle = {
700 let workspace = self.workspace().read(cx);
701 let mut target = None;
702 for dock in workspace.all_docks() {
703 let dock = dock.read(cx);
704 if dock.is_open() {
705 if let Some(panel) = dock.active_panel() {
706 if panel.is_zoomed(window, cx) {
707 target = Some(panel.panel_focus_handle(cx));
708 break;
709 }
710 }
711 }
712 }
713 target.unwrap_or_else(|| {
714 let pane = workspace.active_pane().clone();
715 pane.read(cx).focus_handle(cx)
716 })
717 };
718 window.focus(&focus_handle, cx);
719 }
720
721 pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
722 self.workspace().read(cx).panel::<T>(cx)
723 }
724
725 pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
726 self.workspace().read(cx).active_modal::<V>(cx)
727 }
728
729 pub fn add_panel<T: Panel>(
730 &mut self,
731 panel: Entity<T>,
732 window: &mut Window,
733 cx: &mut Context<Self>,
734 ) {
735 self.workspace().update(cx, |workspace, cx| {
736 workspace.add_panel(panel, window, cx);
737 });
738 }
739
740 pub fn focus_panel<T: Panel>(
741 &mut self,
742 window: &mut Window,
743 cx: &mut Context<Self>,
744 ) -> Option<Entity<T>> {
745 self.workspace()
746 .update(cx, |workspace, cx| workspace.focus_panel::<T>(window, cx))
747 }
748
749 // used in a test
750 pub fn toggle_modal<V: ModalView, B>(
751 &mut self,
752 window: &mut Window,
753 cx: &mut Context<Self>,
754 build: B,
755 ) where
756 B: FnOnce(&mut Window, &mut gpui::Context<V>) -> V,
757 {
758 self.workspace().update(cx, |workspace, cx| {
759 workspace.toggle_modal(window, cx, build);
760 });
761 }
762
763 pub fn toggle_dock(
764 &mut self,
765 dock_side: DockPosition,
766 window: &mut Window,
767 cx: &mut Context<Self>,
768 ) {
769 self.workspace().update(cx, |workspace, cx| {
770 workspace.toggle_dock(dock_side, window, cx);
771 });
772 }
773
774 pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
775 self.workspace().read(cx).active_item_as::<I>(cx)
776 }
777
778 pub fn items_of_type<'a, T: Item>(
779 &'a self,
780 cx: &'a App,
781 ) -> impl 'a + Iterator<Item = Entity<T>> {
782 self.workspace().read(cx).items_of_type::<T>(cx)
783 }
784
785 pub fn database_id(&self, cx: &App) -> Option<WorkspaceId> {
786 self.workspace().read(cx).database_id()
787 }
788
789 pub fn take_pending_removal_tasks(&mut self) -> Vec<Task<()>> {
790 let tasks: Vec<Task<()>> = std::mem::take(&mut self.pending_removal_tasks)
791 .into_iter()
792 .filter(|task| !task.is_ready())
793 .collect();
794 tasks
795 }
796
797 #[cfg(any(test, feature = "test-support"))]
798 pub fn set_random_database_id(&mut self, cx: &mut Context<Self>) {
799 self.workspace().update(cx, |workspace, _cx| {
800 workspace.set_random_database_id();
801 });
802 }
803
804 #[cfg(any(test, feature = "test-support"))]
805 pub fn test_new(project: Entity<Project>, window: &mut Window, cx: &mut Context<Self>) -> Self {
806 let workspace = cx.new(|cx| Workspace::test_new(project, window, cx));
807 Self::new(workspace, window, cx)
808 }
809
810 #[cfg(any(test, feature = "test-support"))]
811 pub fn test_add_workspace(
812 &mut self,
813 project: Entity<Project>,
814 window: &mut Window,
815 cx: &mut Context<Self>,
816 ) -> Entity<Workspace> {
817 let workspace = cx.new(|cx| Workspace::test_new(project, window, cx));
818 self.activate(workspace.clone(), window, cx);
819 workspace
820 }
821
822 #[cfg(any(test, feature = "test-support"))]
823 pub fn create_test_workspace(
824 &mut self,
825 window: &mut Window,
826 cx: &mut Context<Self>,
827 ) -> Task<()> {
828 let app_state = self.workspace().read(cx).app_state().clone();
829 let project = Project::local(
830 app_state.client.clone(),
831 app_state.node_runtime.clone(),
832 app_state.user_store.clone(),
833 app_state.languages.clone(),
834 app_state.fs.clone(),
835 None,
836 project::LocalProjectFlags::default(),
837 cx,
838 );
839 let new_workspace = cx.new(|cx| Workspace::new(None, project, app_state, window, cx));
840 self.activate(new_workspace.clone(), window, cx);
841
842 let weak_workspace = new_workspace.downgrade();
843 let db = crate::persistence::WorkspaceDb::global(cx);
844 cx.spawn_in(window, async move |this, cx| {
845 let workspace_id = db.next_id().await.unwrap();
846 let workspace = weak_workspace.upgrade().unwrap();
847 let task: Task<()> = this
848 .update_in(cx, |this, window, cx| {
849 let session_id = workspace.read(cx).session_id();
850 let window_id = window.window_handle().window_id().as_u64();
851 workspace.update(cx, |workspace, _cx| {
852 workspace.set_database_id(workspace_id);
853 });
854 this.serialize(cx);
855 let db = db.clone();
856 cx.background_spawn(async move {
857 db.set_session_binding(workspace_id, session_id, Some(window_id))
858 .await
859 .log_err();
860 })
861 })
862 .unwrap();
863 task.await
864 })
865 }
866
867 pub fn remove(
868 &mut self,
869 workspace: &Entity<Workspace>,
870 window: &mut Window,
871 cx: &mut Context<Self>,
872 ) -> bool {
873 let Some(index) = self.workspaces.iter().position(|w| w == workspace) else {
874 return false;
875 };
876 if self.workspaces.len() <= 1 {
877 return false;
878 }
879
880 let removed_workspace = self.workspaces.remove(index);
881
882 if self.active_workspace_index >= self.workspaces.len() {
883 self.active_workspace_index = self.workspaces.len() - 1;
884 } else if self.active_workspace_index > index {
885 self.active_workspace_index -= 1;
886 }
887
888 self.detach_workspace(&removed_workspace, cx);
889
890 self.serialize(cx);
891 self.focus_active_workspace(window, cx);
892 cx.emit(MultiWorkspaceEvent::WorkspaceRemoved(
893 removed_workspace.entity_id(),
894 ));
895 cx.emit(MultiWorkspaceEvent::ActiveWorkspaceChanged);
896 cx.notify();
897
898 true
899 }
900
901 pub fn move_workspace_to_new_window(
902 &mut self,
903 workspace: &Entity<Workspace>,
904 window: &mut Window,
905 cx: &mut Context<Self>,
906 ) {
907 let workspace = workspace.clone();
908 if !self.remove(&workspace, window, cx) {
909 return;
910 }
911
912 let app_state: Arc<crate::AppState> = workspace.read(cx).app_state().clone();
913
914 cx.defer(move |cx| {
915 let options = (app_state.build_window_options)(None, cx);
916
917 let Ok(window) = cx.open_window(options, |window, cx| {
918 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
919 }) else {
920 return;
921 };
922
923 let _ = window.update(cx, |_, window, _| {
924 window.activate_window();
925 });
926 });
927 }
928
929 fn move_active_workspace_to_new_window(
930 &mut self,
931 _: &MoveWorkspaceToNewWindow,
932 window: &mut Window,
933 cx: &mut Context<Self>,
934 ) {
935 let workspace = self.workspace().clone();
936 self.move_workspace_to_new_window(&workspace, window, cx);
937 }
938
939 pub fn open_project(
940 &mut self,
941 paths: Vec<PathBuf>,
942 open_mode: OpenMode,
943 window: &mut Window,
944 cx: &mut Context<Self>,
945 ) -> Task<Result<Entity<Workspace>>> {
946 let workspace = self.workspace().clone();
947
948 let needs_close_prompt =
949 open_mode == OpenMode::Replace || !self.multi_workspace_enabled(cx);
950 let open_mode = if self.multi_workspace_enabled(cx) {
951 open_mode
952 } else {
953 OpenMode::Replace
954 };
955
956 if needs_close_prompt {
957 cx.spawn_in(window, async move |_this, cx| {
958 let should_continue = workspace
959 .update_in(cx, |workspace, window, cx| {
960 workspace.prepare_to_close(crate::CloseIntent::ReplaceWindow, window, cx)
961 })?
962 .await?;
963 if should_continue {
964 workspace
965 .update_in(cx, |workspace, window, cx| {
966 workspace.open_workspace_for_paths(open_mode, paths, window, cx)
967 })?
968 .await
969 } else {
970 Ok(workspace)
971 }
972 })
973 } else {
974 workspace.update(cx, |workspace, cx| {
975 workspace.open_workspace_for_paths(open_mode, paths, window, cx)
976 })
977 }
978 }
979}
980
981impl Render for MultiWorkspace {
982 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
983 let multi_workspace_enabled = self.multi_workspace_enabled(cx);
984 let sidebar_side = self.sidebar_side(cx);
985 let sidebar_on_right = sidebar_side == SidebarSide::Right;
986
987 let sidebar: Option<AnyElement> = if multi_workspace_enabled && self.sidebar_open() {
988 self.sidebar.as_ref().map(|sidebar_handle| {
989 let weak = cx.weak_entity();
990
991 let sidebar_width = sidebar_handle.width(cx);
992 let resize_handle = deferred(
993 div()
994 .id("sidebar-resize-handle")
995 .absolute()
996 .when(!sidebar_on_right, |el| {
997 el.right(-SIDEBAR_RESIZE_HANDLE_SIZE / 2.)
998 })
999 .when(sidebar_on_right, |el| {
1000 el.left(-SIDEBAR_RESIZE_HANDLE_SIZE / 2.)
1001 })
1002 .top(px(0.))
1003 .h_full()
1004 .w(SIDEBAR_RESIZE_HANDLE_SIZE)
1005 .cursor_col_resize()
1006 .on_drag(DraggedSidebar, |dragged, _, _, cx| {
1007 cx.stop_propagation();
1008 cx.new(|_| dragged.clone())
1009 })
1010 .on_mouse_down(MouseButton::Left, |_, _, cx| {
1011 cx.stop_propagation();
1012 })
1013 .on_mouse_up(MouseButton::Left, move |event, _, cx| {
1014 if event.click_count == 2 {
1015 weak.update(cx, |this, cx| {
1016 if let Some(sidebar) = this.sidebar.as_mut() {
1017 sidebar.set_width(None, cx);
1018 }
1019 this.serialize(cx);
1020 })
1021 .ok();
1022 cx.stop_propagation();
1023 } else {
1024 weak.update(cx, |this, cx| {
1025 this.serialize(cx);
1026 })
1027 .ok();
1028 }
1029 })
1030 .occlude(),
1031 );
1032
1033 div()
1034 .id("sidebar-container")
1035 .relative()
1036 .h_full()
1037 .w(sidebar_width)
1038 .flex_shrink_0()
1039 .child(sidebar_handle.to_any())
1040 .child(resize_handle)
1041 .into_any_element()
1042 })
1043 } else {
1044 None
1045 };
1046
1047 let (left_sidebar, right_sidebar) = if sidebar_on_right {
1048 (None, sidebar)
1049 } else {
1050 (sidebar, None)
1051 };
1052
1053 let ui_font = theme_settings::setup_ui_font(window, cx);
1054 let text_color = cx.theme().colors().text;
1055
1056 let workspace = self.workspace().clone();
1057 let workspace_key_context = workspace.update(cx, |workspace, cx| workspace.key_context(cx));
1058 let root = workspace.update(cx, |workspace, cx| workspace.actions(h_flex(), window, cx));
1059
1060 client_side_decorations(
1061 root.key_context(workspace_key_context)
1062 .relative()
1063 .size_full()
1064 .font(ui_font)
1065 .text_color(text_color)
1066 .on_action(cx.listener(Self::close_window))
1067 .when(self.multi_workspace_enabled(cx), |this| {
1068 this.on_action(cx.listener(
1069 |this: &mut Self, _: &ToggleWorkspaceSidebar, window, cx| {
1070 this.toggle_sidebar(window, cx);
1071 },
1072 ))
1073 .on_action(cx.listener(
1074 |this: &mut Self, _: &CloseWorkspaceSidebar, window, cx| {
1075 this.close_sidebar_action(window, cx);
1076 },
1077 ))
1078 .on_action(cx.listener(
1079 |this: &mut Self, _: &FocusWorkspaceSidebar, window, cx| {
1080 this.focus_sidebar(window, cx);
1081 },
1082 ))
1083 .on_action(cx.listener(Self::next_workspace))
1084 .on_action(cx.listener(Self::previous_workspace))
1085 .on_action(cx.listener(Self::move_active_workspace_to_new_window))
1086 .on_action(cx.listener(
1087 |this: &mut Self, action: &ToggleThreadSwitcher, window, cx| {
1088 if let Some(sidebar) = &this.sidebar {
1089 sidebar.toggle_thread_switcher(action.select_last, window, cx);
1090 }
1091 },
1092 ))
1093 })
1094 .when(
1095 self.sidebar_open() && self.multi_workspace_enabled(cx),
1096 |this| {
1097 this.on_drag_move(cx.listener(
1098 move |this: &mut Self,
1099 e: &DragMoveEvent<DraggedSidebar>,
1100 window,
1101 cx| {
1102 if let Some(sidebar) = &this.sidebar {
1103 let new_width = if sidebar_on_right {
1104 window.bounds().size.width - e.event.position.x
1105 } else {
1106 e.event.position.x
1107 };
1108 sidebar.set_width(Some(new_width), cx);
1109 }
1110 },
1111 ))
1112 },
1113 )
1114 .children(left_sidebar)
1115 .child(
1116 div()
1117 .flex()
1118 .flex_1()
1119 .size_full()
1120 .overflow_hidden()
1121 .child(self.workspace().clone()),
1122 )
1123 .children(right_sidebar)
1124 .child(self.workspace().read(cx).modal_layer.clone())
1125 .children(self.sidebar_overlay.as_ref().map(|view| {
1126 deferred(div().absolute().size_full().inset_0().occlude().child(
1127 v_flex().h(px(0.0)).top_20().items_center().child(
1128 h_flex().occlude().child(view.clone()).on_mouse_down(
1129 MouseButton::Left,
1130 |_, _, cx| {
1131 cx.stop_propagation();
1132 },
1133 ),
1134 ),
1135 ))
1136 .with_priority(2)
1137 })),
1138 window,
1139 cx,
1140 Tiling {
1141 left: !sidebar_on_right && multi_workspace_enabled && self.sidebar_open(),
1142 right: sidebar_on_right && multi_workspace_enabled && self.sidebar_open(),
1143 ..Tiling::default()
1144 },
1145 )
1146 }
1147}