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