1pub mod active_file_name;
2pub mod dock;
3pub mod history_manager;
4pub mod invalid_item_view;
5pub mod item;
6mod modal_layer;
7mod multi_workspace;
8#[cfg(test)]
9mod multi_workspace_tests;
10pub mod notifications;
11pub mod pane;
12pub mod pane_group;
13pub mod path_list {
14 pub use util::path_list::{PathList, SerializedPathList};
15}
16mod persistence;
17pub mod searchable;
18mod security_modal;
19pub mod shared_screen;
20use db::smol::future::yield_now;
21pub use shared_screen::SharedScreen;
22pub mod focus_follows_mouse;
23mod status_bar;
24pub mod tasks;
25mod theme_preview;
26mod toast_layer;
27mod toolbar;
28pub mod welcome;
29mod workspace_settings;
30
31pub use crate::notifications::NotificationFrame;
32pub use dock::Panel;
33pub use multi_workspace::{
34 CloseWorkspaceSidebar, DraggedSidebar, FocusWorkspaceSidebar, MultiWorkspace,
35 MultiWorkspaceEvent, Sidebar, SidebarEvent, SidebarHandle, SidebarRenderState, SidebarSide,
36 ToggleWorkspaceSidebar, sidebar_side_context_menu,
37};
38pub use path_list::{PathList, SerializedPathList};
39pub use toast_layer::{ToastAction, ToastLayer, ToastView};
40
41use anyhow::{Context as _, Result, anyhow};
42use client::{
43 ChannelId, Client, ErrorExt, ParticipantIndex, Status, TypedEnvelope, User, UserStore,
44 proto::{self, ErrorCode, PanelId, PeerId},
45};
46use collections::{HashMap, HashSet, hash_map};
47use dock::{Dock, DockPosition, PanelButtons, PanelHandle, RESIZE_HANDLE_SIZE};
48use fs::Fs;
49use futures::{
50 Future, FutureExt, StreamExt,
51 channel::{
52 mpsc::{self, UnboundedReceiver, UnboundedSender},
53 oneshot,
54 },
55 future::{Shared, try_join_all},
56};
57use gpui::{
58 Action, AnyEntity, AnyView, AnyWeakView, App, AsyncApp, AsyncWindowContext, Axis, Bounds,
59 Context, CursorStyle, Decorations, DragMoveEvent, Entity, EntityId, EventEmitter, FocusHandle,
60 Focusable, Global, HitboxBehavior, Hsla, KeyContext, Keystroke, ManagedView, MouseButton,
61 PathPromptOptions, Point, PromptLevel, Render, ResizeEdge, Size, Stateful, Subscription,
62 SystemWindowTabController, Task, Tiling, WeakEntity, WindowBounds, WindowHandle, WindowId,
63 WindowOptions, actions, canvas, point, relative, size, transparent_black,
64};
65pub use history_manager::*;
66pub use item::{
67 FollowableItem, FollowableItemHandle, Item, ItemHandle, ItemSettings, PreviewTabsSettings,
68 ProjectItem, SerializableItem, SerializableItemHandle, WeakItemHandle,
69};
70use itertools::Itertools;
71use language::{Buffer, LanguageRegistry, Rope, language_settings::all_language_settings};
72pub use modal_layer::*;
73use node_runtime::NodeRuntime;
74use notifications::{
75 DetachAndPromptErr, Notifications, dismiss_app_notification,
76 simple_message_notification::MessageNotification,
77};
78pub use pane::*;
79pub use pane_group::{
80 ActivePaneDecorator, HANDLE_HITBOX_SIZE, Member, PaneAxis, PaneGroup, PaneRenderContext,
81 SplitDirection,
82};
83use persistence::{SerializedWindowBounds, model::SerializedWorkspace};
84pub use persistence::{
85 WorkspaceDb, delete_unloaded_items,
86 model::{
87 DockStructure, ItemId, MultiWorkspaceState, SerializedMultiWorkspace,
88 SerializedWorkspaceLocation, SessionWorkspace,
89 },
90 read_serialized_multi_workspaces, resolve_worktree_workspaces,
91};
92use postage::stream::Stream;
93use project::{
94 DirectoryLister, Project, ProjectEntryId, ProjectGroupKey, ProjectPath, ResolvedPath, Worktree,
95 WorktreeId, WorktreeSettings,
96 debugger::{breakpoint_store::BreakpointStoreEvent, session::ThreadStatus},
97 project_settings::ProjectSettings,
98 toolchain_store::ToolchainStoreEvent,
99 trusted_worktrees::{RemoteHostLocation, TrustedWorktrees, TrustedWorktreesEvent},
100};
101use remote::{
102 RemoteClientDelegate, RemoteConnection, RemoteConnectionOptions,
103 remote_client::ConnectionIdentifier,
104};
105use schemars::JsonSchema;
106use serde::Deserialize;
107use session::AppSession;
108use settings::{
109 CenteredPaddingSettings, Settings, SettingsLocation, SettingsStore, update_settings_file,
110};
111
112use sqlez::{
113 bindable::{Bind, Column, StaticColumnCount},
114 statement::Statement,
115};
116use status_bar::StatusBar;
117pub use status_bar::StatusItemView;
118use std::{
119 any::TypeId,
120 borrow::Cow,
121 cell::RefCell,
122 cmp,
123 collections::VecDeque,
124 env,
125 hash::Hash,
126 path::{Path, PathBuf},
127 process::ExitStatus,
128 rc::Rc,
129 sync::{
130 Arc, LazyLock,
131 atomic::{AtomicBool, AtomicUsize},
132 },
133 time::Duration,
134};
135use task::{DebugScenario, SharedTaskContext, SpawnInTerminal};
136use theme::{ActiveTheme, SystemAppearance};
137use theme_settings::ThemeSettings;
138pub use toolbar::{
139 PaneSearchBarCallbacks, Toolbar, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView,
140};
141pub use ui;
142use ui::{Window, prelude::*};
143use util::{
144 ResultExt, TryFutureExt,
145 paths::{PathStyle, SanitizedPath},
146 rel_path::RelPath,
147 serde::default_true,
148};
149use uuid::Uuid;
150pub use workspace_settings::{
151 AutosaveSetting, BottomDockLayout, FocusFollowsMouse, RestoreOnStartupBehavior,
152 StatusBarSettings, TabBarSettings, WorkspaceSettings,
153};
154use zed_actions::{Spawn, feedback::FileBugReport, theme::ToggleMode};
155
156use crate::{dock::PanelSizeState, item::ItemBufferKind, notifications::NotificationId};
157use crate::{
158 persistence::{
159 SerializedAxis,
160 model::{DockData, SerializedItem, SerializedPane, SerializedPaneGroup},
161 },
162 security_modal::SecurityModal,
163};
164
165pub const SERIALIZATION_THROTTLE_TIME: Duration = Duration::from_millis(200);
166
167static ZED_WINDOW_SIZE: LazyLock<Option<Size<Pixels>>> = LazyLock::new(|| {
168 env::var("ZED_WINDOW_SIZE")
169 .ok()
170 .as_deref()
171 .and_then(parse_pixel_size_env_var)
172});
173
174static ZED_WINDOW_POSITION: LazyLock<Option<Point<Pixels>>> = LazyLock::new(|| {
175 env::var("ZED_WINDOW_POSITION")
176 .ok()
177 .as_deref()
178 .and_then(parse_pixel_position_env_var)
179});
180
181pub trait TerminalProvider {
182 fn spawn(
183 &self,
184 task: SpawnInTerminal,
185 window: &mut Window,
186 cx: &mut App,
187 ) -> Task<Option<Result<ExitStatus>>>;
188}
189
190pub trait DebuggerProvider {
191 // `active_buffer` is used to resolve build task's name against language-specific tasks.
192 fn start_session(
193 &self,
194 definition: DebugScenario,
195 task_context: SharedTaskContext,
196 active_buffer: Option<Entity<Buffer>>,
197 worktree_id: Option<WorktreeId>,
198 window: &mut Window,
199 cx: &mut App,
200 );
201
202 fn spawn_task_or_modal(
203 &self,
204 workspace: &mut Workspace,
205 action: &Spawn,
206 window: &mut Window,
207 cx: &mut Context<Workspace>,
208 );
209
210 fn task_scheduled(&self, cx: &mut App);
211 fn debug_scenario_scheduled(&self, cx: &mut App);
212 fn debug_scenario_scheduled_last(&self, cx: &App) -> bool;
213
214 fn active_thread_state(&self, cx: &App) -> Option<ThreadStatus>;
215}
216
217/// Opens a file or directory.
218#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
219#[action(namespace = workspace)]
220pub struct Open {
221 /// When true, opens in a new window. When false, adds to the current
222 /// window as a new workspace (multi-workspace).
223 #[serde(default = "Open::default_create_new_window")]
224 pub create_new_window: bool,
225}
226
227impl Open {
228 pub const DEFAULT: Self = Self {
229 create_new_window: true,
230 };
231
232 /// Used by `#[serde(default)]` on the `create_new_window` field so that
233 /// the serde default and `Open::DEFAULT` stay in sync.
234 fn default_create_new_window() -> bool {
235 Self::DEFAULT.create_new_window
236 }
237}
238
239impl Default for Open {
240 fn default() -> Self {
241 Self::DEFAULT
242 }
243}
244
245actions!(
246 workspace,
247 [
248 /// Activates the next pane in the workspace.
249 ActivateNextPane,
250 /// Activates the previous pane in the workspace.
251 ActivatePreviousPane,
252 /// Activates the last pane in the workspace.
253 ActivateLastPane,
254 /// Switches to the next window.
255 ActivateNextWindow,
256 /// Switches to the previous window.
257 ActivatePreviousWindow,
258 /// Adds a folder to the current project.
259 AddFolderToProject,
260 /// Clears all notifications.
261 ClearAllNotifications,
262 /// Clears all navigation history, including forward/backward navigation, recently opened files, and recently closed tabs. **This action is irreversible**.
263 ClearNavigationHistory,
264 /// Closes the active dock.
265 CloseActiveDock,
266 /// Closes all docks.
267 CloseAllDocks,
268 /// Toggles all docks.
269 ToggleAllDocks,
270 /// Closes the current window.
271 CloseWindow,
272 /// Closes the current project.
273 CloseProject,
274 /// Opens the feedback dialog.
275 Feedback,
276 /// Follows the next collaborator in the session.
277 FollowNextCollaborator,
278 /// Moves the focused panel to the next position.
279 MoveFocusedPanelToNextPosition,
280 /// Creates a new file.
281 NewFile,
282 /// Creates a new file in a vertical split.
283 NewFileSplitVertical,
284 /// Creates a new file in a horizontal split.
285 NewFileSplitHorizontal,
286 /// Opens a new search.
287 NewSearch,
288 /// Opens a new window.
289 NewWindow,
290 /// Opens multiple files.
291 OpenFiles,
292 /// Opens the current location in terminal.
293 OpenInTerminal,
294 /// Opens the component preview.
295 OpenComponentPreview,
296 /// Reloads the active item.
297 ReloadActiveItem,
298 /// Resets the active dock to its default size.
299 ResetActiveDockSize,
300 /// Resets all open docks to their default sizes.
301 ResetOpenDocksSize,
302 /// Reloads the application
303 Reload,
304 /// Saves the current file with a new name.
305 SaveAs,
306 /// Saves without formatting.
307 SaveWithoutFormat,
308 /// Shuts down all debug adapters.
309 ShutdownDebugAdapters,
310 /// Suppresses the current notification.
311 SuppressNotification,
312 /// Toggles the bottom dock.
313 ToggleBottomDock,
314 /// Toggles centered layout mode.
315 ToggleCenteredLayout,
316 /// Toggles edit prediction feature globally for all files.
317 ToggleEditPrediction,
318 /// Toggles the left dock.
319 ToggleLeftDock,
320 /// Toggles the right dock.
321 ToggleRightDock,
322 /// Toggles zoom on the active pane.
323 ToggleZoom,
324 /// Toggles read-only mode for the active item (if supported by that item).
325 ToggleReadOnlyFile,
326 /// Zooms in on the active pane.
327 ZoomIn,
328 /// Zooms out of the active pane.
329 ZoomOut,
330 /// If any worktrees are in restricted mode, shows a modal with possible actions.
331 /// If the modal is shown already, closes it without trusting any worktree.
332 ToggleWorktreeSecurity,
333 /// Clears all trusted worktrees, placing them in restricted mode on next open.
334 /// Requires restart to take effect on already opened projects.
335 ClearTrustedWorktrees,
336 /// Stops following a collaborator.
337 Unfollow,
338 /// Restores the banner.
339 RestoreBanner,
340 /// Toggles expansion of the selected item.
341 ToggleExpandItem,
342 ]
343);
344
345/// Activates a specific pane by its index.
346#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
347#[action(namespace = workspace)]
348pub struct ActivatePane(pub usize);
349
350/// Moves an item to a specific pane by index.
351#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
352#[action(namespace = workspace)]
353#[serde(deny_unknown_fields)]
354pub struct MoveItemToPane {
355 #[serde(default = "default_1")]
356 pub destination: usize,
357 #[serde(default = "default_true")]
358 pub focus: bool,
359 #[serde(default)]
360 pub clone: bool,
361}
362
363fn default_1() -> usize {
364 1
365}
366
367/// Moves an item to a pane in the specified direction.
368#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
369#[action(namespace = workspace)]
370#[serde(deny_unknown_fields)]
371pub struct MoveItemToPaneInDirection {
372 #[serde(default = "default_right")]
373 pub direction: SplitDirection,
374 #[serde(default = "default_true")]
375 pub focus: bool,
376 #[serde(default)]
377 pub clone: bool,
378}
379
380/// Creates a new file in a split of the desired direction.
381#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
382#[action(namespace = workspace)]
383#[serde(deny_unknown_fields)]
384pub struct NewFileSplit(pub SplitDirection);
385
386fn default_right() -> SplitDirection {
387 SplitDirection::Right
388}
389
390/// Saves all open files in the workspace.
391#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
392#[action(namespace = workspace)]
393#[serde(deny_unknown_fields)]
394pub struct SaveAll {
395 #[serde(default)]
396 pub save_intent: Option<SaveIntent>,
397}
398
399/// Saves the current file with the specified options.
400#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
401#[action(namespace = workspace)]
402#[serde(deny_unknown_fields)]
403pub struct Save {
404 #[serde(default)]
405 pub save_intent: Option<SaveIntent>,
406}
407
408/// Moves Focus to the central panes in the workspace.
409#[derive(Clone, Debug, PartialEq, Eq, Action)]
410#[action(namespace = workspace)]
411pub struct FocusCenterPane;
412
413/// Closes all items and panes in the workspace.
414#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
415#[action(namespace = workspace)]
416#[serde(deny_unknown_fields)]
417pub struct CloseAllItemsAndPanes {
418 #[serde(default)]
419 pub save_intent: Option<SaveIntent>,
420}
421
422/// Closes all inactive tabs and panes in the workspace.
423#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
424#[action(namespace = workspace)]
425#[serde(deny_unknown_fields)]
426pub struct CloseInactiveTabsAndPanes {
427 #[serde(default)]
428 pub save_intent: Option<SaveIntent>,
429}
430
431/// Closes the active item across all panes.
432#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
433#[action(namespace = workspace)]
434#[serde(deny_unknown_fields)]
435pub struct CloseItemInAllPanes {
436 #[serde(default)]
437 pub save_intent: Option<SaveIntent>,
438 #[serde(default)]
439 pub close_pinned: bool,
440}
441
442/// Sends a sequence of keystrokes to the active element.
443#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
444#[action(namespace = workspace)]
445pub struct SendKeystrokes(pub String);
446
447actions!(
448 project_symbols,
449 [
450 /// Toggles the project symbols search.
451 #[action(name = "Toggle")]
452 ToggleProjectSymbols
453 ]
454);
455
456/// Toggles the file finder interface.
457#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
458#[action(namespace = file_finder, name = "Toggle")]
459#[serde(deny_unknown_fields)]
460pub struct ToggleFileFinder {
461 #[serde(default)]
462 pub separate_history: bool,
463}
464
465/// Opens a new terminal in the center.
466#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
467#[action(namespace = workspace)]
468#[serde(deny_unknown_fields)]
469pub struct NewCenterTerminal {
470 /// If true, creates a local terminal even in remote projects.
471 #[serde(default)]
472 pub local: bool,
473}
474
475/// Opens a new terminal.
476#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
477#[action(namespace = workspace)]
478#[serde(deny_unknown_fields)]
479pub struct NewTerminal {
480 /// If true, creates a local terminal even in remote projects.
481 #[serde(default)]
482 pub local: bool,
483}
484
485/// Increases size of a currently focused dock by a given amount of pixels.
486#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
487#[action(namespace = workspace)]
488#[serde(deny_unknown_fields)]
489pub struct IncreaseActiveDockSize {
490 /// For 0px parameter, uses UI font size value.
491 #[serde(default)]
492 pub px: u32,
493}
494
495/// Decreases size of a currently focused dock by a given amount of pixels.
496#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
497#[action(namespace = workspace)]
498#[serde(deny_unknown_fields)]
499pub struct DecreaseActiveDockSize {
500 /// For 0px parameter, uses UI font size value.
501 #[serde(default)]
502 pub px: u32,
503}
504
505/// Increases size of all currently visible docks uniformly, by a given amount of pixels.
506#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
507#[action(namespace = workspace)]
508#[serde(deny_unknown_fields)]
509pub struct IncreaseOpenDocksSize {
510 /// For 0px parameter, uses UI font size value.
511 #[serde(default)]
512 pub px: u32,
513}
514
515/// Decreases size of all currently visible docks uniformly, by a given amount of pixels.
516#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
517#[action(namespace = workspace)]
518#[serde(deny_unknown_fields)]
519pub struct DecreaseOpenDocksSize {
520 /// For 0px parameter, uses UI font size value.
521 #[serde(default)]
522 pub px: u32,
523}
524
525actions!(
526 workspace,
527 [
528 /// Activates the pane to the left.
529 ActivatePaneLeft,
530 /// Activates the pane to the right.
531 ActivatePaneRight,
532 /// Activates the pane above.
533 ActivatePaneUp,
534 /// Activates the pane below.
535 ActivatePaneDown,
536 /// Swaps the current pane with the one to the left.
537 SwapPaneLeft,
538 /// Swaps the current pane with the one to the right.
539 SwapPaneRight,
540 /// Swaps the current pane with the one above.
541 SwapPaneUp,
542 /// Swaps the current pane with the one below.
543 SwapPaneDown,
544 // Swaps the current pane with the first available adjacent pane (searching in order: below, above, right, left) and activates that pane.
545 SwapPaneAdjacent,
546 /// Move the current pane to be at the far left.
547 MovePaneLeft,
548 /// Move the current pane to be at the far right.
549 MovePaneRight,
550 /// Move the current pane to be at the very top.
551 MovePaneUp,
552 /// Move the current pane to be at the very bottom.
553 MovePaneDown,
554 ]
555);
556
557#[derive(PartialEq, Eq, Debug)]
558pub enum CloseIntent {
559 /// Quit the program entirely.
560 Quit,
561 /// Close a window.
562 CloseWindow,
563 /// Replace the workspace in an existing window.
564 ReplaceWindow,
565}
566
567#[derive(Clone)]
568pub struct Toast {
569 id: NotificationId,
570 msg: Cow<'static, str>,
571 autohide: bool,
572 on_click: Option<(Cow<'static, str>, Arc<dyn Fn(&mut Window, &mut App)>)>,
573}
574
575impl Toast {
576 pub fn new<I: Into<Cow<'static, str>>>(id: NotificationId, msg: I) -> Self {
577 Toast {
578 id,
579 msg: msg.into(),
580 on_click: None,
581 autohide: false,
582 }
583 }
584
585 pub fn on_click<F, M>(mut self, message: M, on_click: F) -> Self
586 where
587 M: Into<Cow<'static, str>>,
588 F: Fn(&mut Window, &mut App) + 'static,
589 {
590 self.on_click = Some((message.into(), Arc::new(on_click)));
591 self
592 }
593
594 pub fn autohide(mut self) -> Self {
595 self.autohide = true;
596 self
597 }
598}
599
600impl PartialEq for Toast {
601 fn eq(&self, other: &Self) -> bool {
602 self.id == other.id
603 && self.msg == other.msg
604 && self.on_click.is_some() == other.on_click.is_some()
605 }
606}
607
608/// Opens a new terminal with the specified working directory.
609#[derive(Debug, Default, Clone, Deserialize, PartialEq, JsonSchema, Action)]
610#[action(namespace = workspace)]
611#[serde(deny_unknown_fields)]
612pub struct OpenTerminal {
613 pub working_directory: PathBuf,
614 /// If true, creates a local terminal even in remote projects.
615 #[serde(default)]
616 pub local: bool,
617}
618
619#[derive(
620 Clone,
621 Copy,
622 Debug,
623 Default,
624 Hash,
625 PartialEq,
626 Eq,
627 PartialOrd,
628 Ord,
629 serde::Serialize,
630 serde::Deserialize,
631)]
632pub struct WorkspaceId(i64);
633
634impl WorkspaceId {
635 pub fn from_i64(value: i64) -> Self {
636 Self(value)
637 }
638}
639
640impl StaticColumnCount for WorkspaceId {}
641impl Bind for WorkspaceId {
642 fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
643 self.0.bind(statement, start_index)
644 }
645}
646impl Column for WorkspaceId {
647 fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
648 i64::column(statement, start_index)
649 .map(|(i, next_index)| (Self(i), next_index))
650 .with_context(|| format!("Failed to read WorkspaceId at index {start_index}"))
651 }
652}
653impl From<WorkspaceId> for i64 {
654 fn from(val: WorkspaceId) -> Self {
655 val.0
656 }
657}
658
659fn prompt_and_open_paths(
660 app_state: Arc<AppState>,
661 options: PathPromptOptions,
662 create_new_window: bool,
663 cx: &mut App,
664) {
665 if let Some(workspace_window) = local_workspace_windows(cx).into_iter().next() {
666 workspace_window
667 .update(cx, |multi_workspace, window, cx| {
668 let workspace = multi_workspace.workspace().clone();
669 workspace.update(cx, |workspace, cx| {
670 prompt_for_open_path_and_open(
671 workspace,
672 app_state,
673 options,
674 create_new_window,
675 window,
676 cx,
677 );
678 });
679 })
680 .ok();
681 } else {
682 let task = Workspace::new_local(
683 Vec::new(),
684 app_state.clone(),
685 None,
686 None,
687 None,
688 OpenMode::Activate,
689 cx,
690 );
691 cx.spawn(async move |cx| {
692 let OpenResult { window, .. } = task.await?;
693 window.update(cx, |multi_workspace, window, cx| {
694 window.activate_window();
695 let workspace = multi_workspace.workspace().clone();
696 workspace.update(cx, |workspace, cx| {
697 prompt_for_open_path_and_open(
698 workspace,
699 app_state,
700 options,
701 create_new_window,
702 window,
703 cx,
704 );
705 });
706 })?;
707 anyhow::Ok(())
708 })
709 .detach_and_log_err(cx);
710 }
711}
712
713pub fn prompt_for_open_path_and_open(
714 workspace: &mut Workspace,
715 app_state: Arc<AppState>,
716 options: PathPromptOptions,
717 create_new_window: bool,
718 window: &mut Window,
719 cx: &mut Context<Workspace>,
720) {
721 let paths = workspace.prompt_for_open_path(
722 options,
723 DirectoryLister::Local(workspace.project().clone(), app_state.fs.clone()),
724 window,
725 cx,
726 );
727 let multi_workspace_handle = window.window_handle().downcast::<MultiWorkspace>();
728 cx.spawn_in(window, async move |this, cx| {
729 let Some(paths) = paths.await.log_err().flatten() else {
730 return;
731 };
732 if !create_new_window {
733 if let Some(handle) = multi_workspace_handle {
734 if let Some(task) = handle
735 .update(cx, |multi_workspace, window, cx| {
736 multi_workspace.open_project(paths, OpenMode::Activate, window, cx)
737 })
738 .log_err()
739 {
740 task.await.log_err();
741 }
742 return;
743 }
744 }
745 if let Some(task) = this
746 .update_in(cx, |this, window, cx| {
747 this.open_workspace_for_paths(OpenMode::NewWindow, paths, window, cx)
748 })
749 .log_err()
750 {
751 task.await.log_err();
752 }
753 })
754 .detach();
755}
756
757pub fn init(app_state: Arc<AppState>, cx: &mut App) {
758 component::init();
759 theme_preview::init(cx);
760 toast_layer::init(cx);
761 history_manager::init(app_state.fs.clone(), cx);
762
763 cx.on_action(|_: &CloseWindow, cx| Workspace::close_global(cx))
764 .on_action(|_: &Reload, cx| reload(cx))
765 .on_action(|action: &Open, cx: &mut App| {
766 let app_state = AppState::global(cx);
767 prompt_and_open_paths(
768 app_state,
769 PathPromptOptions {
770 files: true,
771 directories: true,
772 multiple: true,
773 prompt: None,
774 },
775 action.create_new_window,
776 cx,
777 );
778 })
779 .on_action(|_: &OpenFiles, cx: &mut App| {
780 let directories = cx.can_select_mixed_files_and_dirs();
781 let app_state = AppState::global(cx);
782 prompt_and_open_paths(
783 app_state,
784 PathPromptOptions {
785 files: true,
786 directories,
787 multiple: true,
788 prompt: None,
789 },
790 true,
791 cx,
792 );
793 });
794}
795
796type BuildProjectItemFn =
797 fn(AnyEntity, Entity<Project>, Option<&Pane>, &mut Window, &mut App) -> Box<dyn ItemHandle>;
798
799type BuildProjectItemForPathFn =
800 fn(
801 &Entity<Project>,
802 &ProjectPath,
803 &mut Window,
804 &mut App,
805 ) -> Option<Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>>>;
806
807#[derive(Clone, Default)]
808struct ProjectItemRegistry {
809 build_project_item_fns_by_type: HashMap<TypeId, BuildProjectItemFn>,
810 build_project_item_for_path_fns: Vec<BuildProjectItemForPathFn>,
811}
812
813impl ProjectItemRegistry {
814 fn register<T: ProjectItem>(&mut self) {
815 self.build_project_item_fns_by_type.insert(
816 TypeId::of::<T::Item>(),
817 |item, project, pane, window, cx| {
818 let item = item.downcast().unwrap();
819 Box::new(cx.new(|cx| T::for_project_item(project, pane, item, window, cx)))
820 as Box<dyn ItemHandle>
821 },
822 );
823 self.build_project_item_for_path_fns
824 .push(|project, project_path, window, cx| {
825 let project_path = project_path.clone();
826 let is_file = project
827 .read(cx)
828 .entry_for_path(&project_path, cx)
829 .is_some_and(|entry| entry.is_file());
830 let entry_abs_path = project.read(cx).absolute_path(&project_path, cx);
831 let is_local = project.read(cx).is_local();
832 let project_item =
833 <T::Item as project::ProjectItem>::try_open(project, &project_path, cx)?;
834 let project = project.clone();
835 Some(window.spawn(cx, async move |cx| {
836 match project_item.await.with_context(|| {
837 format!(
838 "opening project path {:?}",
839 entry_abs_path.as_deref().unwrap_or(&project_path.path.as_std_path())
840 )
841 }) {
842 Ok(project_item) => {
843 let project_item = project_item;
844 let project_entry_id: Option<ProjectEntryId> =
845 project_item.read_with(cx, project::ProjectItem::entry_id);
846 let build_workspace_item = Box::new(
847 |pane: &mut Pane, window: &mut Window, cx: &mut Context<Pane>| {
848 Box::new(cx.new(|cx| {
849 T::for_project_item(
850 project,
851 Some(pane),
852 project_item,
853 window,
854 cx,
855 )
856 })) as Box<dyn ItemHandle>
857 },
858 ) as Box<_>;
859 Ok((project_entry_id, build_workspace_item))
860 }
861 Err(e) => {
862 log::warn!("Failed to open a project item: {e:#}");
863 if e.error_code() == ErrorCode::Internal {
864 if let Some(abs_path) =
865 entry_abs_path.as_deref().filter(|_| is_file)
866 {
867 if let Some(broken_project_item_view) =
868 cx.update(|window, cx| {
869 T::for_broken_project_item(
870 abs_path, is_local, &e, window, cx,
871 )
872 })?
873 {
874 let build_workspace_item = Box::new(
875 move |_: &mut Pane, _: &mut Window, cx: &mut Context<Pane>| {
876 cx.new(|_| broken_project_item_view).boxed_clone()
877 },
878 )
879 as Box<_>;
880 return Ok((None, build_workspace_item));
881 }
882 }
883 }
884 Err(e)
885 }
886 }
887 }))
888 });
889 }
890
891 fn open_path(
892 &self,
893 project: &Entity<Project>,
894 path: &ProjectPath,
895 window: &mut Window,
896 cx: &mut App,
897 ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
898 let Some(open_project_item) = self
899 .build_project_item_for_path_fns
900 .iter()
901 .rev()
902 .find_map(|open_project_item| open_project_item(project, path, window, cx))
903 else {
904 return Task::ready(Err(anyhow!("cannot open file {:?}", path.path)));
905 };
906 open_project_item
907 }
908
909 fn build_item<T: project::ProjectItem>(
910 &self,
911 item: Entity<T>,
912 project: Entity<Project>,
913 pane: Option<&Pane>,
914 window: &mut Window,
915 cx: &mut App,
916 ) -> Option<Box<dyn ItemHandle>> {
917 let build = self
918 .build_project_item_fns_by_type
919 .get(&TypeId::of::<T>())?;
920 Some(build(item.into_any(), project, pane, window, cx))
921 }
922}
923
924type WorkspaceItemBuilder =
925 Box<dyn FnOnce(&mut Pane, &mut Window, &mut Context<Pane>) -> Box<dyn ItemHandle>>;
926
927impl Global for ProjectItemRegistry {}
928
929/// Registers a [ProjectItem] for the app. When opening a file, all the registered
930/// items will get a chance to open the file, starting from the project item that
931/// was added last.
932pub fn register_project_item<I: ProjectItem>(cx: &mut App) {
933 cx.default_global::<ProjectItemRegistry>().register::<I>();
934}
935
936#[derive(Default)]
937pub struct FollowableViewRegistry(HashMap<TypeId, FollowableViewDescriptor>);
938
939struct FollowableViewDescriptor {
940 from_state_proto: fn(
941 Entity<Workspace>,
942 ViewId,
943 &mut Option<proto::view::Variant>,
944 &mut Window,
945 &mut App,
946 ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>>,
947 to_followable_view: fn(&AnyView) -> Box<dyn FollowableItemHandle>,
948}
949
950impl Global for FollowableViewRegistry {}
951
952impl FollowableViewRegistry {
953 pub fn register<I: FollowableItem>(cx: &mut App) {
954 cx.default_global::<Self>().0.insert(
955 TypeId::of::<I>(),
956 FollowableViewDescriptor {
957 from_state_proto: |workspace, id, state, window, cx| {
958 I::from_state_proto(workspace, id, state, window, cx).map(|task| {
959 cx.foreground_executor()
960 .spawn(async move { Ok(Box::new(task.await?) as Box<_>) })
961 })
962 },
963 to_followable_view: |view| Box::new(view.clone().downcast::<I>().unwrap()),
964 },
965 );
966 }
967
968 pub fn from_state_proto(
969 workspace: Entity<Workspace>,
970 view_id: ViewId,
971 mut state: Option<proto::view::Variant>,
972 window: &mut Window,
973 cx: &mut App,
974 ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>> {
975 cx.update_default_global(|this: &mut Self, cx| {
976 this.0.values().find_map(|descriptor| {
977 (descriptor.from_state_proto)(workspace.clone(), view_id, &mut state, window, cx)
978 })
979 })
980 }
981
982 pub fn to_followable_view(
983 view: impl Into<AnyView>,
984 cx: &App,
985 ) -> Option<Box<dyn FollowableItemHandle>> {
986 let this = cx.try_global::<Self>()?;
987 let view = view.into();
988 let descriptor = this.0.get(&view.entity_type())?;
989 Some((descriptor.to_followable_view)(&view))
990 }
991}
992
993#[derive(Copy, Clone)]
994struct SerializableItemDescriptor {
995 deserialize: fn(
996 Entity<Project>,
997 WeakEntity<Workspace>,
998 WorkspaceId,
999 ItemId,
1000 &mut Window,
1001 &mut Context<Pane>,
1002 ) -> Task<Result<Box<dyn ItemHandle>>>,
1003 cleanup: fn(WorkspaceId, Vec<ItemId>, &mut Window, &mut App) -> Task<Result<()>>,
1004 view_to_serializable_item: fn(AnyView) -> Box<dyn SerializableItemHandle>,
1005}
1006
1007#[derive(Default)]
1008struct SerializableItemRegistry {
1009 descriptors_by_kind: HashMap<Arc<str>, SerializableItemDescriptor>,
1010 descriptors_by_type: HashMap<TypeId, SerializableItemDescriptor>,
1011}
1012
1013impl Global for SerializableItemRegistry {}
1014
1015impl SerializableItemRegistry {
1016 fn deserialize(
1017 item_kind: &str,
1018 project: Entity<Project>,
1019 workspace: WeakEntity<Workspace>,
1020 workspace_id: WorkspaceId,
1021 item_item: ItemId,
1022 window: &mut Window,
1023 cx: &mut Context<Pane>,
1024 ) -> Task<Result<Box<dyn ItemHandle>>> {
1025 let Some(descriptor) = Self::descriptor(item_kind, cx) else {
1026 return Task::ready(Err(anyhow!(
1027 "cannot deserialize {}, descriptor not found",
1028 item_kind
1029 )));
1030 };
1031
1032 (descriptor.deserialize)(project, workspace, workspace_id, item_item, window, cx)
1033 }
1034
1035 fn cleanup(
1036 item_kind: &str,
1037 workspace_id: WorkspaceId,
1038 loaded_items: Vec<ItemId>,
1039 window: &mut Window,
1040 cx: &mut App,
1041 ) -> Task<Result<()>> {
1042 let Some(descriptor) = Self::descriptor(item_kind, cx) else {
1043 return Task::ready(Err(anyhow!(
1044 "cannot cleanup {}, descriptor not found",
1045 item_kind
1046 )));
1047 };
1048
1049 (descriptor.cleanup)(workspace_id, loaded_items, window, cx)
1050 }
1051
1052 fn view_to_serializable_item_handle(
1053 view: AnyView,
1054 cx: &App,
1055 ) -> Option<Box<dyn SerializableItemHandle>> {
1056 let this = cx.try_global::<Self>()?;
1057 let descriptor = this.descriptors_by_type.get(&view.entity_type())?;
1058 Some((descriptor.view_to_serializable_item)(view))
1059 }
1060
1061 fn descriptor(item_kind: &str, cx: &App) -> Option<SerializableItemDescriptor> {
1062 let this = cx.try_global::<Self>()?;
1063 this.descriptors_by_kind.get(item_kind).copied()
1064 }
1065}
1066
1067pub fn register_serializable_item<I: SerializableItem>(cx: &mut App) {
1068 let serialized_item_kind = I::serialized_item_kind();
1069
1070 let registry = cx.default_global::<SerializableItemRegistry>();
1071 let descriptor = SerializableItemDescriptor {
1072 deserialize: |project, workspace, workspace_id, item_id, window, cx| {
1073 let task = I::deserialize(project, workspace, workspace_id, item_id, window, cx);
1074 cx.foreground_executor()
1075 .spawn(async { Ok(Box::new(task.await?) as Box<_>) })
1076 },
1077 cleanup: |workspace_id, loaded_items, window, cx| {
1078 I::cleanup(workspace_id, loaded_items, window, cx)
1079 },
1080 view_to_serializable_item: |view| Box::new(view.downcast::<I>().unwrap()),
1081 };
1082 registry
1083 .descriptors_by_kind
1084 .insert(Arc::from(serialized_item_kind), descriptor);
1085 registry
1086 .descriptors_by_type
1087 .insert(TypeId::of::<I>(), descriptor);
1088}
1089
1090pub struct AppState {
1091 pub languages: Arc<LanguageRegistry>,
1092 pub client: Arc<Client>,
1093 pub user_store: Entity<UserStore>,
1094 pub workspace_store: Entity<WorkspaceStore>,
1095 pub fs: Arc<dyn fs::Fs>,
1096 pub build_window_options: fn(Option<Uuid>, &mut App) -> WindowOptions,
1097 pub node_runtime: NodeRuntime,
1098 pub session: Entity<AppSession>,
1099}
1100
1101struct GlobalAppState(Arc<AppState>);
1102
1103impl Global for GlobalAppState {}
1104
1105pub struct WorkspaceStore {
1106 workspaces: HashSet<(gpui::AnyWindowHandle, WeakEntity<Workspace>)>,
1107 client: Arc<Client>,
1108 _subscriptions: Vec<client::Subscription>,
1109}
1110
1111#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, PartialOrd, Ord)]
1112pub enum CollaboratorId {
1113 PeerId(PeerId),
1114 Agent,
1115}
1116
1117impl From<PeerId> for CollaboratorId {
1118 fn from(peer_id: PeerId) -> Self {
1119 CollaboratorId::PeerId(peer_id)
1120 }
1121}
1122
1123impl From<&PeerId> for CollaboratorId {
1124 fn from(peer_id: &PeerId) -> Self {
1125 CollaboratorId::PeerId(*peer_id)
1126 }
1127}
1128
1129#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
1130struct Follower {
1131 project_id: Option<u64>,
1132 peer_id: PeerId,
1133}
1134
1135impl AppState {
1136 #[track_caller]
1137 pub fn global(cx: &App) -> Arc<Self> {
1138 cx.global::<GlobalAppState>().0.clone()
1139 }
1140 pub fn try_global(cx: &App) -> Option<Arc<Self>> {
1141 cx.try_global::<GlobalAppState>()
1142 .map(|state| state.0.clone())
1143 }
1144 pub fn set_global(state: Arc<AppState>, cx: &mut App) {
1145 cx.set_global(GlobalAppState(state));
1146 }
1147
1148 #[cfg(any(test, feature = "test-support"))]
1149 pub fn test(cx: &mut App) -> Arc<Self> {
1150 use fs::Fs;
1151 use node_runtime::NodeRuntime;
1152 use session::Session;
1153 use settings::SettingsStore;
1154
1155 if !cx.has_global::<SettingsStore>() {
1156 let settings_store = SettingsStore::test(cx);
1157 cx.set_global(settings_store);
1158 }
1159
1160 let fs = fs::FakeFs::new(cx.background_executor().clone());
1161 <dyn Fs>::set_global(fs.clone(), cx);
1162 let languages = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
1163 let clock = Arc::new(clock::FakeSystemClock::new());
1164 let http_client = http_client::FakeHttpClient::with_404_response();
1165 let client = Client::new(clock, http_client, cx);
1166 let session = cx.new(|cx| AppSession::new(Session::test(), cx));
1167 let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
1168 let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
1169
1170 theme_settings::init(theme::LoadThemes::JustBase, cx);
1171 client::init(&client, cx);
1172
1173 Arc::new(Self {
1174 client,
1175 fs,
1176 languages,
1177 user_store,
1178 workspace_store,
1179 node_runtime: NodeRuntime::unavailable(),
1180 build_window_options: |_, _| Default::default(),
1181 session,
1182 })
1183 }
1184}
1185
1186struct DelayedDebouncedEditAction {
1187 task: Option<Task<()>>,
1188 cancel_channel: Option<oneshot::Sender<()>>,
1189}
1190
1191impl DelayedDebouncedEditAction {
1192 fn new() -> DelayedDebouncedEditAction {
1193 DelayedDebouncedEditAction {
1194 task: None,
1195 cancel_channel: None,
1196 }
1197 }
1198
1199 fn fire_new<F>(
1200 &mut self,
1201 delay: Duration,
1202 window: &mut Window,
1203 cx: &mut Context<Workspace>,
1204 func: F,
1205 ) where
1206 F: 'static
1207 + Send
1208 + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> Task<Result<()>>,
1209 {
1210 if let Some(channel) = self.cancel_channel.take() {
1211 _ = channel.send(());
1212 }
1213
1214 let (sender, mut receiver) = oneshot::channel::<()>();
1215 self.cancel_channel = Some(sender);
1216
1217 let previous_task = self.task.take();
1218 self.task = Some(cx.spawn_in(window, async move |workspace, cx| {
1219 let mut timer = cx.background_executor().timer(delay).fuse();
1220 if let Some(previous_task) = previous_task {
1221 previous_task.await;
1222 }
1223
1224 futures::select_biased! {
1225 _ = receiver => return,
1226 _ = timer => {}
1227 }
1228
1229 if let Some(result) = workspace
1230 .update_in(cx, |workspace, window, cx| (func)(workspace, window, cx))
1231 .log_err()
1232 {
1233 result.await.log_err();
1234 }
1235 }));
1236 }
1237}
1238
1239pub enum Event {
1240 PaneAdded(Entity<Pane>),
1241 PaneRemoved,
1242 ItemAdded {
1243 item: Box<dyn ItemHandle>,
1244 },
1245 ActiveItemChanged,
1246 ItemRemoved {
1247 item_id: EntityId,
1248 },
1249 UserSavedItem {
1250 pane: WeakEntity<Pane>,
1251 item: Box<dyn WeakItemHandle>,
1252 save_intent: SaveIntent,
1253 },
1254 ContactRequestedJoin(u64),
1255 WorkspaceCreated(WeakEntity<Workspace>),
1256 OpenBundledFile {
1257 text: Cow<'static, str>,
1258 title: &'static str,
1259 language: &'static str,
1260 },
1261 ZoomChanged,
1262 ModalOpened,
1263 Activate,
1264 PanelAdded(AnyView),
1265}
1266
1267#[derive(Debug, Clone)]
1268pub enum OpenVisible {
1269 All,
1270 None,
1271 OnlyFiles,
1272 OnlyDirectories,
1273}
1274
1275enum WorkspaceLocation {
1276 // Valid local paths or SSH project to serialize
1277 Location(SerializedWorkspaceLocation, PathList),
1278 // No valid location found hence clear session id
1279 DetachFromSession,
1280 // No valid location found to serialize
1281 None,
1282}
1283
1284type PromptForNewPath = Box<
1285 dyn Fn(
1286 &mut Workspace,
1287 DirectoryLister,
1288 Option<String>,
1289 &mut Window,
1290 &mut Context<Workspace>,
1291 ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
1292>;
1293
1294type PromptForOpenPath = Box<
1295 dyn Fn(
1296 &mut Workspace,
1297 DirectoryLister,
1298 &mut Window,
1299 &mut Context<Workspace>,
1300 ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
1301>;
1302
1303#[derive(Default)]
1304struct DispatchingKeystrokes {
1305 dispatched: HashSet<Vec<Keystroke>>,
1306 queue: VecDeque<Keystroke>,
1307 task: Option<Shared<Task<()>>>,
1308}
1309
1310/// Collects everything project-related for a certain window opened.
1311/// In some way, is a counterpart of a window, as the [`WindowHandle`] could be downcast into `Workspace`.
1312///
1313/// A `Workspace` usually consists of 1 or more projects, a central pane group, 3 docks and a status bar.
1314/// The `Workspace` owns everybody's state and serves as a default, "global context",
1315/// that can be used to register a global action to be triggered from any place in the window.
1316pub struct Workspace {
1317 weak_self: WeakEntity<Self>,
1318 workspace_actions: Vec<Box<dyn Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div>>,
1319 zoomed: Option<AnyWeakView>,
1320 previous_dock_drag_coordinates: Option<Point<Pixels>>,
1321 zoomed_position: Option<DockPosition>,
1322 center: PaneGroup,
1323 left_dock: Entity<Dock>,
1324 bottom_dock: Entity<Dock>,
1325 right_dock: Entity<Dock>,
1326 panes: Vec<Entity<Pane>>,
1327 active_worktree_override: Option<WorktreeId>,
1328 panes_by_item: HashMap<EntityId, WeakEntity<Pane>>,
1329 active_pane: Entity<Pane>,
1330 last_active_center_pane: Option<WeakEntity<Pane>>,
1331 last_active_view_id: Option<proto::ViewId>,
1332 status_bar: Entity<StatusBar>,
1333 pub(crate) modal_layer: Entity<ModalLayer>,
1334 toast_layer: Entity<ToastLayer>,
1335 titlebar_item: Option<AnyView>,
1336 notifications: Notifications,
1337 suppressed_notifications: HashSet<NotificationId>,
1338 project: Entity<Project>,
1339 follower_states: HashMap<CollaboratorId, FollowerState>,
1340 last_leaders_by_pane: HashMap<WeakEntity<Pane>, CollaboratorId>,
1341 window_edited: bool,
1342 last_window_title: Option<String>,
1343 dirty_items: HashMap<EntityId, Subscription>,
1344 active_call: Option<(GlobalAnyActiveCall, Vec<Subscription>)>,
1345 leader_updates_tx: mpsc::UnboundedSender<(PeerId, proto::UpdateFollowers)>,
1346 database_id: Option<WorkspaceId>,
1347 app_state: Arc<AppState>,
1348 dispatching_keystrokes: Rc<RefCell<DispatchingKeystrokes>>,
1349 _subscriptions: Vec<Subscription>,
1350 _apply_leader_updates: Task<Result<()>>,
1351 _observe_current_user: Task<Result<()>>,
1352 _schedule_serialize_workspace: Option<Task<()>>,
1353 _serialize_workspace_task: Option<Task<()>>,
1354 _schedule_serialize_ssh_paths: Option<Task<()>>,
1355 pane_history_timestamp: Arc<AtomicUsize>,
1356 bounds: Bounds<Pixels>,
1357 pub centered_layout: bool,
1358 bounds_save_task_queued: Option<Task<()>>,
1359 on_prompt_for_new_path: Option<PromptForNewPath>,
1360 on_prompt_for_open_path: Option<PromptForOpenPath>,
1361 terminal_provider: Option<Box<dyn TerminalProvider>>,
1362 debugger_provider: Option<Arc<dyn DebuggerProvider>>,
1363 serializable_items_tx: UnboundedSender<Box<dyn SerializableItemHandle>>,
1364 _items_serializer: Task<Result<()>>,
1365 session_id: Option<String>,
1366 scheduled_tasks: Vec<Task<()>>,
1367 last_open_dock_positions: Vec<DockPosition>,
1368 removing: bool,
1369 open_in_dev_container: bool,
1370 _dev_container_task: Option<Task<Result<()>>>,
1371 _panels_task: Option<Task<Result<()>>>,
1372 sidebar_focus_handle: Option<FocusHandle>,
1373 multi_workspace: Option<WeakEntity<MultiWorkspace>>,
1374}
1375
1376impl EventEmitter<Event> for Workspace {}
1377
1378#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1379pub struct ViewId {
1380 pub creator: CollaboratorId,
1381 pub id: u64,
1382}
1383
1384pub struct FollowerState {
1385 center_pane: Entity<Pane>,
1386 dock_pane: Option<Entity<Pane>>,
1387 active_view_id: Option<ViewId>,
1388 items_by_leader_view_id: HashMap<ViewId, FollowerView>,
1389}
1390
1391struct FollowerView {
1392 view: Box<dyn FollowableItemHandle>,
1393 location: Option<proto::PanelId>,
1394}
1395
1396#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1397pub enum OpenMode {
1398 /// Open the workspace in a new window.
1399 NewWindow,
1400 /// Add to the window's multi workspace without activating it (used during deserialization).
1401 Add,
1402 /// Add to the window's multi workspace and activate it.
1403 #[default]
1404 Activate,
1405}
1406
1407impl Workspace {
1408 pub fn new(
1409 workspace_id: Option<WorkspaceId>,
1410 project: Entity<Project>,
1411 app_state: Arc<AppState>,
1412 window: &mut Window,
1413 cx: &mut Context<Self>,
1414 ) -> Self {
1415 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
1416 cx.subscribe(&trusted_worktrees, |_, worktrees_store, e, cx| {
1417 if let TrustedWorktreesEvent::Trusted(..) = e {
1418 // Do not persist auto trusted worktrees
1419 if !ProjectSettings::get_global(cx).session.trust_all_worktrees {
1420 worktrees_store.update(cx, |worktrees_store, cx| {
1421 worktrees_store.schedule_serialization(
1422 cx,
1423 |new_trusted_worktrees, cx| {
1424 let timeout =
1425 cx.background_executor().timer(SERIALIZATION_THROTTLE_TIME);
1426 let db = WorkspaceDb::global(cx);
1427 cx.background_spawn(async move {
1428 timeout.await;
1429 db.save_trusted_worktrees(new_trusted_worktrees)
1430 .await
1431 .log_err();
1432 })
1433 },
1434 )
1435 });
1436 }
1437 }
1438 })
1439 .detach();
1440
1441 cx.observe_global::<SettingsStore>(|_, cx| {
1442 if ProjectSettings::get_global(cx).session.trust_all_worktrees {
1443 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
1444 trusted_worktrees.update(cx, |trusted_worktrees, cx| {
1445 trusted_worktrees.auto_trust_all(cx);
1446 })
1447 }
1448 }
1449 })
1450 .detach();
1451 }
1452
1453 cx.subscribe_in(&project, window, move |this, _, event, window, cx| {
1454 match event {
1455 project::Event::RemoteIdChanged(_) => {
1456 this.update_window_title(window, cx);
1457 }
1458
1459 project::Event::CollaboratorLeft(peer_id) => {
1460 this.collaborator_left(*peer_id, window, cx);
1461 }
1462
1463 &project::Event::WorktreeRemoved(_) => {
1464 this.update_window_title(window, cx);
1465 this.serialize_workspace(window, cx);
1466 this.update_history(cx);
1467 }
1468
1469 &project::Event::WorktreeAdded(id) => {
1470 this.update_window_title(window, cx);
1471 if this
1472 .project()
1473 .read(cx)
1474 .worktree_for_id(id, cx)
1475 .is_some_and(|wt| wt.read(cx).is_visible())
1476 {
1477 this.serialize_workspace(window, cx);
1478 this.update_history(cx);
1479 }
1480 }
1481 project::Event::WorktreeUpdatedEntries(..) => {
1482 this.update_window_title(window, cx);
1483 this.serialize_workspace(window, cx);
1484 }
1485
1486 project::Event::DisconnectedFromHost => {
1487 this.update_window_edited(window, cx);
1488 let leaders_to_unfollow =
1489 this.follower_states.keys().copied().collect::<Vec<_>>();
1490 for leader_id in leaders_to_unfollow {
1491 this.unfollow(leader_id, window, cx);
1492 }
1493 }
1494
1495 project::Event::DisconnectedFromRemote {
1496 server_not_running: _,
1497 } => {
1498 this.update_window_edited(window, cx);
1499 }
1500
1501 project::Event::Closed => {
1502 window.remove_window();
1503 }
1504
1505 project::Event::DeletedEntry(_, entry_id) => {
1506 for pane in this.panes.iter() {
1507 pane.update(cx, |pane, cx| {
1508 pane.handle_deleted_project_item(*entry_id, window, cx)
1509 });
1510 }
1511 }
1512
1513 project::Event::Toast {
1514 notification_id,
1515 message,
1516 link,
1517 } => this.show_notification(
1518 NotificationId::named(notification_id.clone()),
1519 cx,
1520 |cx| {
1521 let mut notification = MessageNotification::new(message.clone(), cx);
1522 if let Some(link) = link {
1523 notification = notification
1524 .more_info_message(link.label)
1525 .more_info_url(link.url);
1526 }
1527
1528 cx.new(|_| notification)
1529 },
1530 ),
1531
1532 project::Event::HideToast { notification_id } => {
1533 this.dismiss_notification(&NotificationId::named(notification_id.clone()), cx)
1534 }
1535
1536 project::Event::LanguageServerPrompt(request) => {
1537 struct LanguageServerPrompt;
1538
1539 this.show_notification(
1540 NotificationId::composite::<LanguageServerPrompt>(request.id),
1541 cx,
1542 |cx| {
1543 cx.new(|cx| {
1544 notifications::LanguageServerPrompt::new(request.clone(), cx)
1545 })
1546 },
1547 );
1548 }
1549
1550 project::Event::AgentLocationChanged => {
1551 this.handle_agent_location_changed(window, cx)
1552 }
1553
1554 _ => {}
1555 }
1556 cx.notify()
1557 })
1558 .detach();
1559
1560 cx.subscribe_in(
1561 &project.read(cx).breakpoint_store(),
1562 window,
1563 |workspace, _, event, window, cx| match event {
1564 BreakpointStoreEvent::BreakpointsUpdated(_, _)
1565 | BreakpointStoreEvent::BreakpointsCleared(_) => {
1566 workspace.serialize_workspace(window, cx);
1567 }
1568 BreakpointStoreEvent::SetDebugLine | BreakpointStoreEvent::ClearDebugLines => {}
1569 },
1570 )
1571 .detach();
1572 if let Some(toolchain_store) = project.read(cx).toolchain_store() {
1573 cx.subscribe_in(
1574 &toolchain_store,
1575 window,
1576 |workspace, _, event, window, cx| match event {
1577 ToolchainStoreEvent::CustomToolchainsModified => {
1578 workspace.serialize_workspace(window, cx);
1579 }
1580 _ => {}
1581 },
1582 )
1583 .detach();
1584 }
1585
1586 cx.on_focus_lost(window, |this, window, cx| {
1587 let focus_handle = this.focus_handle(cx);
1588 window.focus(&focus_handle, cx);
1589 })
1590 .detach();
1591
1592 let weak_handle = cx.entity().downgrade();
1593 let pane_history_timestamp = Arc::new(AtomicUsize::new(0));
1594
1595 let center_pane = cx.new(|cx| {
1596 let mut center_pane = Pane::new(
1597 weak_handle.clone(),
1598 project.clone(),
1599 pane_history_timestamp.clone(),
1600 None,
1601 NewFile.boxed_clone(),
1602 true,
1603 window,
1604 cx,
1605 );
1606 center_pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
1607 center_pane.set_should_display_welcome_page(true);
1608 center_pane
1609 });
1610 cx.subscribe_in(¢er_pane, window, Self::handle_pane_event)
1611 .detach();
1612
1613 window.focus(¢er_pane.focus_handle(cx), cx);
1614
1615 cx.emit(Event::PaneAdded(center_pane.clone()));
1616
1617 let any_window_handle = window.window_handle();
1618 app_state.workspace_store.update(cx, |store, _| {
1619 store
1620 .workspaces
1621 .insert((any_window_handle, weak_handle.clone()));
1622 });
1623
1624 let mut current_user = app_state.user_store.read(cx).watch_current_user();
1625 let mut connection_status = app_state.client.status();
1626 let _observe_current_user = cx.spawn_in(window, async move |this, cx| {
1627 current_user.next().await;
1628 connection_status.next().await;
1629 let mut stream =
1630 Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
1631
1632 while stream.recv().await.is_some() {
1633 this.update(cx, |_, cx| cx.notify())?;
1634 }
1635 anyhow::Ok(())
1636 });
1637
1638 // All leader updates are enqueued and then processed in a single task, so
1639 // that each asynchronous operation can be run in order.
1640 let (leader_updates_tx, mut leader_updates_rx) =
1641 mpsc::unbounded::<(PeerId, proto::UpdateFollowers)>();
1642 let _apply_leader_updates = cx.spawn_in(window, async move |this, cx| {
1643 while let Some((leader_id, update)) = leader_updates_rx.next().await {
1644 Self::process_leader_update(&this, leader_id, update, cx)
1645 .await
1646 .log_err();
1647 }
1648
1649 Ok(())
1650 });
1651
1652 cx.emit(Event::WorkspaceCreated(weak_handle.clone()));
1653 let modal_layer = cx.new(|_| ModalLayer::new());
1654 let toast_layer = cx.new(|_| ToastLayer::new());
1655 cx.subscribe(
1656 &modal_layer,
1657 |_, _, _: &modal_layer::ModalOpenedEvent, cx| {
1658 cx.emit(Event::ModalOpened);
1659 },
1660 )
1661 .detach();
1662
1663 let left_dock = Dock::new(DockPosition::Left, modal_layer.clone(), window, cx);
1664 let bottom_dock = Dock::new(DockPosition::Bottom, modal_layer.clone(), window, cx);
1665 let right_dock = Dock::new(DockPosition::Right, modal_layer.clone(), window, cx);
1666 let left_dock_buttons = cx.new(|cx| PanelButtons::new(left_dock.clone(), cx));
1667 let bottom_dock_buttons = cx.new(|cx| PanelButtons::new(bottom_dock.clone(), cx));
1668 let right_dock_buttons = cx.new(|cx| PanelButtons::new(right_dock.clone(), cx));
1669 let multi_workspace = window
1670 .root::<MultiWorkspace>()
1671 .flatten()
1672 .map(|mw| mw.downgrade());
1673 let status_bar = cx.new(|cx| {
1674 let mut status_bar =
1675 StatusBar::new(¢er_pane.clone(), multi_workspace.clone(), window, cx);
1676 status_bar.add_left_item(left_dock_buttons, window, cx);
1677 status_bar.add_right_item(right_dock_buttons, window, cx);
1678 status_bar.add_right_item(bottom_dock_buttons, window, cx);
1679 status_bar
1680 });
1681
1682 let session_id = app_state.session.read(cx).id().to_owned();
1683
1684 let mut active_call = None;
1685 if let Some(call) = GlobalAnyActiveCall::try_global(cx).cloned() {
1686 let subscriptions =
1687 vec![
1688 call.0
1689 .subscribe(window, cx, Box::new(Self::on_active_call_event)),
1690 ];
1691 active_call = Some((call, subscriptions));
1692 }
1693
1694 let (serializable_items_tx, serializable_items_rx) =
1695 mpsc::unbounded::<Box<dyn SerializableItemHandle>>();
1696 let _items_serializer = cx.spawn_in(window, async move |this, cx| {
1697 Self::serialize_items(&this, serializable_items_rx, cx).await
1698 });
1699
1700 let subscriptions = vec![
1701 cx.observe_window_activation(window, Self::on_window_activation_changed),
1702 cx.observe_window_bounds(window, move |this, window, cx| {
1703 if this.bounds_save_task_queued.is_some() {
1704 return;
1705 }
1706 this.bounds_save_task_queued = Some(cx.spawn_in(window, async move |this, cx| {
1707 cx.background_executor()
1708 .timer(Duration::from_millis(100))
1709 .await;
1710 this.update_in(cx, |this, window, cx| {
1711 this.save_window_bounds(window, cx).detach();
1712 this.bounds_save_task_queued.take();
1713 })
1714 .ok();
1715 }));
1716 cx.notify();
1717 }),
1718 cx.observe_window_appearance(window, |_, window, cx| {
1719 let window_appearance = window.appearance();
1720
1721 *SystemAppearance::global_mut(cx) = SystemAppearance(window_appearance.into());
1722
1723 theme_settings::reload_theme(cx);
1724 theme_settings::reload_icon_theme(cx);
1725 }),
1726 cx.on_release({
1727 let weak_handle = weak_handle.clone();
1728 move |this, cx| {
1729 this.app_state.workspace_store.update(cx, move |store, _| {
1730 store.workspaces.retain(|(_, weak)| weak != &weak_handle);
1731 })
1732 }
1733 }),
1734 ];
1735
1736 cx.defer_in(window, move |this, window, cx| {
1737 this.update_window_title(window, cx);
1738 this.show_initial_notifications(cx);
1739 });
1740
1741 let mut center = PaneGroup::new(center_pane.clone());
1742 center.set_is_center(true);
1743 center.mark_positions(cx);
1744
1745 Workspace {
1746 weak_self: weak_handle.clone(),
1747 zoomed: None,
1748 zoomed_position: None,
1749 previous_dock_drag_coordinates: None,
1750 center,
1751 panes: vec![center_pane.clone()],
1752 panes_by_item: Default::default(),
1753 active_pane: center_pane.clone(),
1754 last_active_center_pane: Some(center_pane.downgrade()),
1755 last_active_view_id: None,
1756 status_bar,
1757 modal_layer,
1758 toast_layer,
1759 titlebar_item: None,
1760 active_worktree_override: None,
1761 notifications: Notifications::default(),
1762 suppressed_notifications: HashSet::default(),
1763 left_dock,
1764 bottom_dock,
1765 right_dock,
1766 _panels_task: None,
1767 project: project.clone(),
1768 follower_states: Default::default(),
1769 last_leaders_by_pane: Default::default(),
1770 dispatching_keystrokes: Default::default(),
1771 window_edited: false,
1772 last_window_title: None,
1773 dirty_items: Default::default(),
1774 active_call,
1775 database_id: workspace_id,
1776 app_state,
1777 _observe_current_user,
1778 _apply_leader_updates,
1779 _schedule_serialize_workspace: None,
1780 _serialize_workspace_task: None,
1781 _schedule_serialize_ssh_paths: None,
1782 leader_updates_tx,
1783 _subscriptions: subscriptions,
1784 pane_history_timestamp,
1785 workspace_actions: Default::default(),
1786 // This data will be incorrect, but it will be overwritten by the time it needs to be used.
1787 bounds: Default::default(),
1788 centered_layout: false,
1789 bounds_save_task_queued: None,
1790 on_prompt_for_new_path: None,
1791 on_prompt_for_open_path: None,
1792 terminal_provider: None,
1793 debugger_provider: None,
1794 serializable_items_tx,
1795 _items_serializer,
1796 session_id: Some(session_id),
1797
1798 scheduled_tasks: Vec::new(),
1799 last_open_dock_positions: Vec::new(),
1800 removing: false,
1801 sidebar_focus_handle: None,
1802 multi_workspace,
1803 open_in_dev_container: false,
1804 _dev_container_task: None,
1805 }
1806 }
1807
1808 pub fn new_local(
1809 abs_paths: Vec<PathBuf>,
1810 app_state: Arc<AppState>,
1811 requesting_window: Option<WindowHandle<MultiWorkspace>>,
1812 env: Option<HashMap<String, String>>,
1813 init: Option<Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>>,
1814 open_mode: OpenMode,
1815 cx: &mut App,
1816 ) -> Task<anyhow::Result<OpenResult>> {
1817 let project_handle = Project::local(
1818 app_state.client.clone(),
1819 app_state.node_runtime.clone(),
1820 app_state.user_store.clone(),
1821 app_state.languages.clone(),
1822 app_state.fs.clone(),
1823 env,
1824 Default::default(),
1825 cx,
1826 );
1827
1828 let db = WorkspaceDb::global(cx);
1829 let kvp = db::kvp::KeyValueStore::global(cx);
1830 cx.spawn(async move |cx| {
1831 let mut paths_to_open = Vec::with_capacity(abs_paths.len());
1832 for path in abs_paths.into_iter() {
1833 if let Some(canonical) = app_state.fs.canonicalize(&path).await.ok() {
1834 paths_to_open.push(canonical)
1835 } else {
1836 paths_to_open.push(path)
1837 }
1838 }
1839
1840 let serialized_workspace = db.workspace_for_roots(paths_to_open.as_slice());
1841
1842 if let Some(paths) = serialized_workspace.as_ref().map(|ws| &ws.paths) {
1843 paths_to_open = paths.ordered_paths().cloned().collect();
1844 if !paths.is_lexicographically_ordered() {
1845 project_handle.update(cx, |project, cx| {
1846 project.set_worktrees_reordered(true, cx);
1847 });
1848 }
1849 }
1850
1851 // Get project paths for all of the abs_paths
1852 let mut project_paths: Vec<(PathBuf, Option<ProjectPath>)> =
1853 Vec::with_capacity(paths_to_open.len());
1854
1855 for path in paths_to_open.into_iter() {
1856 if let Some((_, project_entry)) = cx
1857 .update(|cx| {
1858 Workspace::project_path_for_path(project_handle.clone(), &path, true, cx)
1859 })
1860 .await
1861 .log_err()
1862 {
1863 project_paths.push((path, Some(project_entry)));
1864 } else {
1865 project_paths.push((path, None));
1866 }
1867 }
1868
1869 let workspace_id = if let Some(serialized_workspace) = serialized_workspace.as_ref() {
1870 serialized_workspace.id
1871 } else {
1872 db.next_id().await.unwrap_or_else(|_| Default::default())
1873 };
1874
1875 let toolchains = db.toolchains(workspace_id).await?;
1876
1877 for (toolchain, worktree_path, path) in toolchains {
1878 let toolchain_path = PathBuf::from(toolchain.path.clone().to_string());
1879 let Some(worktree_id) = project_handle.read_with(cx, |this, cx| {
1880 this.find_worktree(&worktree_path, cx)
1881 .and_then(|(worktree, rel_path)| {
1882 if rel_path.is_empty() {
1883 Some(worktree.read(cx).id())
1884 } else {
1885 None
1886 }
1887 })
1888 }) else {
1889 // We did not find a worktree with a given path, but that's whatever.
1890 continue;
1891 };
1892 if !app_state.fs.is_file(toolchain_path.as_path()).await {
1893 continue;
1894 }
1895
1896 project_handle
1897 .update(cx, |this, cx| {
1898 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
1899 })
1900 .await;
1901 }
1902 if let Some(workspace) = serialized_workspace.as_ref() {
1903 project_handle.update(cx, |this, cx| {
1904 for (scope, toolchains) in &workspace.user_toolchains {
1905 for toolchain in toolchains {
1906 this.add_toolchain(toolchain.clone(), scope.clone(), cx);
1907 }
1908 }
1909 });
1910 }
1911
1912 let window_to_replace = match open_mode {
1913 OpenMode::NewWindow => None,
1914 _ => requesting_window,
1915 };
1916
1917 let (window, workspace): (WindowHandle<MultiWorkspace>, Entity<Workspace>) =
1918 if let Some(window) = window_to_replace {
1919 let centered_layout = serialized_workspace
1920 .as_ref()
1921 .map(|w| w.centered_layout)
1922 .unwrap_or(false);
1923
1924 let workspace = window.update(cx, |multi_workspace, window, cx| {
1925 let workspace = cx.new(|cx| {
1926 let mut workspace = Workspace::new(
1927 Some(workspace_id),
1928 project_handle.clone(),
1929 app_state.clone(),
1930 window,
1931 cx,
1932 );
1933
1934 workspace.centered_layout = centered_layout;
1935
1936 // Call init callback to add items before window renders
1937 if let Some(init) = init {
1938 init(&mut workspace, window, cx);
1939 }
1940
1941 workspace
1942 });
1943 match open_mode {
1944 OpenMode::Activate => {
1945 multi_workspace.activate(workspace.clone(), window, cx);
1946 }
1947 OpenMode::Add => {
1948 multi_workspace.add(workspace.clone(), &*window, cx);
1949 }
1950 OpenMode::NewWindow => {
1951 unreachable!()
1952 }
1953 }
1954 workspace
1955 })?;
1956 (window, workspace)
1957 } else {
1958 let window_bounds_override = window_bounds_env_override();
1959
1960 let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
1961 (Some(WindowBounds::Windowed(bounds)), None)
1962 } else if let Some(workspace) = serialized_workspace.as_ref()
1963 && let Some(display) = workspace.display
1964 && let Some(bounds) = workspace.window_bounds.as_ref()
1965 {
1966 // Reopening an existing workspace - restore its saved bounds
1967 (Some(bounds.0), Some(display))
1968 } else if let Some((display, bounds)) =
1969 persistence::read_default_window_bounds(&kvp)
1970 {
1971 // New or empty workspace - use the last known window bounds
1972 (Some(bounds), Some(display))
1973 } else {
1974 // New window - let GPUI's default_bounds() handle cascading
1975 (None, None)
1976 };
1977
1978 // Use the serialized workspace to construct the new window
1979 let mut options = cx.update(|cx| (app_state.build_window_options)(display, cx));
1980 options.window_bounds = window_bounds;
1981 let centered_layout = serialized_workspace
1982 .as_ref()
1983 .map(|w| w.centered_layout)
1984 .unwrap_or(false);
1985 let window = cx.open_window(options, {
1986 let app_state = app_state.clone();
1987 let project_handle = project_handle.clone();
1988 move |window, cx| {
1989 let workspace = cx.new(|cx| {
1990 let mut workspace = Workspace::new(
1991 Some(workspace_id),
1992 project_handle,
1993 app_state,
1994 window,
1995 cx,
1996 );
1997 workspace.centered_layout = centered_layout;
1998
1999 // Call init callback to add items before window renders
2000 if let Some(init) = init {
2001 init(&mut workspace, window, cx);
2002 }
2003
2004 workspace
2005 });
2006 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
2007 }
2008 })?;
2009 let workspace =
2010 window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
2011 multi_workspace.workspace().clone()
2012 })?;
2013 (window, workspace)
2014 };
2015
2016 notify_if_database_failed(window, cx);
2017 // Check if this is an empty workspace (no paths to open)
2018 // An empty workspace is one where project_paths is empty
2019 let is_empty_workspace = project_paths.is_empty();
2020 // Check if serialized workspace has paths before it's moved
2021 let serialized_workspace_has_paths = serialized_workspace
2022 .as_ref()
2023 .map(|ws| !ws.paths.is_empty())
2024 .unwrap_or(false);
2025
2026 let opened_items = window
2027 .update(cx, |_, window, cx| {
2028 workspace.update(cx, |_workspace: &mut Workspace, cx| {
2029 open_items(serialized_workspace, project_paths, window, cx)
2030 })
2031 })?
2032 .await
2033 .unwrap_or_default();
2034
2035 // Restore default dock state for empty workspaces
2036 // Only restore if:
2037 // 1. This is an empty workspace (no paths), AND
2038 // 2. The serialized workspace either doesn't exist or has no paths
2039 if is_empty_workspace && !serialized_workspace_has_paths {
2040 if let Some(default_docks) = persistence::read_default_dock_state(&kvp) {
2041 window
2042 .update(cx, |_, window, cx| {
2043 workspace.update(cx, |workspace, cx| {
2044 for (dock, serialized_dock) in [
2045 (&workspace.right_dock, &default_docks.right),
2046 (&workspace.left_dock, &default_docks.left),
2047 (&workspace.bottom_dock, &default_docks.bottom),
2048 ] {
2049 dock.update(cx, |dock, cx| {
2050 dock.serialized_dock = Some(serialized_dock.clone());
2051 dock.restore_state(window, cx);
2052 });
2053 }
2054 cx.notify();
2055 });
2056 })
2057 .log_err();
2058 }
2059 }
2060
2061 window
2062 .update(cx, |_, _window, cx| {
2063 workspace.update(cx, |this: &mut Workspace, cx| {
2064 this.update_history(cx);
2065 });
2066 })
2067 .log_err();
2068 Ok(OpenResult {
2069 window,
2070 workspace,
2071 opened_items,
2072 })
2073 })
2074 }
2075
2076 pub fn project_group_key(&self, cx: &App) -> ProjectGroupKey {
2077 self.project.read(cx).project_group_key(cx)
2078 }
2079
2080 pub fn weak_handle(&self) -> WeakEntity<Self> {
2081 self.weak_self.clone()
2082 }
2083
2084 pub fn left_dock(&self) -> &Entity<Dock> {
2085 &self.left_dock
2086 }
2087
2088 pub fn bottom_dock(&self) -> &Entity<Dock> {
2089 &self.bottom_dock
2090 }
2091
2092 pub fn set_bottom_dock_layout(
2093 &mut self,
2094 layout: BottomDockLayout,
2095 window: &mut Window,
2096 cx: &mut Context<Self>,
2097 ) {
2098 let fs = self.project().read(cx).fs();
2099 settings::update_settings_file(fs.clone(), cx, move |content, _cx| {
2100 content.workspace.bottom_dock_layout = Some(layout);
2101 });
2102
2103 cx.notify();
2104 self.serialize_workspace(window, cx);
2105 }
2106
2107 pub fn right_dock(&self) -> &Entity<Dock> {
2108 &self.right_dock
2109 }
2110
2111 pub fn all_docks(&self) -> [&Entity<Dock>; 3] {
2112 [&self.left_dock, &self.bottom_dock, &self.right_dock]
2113 }
2114
2115 pub fn capture_dock_state(&self, _window: &Window, cx: &App) -> DockStructure {
2116 let left_dock = self.left_dock.read(cx);
2117 let left_visible = left_dock.is_open();
2118 let left_active_panel = left_dock
2119 .active_panel()
2120 .map(|panel| panel.persistent_name().to_string());
2121 // `zoomed_position` is kept in sync with individual panel zoom state
2122 // by the dock code in `Dock::new` and `Dock::add_panel`.
2123 let left_dock_zoom = self.zoomed_position == Some(DockPosition::Left);
2124
2125 let right_dock = self.right_dock.read(cx);
2126 let right_visible = right_dock.is_open();
2127 let right_active_panel = right_dock
2128 .active_panel()
2129 .map(|panel| panel.persistent_name().to_string());
2130 let right_dock_zoom = self.zoomed_position == Some(DockPosition::Right);
2131
2132 let bottom_dock = self.bottom_dock.read(cx);
2133 let bottom_visible = bottom_dock.is_open();
2134 let bottom_active_panel = bottom_dock
2135 .active_panel()
2136 .map(|panel| panel.persistent_name().to_string());
2137 let bottom_dock_zoom = self.zoomed_position == Some(DockPosition::Bottom);
2138
2139 DockStructure {
2140 left: DockData {
2141 visible: left_visible,
2142 active_panel: left_active_panel,
2143 zoom: left_dock_zoom,
2144 },
2145 right: DockData {
2146 visible: right_visible,
2147 active_panel: right_active_panel,
2148 zoom: right_dock_zoom,
2149 },
2150 bottom: DockData {
2151 visible: bottom_visible,
2152 active_panel: bottom_active_panel,
2153 zoom: bottom_dock_zoom,
2154 },
2155 }
2156 }
2157
2158 pub fn set_dock_structure(
2159 &self,
2160 docks: DockStructure,
2161 window: &mut Window,
2162 cx: &mut Context<Self>,
2163 ) {
2164 for (dock, data) in [
2165 (&self.left_dock, docks.left),
2166 (&self.bottom_dock, docks.bottom),
2167 (&self.right_dock, docks.right),
2168 ] {
2169 dock.update(cx, |dock, cx| {
2170 dock.serialized_dock = Some(data);
2171 dock.restore_state(window, cx);
2172 });
2173 }
2174 }
2175
2176 pub fn open_item_abs_paths(&self, cx: &App) -> Vec<PathBuf> {
2177 self.items(cx)
2178 .filter_map(|item| {
2179 let project_path = item.project_path(cx)?;
2180 self.project.read(cx).absolute_path(&project_path, cx)
2181 })
2182 .collect()
2183 }
2184
2185 pub fn dock_at_position(&self, position: DockPosition) -> &Entity<Dock> {
2186 match position {
2187 DockPosition::Left => &self.left_dock,
2188 DockPosition::Bottom => &self.bottom_dock,
2189 DockPosition::Right => &self.right_dock,
2190 }
2191 }
2192
2193 pub fn agent_panel_position(&self, cx: &App) -> Option<DockPosition> {
2194 self.all_docks().into_iter().find_map(|dock| {
2195 let dock = dock.read(cx);
2196 dock.has_agent_panel(cx).then_some(dock.position())
2197 })
2198 }
2199
2200 pub fn panel_size_state<T: Panel>(&self, cx: &App) -> Option<dock::PanelSizeState> {
2201 self.all_docks().into_iter().find_map(|dock| {
2202 let dock = dock.read(cx);
2203 let panel = dock.panel::<T>()?;
2204 dock.stored_panel_size_state(&panel)
2205 })
2206 }
2207
2208 pub fn persisted_panel_size_state(
2209 &self,
2210 panel_key: &'static str,
2211 cx: &App,
2212 ) -> Option<dock::PanelSizeState> {
2213 dock::Dock::load_persisted_size_state(self, panel_key, cx)
2214 }
2215
2216 pub fn persist_panel_size_state(
2217 &self,
2218 panel_key: &str,
2219 size_state: dock::PanelSizeState,
2220 cx: &mut App,
2221 ) {
2222 let Some(workspace_id) = self
2223 .database_id()
2224 .map(|id| i64::from(id).to_string())
2225 .or(self.session_id())
2226 else {
2227 return;
2228 };
2229
2230 let kvp = db::kvp::KeyValueStore::global(cx);
2231 let panel_key = panel_key.to_string();
2232 cx.background_spawn(async move {
2233 let scope = kvp.scoped(dock::PANEL_SIZE_STATE_KEY);
2234 scope
2235 .write(
2236 format!("{workspace_id}:{panel_key}"),
2237 serde_json::to_string(&size_state)?,
2238 )
2239 .await
2240 })
2241 .detach_and_log_err(cx);
2242 }
2243
2244 pub fn set_panel_size_state<T: Panel>(
2245 &mut self,
2246 size_state: dock::PanelSizeState,
2247 window: &mut Window,
2248 cx: &mut Context<Self>,
2249 ) -> bool {
2250 let Some(panel) = self.panel::<T>(cx) else {
2251 return false;
2252 };
2253
2254 let dock = self.dock_at_position(panel.position(window, cx));
2255 let did_set = dock.update(cx, |dock, cx| {
2256 dock.set_panel_size_state(&panel, size_state, cx)
2257 });
2258
2259 if did_set {
2260 self.persist_panel_size_state(T::panel_key(), size_state, cx);
2261 }
2262
2263 did_set
2264 }
2265
2266 pub fn toggle_dock_panel_flexible_size(
2267 &self,
2268 dock: &Entity<Dock>,
2269 panel: &dyn PanelHandle,
2270 window: &mut Window,
2271 cx: &mut App,
2272 ) {
2273 let position = dock.read(cx).position();
2274 let current_size = self.dock_size(&dock.read(cx), window, cx);
2275 let current_flex =
2276 current_size.and_then(|size| self.dock_flex_for_size(position, size, window, cx));
2277 dock.update(cx, |dock, cx| {
2278 dock.toggle_panel_flexible_size(panel, current_size, current_flex, window, cx);
2279 });
2280 }
2281
2282 fn dock_size(&self, dock: &Dock, window: &Window, cx: &App) -> Option<Pixels> {
2283 let panel = dock.active_panel()?;
2284 let size_state = dock
2285 .stored_panel_size_state(panel.as_ref())
2286 .unwrap_or_default();
2287 let position = dock.position();
2288
2289 let use_flex = panel.has_flexible_size(window, cx);
2290
2291 if position.axis() == Axis::Horizontal
2292 && use_flex
2293 && let Some(flex) = size_state.flex.or_else(|| self.default_dock_flex(position))
2294 {
2295 let workspace_width = self.bounds.size.width;
2296 if workspace_width <= Pixels::ZERO {
2297 return None;
2298 }
2299 let flex = flex.max(0.001);
2300 let opposite = self.opposite_dock_panel_and_size_state(position, window, cx);
2301 if let Some(opposite_flex) = opposite.as_ref().and_then(|(_, s)| s.flex) {
2302 // Both docks are flex items sharing the full workspace width.
2303 let total_flex = flex + 1.0 + opposite_flex;
2304 return Some((flex / total_flex * workspace_width).max(RESIZE_HANDLE_SIZE));
2305 } else {
2306 // Opposite dock is fixed-width; flex items share (W - fixed).
2307 let opposite_fixed = opposite
2308 .map(|(panel, s)| s.size.unwrap_or_else(|| panel.default_size(window, cx)))
2309 .unwrap_or_default();
2310 let available = (workspace_width - opposite_fixed).max(RESIZE_HANDLE_SIZE);
2311 return Some((flex / (flex + 1.0) * available).max(RESIZE_HANDLE_SIZE));
2312 }
2313 }
2314
2315 Some(
2316 size_state
2317 .size
2318 .unwrap_or_else(|| panel.default_size(window, cx)),
2319 )
2320 }
2321
2322 pub fn dock_flex_for_size(
2323 &self,
2324 position: DockPosition,
2325 size: Pixels,
2326 window: &Window,
2327 cx: &App,
2328 ) -> Option<f32> {
2329 if position.axis() != Axis::Horizontal {
2330 return None;
2331 }
2332
2333 let workspace_width = self.bounds.size.width;
2334 if workspace_width <= Pixels::ZERO {
2335 return None;
2336 }
2337
2338 let opposite = self.opposite_dock_panel_and_size_state(position, window, cx);
2339 if let Some(opposite_flex) = opposite.as_ref().and_then(|(_, s)| s.flex) {
2340 let size = size.clamp(px(0.), workspace_width - px(1.));
2341 Some((size * (1.0 + opposite_flex) / (workspace_width - size)).max(0.0))
2342 } else {
2343 let opposite_width = opposite
2344 .map(|(panel, s)| s.size.unwrap_or_else(|| panel.default_size(window, cx)))
2345 .unwrap_or_default();
2346 let available = (workspace_width - opposite_width).max(RESIZE_HANDLE_SIZE);
2347 let remaining = (available - size).max(px(1.));
2348 Some((size / remaining).max(0.0))
2349 }
2350 }
2351
2352 fn opposite_dock_panel_and_size_state(
2353 &self,
2354 position: DockPosition,
2355 window: &Window,
2356 cx: &App,
2357 ) -> Option<(Arc<dyn PanelHandle>, PanelSizeState)> {
2358 let opposite_position = match position {
2359 DockPosition::Left => DockPosition::Right,
2360 DockPosition::Right => DockPosition::Left,
2361 DockPosition::Bottom => return None,
2362 };
2363
2364 let opposite_dock = self.dock_at_position(opposite_position).read(cx);
2365 let panel = opposite_dock.visible_panel()?;
2366 let mut size_state = opposite_dock
2367 .stored_panel_size_state(panel.as_ref())
2368 .unwrap_or_default();
2369 if size_state.flex.is_none() && panel.has_flexible_size(window, cx) {
2370 size_state.flex = self.default_dock_flex(opposite_position);
2371 }
2372 Some((panel.clone(), size_state))
2373 }
2374
2375 pub fn default_dock_flex(&self, position: DockPosition) -> Option<f32> {
2376 if position.axis() != Axis::Horizontal {
2377 return None;
2378 }
2379
2380 let pane = self.last_active_center_pane.clone()?.upgrade()?;
2381 Some(self.center.width_fraction_for_pane(&pane).unwrap_or(1.0))
2382 }
2383
2384 pub fn is_edited(&self) -> bool {
2385 self.window_edited
2386 }
2387
2388 pub fn add_panel<T: Panel>(
2389 &mut self,
2390 panel: Entity<T>,
2391 window: &mut Window,
2392 cx: &mut Context<Self>,
2393 ) {
2394 let focus_handle = panel.panel_focus_handle(cx);
2395 cx.on_focus_in(&focus_handle, window, Self::handle_panel_focused)
2396 .detach();
2397
2398 let dock_position = panel.position(window, cx);
2399 let dock = self.dock_at_position(dock_position);
2400 let any_panel = panel.to_any();
2401 let persisted_size_state =
2402 self.persisted_panel_size_state(T::panel_key(), cx)
2403 .or_else(|| {
2404 load_legacy_panel_size(T::panel_key(), dock_position, self, cx).map(|size| {
2405 let state = dock::PanelSizeState {
2406 size: Some(size),
2407 flex: None,
2408 };
2409 self.persist_panel_size_state(T::panel_key(), state, cx);
2410 state
2411 })
2412 });
2413
2414 dock.update(cx, |dock, cx| {
2415 let index = dock.add_panel(panel.clone(), self.weak_self.clone(), window, cx);
2416 if let Some(size_state) = persisted_size_state {
2417 dock.set_panel_size_state(&panel, size_state, cx);
2418 }
2419 index
2420 });
2421
2422 cx.emit(Event::PanelAdded(any_panel));
2423 }
2424
2425 pub fn remove_panel<T: Panel>(
2426 &mut self,
2427 panel: &Entity<T>,
2428 window: &mut Window,
2429 cx: &mut Context<Self>,
2430 ) {
2431 for dock in [&self.left_dock, &self.bottom_dock, &self.right_dock] {
2432 dock.update(cx, |dock, cx| dock.remove_panel(panel, window, cx));
2433 }
2434 }
2435
2436 pub fn status_bar(&self) -> &Entity<StatusBar> {
2437 &self.status_bar
2438 }
2439
2440 pub fn set_sidebar_focus_handle(&mut self, handle: Option<FocusHandle>) {
2441 self.sidebar_focus_handle = handle;
2442 }
2443
2444 pub fn status_bar_visible(&self, cx: &App) -> bool {
2445 StatusBarSettings::get_global(cx).show
2446 }
2447
2448 pub fn multi_workspace(&self) -> Option<&WeakEntity<MultiWorkspace>> {
2449 self.multi_workspace.as_ref()
2450 }
2451
2452 pub fn set_multi_workspace(
2453 &mut self,
2454 multi_workspace: WeakEntity<MultiWorkspace>,
2455 cx: &mut App,
2456 ) {
2457 self.status_bar.update(cx, |status_bar, cx| {
2458 status_bar.set_multi_workspace(multi_workspace.clone(), cx);
2459 });
2460 self.multi_workspace = Some(multi_workspace);
2461 }
2462
2463 pub fn app_state(&self) -> &Arc<AppState> {
2464 &self.app_state
2465 }
2466
2467 pub fn set_panels_task(&mut self, task: Task<Result<()>>) {
2468 self._panels_task = Some(task);
2469 }
2470
2471 pub fn take_panels_task(&mut self) -> Option<Task<Result<()>>> {
2472 self._panels_task.take()
2473 }
2474
2475 pub fn user_store(&self) -> &Entity<UserStore> {
2476 &self.app_state.user_store
2477 }
2478
2479 pub fn project(&self) -> &Entity<Project> {
2480 &self.project
2481 }
2482
2483 pub fn path_style(&self, cx: &App) -> PathStyle {
2484 self.project.read(cx).path_style(cx)
2485 }
2486
2487 pub fn recently_activated_items(&self, cx: &App) -> HashMap<EntityId, usize> {
2488 let mut history: HashMap<EntityId, usize> = HashMap::default();
2489
2490 for pane_handle in &self.panes {
2491 let pane = pane_handle.read(cx);
2492
2493 for entry in pane.activation_history() {
2494 history.insert(
2495 entry.entity_id,
2496 history
2497 .get(&entry.entity_id)
2498 .cloned()
2499 .unwrap_or(0)
2500 .max(entry.timestamp),
2501 );
2502 }
2503 }
2504
2505 history
2506 }
2507
2508 pub fn recent_active_item_by_type<T: 'static>(&self, cx: &App) -> Option<Entity<T>> {
2509 let mut recent_item: Option<Entity<T>> = None;
2510 let mut recent_timestamp = 0;
2511 for pane_handle in &self.panes {
2512 let pane = pane_handle.read(cx);
2513 let item_map: HashMap<EntityId, &Box<dyn ItemHandle>> =
2514 pane.items().map(|item| (item.item_id(), item)).collect();
2515 for entry in pane.activation_history() {
2516 if entry.timestamp > recent_timestamp
2517 && let Some(&item) = item_map.get(&entry.entity_id)
2518 && let Some(typed_item) = item.act_as::<T>(cx)
2519 {
2520 recent_timestamp = entry.timestamp;
2521 recent_item = Some(typed_item);
2522 }
2523 }
2524 }
2525 recent_item
2526 }
2527
2528 pub fn recent_navigation_history_iter(
2529 &self,
2530 cx: &App,
2531 ) -> impl Iterator<Item = (ProjectPath, Option<PathBuf>)> + use<> {
2532 let mut abs_paths_opened: HashMap<PathBuf, HashSet<ProjectPath>> = HashMap::default();
2533 let mut history: HashMap<ProjectPath, (Option<PathBuf>, usize)> = HashMap::default();
2534
2535 for pane in &self.panes {
2536 let pane = pane.read(cx);
2537
2538 pane.nav_history()
2539 .for_each_entry(cx, &mut |entry, (project_path, fs_path)| {
2540 if let Some(fs_path) = &fs_path {
2541 abs_paths_opened
2542 .entry(fs_path.clone())
2543 .or_default()
2544 .insert(project_path.clone());
2545 }
2546 let timestamp = entry.timestamp;
2547 match history.entry(project_path) {
2548 hash_map::Entry::Occupied(mut entry) => {
2549 let (_, old_timestamp) = entry.get();
2550 if ×tamp > old_timestamp {
2551 entry.insert((fs_path, timestamp));
2552 }
2553 }
2554 hash_map::Entry::Vacant(entry) => {
2555 entry.insert((fs_path, timestamp));
2556 }
2557 }
2558 });
2559
2560 if let Some(item) = pane.active_item()
2561 && let Some(project_path) = item.project_path(cx)
2562 {
2563 let fs_path = self.project.read(cx).absolute_path(&project_path, cx);
2564
2565 if let Some(fs_path) = &fs_path {
2566 abs_paths_opened
2567 .entry(fs_path.clone())
2568 .or_default()
2569 .insert(project_path.clone());
2570 }
2571
2572 history.insert(project_path, (fs_path, std::usize::MAX));
2573 }
2574 }
2575
2576 history
2577 .into_iter()
2578 .sorted_by_key(|(_, (_, order))| *order)
2579 .map(|(project_path, (fs_path, _))| (project_path, fs_path))
2580 .rev()
2581 .filter(move |(history_path, abs_path)| {
2582 let latest_project_path_opened = abs_path
2583 .as_ref()
2584 .and_then(|abs_path| abs_paths_opened.get(abs_path))
2585 .and_then(|project_paths| {
2586 project_paths
2587 .iter()
2588 .max_by(|b1, b2| b1.worktree_id.cmp(&b2.worktree_id))
2589 });
2590
2591 latest_project_path_opened.is_none_or(|path| path == history_path)
2592 })
2593 }
2594
2595 pub fn recent_navigation_history(
2596 &self,
2597 limit: Option<usize>,
2598 cx: &App,
2599 ) -> Vec<(ProjectPath, Option<PathBuf>)> {
2600 self.recent_navigation_history_iter(cx)
2601 .take(limit.unwrap_or(usize::MAX))
2602 .collect()
2603 }
2604
2605 pub fn clear_navigation_history(&mut self, _window: &mut Window, cx: &mut Context<Workspace>) {
2606 for pane in &self.panes {
2607 pane.update(cx, |pane, cx| pane.nav_history_mut().clear(cx));
2608 }
2609 }
2610
2611 fn navigate_history(
2612 &mut self,
2613 pane: WeakEntity<Pane>,
2614 mode: NavigationMode,
2615 window: &mut Window,
2616 cx: &mut Context<Workspace>,
2617 ) -> Task<Result<()>> {
2618 self.navigate_history_impl(
2619 pane,
2620 mode,
2621 window,
2622 &mut |history, cx| history.pop(mode, cx),
2623 cx,
2624 )
2625 }
2626
2627 fn navigate_tag_history(
2628 &mut self,
2629 pane: WeakEntity<Pane>,
2630 mode: TagNavigationMode,
2631 window: &mut Window,
2632 cx: &mut Context<Workspace>,
2633 ) -> Task<Result<()>> {
2634 self.navigate_history_impl(
2635 pane,
2636 NavigationMode::Normal,
2637 window,
2638 &mut |history, _cx| history.pop_tag(mode),
2639 cx,
2640 )
2641 }
2642
2643 fn navigate_history_impl(
2644 &mut self,
2645 pane: WeakEntity<Pane>,
2646 mode: NavigationMode,
2647 window: &mut Window,
2648 cb: &mut dyn FnMut(&mut NavHistory, &mut App) -> Option<NavigationEntry>,
2649 cx: &mut Context<Workspace>,
2650 ) -> Task<Result<()>> {
2651 let to_load = if let Some(pane) = pane.upgrade() {
2652 pane.update(cx, |pane, cx| {
2653 window.focus(&pane.focus_handle(cx), cx);
2654 loop {
2655 // Retrieve the weak item handle from the history.
2656 let entry = cb(pane.nav_history_mut(), cx)?;
2657
2658 // If the item is still present in this pane, then activate it.
2659 if let Some(index) = entry
2660 .item
2661 .upgrade()
2662 .and_then(|v| pane.index_for_item(v.as_ref()))
2663 {
2664 let prev_active_item_index = pane.active_item_index();
2665 pane.nav_history_mut().set_mode(mode);
2666 pane.activate_item(index, true, true, window, cx);
2667 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2668
2669 let mut navigated = prev_active_item_index != pane.active_item_index();
2670 if let Some(data) = entry.data {
2671 navigated |= pane.active_item()?.navigate(data, window, cx);
2672 }
2673
2674 if navigated {
2675 break None;
2676 }
2677 } else {
2678 // If the item is no longer present in this pane, then retrieve its
2679 // path info in order to reopen it.
2680 break pane
2681 .nav_history()
2682 .path_for_item(entry.item.id())
2683 .map(|(project_path, abs_path)| (project_path, abs_path, entry));
2684 }
2685 }
2686 })
2687 } else {
2688 None
2689 };
2690
2691 if let Some((project_path, abs_path, entry)) = to_load {
2692 // If the item was no longer present, then load it again from its previous path, first try the local path
2693 let open_by_project_path = self.load_path(project_path.clone(), window, cx);
2694
2695 cx.spawn_in(window, async move |workspace, cx| {
2696 let open_by_project_path = open_by_project_path.await;
2697 let mut navigated = false;
2698 match open_by_project_path
2699 .with_context(|| format!("Navigating to {project_path:?}"))
2700 {
2701 Ok((project_entry_id, build_item)) => {
2702 let prev_active_item_id = pane.update(cx, |pane, _| {
2703 pane.nav_history_mut().set_mode(mode);
2704 pane.active_item().map(|p| p.item_id())
2705 })?;
2706
2707 pane.update_in(cx, |pane, window, cx| {
2708 let item = pane.open_item(
2709 project_entry_id,
2710 project_path,
2711 true,
2712 entry.is_preview,
2713 true,
2714 None,
2715 window, cx,
2716 build_item,
2717 );
2718 navigated |= Some(item.item_id()) != prev_active_item_id;
2719 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2720 if let Some(data) = entry.data {
2721 navigated |= item.navigate(data, window, cx);
2722 }
2723 })?;
2724 }
2725 Err(open_by_project_path_e) => {
2726 // Fall back to opening by abs path, in case an external file was opened and closed,
2727 // and its worktree is now dropped
2728 if let Some(abs_path) = abs_path {
2729 let prev_active_item_id = pane.update(cx, |pane, _| {
2730 pane.nav_history_mut().set_mode(mode);
2731 pane.active_item().map(|p| p.item_id())
2732 })?;
2733 let open_by_abs_path = workspace.update_in(cx, |workspace, window, cx| {
2734 workspace.open_abs_path(abs_path.clone(), OpenOptions { visible: Some(OpenVisible::None), ..Default::default() }, window, cx)
2735 })?;
2736 match open_by_abs_path
2737 .await
2738 .with_context(|| format!("Navigating to {abs_path:?}"))
2739 {
2740 Ok(item) => {
2741 pane.update_in(cx, |pane, window, cx| {
2742 navigated |= Some(item.item_id()) != prev_active_item_id;
2743 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2744 if let Some(data) = entry.data {
2745 navigated |= item.navigate(data, window, cx);
2746 }
2747 })?;
2748 }
2749 Err(open_by_abs_path_e) => {
2750 log::error!("Failed to navigate history: {open_by_project_path_e:#} and {open_by_abs_path_e:#}");
2751 }
2752 }
2753 }
2754 }
2755 }
2756
2757 if !navigated {
2758 workspace
2759 .update_in(cx, |workspace, window, cx| {
2760 Self::navigate_history(workspace, pane, mode, window, cx)
2761 })?
2762 .await?;
2763 }
2764
2765 Ok(())
2766 })
2767 } else {
2768 Task::ready(Ok(()))
2769 }
2770 }
2771
2772 pub fn go_back(
2773 &mut self,
2774 pane: WeakEntity<Pane>,
2775 window: &mut Window,
2776 cx: &mut Context<Workspace>,
2777 ) -> Task<Result<()>> {
2778 self.navigate_history(pane, NavigationMode::GoingBack, window, cx)
2779 }
2780
2781 pub fn go_forward(
2782 &mut self,
2783 pane: WeakEntity<Pane>,
2784 window: &mut Window,
2785 cx: &mut Context<Workspace>,
2786 ) -> Task<Result<()>> {
2787 self.navigate_history(pane, NavigationMode::GoingForward, window, cx)
2788 }
2789
2790 pub fn reopen_closed_item(
2791 &mut self,
2792 window: &mut Window,
2793 cx: &mut Context<Workspace>,
2794 ) -> Task<Result<()>> {
2795 self.navigate_history(
2796 self.active_pane().downgrade(),
2797 NavigationMode::ReopeningClosedItem,
2798 window,
2799 cx,
2800 )
2801 }
2802
2803 pub fn client(&self) -> &Arc<Client> {
2804 &self.app_state.client
2805 }
2806
2807 pub fn set_titlebar_item(&mut self, item: AnyView, _: &mut Window, cx: &mut Context<Self>) {
2808 self.titlebar_item = Some(item);
2809 cx.notify();
2810 }
2811
2812 pub fn set_prompt_for_new_path(&mut self, prompt: PromptForNewPath) {
2813 self.on_prompt_for_new_path = Some(prompt)
2814 }
2815
2816 pub fn set_prompt_for_open_path(&mut self, prompt: PromptForOpenPath) {
2817 self.on_prompt_for_open_path = Some(prompt)
2818 }
2819
2820 pub fn set_terminal_provider(&mut self, provider: impl TerminalProvider + 'static) {
2821 self.terminal_provider = Some(Box::new(provider));
2822 }
2823
2824 pub fn set_debugger_provider(&mut self, provider: impl DebuggerProvider + 'static) {
2825 self.debugger_provider = Some(Arc::new(provider));
2826 }
2827
2828 pub fn set_open_in_dev_container(&mut self, value: bool) {
2829 self.open_in_dev_container = value;
2830 }
2831
2832 pub fn open_in_dev_container(&self) -> bool {
2833 self.open_in_dev_container
2834 }
2835
2836 pub fn set_dev_container_task(&mut self, task: Task<Result<()>>) {
2837 self._dev_container_task = Some(task);
2838 }
2839
2840 pub fn debugger_provider(&self) -> Option<Arc<dyn DebuggerProvider>> {
2841 self.debugger_provider.clone()
2842 }
2843
2844 pub fn prompt_for_open_path(
2845 &mut self,
2846 path_prompt_options: PathPromptOptions,
2847 lister: DirectoryLister,
2848 window: &mut Window,
2849 cx: &mut Context<Self>,
2850 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2851 if !lister.is_local(cx) || !WorkspaceSettings::get_global(cx).use_system_path_prompts {
2852 let prompt = self.on_prompt_for_open_path.take().unwrap();
2853 let rx = prompt(self, lister, window, cx);
2854 self.on_prompt_for_open_path = Some(prompt);
2855 rx
2856 } else {
2857 let (tx, rx) = oneshot::channel();
2858 let abs_path = cx.prompt_for_paths(path_prompt_options);
2859
2860 cx.spawn_in(window, async move |workspace, cx| {
2861 let Ok(result) = abs_path.await else {
2862 return Ok(());
2863 };
2864
2865 match result {
2866 Ok(result) => {
2867 tx.send(result).ok();
2868 }
2869 Err(err) => {
2870 let rx = workspace.update_in(cx, |workspace, window, cx| {
2871 workspace.show_portal_error(err.to_string(), cx);
2872 let prompt = workspace.on_prompt_for_open_path.take().unwrap();
2873 let rx = prompt(workspace, lister, window, cx);
2874 workspace.on_prompt_for_open_path = Some(prompt);
2875 rx
2876 })?;
2877 if let Ok(path) = rx.await {
2878 tx.send(path).ok();
2879 }
2880 }
2881 };
2882 anyhow::Ok(())
2883 })
2884 .detach();
2885
2886 rx
2887 }
2888 }
2889
2890 pub fn prompt_for_new_path(
2891 &mut self,
2892 lister: DirectoryLister,
2893 suggested_name: Option<String>,
2894 window: &mut Window,
2895 cx: &mut Context<Self>,
2896 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2897 if self.project.read(cx).is_via_collab()
2898 || self.project.read(cx).is_via_remote_server()
2899 || !WorkspaceSettings::get_global(cx).use_system_path_prompts
2900 {
2901 let prompt = self.on_prompt_for_new_path.take().unwrap();
2902 let rx = prompt(self, lister, suggested_name, window, cx);
2903 self.on_prompt_for_new_path = Some(prompt);
2904 return rx;
2905 }
2906
2907 let (tx, rx) = oneshot::channel();
2908 cx.spawn_in(window, async move |workspace, cx| {
2909 let abs_path = workspace.update(cx, |workspace, cx| {
2910 let relative_to = workspace
2911 .most_recent_active_path(cx)
2912 .and_then(|p| p.parent().map(|p| p.to_path_buf()))
2913 .or_else(|| {
2914 let project = workspace.project.read(cx);
2915 project.visible_worktrees(cx).find_map(|worktree| {
2916 Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
2917 })
2918 })
2919 .or_else(std::env::home_dir)
2920 .unwrap_or_else(|| PathBuf::from(""));
2921 cx.prompt_for_new_path(&relative_to, suggested_name.as_deref())
2922 })?;
2923 let abs_path = match abs_path.await? {
2924 Ok(path) => path,
2925 Err(err) => {
2926 let rx = workspace.update_in(cx, |workspace, window, cx| {
2927 workspace.show_portal_error(err.to_string(), cx);
2928
2929 let prompt = workspace.on_prompt_for_new_path.take().unwrap();
2930 let rx = prompt(workspace, lister, suggested_name, window, cx);
2931 workspace.on_prompt_for_new_path = Some(prompt);
2932 rx
2933 })?;
2934 if let Ok(path) = rx.await {
2935 tx.send(path).ok();
2936 }
2937 return anyhow::Ok(());
2938 }
2939 };
2940
2941 tx.send(abs_path.map(|path| vec![path])).ok();
2942 anyhow::Ok(())
2943 })
2944 .detach();
2945
2946 rx
2947 }
2948
2949 pub fn titlebar_item(&self) -> Option<AnyView> {
2950 self.titlebar_item.clone()
2951 }
2952
2953 /// Returns the worktree override set by the user (e.g., via the project dropdown).
2954 /// When set, git-related operations should use this worktree instead of deriving
2955 /// the active worktree from the focused file.
2956 pub fn active_worktree_override(&self) -> Option<WorktreeId> {
2957 self.active_worktree_override
2958 }
2959
2960 pub fn set_active_worktree_override(
2961 &mut self,
2962 worktree_id: Option<WorktreeId>,
2963 cx: &mut Context<Self>,
2964 ) {
2965 self.active_worktree_override = worktree_id;
2966 cx.notify();
2967 }
2968
2969 pub fn clear_active_worktree_override(&mut self, cx: &mut Context<Self>) {
2970 self.active_worktree_override = None;
2971 cx.notify();
2972 }
2973
2974 /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
2975 ///
2976 /// If the given workspace has a local project, then it will be passed
2977 /// to the callback. Otherwise, a new empty window will be created.
2978 pub fn with_local_workspace<T, F>(
2979 &mut self,
2980 window: &mut Window,
2981 cx: &mut Context<Self>,
2982 callback: F,
2983 ) -> Task<Result<T>>
2984 where
2985 T: 'static,
2986 F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
2987 {
2988 if self.project.read(cx).is_local() {
2989 Task::ready(Ok(callback(self, window, cx)))
2990 } else {
2991 let env = self.project.read(cx).cli_environment(cx);
2992 let task = Self::new_local(
2993 Vec::new(),
2994 self.app_state.clone(),
2995 None,
2996 env,
2997 None,
2998 OpenMode::Activate,
2999 cx,
3000 );
3001 cx.spawn_in(window, async move |_vh, cx| {
3002 let OpenResult {
3003 window: multi_workspace_window,
3004 ..
3005 } = task.await?;
3006 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
3007 let workspace = multi_workspace.workspace().clone();
3008 workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
3009 })
3010 })
3011 }
3012 }
3013
3014 /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
3015 ///
3016 /// If the given workspace has a local project, then it will be passed
3017 /// to the callback. Otherwise, a new empty window will be created.
3018 pub fn with_local_or_wsl_workspace<T, F>(
3019 &mut self,
3020 window: &mut Window,
3021 cx: &mut Context<Self>,
3022 callback: F,
3023 ) -> Task<Result<T>>
3024 where
3025 T: 'static,
3026 F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
3027 {
3028 let project = self.project.read(cx);
3029 if project.is_local() || project.is_via_wsl_with_host_interop(cx) {
3030 Task::ready(Ok(callback(self, window, cx)))
3031 } else {
3032 let env = self.project.read(cx).cli_environment(cx);
3033 let task = Self::new_local(
3034 Vec::new(),
3035 self.app_state.clone(),
3036 None,
3037 env,
3038 None,
3039 OpenMode::Activate,
3040 cx,
3041 );
3042 cx.spawn_in(window, async move |_vh, cx| {
3043 let OpenResult {
3044 window: multi_workspace_window,
3045 ..
3046 } = task.await?;
3047 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
3048 let workspace = multi_workspace.workspace().clone();
3049 workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
3050 })
3051 })
3052 }
3053 }
3054
3055 pub fn worktrees<'a>(&self, cx: &'a App) -> impl 'a + Iterator<Item = Entity<Worktree>> {
3056 self.project.read(cx).worktrees(cx)
3057 }
3058
3059 pub fn visible_worktrees<'a>(
3060 &self,
3061 cx: &'a App,
3062 ) -> impl 'a + Iterator<Item = Entity<Worktree>> {
3063 self.project.read(cx).visible_worktrees(cx)
3064 }
3065
3066 pub fn worktree_scans_complete(&self, cx: &App) -> impl Future<Output = ()> + 'static + use<> {
3067 let futures = self
3068 .worktrees(cx)
3069 .filter_map(|worktree| worktree.read(cx).as_local())
3070 .map(|worktree| worktree.scan_complete())
3071 .collect::<Vec<_>>();
3072 async move {
3073 for future in futures {
3074 future.await;
3075 }
3076 }
3077 }
3078
3079 pub fn close_global(cx: &mut App) {
3080 cx.defer(|cx| {
3081 cx.windows().iter().find(|window| {
3082 window
3083 .update(cx, |_, window, _| {
3084 if window.is_window_active() {
3085 //This can only get called when the window's project connection has been lost
3086 //so we don't need to prompt the user for anything and instead just close the window
3087 window.remove_window();
3088 true
3089 } else {
3090 false
3091 }
3092 })
3093 .unwrap_or(false)
3094 });
3095 });
3096 }
3097
3098 pub fn move_focused_panel_to_next_position(
3099 &mut self,
3100 _: &MoveFocusedPanelToNextPosition,
3101 window: &mut Window,
3102 cx: &mut Context<Self>,
3103 ) {
3104 let docks = self.all_docks();
3105 let active_dock = docks
3106 .into_iter()
3107 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
3108
3109 if let Some(dock) = active_dock {
3110 dock.update(cx, |dock, cx| {
3111 let active_panel = dock
3112 .active_panel()
3113 .filter(|panel| panel.panel_focus_handle(cx).contains_focused(window, cx));
3114
3115 if let Some(panel) = active_panel {
3116 panel.move_to_next_position(window, cx);
3117 }
3118 })
3119 }
3120 }
3121
3122 pub fn prepare_to_close(
3123 &mut self,
3124 close_intent: CloseIntent,
3125 window: &mut Window,
3126 cx: &mut Context<Self>,
3127 ) -> Task<Result<bool>> {
3128 let active_call = self.active_global_call();
3129
3130 cx.spawn_in(window, async move |this, cx| {
3131 this.update(cx, |this, _| {
3132 if close_intent == CloseIntent::CloseWindow {
3133 this.removing = true;
3134 }
3135 })?;
3136
3137 let workspace_count = cx.update(|_window, cx| {
3138 cx.windows()
3139 .iter()
3140 .filter(|window| window.downcast::<MultiWorkspace>().is_some())
3141 .count()
3142 })?;
3143
3144 #[cfg(target_os = "macos")]
3145 let save_last_workspace = false;
3146
3147 // On Linux and Windows, closing the last window should restore the last workspace.
3148 #[cfg(not(target_os = "macos"))]
3149 let save_last_workspace = {
3150 let remaining_workspaces = cx.update(|_window, cx| {
3151 cx.windows()
3152 .iter()
3153 .filter_map(|window| window.downcast::<MultiWorkspace>())
3154 .filter_map(|multi_workspace| {
3155 multi_workspace
3156 .update(cx, |multi_workspace, _, cx| {
3157 multi_workspace.workspace().read(cx).removing
3158 })
3159 .ok()
3160 })
3161 .filter(|removing| !removing)
3162 .count()
3163 })?;
3164
3165 close_intent != CloseIntent::ReplaceWindow && remaining_workspaces == 0
3166 };
3167
3168 if let Some(active_call) = active_call
3169 && workspace_count == 1
3170 && cx
3171 .update(|_window, cx| active_call.0.is_in_room(cx))
3172 .unwrap_or(false)
3173 {
3174 if close_intent == CloseIntent::CloseWindow {
3175 this.update(cx, |_, cx| cx.emit(Event::Activate))?;
3176 let answer = cx.update(|window, cx| {
3177 window.prompt(
3178 PromptLevel::Warning,
3179 "Do you want to leave the current call?",
3180 None,
3181 &["Close window and hang up", "Cancel"],
3182 cx,
3183 )
3184 })?;
3185
3186 if answer.await.log_err() == Some(1) {
3187 return anyhow::Ok(false);
3188 } else {
3189 if let Ok(task) = cx.update(|_window, cx| active_call.0.hang_up(cx)) {
3190 task.await.log_err();
3191 }
3192 }
3193 }
3194 if close_intent == CloseIntent::ReplaceWindow {
3195 _ = cx.update(|_window, cx| {
3196 let multi_workspace = cx
3197 .windows()
3198 .iter()
3199 .filter_map(|window| window.downcast::<MultiWorkspace>())
3200 .next()
3201 .unwrap();
3202 let project = multi_workspace
3203 .read(cx)?
3204 .workspace()
3205 .read(cx)
3206 .project
3207 .clone();
3208 if project.read(cx).is_shared() {
3209 active_call.0.unshare_project(project, cx)?;
3210 }
3211 Ok::<_, anyhow::Error>(())
3212 });
3213 }
3214 }
3215
3216 let save_result = this
3217 .update_in(cx, |this, window, cx| {
3218 this.save_all_internal(SaveIntent::Close, window, cx)
3219 })?
3220 .await;
3221
3222 // If we're not quitting, but closing, we remove the workspace from
3223 // the current session.
3224 if close_intent != CloseIntent::Quit
3225 && !save_last_workspace
3226 && save_result.as_ref().is_ok_and(|&res| res)
3227 {
3228 this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))?
3229 .await;
3230 }
3231
3232 save_result
3233 })
3234 }
3235
3236 fn save_all(&mut self, action: &SaveAll, window: &mut Window, cx: &mut Context<Self>) {
3237 self.save_all_internal(
3238 action.save_intent.unwrap_or(SaveIntent::SaveAll),
3239 window,
3240 cx,
3241 )
3242 .detach_and_log_err(cx);
3243 }
3244
3245 fn send_keystrokes(
3246 &mut self,
3247 action: &SendKeystrokes,
3248 window: &mut Window,
3249 cx: &mut Context<Self>,
3250 ) {
3251 let keystrokes: Vec<Keystroke> = action
3252 .0
3253 .split(' ')
3254 .flat_map(|k| Keystroke::parse(k).log_err())
3255 .map(|k| {
3256 cx.keyboard_mapper()
3257 .map_key_equivalent(k, false)
3258 .inner()
3259 .clone()
3260 })
3261 .collect();
3262 let _ = self.send_keystrokes_impl(keystrokes, window, cx);
3263 }
3264
3265 pub fn send_keystrokes_impl(
3266 &mut self,
3267 keystrokes: Vec<Keystroke>,
3268 window: &mut Window,
3269 cx: &mut Context<Self>,
3270 ) -> Shared<Task<()>> {
3271 let mut state = self.dispatching_keystrokes.borrow_mut();
3272 if !state.dispatched.insert(keystrokes.clone()) {
3273 cx.propagate();
3274 return state.task.clone().unwrap();
3275 }
3276
3277 state.queue.extend(keystrokes);
3278
3279 let keystrokes = self.dispatching_keystrokes.clone();
3280 if state.task.is_none() {
3281 state.task = Some(
3282 window
3283 .spawn(cx, async move |cx| {
3284 // limit to 100 keystrokes to avoid infinite recursion.
3285 for _ in 0..100 {
3286 let keystroke = {
3287 let mut state = keystrokes.borrow_mut();
3288 let Some(keystroke) = state.queue.pop_front() else {
3289 state.dispatched.clear();
3290 state.task.take();
3291 return;
3292 };
3293 keystroke
3294 };
3295 cx.update(|window, cx| {
3296 let focused = window.focused(cx);
3297 window.dispatch_keystroke(keystroke.clone(), cx);
3298 if window.focused(cx) != focused {
3299 // dispatch_keystroke may cause the focus to change.
3300 // draw's side effect is to schedule the FocusChanged events in the current flush effect cycle
3301 // And we need that to happen before the next keystroke to keep vim mode happy...
3302 // (Note that the tests always do this implicitly, so you must manually test with something like:
3303 // "bindings": { "g z": ["workspace::SendKeystrokes", ": j <enter> u"]}
3304 // )
3305 window.draw(cx).clear();
3306 }
3307 })
3308 .ok();
3309
3310 // Yield between synthetic keystrokes so deferred focus and
3311 // other effects can settle before dispatching the next key.
3312 yield_now().await;
3313 }
3314
3315 *keystrokes.borrow_mut() = Default::default();
3316 log::error!("over 100 keystrokes passed to send_keystrokes");
3317 })
3318 .shared(),
3319 );
3320 }
3321 state.task.clone().unwrap()
3322 }
3323
3324 fn save_all_internal(
3325 &mut self,
3326 mut save_intent: SaveIntent,
3327 window: &mut Window,
3328 cx: &mut Context<Self>,
3329 ) -> Task<Result<bool>> {
3330 if self.project.read(cx).is_disconnected(cx) {
3331 return Task::ready(Ok(true));
3332 }
3333 let dirty_items = self
3334 .panes
3335 .iter()
3336 .flat_map(|pane| {
3337 pane.read(cx).items().filter_map(|item| {
3338 if item.is_dirty(cx) {
3339 item.tab_content_text(0, cx);
3340 Some((pane.downgrade(), item.boxed_clone()))
3341 } else {
3342 None
3343 }
3344 })
3345 })
3346 .collect::<Vec<_>>();
3347
3348 let project = self.project.clone();
3349 cx.spawn_in(window, async move |workspace, cx| {
3350 let dirty_items = if save_intent == SaveIntent::Close && !dirty_items.is_empty() {
3351 let (serialize_tasks, remaining_dirty_items) =
3352 workspace.update_in(cx, |workspace, window, cx| {
3353 let mut remaining_dirty_items = Vec::new();
3354 let mut serialize_tasks = Vec::new();
3355 for (pane, item) in dirty_items {
3356 if let Some(task) = item
3357 .to_serializable_item_handle(cx)
3358 .and_then(|handle| handle.serialize(workspace, true, window, cx))
3359 {
3360 serialize_tasks.push(task);
3361 } else {
3362 remaining_dirty_items.push((pane, item));
3363 }
3364 }
3365 (serialize_tasks, remaining_dirty_items)
3366 })?;
3367
3368 futures::future::try_join_all(serialize_tasks).await?;
3369
3370 if !remaining_dirty_items.is_empty() {
3371 workspace.update(cx, |_, cx| cx.emit(Event::Activate))?;
3372 }
3373
3374 if remaining_dirty_items.len() > 1 {
3375 let answer = workspace.update_in(cx, |_, window, cx| {
3376 let detail = Pane::file_names_for_prompt(
3377 &mut remaining_dirty_items.iter().map(|(_, handle)| handle),
3378 cx,
3379 );
3380 window.prompt(
3381 PromptLevel::Warning,
3382 "Do you want to save all changes in the following files?",
3383 Some(&detail),
3384 &["Save all", "Discard all", "Cancel"],
3385 cx,
3386 )
3387 })?;
3388 match answer.await.log_err() {
3389 Some(0) => save_intent = SaveIntent::SaveAll,
3390 Some(1) => save_intent = SaveIntent::Skip,
3391 Some(2) => return Ok(false),
3392 _ => {}
3393 }
3394 }
3395
3396 remaining_dirty_items
3397 } else {
3398 dirty_items
3399 };
3400
3401 for (pane, item) in dirty_items {
3402 let (singleton, project_entry_ids) = cx.update(|_, cx| {
3403 (
3404 item.buffer_kind(cx) == ItemBufferKind::Singleton,
3405 item.project_entry_ids(cx),
3406 )
3407 })?;
3408 if (singleton || !project_entry_ids.is_empty())
3409 && !Pane::save_item(project.clone(), &pane, &*item, save_intent, cx).await?
3410 {
3411 return Ok(false);
3412 }
3413 }
3414 Ok(true)
3415 })
3416 }
3417
3418 pub fn open_workspace_for_paths(
3419 &mut self,
3420 // replace_current_window: bool,
3421 mut open_mode: OpenMode,
3422 paths: Vec<PathBuf>,
3423 window: &mut Window,
3424 cx: &mut Context<Self>,
3425 ) -> Task<Result<Entity<Workspace>>> {
3426 let requesting_window = window.window_handle().downcast::<MultiWorkspace>();
3427 let is_remote = self.project.read(cx).is_via_collab();
3428 let has_worktree = self.project.read(cx).worktrees(cx).next().is_some();
3429 let has_dirty_items = self.items(cx).any(|item| item.is_dirty(cx));
3430
3431 let workspace_is_empty = !is_remote && !has_worktree && !has_dirty_items;
3432 if workspace_is_empty {
3433 open_mode = OpenMode::Activate;
3434 }
3435
3436 let app_state = self.app_state.clone();
3437
3438 cx.spawn(async move |_, cx| {
3439 let OpenResult { workspace, .. } = cx
3440 .update(|cx| {
3441 open_paths(
3442 &paths,
3443 app_state,
3444 OpenOptions {
3445 requesting_window,
3446 open_mode,
3447 ..Default::default()
3448 },
3449 cx,
3450 )
3451 })
3452 .await?;
3453 Ok(workspace)
3454 })
3455 }
3456
3457 #[allow(clippy::type_complexity)]
3458 pub fn open_paths(
3459 &mut self,
3460 mut abs_paths: Vec<PathBuf>,
3461 options: OpenOptions,
3462 pane: Option<WeakEntity<Pane>>,
3463 window: &mut Window,
3464 cx: &mut Context<Self>,
3465 ) -> Task<Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>> {
3466 let fs = self.app_state.fs.clone();
3467
3468 let caller_ordered_abs_paths = abs_paths.clone();
3469
3470 // Sort the paths to ensure we add worktrees for parents before their children.
3471 abs_paths.sort_unstable();
3472 cx.spawn_in(window, async move |this, cx| {
3473 let mut tasks = Vec::with_capacity(abs_paths.len());
3474
3475 for abs_path in &abs_paths {
3476 let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
3477 OpenVisible::All => Some(true),
3478 OpenVisible::None => Some(false),
3479 OpenVisible::OnlyFiles => match fs.metadata(abs_path).await.log_err() {
3480 Some(Some(metadata)) => Some(!metadata.is_dir),
3481 Some(None) => Some(true),
3482 None => None,
3483 },
3484 OpenVisible::OnlyDirectories => match fs.metadata(abs_path).await.log_err() {
3485 Some(Some(metadata)) => Some(metadata.is_dir),
3486 Some(None) => Some(false),
3487 None => None,
3488 },
3489 };
3490 let project_path = match visible {
3491 Some(visible) => match this
3492 .update(cx, |this, cx| {
3493 Workspace::project_path_for_path(
3494 this.project.clone(),
3495 abs_path,
3496 visible,
3497 cx,
3498 )
3499 })
3500 .log_err()
3501 {
3502 Some(project_path) => project_path.await.log_err(),
3503 None => None,
3504 },
3505 None => None,
3506 };
3507
3508 let this = this.clone();
3509 let abs_path: Arc<Path> = SanitizedPath::new(&abs_path).as_path().into();
3510 let fs = fs.clone();
3511 let pane = pane.clone();
3512 let task = cx.spawn(async move |cx| {
3513 let (_worktree, project_path) = project_path?;
3514 if fs.is_dir(&abs_path).await {
3515 // Opening a directory should not race to update the active entry.
3516 // We'll select/reveal a deterministic final entry after all paths finish opening.
3517 None
3518 } else {
3519 Some(
3520 this.update_in(cx, |this, window, cx| {
3521 this.open_path(
3522 project_path,
3523 pane,
3524 options.focus.unwrap_or(true),
3525 window,
3526 cx,
3527 )
3528 })
3529 .ok()?
3530 .await,
3531 )
3532 }
3533 });
3534 tasks.push(task);
3535 }
3536
3537 let results = futures::future::join_all(tasks).await;
3538
3539 // Determine the winner using the fake/abstract FS metadata, not `Path::is_dir`.
3540 let mut winner: Option<(PathBuf, bool)> = None;
3541 for abs_path in caller_ordered_abs_paths.into_iter().rev() {
3542 if let Some(Some(metadata)) = fs.metadata(&abs_path).await.log_err() {
3543 if !metadata.is_dir {
3544 winner = Some((abs_path, false));
3545 break;
3546 }
3547 if winner.is_none() {
3548 winner = Some((abs_path, true));
3549 }
3550 } else if winner.is_none() {
3551 winner = Some((abs_path, false));
3552 }
3553 }
3554
3555 // Compute the winner entry id on the foreground thread and emit once, after all
3556 // paths finish opening. This avoids races between concurrently-opening paths
3557 // (directories in particular) and makes the resulting project panel selection
3558 // deterministic.
3559 if let Some((winner_abs_path, winner_is_dir)) = winner {
3560 'emit_winner: {
3561 let winner_abs_path: Arc<Path> =
3562 SanitizedPath::new(&winner_abs_path).as_path().into();
3563
3564 let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
3565 OpenVisible::All => true,
3566 OpenVisible::None => false,
3567 OpenVisible::OnlyFiles => !winner_is_dir,
3568 OpenVisible::OnlyDirectories => winner_is_dir,
3569 };
3570
3571 let Some(worktree_task) = this
3572 .update(cx, |workspace, cx| {
3573 workspace.project.update(cx, |project, cx| {
3574 project.find_or_create_worktree(
3575 winner_abs_path.as_ref(),
3576 visible,
3577 cx,
3578 )
3579 })
3580 })
3581 .ok()
3582 else {
3583 break 'emit_winner;
3584 };
3585
3586 let Ok((worktree, _)) = worktree_task.await else {
3587 break 'emit_winner;
3588 };
3589
3590 let Ok(Some(entry_id)) = this.update(cx, |_, cx| {
3591 let worktree = worktree.read(cx);
3592 let worktree_abs_path = worktree.abs_path();
3593 let entry = if winner_abs_path.as_ref() == worktree_abs_path.as_ref() {
3594 worktree.root_entry()
3595 } else {
3596 winner_abs_path
3597 .strip_prefix(worktree_abs_path.as_ref())
3598 .ok()
3599 .and_then(|relative_path| {
3600 let relative_path =
3601 RelPath::new(relative_path, PathStyle::local())
3602 .log_err()?;
3603 worktree.entry_for_path(&relative_path)
3604 })
3605 }?;
3606 Some(entry.id)
3607 }) else {
3608 break 'emit_winner;
3609 };
3610
3611 this.update(cx, |workspace, cx| {
3612 workspace.project.update(cx, |_, cx| {
3613 cx.emit(project::Event::ActiveEntryChanged(Some(entry_id)));
3614 });
3615 })
3616 .ok();
3617 }
3618 }
3619
3620 results
3621 })
3622 }
3623
3624 pub fn open_resolved_path(
3625 &mut self,
3626 path: ResolvedPath,
3627 window: &mut Window,
3628 cx: &mut Context<Self>,
3629 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3630 match path {
3631 ResolvedPath::ProjectPath { project_path, .. } => {
3632 self.open_path(project_path, None, true, window, cx)
3633 }
3634 ResolvedPath::AbsPath { path, .. } => self.open_abs_path(
3635 PathBuf::from(path),
3636 OpenOptions {
3637 visible: Some(OpenVisible::None),
3638 ..Default::default()
3639 },
3640 window,
3641 cx,
3642 ),
3643 }
3644 }
3645
3646 pub fn absolute_path_of_worktree(
3647 &self,
3648 worktree_id: WorktreeId,
3649 cx: &mut Context<Self>,
3650 ) -> Option<PathBuf> {
3651 self.project
3652 .read(cx)
3653 .worktree_for_id(worktree_id, cx)
3654 // TODO: use `abs_path` or `root_dir`
3655 .map(|wt| wt.read(cx).abs_path().as_ref().to_path_buf())
3656 }
3657
3658 pub fn add_folder_to_project(
3659 &mut self,
3660 _: &AddFolderToProject,
3661 window: &mut Window,
3662 cx: &mut Context<Self>,
3663 ) {
3664 let project = self.project.read(cx);
3665 if project.is_via_collab() {
3666 self.show_error(
3667 &anyhow!("You cannot add folders to someone else's project"),
3668 cx,
3669 );
3670 return;
3671 }
3672 let paths = self.prompt_for_open_path(
3673 PathPromptOptions {
3674 files: false,
3675 directories: true,
3676 multiple: true,
3677 prompt: None,
3678 },
3679 DirectoryLister::Project(self.project.clone()),
3680 window,
3681 cx,
3682 );
3683 cx.spawn_in(window, async move |this, cx| {
3684 if let Some(paths) = paths.await.log_err().flatten() {
3685 let results = this
3686 .update_in(cx, |this, window, cx| {
3687 this.open_paths(
3688 paths,
3689 OpenOptions {
3690 visible: Some(OpenVisible::All),
3691 ..Default::default()
3692 },
3693 None,
3694 window,
3695 cx,
3696 )
3697 })?
3698 .await;
3699 for result in results.into_iter().flatten() {
3700 result.log_err();
3701 }
3702 }
3703 anyhow::Ok(())
3704 })
3705 .detach_and_log_err(cx);
3706 }
3707
3708 pub fn project_path_for_path(
3709 project: Entity<Project>,
3710 abs_path: &Path,
3711 visible: bool,
3712 cx: &mut App,
3713 ) -> Task<Result<(Entity<Worktree>, ProjectPath)>> {
3714 let entry = project.update(cx, |project, cx| {
3715 project.find_or_create_worktree(abs_path, visible, cx)
3716 });
3717 cx.spawn(async move |cx| {
3718 let (worktree, path) = entry.await?;
3719 let worktree_id = worktree.read_with(cx, |t, _| t.id());
3720 Ok((worktree, ProjectPath { worktree_id, path }))
3721 })
3722 }
3723
3724 pub fn items<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = &'a Box<dyn ItemHandle>> {
3725 self.panes.iter().flat_map(|pane| pane.read(cx).items())
3726 }
3727
3728 pub fn item_of_type<T: Item>(&self, cx: &App) -> Option<Entity<T>> {
3729 self.items_of_type(cx).max_by_key(|item| item.item_id())
3730 }
3731
3732 pub fn items_of_type<'a, T: Item>(
3733 &'a self,
3734 cx: &'a App,
3735 ) -> impl 'a + Iterator<Item = Entity<T>> {
3736 self.panes
3737 .iter()
3738 .flat_map(|pane| pane.read(cx).items_of_type())
3739 }
3740
3741 pub fn active_item(&self, cx: &App) -> Option<Box<dyn ItemHandle>> {
3742 self.active_pane().read(cx).active_item()
3743 }
3744
3745 pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
3746 let item = self.active_item(cx)?;
3747 item.to_any_view().downcast::<I>().ok()
3748 }
3749
3750 fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
3751 self.active_item(cx).and_then(|item| item.project_path(cx))
3752 }
3753
3754 pub fn most_recent_active_path(&self, cx: &App) -> Option<PathBuf> {
3755 self.recent_navigation_history_iter(cx)
3756 .filter_map(|(path, abs_path)| {
3757 let worktree = self
3758 .project
3759 .read(cx)
3760 .worktree_for_id(path.worktree_id, cx)?;
3761 if worktree.read(cx).is_visible() {
3762 abs_path
3763 } else {
3764 None
3765 }
3766 })
3767 .next()
3768 }
3769
3770 pub fn save_active_item(
3771 &mut self,
3772 save_intent: SaveIntent,
3773 window: &mut Window,
3774 cx: &mut App,
3775 ) -> Task<Result<()>> {
3776 let project = self.project.clone();
3777 let pane = self.active_pane();
3778 let item = pane.read(cx).active_item();
3779 let pane = pane.downgrade();
3780
3781 window.spawn(cx, async move |cx| {
3782 if let Some(item) = item {
3783 Pane::save_item(project, &pane, item.as_ref(), save_intent, cx)
3784 .await
3785 .map(|_| ())
3786 } else {
3787 Ok(())
3788 }
3789 })
3790 }
3791
3792 pub fn close_inactive_items_and_panes(
3793 &mut self,
3794 action: &CloseInactiveTabsAndPanes,
3795 window: &mut Window,
3796 cx: &mut Context<Self>,
3797 ) {
3798 if let Some(task) = self.close_all_internal(
3799 true,
3800 action.save_intent.unwrap_or(SaveIntent::Close),
3801 window,
3802 cx,
3803 ) {
3804 task.detach_and_log_err(cx)
3805 }
3806 }
3807
3808 pub fn close_all_items_and_panes(
3809 &mut self,
3810 action: &CloseAllItemsAndPanes,
3811 window: &mut Window,
3812 cx: &mut Context<Self>,
3813 ) {
3814 if let Some(task) = self.close_all_internal(
3815 false,
3816 action.save_intent.unwrap_or(SaveIntent::Close),
3817 window,
3818 cx,
3819 ) {
3820 task.detach_and_log_err(cx)
3821 }
3822 }
3823
3824 /// Closes the active item across all panes.
3825 pub fn close_item_in_all_panes(
3826 &mut self,
3827 action: &CloseItemInAllPanes,
3828 window: &mut Window,
3829 cx: &mut Context<Self>,
3830 ) {
3831 let Some(active_item) = self.active_pane().read(cx).active_item() else {
3832 return;
3833 };
3834
3835 let save_intent = action.save_intent.unwrap_or(SaveIntent::Close);
3836 let close_pinned = action.close_pinned;
3837
3838 if let Some(project_path) = active_item.project_path(cx) {
3839 self.close_items_with_project_path(
3840 &project_path,
3841 save_intent,
3842 close_pinned,
3843 window,
3844 cx,
3845 );
3846 } else if close_pinned || !self.active_pane().read(cx).is_active_item_pinned() {
3847 let item_id = active_item.item_id();
3848 self.active_pane().update(cx, |pane, cx| {
3849 pane.close_item_by_id(item_id, save_intent, window, cx)
3850 .detach_and_log_err(cx);
3851 });
3852 }
3853 }
3854
3855 /// Closes all items with the given project path across all panes.
3856 pub fn close_items_with_project_path(
3857 &mut self,
3858 project_path: &ProjectPath,
3859 save_intent: SaveIntent,
3860 close_pinned: bool,
3861 window: &mut Window,
3862 cx: &mut Context<Self>,
3863 ) {
3864 let panes = self.panes().to_vec();
3865 for pane in panes {
3866 pane.update(cx, |pane, cx| {
3867 pane.close_items_for_project_path(
3868 project_path,
3869 save_intent,
3870 close_pinned,
3871 window,
3872 cx,
3873 )
3874 .detach_and_log_err(cx);
3875 });
3876 }
3877 }
3878
3879 fn close_all_internal(
3880 &mut self,
3881 retain_active_pane: bool,
3882 save_intent: SaveIntent,
3883 window: &mut Window,
3884 cx: &mut Context<Self>,
3885 ) -> Option<Task<Result<()>>> {
3886 let current_pane = self.active_pane();
3887
3888 let mut tasks = Vec::new();
3889
3890 if retain_active_pane {
3891 let current_pane_close = current_pane.update(cx, |pane, cx| {
3892 pane.close_other_items(
3893 &CloseOtherItems {
3894 save_intent: None,
3895 close_pinned: false,
3896 },
3897 None,
3898 window,
3899 cx,
3900 )
3901 });
3902
3903 tasks.push(current_pane_close);
3904 }
3905
3906 for pane in self.panes() {
3907 if retain_active_pane && pane.entity_id() == current_pane.entity_id() {
3908 continue;
3909 }
3910
3911 let close_pane_items = pane.update(cx, |pane: &mut Pane, cx| {
3912 pane.close_all_items(
3913 &CloseAllItems {
3914 save_intent: Some(save_intent),
3915 close_pinned: false,
3916 },
3917 window,
3918 cx,
3919 )
3920 });
3921
3922 tasks.push(close_pane_items)
3923 }
3924
3925 if tasks.is_empty() {
3926 None
3927 } else {
3928 Some(cx.spawn_in(window, async move |_, _| {
3929 for task in tasks {
3930 task.await?
3931 }
3932 Ok(())
3933 }))
3934 }
3935 }
3936
3937 pub fn is_dock_at_position_open(&self, position: DockPosition, cx: &mut Context<Self>) -> bool {
3938 self.dock_at_position(position).read(cx).is_open()
3939 }
3940
3941 pub fn toggle_dock(
3942 &mut self,
3943 dock_side: DockPosition,
3944 window: &mut Window,
3945 cx: &mut Context<Self>,
3946 ) {
3947 let mut focus_center = false;
3948 let mut reveal_dock = false;
3949
3950 let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side);
3951 let was_visible = self.is_dock_at_position_open(dock_side, cx) && !other_is_zoomed;
3952
3953 if let Some(panel) = self.dock_at_position(dock_side).read(cx).active_panel() {
3954 telemetry::event!(
3955 "Panel Button Clicked",
3956 name = panel.persistent_name(),
3957 toggle_state = !was_visible
3958 );
3959 }
3960 if was_visible {
3961 self.save_open_dock_positions(cx);
3962 }
3963
3964 let dock = self.dock_at_position(dock_side);
3965 dock.update(cx, |dock, cx| {
3966 dock.set_open(!was_visible, window, cx);
3967
3968 if dock.active_panel().is_none() {
3969 let Some(panel_ix) = dock
3970 .first_enabled_panel_idx(cx)
3971 .log_with_level(log::Level::Info)
3972 else {
3973 return;
3974 };
3975 dock.activate_panel(panel_ix, window, cx);
3976 }
3977
3978 if let Some(active_panel) = dock.active_panel() {
3979 if was_visible {
3980 if active_panel
3981 .panel_focus_handle(cx)
3982 .contains_focused(window, cx)
3983 {
3984 focus_center = true;
3985 }
3986 } else {
3987 let focus_handle = &active_panel.panel_focus_handle(cx);
3988 window.focus(focus_handle, cx);
3989 reveal_dock = true;
3990 }
3991 }
3992 });
3993
3994 if reveal_dock {
3995 self.dismiss_zoomed_items_to_reveal(Some(dock_side), window, cx);
3996 }
3997
3998 if focus_center {
3999 self.active_pane
4000 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
4001 }
4002
4003 cx.notify();
4004 self.serialize_workspace(window, cx);
4005 }
4006
4007 fn active_dock(&self, window: &Window, cx: &Context<Self>) -> Option<&Entity<Dock>> {
4008 self.all_docks().into_iter().find(|&dock| {
4009 dock.read(cx).is_open() && dock.focus_handle(cx).contains_focused(window, cx)
4010 })
4011 }
4012
4013 fn close_active_dock(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
4014 if let Some(dock) = self.active_dock(window, cx).cloned() {
4015 self.save_open_dock_positions(cx);
4016 dock.update(cx, |dock, cx| {
4017 dock.set_open(false, window, cx);
4018 });
4019 return true;
4020 }
4021 false
4022 }
4023
4024 pub fn close_all_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4025 self.save_open_dock_positions(cx);
4026 for dock in self.all_docks() {
4027 dock.update(cx, |dock, cx| {
4028 dock.set_open(false, window, cx);
4029 });
4030 }
4031
4032 cx.focus_self(window);
4033 cx.notify();
4034 self.serialize_workspace(window, cx);
4035 }
4036
4037 fn get_open_dock_positions(&self, cx: &Context<Self>) -> Vec<DockPosition> {
4038 self.all_docks()
4039 .into_iter()
4040 .filter_map(|dock| {
4041 let dock_ref = dock.read(cx);
4042 if dock_ref.is_open() {
4043 Some(dock_ref.position())
4044 } else {
4045 None
4046 }
4047 })
4048 .collect()
4049 }
4050
4051 /// Saves the positions of currently open docks.
4052 ///
4053 /// Updates `last_open_dock_positions` with positions of all currently open
4054 /// docks, to later be restored by the 'Toggle All Docks' action.
4055 fn save_open_dock_positions(&mut self, cx: &mut Context<Self>) {
4056 let open_dock_positions = self.get_open_dock_positions(cx);
4057 if !open_dock_positions.is_empty() {
4058 self.last_open_dock_positions = open_dock_positions;
4059 }
4060 }
4061
4062 /// Toggles all docks between open and closed states.
4063 ///
4064 /// If any docks are open, closes all and remembers their positions. If all
4065 /// docks are closed, restores the last remembered dock configuration.
4066 fn toggle_all_docks(
4067 &mut self,
4068 _: &ToggleAllDocks,
4069 window: &mut Window,
4070 cx: &mut Context<Self>,
4071 ) {
4072 let open_dock_positions = self.get_open_dock_positions(cx);
4073
4074 if !open_dock_positions.is_empty() {
4075 self.close_all_docks(window, cx);
4076 } else if !self.last_open_dock_positions.is_empty() {
4077 self.restore_last_open_docks(window, cx);
4078 }
4079 }
4080
4081 /// Reopens docks from the most recently remembered configuration.
4082 ///
4083 /// Opens all docks whose positions are stored in `last_open_dock_positions`
4084 /// and clears the stored positions.
4085 fn restore_last_open_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4086 let positions_to_open = std::mem::take(&mut self.last_open_dock_positions);
4087
4088 for position in positions_to_open {
4089 let dock = self.dock_at_position(position);
4090 dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
4091 }
4092
4093 cx.focus_self(window);
4094 cx.notify();
4095 self.serialize_workspace(window, cx);
4096 }
4097
4098 /// Transfer focus to the panel of the given type.
4099 pub fn focus_panel<T: Panel>(
4100 &mut self,
4101 window: &mut Window,
4102 cx: &mut Context<Self>,
4103 ) -> Option<Entity<T>> {
4104 let panel = self.focus_or_unfocus_panel::<T>(window, cx, &mut |_, _, _| true)?;
4105 panel.to_any().downcast().ok()
4106 }
4107
4108 /// Focus the panel of the given type if it isn't already focused. If it is
4109 /// already focused, then transfer focus back to the workspace center.
4110 /// When the `close_panel_on_toggle` setting is enabled, also closes the
4111 /// panel when transferring focus back to the center.
4112 pub fn toggle_panel_focus<T: Panel>(
4113 &mut self,
4114 window: &mut Window,
4115 cx: &mut Context<Self>,
4116 ) -> bool {
4117 let mut did_focus_panel = false;
4118 self.focus_or_unfocus_panel::<T>(window, cx, &mut |panel, window, cx| {
4119 did_focus_panel = !panel.panel_focus_handle(cx).contains_focused(window, cx);
4120 did_focus_panel
4121 });
4122
4123 if !did_focus_panel && WorkspaceSettings::get_global(cx).close_panel_on_toggle {
4124 self.close_panel::<T>(window, cx);
4125 }
4126
4127 telemetry::event!(
4128 "Panel Button Clicked",
4129 name = T::persistent_name(),
4130 toggle_state = did_focus_panel
4131 );
4132
4133 did_focus_panel
4134 }
4135
4136 pub fn focus_center_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4137 if let Some(item) = self.active_item(cx) {
4138 item.item_focus_handle(cx).focus(window, cx);
4139 } else {
4140 log::error!("Could not find a focus target when switching focus to the center panes",);
4141 }
4142 }
4143
4144 pub fn activate_panel_for_proto_id(
4145 &mut self,
4146 panel_id: PanelId,
4147 window: &mut Window,
4148 cx: &mut Context<Self>,
4149 ) -> Option<Arc<dyn PanelHandle>> {
4150 let mut panel = None;
4151 for dock in self.all_docks() {
4152 if let Some(panel_index) = dock.read(cx).panel_index_for_proto_id(panel_id) {
4153 panel = dock.update(cx, |dock, cx| {
4154 dock.activate_panel(panel_index, window, cx);
4155 dock.set_open(true, window, cx);
4156 dock.active_panel().cloned()
4157 });
4158 break;
4159 }
4160 }
4161
4162 if panel.is_some() {
4163 cx.notify();
4164 self.serialize_workspace(window, cx);
4165 }
4166
4167 panel
4168 }
4169
4170 /// Focus or unfocus the given panel type, depending on the given callback.
4171 fn focus_or_unfocus_panel<T: Panel>(
4172 &mut self,
4173 window: &mut Window,
4174 cx: &mut Context<Self>,
4175 should_focus: &mut dyn FnMut(&dyn PanelHandle, &mut Window, &mut Context<Dock>) -> bool,
4176 ) -> Option<Arc<dyn PanelHandle>> {
4177 let mut result_panel = None;
4178 let mut serialize = false;
4179 for dock in self.all_docks() {
4180 if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
4181 let mut focus_center = false;
4182 let panel = dock.update(cx, |dock, cx| {
4183 dock.activate_panel(panel_index, window, cx);
4184
4185 let panel = dock.active_panel().cloned();
4186 if let Some(panel) = panel.as_ref() {
4187 if should_focus(&**panel, window, cx) {
4188 dock.set_open(true, window, cx);
4189 panel.panel_focus_handle(cx).focus(window, cx);
4190 } else {
4191 focus_center = true;
4192 }
4193 }
4194 panel
4195 });
4196
4197 if focus_center {
4198 self.active_pane
4199 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
4200 }
4201
4202 result_panel = panel;
4203 serialize = true;
4204 break;
4205 }
4206 }
4207
4208 if serialize {
4209 self.serialize_workspace(window, cx);
4210 }
4211
4212 cx.notify();
4213 result_panel
4214 }
4215
4216 /// Open the panel of the given type
4217 pub fn open_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4218 for dock in self.all_docks() {
4219 if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
4220 dock.update(cx, |dock, cx| {
4221 dock.activate_panel(panel_index, window, cx);
4222 dock.set_open(true, window, cx);
4223 });
4224 }
4225 }
4226 }
4227
4228 /// Open the panel of the given type, dismissing any zoomed items that
4229 /// would obscure it (e.g. a zoomed terminal).
4230 pub fn reveal_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4231 let dock_position = self.all_docks().iter().find_map(|dock| {
4232 let dock = dock.read(cx);
4233 dock.panel_index_for_type::<T>().map(|_| dock.position())
4234 });
4235 self.dismiss_zoomed_items_to_reveal(dock_position, window, cx);
4236 self.open_panel::<T>(window, cx);
4237 }
4238
4239 pub fn close_panel<T: Panel>(&self, window: &mut Window, cx: &mut Context<Self>) {
4240 for dock in self.all_docks().iter() {
4241 dock.update(cx, |dock, cx| {
4242 if dock.panel::<T>().is_some() {
4243 dock.set_open(false, window, cx)
4244 }
4245 })
4246 }
4247 }
4248
4249 pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
4250 self.all_docks()
4251 .iter()
4252 .find_map(|dock| dock.read(cx).panel::<T>())
4253 }
4254
4255 fn dismiss_zoomed_items_to_reveal(
4256 &mut self,
4257 dock_to_reveal: Option<DockPosition>,
4258 window: &mut Window,
4259 cx: &mut Context<Self>,
4260 ) {
4261 // If a center pane is zoomed, unzoom it.
4262 for pane in &self.panes {
4263 if pane != &self.active_pane || dock_to_reveal.is_some() {
4264 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
4265 }
4266 }
4267
4268 // If another dock is zoomed, hide it.
4269 let mut focus_center = false;
4270 for dock in self.all_docks() {
4271 dock.update(cx, |dock, cx| {
4272 if Some(dock.position()) != dock_to_reveal
4273 && let Some(panel) = dock.active_panel()
4274 && panel.is_zoomed(window, cx)
4275 {
4276 focus_center |= panel.panel_focus_handle(cx).contains_focused(window, cx);
4277 dock.set_open(false, window, cx);
4278 }
4279 });
4280 }
4281
4282 if focus_center {
4283 self.active_pane
4284 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
4285 }
4286
4287 if self.zoomed_position != dock_to_reveal {
4288 self.zoomed = None;
4289 self.zoomed_position = None;
4290 cx.emit(Event::ZoomChanged);
4291 }
4292
4293 cx.notify();
4294 }
4295
4296 fn add_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
4297 let pane = cx.new(|cx| {
4298 let mut pane = Pane::new(
4299 self.weak_handle(),
4300 self.project.clone(),
4301 self.pane_history_timestamp.clone(),
4302 None,
4303 NewFile.boxed_clone(),
4304 true,
4305 window,
4306 cx,
4307 );
4308 pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
4309 pane
4310 });
4311 cx.subscribe_in(&pane, window, Self::handle_pane_event)
4312 .detach();
4313 self.panes.push(pane.clone());
4314
4315 window.focus(&pane.focus_handle(cx), cx);
4316
4317 cx.emit(Event::PaneAdded(pane.clone()));
4318 pane
4319 }
4320
4321 pub fn add_item_to_center(
4322 &mut self,
4323 item: Box<dyn ItemHandle>,
4324 window: &mut Window,
4325 cx: &mut Context<Self>,
4326 ) -> bool {
4327 if let Some(center_pane) = self.last_active_center_pane.clone() {
4328 if let Some(center_pane) = center_pane.upgrade() {
4329 center_pane.update(cx, |pane, cx| {
4330 pane.add_item(item, true, true, None, window, cx)
4331 });
4332 true
4333 } else {
4334 false
4335 }
4336 } else {
4337 false
4338 }
4339 }
4340
4341 pub fn add_item_to_active_pane(
4342 &mut self,
4343 item: Box<dyn ItemHandle>,
4344 destination_index: Option<usize>,
4345 focus_item: bool,
4346 window: &mut Window,
4347 cx: &mut App,
4348 ) {
4349 self.add_item(
4350 self.active_pane.clone(),
4351 item,
4352 destination_index,
4353 false,
4354 focus_item,
4355 window,
4356 cx,
4357 )
4358 }
4359
4360 pub fn add_item(
4361 &mut self,
4362 pane: Entity<Pane>,
4363 item: Box<dyn ItemHandle>,
4364 destination_index: Option<usize>,
4365 activate_pane: bool,
4366 focus_item: bool,
4367 window: &mut Window,
4368 cx: &mut App,
4369 ) {
4370 pane.update(cx, |pane, cx| {
4371 pane.add_item(
4372 item,
4373 activate_pane,
4374 focus_item,
4375 destination_index,
4376 window,
4377 cx,
4378 )
4379 });
4380 }
4381
4382 pub fn split_item(
4383 &mut self,
4384 split_direction: SplitDirection,
4385 item: Box<dyn ItemHandle>,
4386 window: &mut Window,
4387 cx: &mut Context<Self>,
4388 ) {
4389 let new_pane = self.split_pane(self.active_pane.clone(), split_direction, window, cx);
4390 self.add_item(new_pane, item, None, true, true, window, cx);
4391 }
4392
4393 pub fn open_abs_path(
4394 &mut self,
4395 abs_path: PathBuf,
4396 options: OpenOptions,
4397 window: &mut Window,
4398 cx: &mut Context<Self>,
4399 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4400 cx.spawn_in(window, async move |workspace, cx| {
4401 let open_paths_task_result = workspace
4402 .update_in(cx, |workspace, window, cx| {
4403 workspace.open_paths(vec![abs_path.clone()], options, None, window, cx)
4404 })
4405 .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
4406 .await;
4407 anyhow::ensure!(
4408 open_paths_task_result.len() == 1,
4409 "open abs path {abs_path:?} task returned incorrect number of results"
4410 );
4411 match open_paths_task_result
4412 .into_iter()
4413 .next()
4414 .expect("ensured single task result")
4415 {
4416 Some(open_result) => {
4417 open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
4418 }
4419 None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
4420 }
4421 })
4422 }
4423
4424 pub fn split_abs_path(
4425 &mut self,
4426 abs_path: PathBuf,
4427 visible: bool,
4428 window: &mut Window,
4429 cx: &mut Context<Self>,
4430 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4431 let project_path_task =
4432 Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
4433 cx.spawn_in(window, async move |this, cx| {
4434 let (_, path) = project_path_task.await?;
4435 this.update_in(cx, |this, window, cx| this.split_path(path, window, cx))?
4436 .await
4437 })
4438 }
4439
4440 pub fn open_path(
4441 &mut self,
4442 path: impl Into<ProjectPath>,
4443 pane: Option<WeakEntity<Pane>>,
4444 focus_item: bool,
4445 window: &mut Window,
4446 cx: &mut App,
4447 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4448 self.open_path_preview(path, pane, focus_item, false, true, window, cx)
4449 }
4450
4451 pub fn open_path_preview(
4452 &mut self,
4453 path: impl Into<ProjectPath>,
4454 pane: Option<WeakEntity<Pane>>,
4455 focus_item: bool,
4456 allow_preview: bool,
4457 activate: bool,
4458 window: &mut Window,
4459 cx: &mut App,
4460 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4461 let pane = pane.unwrap_or_else(|| {
4462 self.last_active_center_pane.clone().unwrap_or_else(|| {
4463 self.panes
4464 .first()
4465 .expect("There must be an active pane")
4466 .downgrade()
4467 })
4468 });
4469
4470 let project_path = path.into();
4471 let task = self.load_path(project_path.clone(), window, cx);
4472 window.spawn(cx, async move |cx| {
4473 let (project_entry_id, build_item) = task.await?;
4474
4475 pane.update_in(cx, |pane, window, cx| {
4476 pane.open_item(
4477 project_entry_id,
4478 project_path,
4479 focus_item,
4480 allow_preview,
4481 activate,
4482 None,
4483 window,
4484 cx,
4485 build_item,
4486 )
4487 })
4488 })
4489 }
4490
4491 pub fn split_path(
4492 &mut self,
4493 path: impl Into<ProjectPath>,
4494 window: &mut Window,
4495 cx: &mut Context<Self>,
4496 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4497 self.split_path_preview(path, false, None, window, cx)
4498 }
4499
4500 pub fn split_path_preview(
4501 &mut self,
4502 path: impl Into<ProjectPath>,
4503 allow_preview: bool,
4504 split_direction: Option<SplitDirection>,
4505 window: &mut Window,
4506 cx: &mut Context<Self>,
4507 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4508 let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
4509 self.panes
4510 .first()
4511 .expect("There must be an active pane")
4512 .downgrade()
4513 });
4514
4515 if let Member::Pane(center_pane) = &self.center.root
4516 && center_pane.read(cx).items_len() == 0
4517 {
4518 return self.open_path(path, Some(pane), true, window, cx);
4519 }
4520
4521 let project_path = path.into();
4522 let task = self.load_path(project_path.clone(), window, cx);
4523 cx.spawn_in(window, async move |this, cx| {
4524 let (project_entry_id, build_item) = task.await?;
4525 this.update_in(cx, move |this, window, cx| -> Option<_> {
4526 let pane = pane.upgrade()?;
4527 let new_pane = this.split_pane(
4528 pane,
4529 split_direction.unwrap_or(SplitDirection::Right),
4530 window,
4531 cx,
4532 );
4533 new_pane.update(cx, |new_pane, cx| {
4534 Some(new_pane.open_item(
4535 project_entry_id,
4536 project_path,
4537 true,
4538 allow_preview,
4539 true,
4540 None,
4541 window,
4542 cx,
4543 build_item,
4544 ))
4545 })
4546 })
4547 .map(|option| option.context("pane was dropped"))?
4548 })
4549 }
4550
4551 fn load_path(
4552 &mut self,
4553 path: ProjectPath,
4554 window: &mut Window,
4555 cx: &mut App,
4556 ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
4557 let registry = cx.default_global::<ProjectItemRegistry>().clone();
4558 registry.open_path(self.project(), &path, window, cx)
4559 }
4560
4561 pub fn find_project_item<T>(
4562 &self,
4563 pane: &Entity<Pane>,
4564 project_item: &Entity<T::Item>,
4565 cx: &App,
4566 ) -> Option<Entity<T>>
4567 where
4568 T: ProjectItem,
4569 {
4570 use project::ProjectItem as _;
4571 let project_item = project_item.read(cx);
4572 let entry_id = project_item.entry_id(cx);
4573 let project_path = project_item.project_path(cx);
4574
4575 let mut item = None;
4576 if let Some(entry_id) = entry_id {
4577 item = pane.read(cx).item_for_entry(entry_id, cx);
4578 }
4579 if item.is_none()
4580 && let Some(project_path) = project_path
4581 {
4582 item = pane.read(cx).item_for_path(project_path, cx);
4583 }
4584
4585 item.and_then(|item| item.downcast::<T>())
4586 }
4587
4588 pub fn is_project_item_open<T>(
4589 &self,
4590 pane: &Entity<Pane>,
4591 project_item: &Entity<T::Item>,
4592 cx: &App,
4593 ) -> bool
4594 where
4595 T: ProjectItem,
4596 {
4597 self.find_project_item::<T>(pane, project_item, cx)
4598 .is_some()
4599 }
4600
4601 pub fn open_project_item<T>(
4602 &mut self,
4603 pane: Entity<Pane>,
4604 project_item: Entity<T::Item>,
4605 activate_pane: bool,
4606 focus_item: bool,
4607 keep_old_preview: bool,
4608 allow_new_preview: bool,
4609 window: &mut Window,
4610 cx: &mut Context<Self>,
4611 ) -> Entity<T>
4612 where
4613 T: ProjectItem,
4614 {
4615 let old_item_id = pane.read(cx).active_item().map(|item| item.item_id());
4616
4617 if let Some(item) = self.find_project_item(&pane, &project_item, cx) {
4618 if !keep_old_preview
4619 && let Some(old_id) = old_item_id
4620 && old_id != item.item_id()
4621 {
4622 // switching to a different item, so unpreview old active item
4623 pane.update(cx, |pane, _| {
4624 pane.unpreview_item_if_preview(old_id);
4625 });
4626 }
4627
4628 self.activate_item(&item, activate_pane, focus_item, window, cx);
4629 if !allow_new_preview {
4630 pane.update(cx, |pane, _| {
4631 pane.unpreview_item_if_preview(item.item_id());
4632 });
4633 }
4634 return item;
4635 }
4636
4637 let item = pane.update(cx, |pane, cx| {
4638 cx.new(|cx| {
4639 T::for_project_item(self.project().clone(), Some(pane), project_item, window, cx)
4640 })
4641 });
4642 let mut destination_index = None;
4643 pane.update(cx, |pane, cx| {
4644 if !keep_old_preview && let Some(old_id) = old_item_id {
4645 pane.unpreview_item_if_preview(old_id);
4646 }
4647 if allow_new_preview {
4648 destination_index = pane.replace_preview_item_id(item.item_id(), window, cx);
4649 }
4650 });
4651
4652 self.add_item(
4653 pane,
4654 Box::new(item.clone()),
4655 destination_index,
4656 activate_pane,
4657 focus_item,
4658 window,
4659 cx,
4660 );
4661 item
4662 }
4663
4664 pub fn open_shared_screen(
4665 &mut self,
4666 peer_id: PeerId,
4667 window: &mut Window,
4668 cx: &mut Context<Self>,
4669 ) {
4670 if let Some(shared_screen) =
4671 self.shared_screen_for_peer(peer_id, &self.active_pane, window, cx)
4672 {
4673 self.active_pane.update(cx, |pane, cx| {
4674 pane.add_item(Box::new(shared_screen), false, true, None, window, cx)
4675 });
4676 }
4677 }
4678
4679 pub fn activate_item(
4680 &mut self,
4681 item: &dyn ItemHandle,
4682 activate_pane: bool,
4683 focus_item: bool,
4684 window: &mut Window,
4685 cx: &mut App,
4686 ) -> bool {
4687 let result = self.panes.iter().find_map(|pane| {
4688 pane.read(cx)
4689 .index_for_item(item)
4690 .map(|ix| (pane.clone(), ix))
4691 });
4692 if let Some((pane, ix)) = result {
4693 pane.update(cx, |pane, cx| {
4694 pane.activate_item(ix, activate_pane, focus_item, window, cx)
4695 });
4696 true
4697 } else {
4698 false
4699 }
4700 }
4701
4702 fn activate_pane_at_index(
4703 &mut self,
4704 action: &ActivatePane,
4705 window: &mut Window,
4706 cx: &mut Context<Self>,
4707 ) {
4708 let panes = self.center.panes();
4709 if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
4710 window.focus(&pane.focus_handle(cx), cx);
4711 } else {
4712 self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, window, cx)
4713 .detach();
4714 }
4715 }
4716
4717 fn move_item_to_pane_at_index(
4718 &mut self,
4719 action: &MoveItemToPane,
4720 window: &mut Window,
4721 cx: &mut Context<Self>,
4722 ) {
4723 let panes = self.center.panes();
4724 let destination = match panes.get(action.destination) {
4725 Some(&destination) => destination.clone(),
4726 None => {
4727 if !action.clone && self.active_pane.read(cx).items_len() < 2 {
4728 return;
4729 }
4730 let direction = SplitDirection::Right;
4731 let split_off_pane = self
4732 .find_pane_in_direction(direction, cx)
4733 .unwrap_or_else(|| self.active_pane.clone());
4734 let new_pane = self.add_pane(window, cx);
4735 self.center.split(&split_off_pane, &new_pane, direction, cx);
4736 new_pane
4737 }
4738 };
4739
4740 if action.clone {
4741 if self
4742 .active_pane
4743 .read(cx)
4744 .active_item()
4745 .is_some_and(|item| item.can_split(cx))
4746 {
4747 clone_active_item(
4748 self.database_id(),
4749 &self.active_pane,
4750 &destination,
4751 action.focus,
4752 window,
4753 cx,
4754 );
4755 return;
4756 }
4757 }
4758 move_active_item(
4759 &self.active_pane,
4760 &destination,
4761 action.focus,
4762 true,
4763 window,
4764 cx,
4765 )
4766 }
4767
4768 pub fn activate_next_pane(&mut self, window: &mut Window, cx: &mut App) {
4769 let panes = self.center.panes();
4770 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
4771 let next_ix = (ix + 1) % panes.len();
4772 let next_pane = panes[next_ix].clone();
4773 window.focus(&next_pane.focus_handle(cx), cx);
4774 }
4775 }
4776
4777 pub fn activate_previous_pane(&mut self, window: &mut Window, cx: &mut App) {
4778 let panes = self.center.panes();
4779 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
4780 let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
4781 let prev_pane = panes[prev_ix].clone();
4782 window.focus(&prev_pane.focus_handle(cx), cx);
4783 }
4784 }
4785
4786 pub fn activate_last_pane(&mut self, window: &mut Window, cx: &mut App) {
4787 let last_pane = self.center.last_pane();
4788 window.focus(&last_pane.focus_handle(cx), cx);
4789 }
4790
4791 pub fn activate_pane_in_direction(
4792 &mut self,
4793 direction: SplitDirection,
4794 window: &mut Window,
4795 cx: &mut App,
4796 ) {
4797 use ActivateInDirectionTarget as Target;
4798 enum Origin {
4799 Sidebar,
4800 LeftDock,
4801 RightDock,
4802 BottomDock,
4803 Center,
4804 }
4805
4806 let origin: Origin = if self
4807 .sidebar_focus_handle
4808 .as_ref()
4809 .is_some_and(|h| h.contains_focused(window, cx))
4810 {
4811 Origin::Sidebar
4812 } else {
4813 [
4814 (&self.left_dock, Origin::LeftDock),
4815 (&self.right_dock, Origin::RightDock),
4816 (&self.bottom_dock, Origin::BottomDock),
4817 ]
4818 .into_iter()
4819 .find_map(|(dock, origin)| {
4820 if dock.focus_handle(cx).contains_focused(window, cx) && dock.read(cx).is_open() {
4821 Some(origin)
4822 } else {
4823 None
4824 }
4825 })
4826 .unwrap_or(Origin::Center)
4827 };
4828
4829 let get_last_active_pane = || {
4830 let pane = self
4831 .last_active_center_pane
4832 .clone()
4833 .unwrap_or_else(|| {
4834 self.panes
4835 .first()
4836 .expect("There must be an active pane")
4837 .downgrade()
4838 })
4839 .upgrade()?;
4840 (pane.read(cx).items_len() != 0).then_some(pane)
4841 };
4842
4843 let try_dock =
4844 |dock: &Entity<Dock>| dock.read(cx).is_open().then(|| Target::Dock(dock.clone()));
4845
4846 let sidebar_target = self
4847 .sidebar_focus_handle
4848 .as_ref()
4849 .map(|h| Target::Sidebar(h.clone()));
4850
4851 let target = match (origin, direction) {
4852 // From the sidebar, only Right navigates into the workspace.
4853 (Origin::Sidebar, SplitDirection::Right) => try_dock(&self.left_dock)
4854 .or_else(|| get_last_active_pane().map(Target::Pane))
4855 .or_else(|| try_dock(&self.bottom_dock))
4856 .or_else(|| try_dock(&self.right_dock)),
4857
4858 (Origin::Sidebar, _) => None,
4859
4860 // We're in the center, so we first try to go to a different pane,
4861 // otherwise try to go to a dock.
4862 (Origin::Center, direction) => {
4863 if let Some(pane) = self.find_pane_in_direction(direction, cx) {
4864 Some(Target::Pane(pane))
4865 } else {
4866 match direction {
4867 SplitDirection::Up => None,
4868 SplitDirection::Down => try_dock(&self.bottom_dock),
4869 SplitDirection::Left => try_dock(&self.left_dock).or(sidebar_target),
4870 SplitDirection::Right => try_dock(&self.right_dock),
4871 }
4872 }
4873 }
4874
4875 (Origin::LeftDock, SplitDirection::Right) => {
4876 if let Some(last_active_pane) = get_last_active_pane() {
4877 Some(Target::Pane(last_active_pane))
4878 } else {
4879 try_dock(&self.bottom_dock).or_else(|| try_dock(&self.right_dock))
4880 }
4881 }
4882
4883 (Origin::LeftDock, SplitDirection::Left) => sidebar_target,
4884
4885 (Origin::LeftDock, SplitDirection::Down)
4886 | (Origin::RightDock, SplitDirection::Down) => try_dock(&self.bottom_dock),
4887
4888 (Origin::BottomDock, SplitDirection::Up) => get_last_active_pane().map(Target::Pane),
4889 (Origin::BottomDock, SplitDirection::Left) => {
4890 try_dock(&self.left_dock).or(sidebar_target)
4891 }
4892 (Origin::BottomDock, SplitDirection::Right) => try_dock(&self.right_dock),
4893
4894 (Origin::RightDock, SplitDirection::Left) => {
4895 if let Some(last_active_pane) = get_last_active_pane() {
4896 Some(Target::Pane(last_active_pane))
4897 } else {
4898 try_dock(&self.bottom_dock)
4899 .or_else(|| try_dock(&self.left_dock))
4900 .or(sidebar_target)
4901 }
4902 }
4903
4904 _ => None,
4905 };
4906
4907 match target {
4908 Some(ActivateInDirectionTarget::Pane(pane)) => {
4909 let pane = pane.read(cx);
4910 if let Some(item) = pane.active_item() {
4911 item.item_focus_handle(cx).focus(window, cx);
4912 } else {
4913 log::error!(
4914 "Could not find a focus target when in switching focus in {direction} direction for a pane",
4915 );
4916 }
4917 }
4918 Some(ActivateInDirectionTarget::Dock(dock)) => {
4919 // Defer this to avoid a panic when the dock's active panel is already on the stack.
4920 window.defer(cx, move |window, cx| {
4921 let dock = dock.read(cx);
4922 if let Some(panel) = dock.active_panel() {
4923 panel.panel_focus_handle(cx).focus(window, cx);
4924 } else {
4925 log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
4926 }
4927 })
4928 }
4929 Some(ActivateInDirectionTarget::Sidebar(focus_handle)) => {
4930 focus_handle.focus(window, cx);
4931 }
4932 None => {}
4933 }
4934 }
4935
4936 pub fn move_item_to_pane_in_direction(
4937 &mut self,
4938 action: &MoveItemToPaneInDirection,
4939 window: &mut Window,
4940 cx: &mut Context<Self>,
4941 ) {
4942 let destination = match self.find_pane_in_direction(action.direction, cx) {
4943 Some(destination) => destination,
4944 None => {
4945 if !action.clone && self.active_pane.read(cx).items_len() < 2 {
4946 return;
4947 }
4948 let new_pane = self.add_pane(window, cx);
4949 self.center
4950 .split(&self.active_pane, &new_pane, action.direction, cx);
4951 new_pane
4952 }
4953 };
4954
4955 if action.clone {
4956 if self
4957 .active_pane
4958 .read(cx)
4959 .active_item()
4960 .is_some_and(|item| item.can_split(cx))
4961 {
4962 clone_active_item(
4963 self.database_id(),
4964 &self.active_pane,
4965 &destination,
4966 action.focus,
4967 window,
4968 cx,
4969 );
4970 return;
4971 }
4972 }
4973 move_active_item(
4974 &self.active_pane,
4975 &destination,
4976 action.focus,
4977 true,
4978 window,
4979 cx,
4980 );
4981 }
4982
4983 pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
4984 self.center.bounding_box_for_pane(pane)
4985 }
4986
4987 pub fn find_pane_in_direction(
4988 &mut self,
4989 direction: SplitDirection,
4990 cx: &App,
4991 ) -> Option<Entity<Pane>> {
4992 self.center
4993 .find_pane_in_direction(&self.active_pane, direction, cx)
4994 .cloned()
4995 }
4996
4997 pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
4998 if let Some(to) = self.find_pane_in_direction(direction, cx) {
4999 self.center.swap(&self.active_pane, &to, cx);
5000 cx.notify();
5001 }
5002 }
5003
5004 pub fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
5005 if self
5006 .center
5007 .move_to_border(&self.active_pane, direction, cx)
5008 .unwrap()
5009 {
5010 cx.notify();
5011 }
5012 }
5013
5014 pub fn resize_pane(
5015 &mut self,
5016 axis: gpui::Axis,
5017 amount: Pixels,
5018 window: &mut Window,
5019 cx: &mut Context<Self>,
5020 ) {
5021 let docks = self.all_docks();
5022 let active_dock = docks
5023 .into_iter()
5024 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
5025
5026 if let Some(dock_entity) = active_dock {
5027 let dock = dock_entity.read(cx);
5028 let Some(panel_size) = self.dock_size(&dock, window, cx) else {
5029 return;
5030 };
5031 match dock.position() {
5032 DockPosition::Left => self.resize_left_dock(panel_size + amount, window, cx),
5033 DockPosition::Bottom => self.resize_bottom_dock(panel_size + amount, window, cx),
5034 DockPosition::Right => self.resize_right_dock(panel_size + amount, window, cx),
5035 }
5036 } else {
5037 self.center
5038 .resize(&self.active_pane, axis, amount, &self.bounds, cx);
5039 }
5040 cx.notify();
5041 }
5042
5043 pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
5044 self.center.reset_pane_sizes(cx);
5045 cx.notify();
5046 }
5047
5048 fn handle_pane_focused(
5049 &mut self,
5050 pane: Entity<Pane>,
5051 window: &mut Window,
5052 cx: &mut Context<Self>,
5053 ) {
5054 // This is explicitly hoisted out of the following check for pane identity as
5055 // terminal panel panes are not registered as a center panes.
5056 self.status_bar.update(cx, |status_bar, cx| {
5057 status_bar.set_active_pane(&pane, window, cx);
5058 });
5059 if self.active_pane != pane {
5060 self.set_active_pane(&pane, window, cx);
5061 }
5062
5063 if self.last_active_center_pane.is_none() {
5064 self.last_active_center_pane = Some(pane.downgrade());
5065 }
5066
5067 // If this pane is in a dock, preserve that dock when dismissing zoomed items.
5068 // This prevents the dock from closing when focus events fire during window activation.
5069 // We also preserve any dock whose active panel itself has focus — this covers
5070 // panels like AgentPanel that don't implement `pane()` but can still be zoomed.
5071 let dock_to_preserve = self.all_docks().iter().find_map(|dock| {
5072 let dock_read = dock.read(cx);
5073 if let Some(panel) = dock_read.active_panel() {
5074 if panel.pane(cx).is_some_and(|dock_pane| dock_pane == pane)
5075 || panel.panel_focus_handle(cx).contains_focused(window, cx)
5076 {
5077 return Some(dock_read.position());
5078 }
5079 }
5080 None
5081 });
5082
5083 self.dismiss_zoomed_items_to_reveal(dock_to_preserve, window, cx);
5084 if pane.read(cx).is_zoomed() {
5085 self.zoomed = Some(pane.downgrade().into());
5086 } else {
5087 self.zoomed = None;
5088 }
5089 self.zoomed_position = None;
5090 cx.emit(Event::ZoomChanged);
5091 self.update_active_view_for_followers(window, cx);
5092 pane.update(cx, |pane, _| {
5093 pane.track_alternate_file_items();
5094 });
5095
5096 cx.notify();
5097 }
5098
5099 fn set_active_pane(
5100 &mut self,
5101 pane: &Entity<Pane>,
5102 window: &mut Window,
5103 cx: &mut Context<Self>,
5104 ) {
5105 self.active_pane = pane.clone();
5106 self.active_item_path_changed(true, window, cx);
5107 self.last_active_center_pane = Some(pane.downgrade());
5108 }
5109
5110 fn handle_panel_focused(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5111 self.update_active_view_for_followers(window, cx);
5112 }
5113
5114 fn handle_pane_event(
5115 &mut self,
5116 pane: &Entity<Pane>,
5117 event: &pane::Event,
5118 window: &mut Window,
5119 cx: &mut Context<Self>,
5120 ) {
5121 let mut serialize_workspace = true;
5122 match event {
5123 pane::Event::AddItem { item } => {
5124 item.added_to_pane(self, pane.clone(), window, cx);
5125 cx.emit(Event::ItemAdded {
5126 item: item.boxed_clone(),
5127 });
5128 }
5129 pane::Event::Split { direction, mode } => {
5130 match mode {
5131 SplitMode::ClonePane => {
5132 self.split_and_clone(pane.clone(), *direction, window, cx)
5133 .detach();
5134 }
5135 SplitMode::EmptyPane => {
5136 self.split_pane(pane.clone(), *direction, window, cx);
5137 }
5138 SplitMode::MovePane => {
5139 self.split_and_move(pane.clone(), *direction, window, cx);
5140 }
5141 };
5142 }
5143 pane::Event::JoinIntoNext => {
5144 self.join_pane_into_next(pane.clone(), window, cx);
5145 }
5146 pane::Event::JoinAll => {
5147 self.join_all_panes(window, cx);
5148 }
5149 pane::Event::Remove { focus_on_pane } => {
5150 self.remove_pane(pane.clone(), focus_on_pane.clone(), window, cx);
5151 }
5152 pane::Event::ActivateItem {
5153 local,
5154 focus_changed,
5155 } => {
5156 window.invalidate_character_coordinates();
5157
5158 pane.update(cx, |pane, _| {
5159 pane.track_alternate_file_items();
5160 });
5161 if *local {
5162 self.unfollow_in_pane(pane, window, cx);
5163 }
5164 serialize_workspace = *focus_changed || pane != self.active_pane();
5165 if pane == self.active_pane() {
5166 self.active_item_path_changed(*focus_changed, window, cx);
5167 self.update_active_view_for_followers(window, cx);
5168 } else if *local {
5169 self.set_active_pane(pane, window, cx);
5170 }
5171 }
5172 pane::Event::UserSavedItem { item, save_intent } => {
5173 cx.emit(Event::UserSavedItem {
5174 pane: pane.downgrade(),
5175 item: item.boxed_clone(),
5176 save_intent: *save_intent,
5177 });
5178 serialize_workspace = false;
5179 }
5180 pane::Event::ChangeItemTitle => {
5181 if *pane == self.active_pane {
5182 self.active_item_path_changed(false, window, cx);
5183 }
5184 serialize_workspace = false;
5185 }
5186 pane::Event::RemovedItem { item } => {
5187 cx.emit(Event::ActiveItemChanged);
5188 self.update_window_edited(window, cx);
5189 if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(item.item_id())
5190 && entry.get().entity_id() == pane.entity_id()
5191 {
5192 entry.remove();
5193 }
5194 cx.emit(Event::ItemRemoved {
5195 item_id: item.item_id(),
5196 });
5197 }
5198 pane::Event::Focus => {
5199 window.invalidate_character_coordinates();
5200 self.handle_pane_focused(pane.clone(), window, cx);
5201 }
5202 pane::Event::ZoomIn => {
5203 if *pane == self.active_pane {
5204 pane.update(cx, |pane, cx| pane.set_zoomed(true, cx));
5205 if pane.read(cx).has_focus(window, cx) {
5206 self.zoomed = Some(pane.downgrade().into());
5207 self.zoomed_position = None;
5208 cx.emit(Event::ZoomChanged);
5209 }
5210 cx.notify();
5211 }
5212 }
5213 pane::Event::ZoomOut => {
5214 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
5215 if self.zoomed_position.is_none() {
5216 self.zoomed = None;
5217 cx.emit(Event::ZoomChanged);
5218 }
5219 cx.notify();
5220 }
5221 pane::Event::ItemPinned | pane::Event::ItemUnpinned => {}
5222 }
5223
5224 if serialize_workspace {
5225 self.serialize_workspace(window, cx);
5226 }
5227 }
5228
5229 pub fn unfollow_in_pane(
5230 &mut self,
5231 pane: &Entity<Pane>,
5232 window: &mut Window,
5233 cx: &mut Context<Workspace>,
5234 ) -> Option<CollaboratorId> {
5235 let leader_id = self.leader_for_pane(pane)?;
5236 self.unfollow(leader_id, window, cx);
5237 Some(leader_id)
5238 }
5239
5240 pub fn split_pane(
5241 &mut self,
5242 pane_to_split: Entity<Pane>,
5243 split_direction: SplitDirection,
5244 window: &mut Window,
5245 cx: &mut Context<Self>,
5246 ) -> Entity<Pane> {
5247 let new_pane = self.add_pane(window, cx);
5248 self.center
5249 .split(&pane_to_split, &new_pane, split_direction, cx);
5250 cx.notify();
5251 new_pane
5252 }
5253
5254 pub fn split_and_move(
5255 &mut self,
5256 pane: Entity<Pane>,
5257 direction: SplitDirection,
5258 window: &mut Window,
5259 cx: &mut Context<Self>,
5260 ) {
5261 let Some(item) = pane.update(cx, |pane, cx| pane.take_active_item(window, cx)) else {
5262 return;
5263 };
5264 let new_pane = self.add_pane(window, cx);
5265 new_pane.update(cx, |pane, cx| {
5266 pane.add_item(item, true, true, None, window, cx)
5267 });
5268 self.center.split(&pane, &new_pane, direction, cx);
5269 cx.notify();
5270 }
5271
5272 pub fn split_and_clone(
5273 &mut self,
5274 pane: Entity<Pane>,
5275 direction: SplitDirection,
5276 window: &mut Window,
5277 cx: &mut Context<Self>,
5278 ) -> Task<Option<Entity<Pane>>> {
5279 let Some(item) = pane.read(cx).active_item() else {
5280 return Task::ready(None);
5281 };
5282 if !item.can_split(cx) {
5283 return Task::ready(None);
5284 }
5285 let task = item.clone_on_split(self.database_id(), window, cx);
5286 cx.spawn_in(window, async move |this, cx| {
5287 if let Some(clone) = task.await {
5288 this.update_in(cx, |this, window, cx| {
5289 let new_pane = this.add_pane(window, cx);
5290 let nav_history = pane.read(cx).fork_nav_history();
5291 new_pane.update(cx, |pane, cx| {
5292 pane.set_nav_history(nav_history, cx);
5293 pane.add_item(clone, true, true, None, window, cx)
5294 });
5295 this.center.split(&pane, &new_pane, direction, cx);
5296 cx.notify();
5297 new_pane
5298 })
5299 .ok()
5300 } else {
5301 None
5302 }
5303 })
5304 }
5305
5306 pub fn join_all_panes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5307 let active_item = self.active_pane.read(cx).active_item();
5308 for pane in &self.panes {
5309 join_pane_into_active(&self.active_pane, pane, window, cx);
5310 }
5311 if let Some(active_item) = active_item {
5312 self.activate_item(active_item.as_ref(), true, true, window, cx);
5313 }
5314 cx.notify();
5315 }
5316
5317 pub fn join_pane_into_next(
5318 &mut self,
5319 pane: Entity<Pane>,
5320 window: &mut Window,
5321 cx: &mut Context<Self>,
5322 ) {
5323 let next_pane = self
5324 .find_pane_in_direction(SplitDirection::Right, cx)
5325 .or_else(|| self.find_pane_in_direction(SplitDirection::Down, cx))
5326 .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
5327 .or_else(|| self.find_pane_in_direction(SplitDirection::Up, cx));
5328 let Some(next_pane) = next_pane else {
5329 return;
5330 };
5331 move_all_items(&pane, &next_pane, window, cx);
5332 cx.notify();
5333 }
5334
5335 fn remove_pane(
5336 &mut self,
5337 pane: Entity<Pane>,
5338 focus_on: Option<Entity<Pane>>,
5339 window: &mut Window,
5340 cx: &mut Context<Self>,
5341 ) {
5342 if self.center.remove(&pane, cx).unwrap() {
5343 self.force_remove_pane(&pane, &focus_on, window, cx);
5344 self.unfollow_in_pane(&pane, window, cx);
5345 self.last_leaders_by_pane.remove(&pane.downgrade());
5346 for removed_item in pane.read(cx).items() {
5347 self.panes_by_item.remove(&removed_item.item_id());
5348 }
5349
5350 cx.notify();
5351 } else {
5352 self.active_item_path_changed(true, window, cx);
5353 }
5354 cx.emit(Event::PaneRemoved);
5355 }
5356
5357 pub fn panes_mut(&mut self) -> &mut [Entity<Pane>] {
5358 &mut self.panes
5359 }
5360
5361 pub fn panes(&self) -> &[Entity<Pane>] {
5362 &self.panes
5363 }
5364
5365 pub fn active_pane(&self) -> &Entity<Pane> {
5366 &self.active_pane
5367 }
5368
5369 pub fn focused_pane(&self, window: &Window, cx: &App) -> Entity<Pane> {
5370 for dock in self.all_docks() {
5371 if dock.focus_handle(cx).contains_focused(window, cx)
5372 && let Some(pane) = dock
5373 .read(cx)
5374 .active_panel()
5375 .and_then(|panel| panel.pane(cx))
5376 {
5377 return pane;
5378 }
5379 }
5380 self.active_pane().clone()
5381 }
5382
5383 pub fn adjacent_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
5384 self.find_pane_in_direction(SplitDirection::Right, cx)
5385 .unwrap_or_else(|| {
5386 self.split_pane(self.active_pane.clone(), SplitDirection::Right, window, cx)
5387 })
5388 }
5389
5390 pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<Entity<Pane>> {
5391 self.pane_for_item_id(handle.item_id())
5392 }
5393
5394 pub fn pane_for_item_id(&self, item_id: EntityId) -> Option<Entity<Pane>> {
5395 let weak_pane = self.panes_by_item.get(&item_id)?;
5396 weak_pane.upgrade()
5397 }
5398
5399 pub fn pane_for_entity_id(&self, entity_id: EntityId) -> Option<Entity<Pane>> {
5400 self.panes
5401 .iter()
5402 .find(|pane| pane.entity_id() == entity_id)
5403 .cloned()
5404 }
5405
5406 fn collaborator_left(&mut self, peer_id: PeerId, window: &mut Window, cx: &mut Context<Self>) {
5407 self.follower_states.retain(|leader_id, state| {
5408 if *leader_id == CollaboratorId::PeerId(peer_id) {
5409 for item in state.items_by_leader_view_id.values() {
5410 item.view.set_leader_id(None, window, cx);
5411 }
5412 false
5413 } else {
5414 true
5415 }
5416 });
5417 cx.notify();
5418 }
5419
5420 pub fn start_following(
5421 &mut self,
5422 leader_id: impl Into<CollaboratorId>,
5423 window: &mut Window,
5424 cx: &mut Context<Self>,
5425 ) -> Option<Task<Result<()>>> {
5426 let leader_id = leader_id.into();
5427 let pane = self.active_pane().clone();
5428
5429 self.last_leaders_by_pane
5430 .insert(pane.downgrade(), leader_id);
5431 self.unfollow(leader_id, window, cx);
5432 self.unfollow_in_pane(&pane, window, cx);
5433 self.follower_states.insert(
5434 leader_id,
5435 FollowerState {
5436 center_pane: pane.clone(),
5437 dock_pane: None,
5438 active_view_id: None,
5439 items_by_leader_view_id: Default::default(),
5440 },
5441 );
5442 cx.notify();
5443
5444 match leader_id {
5445 CollaboratorId::PeerId(leader_peer_id) => {
5446 let room_id = self.active_call()?.room_id(cx)?;
5447 let project_id = self.project.read(cx).remote_id();
5448 let request = self.app_state.client.request(proto::Follow {
5449 room_id,
5450 project_id,
5451 leader_id: Some(leader_peer_id),
5452 });
5453
5454 Some(cx.spawn_in(window, async move |this, cx| {
5455 let response = request.await?;
5456 this.update(cx, |this, _| {
5457 let state = this
5458 .follower_states
5459 .get_mut(&leader_id)
5460 .context("following interrupted")?;
5461 state.active_view_id = response
5462 .active_view
5463 .as_ref()
5464 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
5465 anyhow::Ok(())
5466 })??;
5467 if let Some(view) = response.active_view {
5468 Self::add_view_from_leader(this.clone(), leader_peer_id, &view, cx).await?;
5469 }
5470 this.update_in(cx, |this, window, cx| {
5471 this.leader_updated(leader_id, window, cx)
5472 })?;
5473 Ok(())
5474 }))
5475 }
5476 CollaboratorId::Agent => {
5477 self.leader_updated(leader_id, window, cx)?;
5478 Some(Task::ready(Ok(())))
5479 }
5480 }
5481 }
5482
5483 pub fn follow_next_collaborator(
5484 &mut self,
5485 _: &FollowNextCollaborator,
5486 window: &mut Window,
5487 cx: &mut Context<Self>,
5488 ) {
5489 let collaborators = self.project.read(cx).collaborators();
5490 let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
5491 let mut collaborators = collaborators.keys().copied();
5492 for peer_id in collaborators.by_ref() {
5493 if CollaboratorId::PeerId(peer_id) == leader_id {
5494 break;
5495 }
5496 }
5497 collaborators.next().map(CollaboratorId::PeerId)
5498 } else if let Some(last_leader_id) =
5499 self.last_leaders_by_pane.get(&self.active_pane.downgrade())
5500 {
5501 match last_leader_id {
5502 CollaboratorId::PeerId(peer_id) => {
5503 if collaborators.contains_key(peer_id) {
5504 Some(*last_leader_id)
5505 } else {
5506 None
5507 }
5508 }
5509 CollaboratorId::Agent => Some(CollaboratorId::Agent),
5510 }
5511 } else {
5512 None
5513 };
5514
5515 let pane = self.active_pane.clone();
5516 let Some(leader_id) = next_leader_id.or_else(|| {
5517 Some(CollaboratorId::PeerId(
5518 collaborators.keys().copied().next()?,
5519 ))
5520 }) else {
5521 return;
5522 };
5523 if self.unfollow_in_pane(&pane, window, cx) == Some(leader_id) {
5524 return;
5525 }
5526 if let Some(task) = self.start_following(leader_id, window, cx) {
5527 task.detach_and_log_err(cx)
5528 }
5529 }
5530
5531 pub fn follow(
5532 &mut self,
5533 leader_id: impl Into<CollaboratorId>,
5534 window: &mut Window,
5535 cx: &mut Context<Self>,
5536 ) {
5537 let leader_id = leader_id.into();
5538
5539 if let CollaboratorId::PeerId(peer_id) = leader_id {
5540 let Some(active_call) = GlobalAnyActiveCall::try_global(cx) else {
5541 return;
5542 };
5543 let Some(remote_participant) =
5544 active_call.0.remote_participant_for_peer_id(peer_id, cx)
5545 else {
5546 return;
5547 };
5548
5549 let project = self.project.read(cx);
5550
5551 let other_project_id = match remote_participant.location {
5552 ParticipantLocation::External => None,
5553 ParticipantLocation::UnsharedProject => None,
5554 ParticipantLocation::SharedProject { project_id } => {
5555 if Some(project_id) == project.remote_id() {
5556 None
5557 } else {
5558 Some(project_id)
5559 }
5560 }
5561 };
5562
5563 // if they are active in another project, follow there.
5564 if let Some(project_id) = other_project_id {
5565 let app_state = self.app_state.clone();
5566 crate::join_in_room_project(project_id, remote_participant.user.id, app_state, cx)
5567 .detach_and_prompt_err("Failed to join project", window, cx, |error, _, _| {
5568 Some(format!("{error:#}"))
5569 });
5570 }
5571 }
5572
5573 // if you're already following, find the right pane and focus it.
5574 if let Some(follower_state) = self.follower_states.get(&leader_id) {
5575 window.focus(&follower_state.pane().focus_handle(cx), cx);
5576
5577 return;
5578 }
5579
5580 // Otherwise, follow.
5581 if let Some(task) = self.start_following(leader_id, window, cx) {
5582 task.detach_and_log_err(cx)
5583 }
5584 }
5585
5586 pub fn unfollow(
5587 &mut self,
5588 leader_id: impl Into<CollaboratorId>,
5589 window: &mut Window,
5590 cx: &mut Context<Self>,
5591 ) -> Option<()> {
5592 cx.notify();
5593
5594 let leader_id = leader_id.into();
5595 let state = self.follower_states.remove(&leader_id)?;
5596 for (_, item) in state.items_by_leader_view_id {
5597 item.view.set_leader_id(None, window, cx);
5598 }
5599
5600 if let CollaboratorId::PeerId(leader_peer_id) = leader_id {
5601 let project_id = self.project.read(cx).remote_id();
5602 let room_id = self.active_call()?.room_id(cx)?;
5603 self.app_state
5604 .client
5605 .send(proto::Unfollow {
5606 room_id,
5607 project_id,
5608 leader_id: Some(leader_peer_id),
5609 })
5610 .log_err();
5611 }
5612
5613 Some(())
5614 }
5615
5616 pub fn is_being_followed(&self, id: impl Into<CollaboratorId>) -> bool {
5617 self.follower_states.contains_key(&id.into())
5618 }
5619
5620 fn active_item_path_changed(
5621 &mut self,
5622 focus_changed: bool,
5623 window: &mut Window,
5624 cx: &mut Context<Self>,
5625 ) {
5626 cx.emit(Event::ActiveItemChanged);
5627 let active_entry = self.active_project_path(cx);
5628 self.project.update(cx, |project, cx| {
5629 project.set_active_path(active_entry.clone(), cx)
5630 });
5631
5632 if focus_changed && let Some(project_path) = &active_entry {
5633 let git_store_entity = self.project.read(cx).git_store().clone();
5634 git_store_entity.update(cx, |git_store, cx| {
5635 git_store.set_active_repo_for_path(project_path, cx);
5636 });
5637 }
5638
5639 self.update_window_title(window, cx);
5640 }
5641
5642 fn update_window_title(&mut self, window: &mut Window, cx: &mut App) {
5643 let project = self.project().read(cx);
5644 let mut title = String::new();
5645
5646 for (i, worktree) in project.visible_worktrees(cx).enumerate() {
5647 let name = {
5648 let settings_location = SettingsLocation {
5649 worktree_id: worktree.read(cx).id(),
5650 path: RelPath::empty(),
5651 };
5652
5653 let settings = WorktreeSettings::get(Some(settings_location), cx);
5654 match &settings.project_name {
5655 Some(name) => name.as_str(),
5656 None => worktree.read(cx).root_name_str(),
5657 }
5658 };
5659 if i > 0 {
5660 title.push_str(", ");
5661 }
5662 title.push_str(name);
5663 }
5664
5665 if title.is_empty() {
5666 title = "empty project".to_string();
5667 }
5668
5669 if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
5670 let filename = path.path.file_name().or_else(|| {
5671 Some(
5672 project
5673 .worktree_for_id(path.worktree_id, cx)?
5674 .read(cx)
5675 .root_name_str(),
5676 )
5677 });
5678
5679 if let Some(filename) = filename {
5680 title.push_str(" — ");
5681 title.push_str(filename.as_ref());
5682 }
5683 }
5684
5685 if project.is_via_collab() {
5686 title.push_str(" ↙");
5687 } else if project.is_shared() {
5688 title.push_str(" ↗");
5689 }
5690
5691 if let Some(last_title) = self.last_window_title.as_ref()
5692 && &title == last_title
5693 {
5694 return;
5695 }
5696 window.set_window_title(&title);
5697 SystemWindowTabController::update_tab_title(
5698 cx,
5699 window.window_handle().window_id(),
5700 SharedString::from(&title),
5701 );
5702 self.last_window_title = Some(title);
5703 }
5704
5705 fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
5706 let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
5707 if is_edited != self.window_edited {
5708 self.window_edited = is_edited;
5709 window.set_window_edited(self.window_edited)
5710 }
5711 }
5712
5713 fn update_item_dirty_state(
5714 &mut self,
5715 item: &dyn ItemHandle,
5716 window: &mut Window,
5717 cx: &mut App,
5718 ) {
5719 let is_dirty = item.is_dirty(cx);
5720 let item_id = item.item_id();
5721 let was_dirty = self.dirty_items.contains_key(&item_id);
5722 if is_dirty == was_dirty {
5723 return;
5724 }
5725 if was_dirty {
5726 self.dirty_items.remove(&item_id);
5727 self.update_window_edited(window, cx);
5728 return;
5729 }
5730
5731 let workspace = self.weak_handle();
5732 let Some(window_handle) = window.window_handle().downcast::<MultiWorkspace>() else {
5733 return;
5734 };
5735 let on_release_callback = Box::new(move |cx: &mut App| {
5736 window_handle
5737 .update(cx, |_, window, cx| {
5738 workspace
5739 .update(cx, |workspace, cx| {
5740 workspace.dirty_items.remove(&item_id);
5741 workspace.update_window_edited(window, cx)
5742 })
5743 .ok();
5744 })
5745 .ok();
5746 });
5747
5748 let s = item.on_release(cx, on_release_callback);
5749 self.dirty_items.insert(item_id, s);
5750 self.update_window_edited(window, cx);
5751 }
5752
5753 fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
5754 if self.notifications.is_empty() {
5755 None
5756 } else {
5757 Some(
5758 div()
5759 .absolute()
5760 .right_3()
5761 .bottom_3()
5762 .w_112()
5763 .h_full()
5764 .flex()
5765 .flex_col()
5766 .justify_end()
5767 .gap_2()
5768 .children(
5769 self.notifications
5770 .iter()
5771 .map(|(_, notification)| notification.clone().into_any()),
5772 ),
5773 )
5774 }
5775 }
5776
5777 // RPC handlers
5778
5779 fn active_view_for_follower(
5780 &self,
5781 follower_project_id: Option<u64>,
5782 window: &mut Window,
5783 cx: &mut Context<Self>,
5784 ) -> Option<proto::View> {
5785 let (item, panel_id) = self.active_item_for_followers(window, cx);
5786 let item = item?;
5787 let leader_id = self
5788 .pane_for(&*item)
5789 .and_then(|pane| self.leader_for_pane(&pane));
5790 let leader_peer_id = match leader_id {
5791 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
5792 Some(CollaboratorId::Agent) | None => None,
5793 };
5794
5795 let item_handle = item.to_followable_item_handle(cx)?;
5796 let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
5797 let variant = item_handle.to_state_proto(window, cx)?;
5798
5799 if item_handle.is_project_item(window, cx)
5800 && (follower_project_id.is_none()
5801 || follower_project_id != self.project.read(cx).remote_id())
5802 {
5803 return None;
5804 }
5805
5806 Some(proto::View {
5807 id: id.to_proto(),
5808 leader_id: leader_peer_id,
5809 variant: Some(variant),
5810 panel_id: panel_id.map(|id| id as i32),
5811 })
5812 }
5813
5814 fn handle_follow(
5815 &mut self,
5816 follower_project_id: Option<u64>,
5817 window: &mut Window,
5818 cx: &mut Context<Self>,
5819 ) -> proto::FollowResponse {
5820 let active_view = self.active_view_for_follower(follower_project_id, window, cx);
5821
5822 cx.notify();
5823 proto::FollowResponse {
5824 views: active_view.iter().cloned().collect(),
5825 active_view,
5826 }
5827 }
5828
5829 fn handle_update_followers(
5830 &mut self,
5831 leader_id: PeerId,
5832 message: proto::UpdateFollowers,
5833 _window: &mut Window,
5834 _cx: &mut Context<Self>,
5835 ) {
5836 self.leader_updates_tx
5837 .unbounded_send((leader_id, message))
5838 .ok();
5839 }
5840
5841 async fn process_leader_update(
5842 this: &WeakEntity<Self>,
5843 leader_id: PeerId,
5844 update: proto::UpdateFollowers,
5845 cx: &mut AsyncWindowContext,
5846 ) -> Result<()> {
5847 match update.variant.context("invalid update")? {
5848 proto::update_followers::Variant::CreateView(view) => {
5849 let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
5850 let should_add_view = this.update(cx, |this, _| {
5851 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
5852 anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
5853 } else {
5854 anyhow::Ok(false)
5855 }
5856 })??;
5857
5858 if should_add_view {
5859 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
5860 }
5861 }
5862 proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
5863 let should_add_view = this.update(cx, |this, _| {
5864 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
5865 state.active_view_id = update_active_view
5866 .view
5867 .as_ref()
5868 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
5869
5870 if state.active_view_id.is_some_and(|view_id| {
5871 !state.items_by_leader_view_id.contains_key(&view_id)
5872 }) {
5873 anyhow::Ok(true)
5874 } else {
5875 anyhow::Ok(false)
5876 }
5877 } else {
5878 anyhow::Ok(false)
5879 }
5880 })??;
5881
5882 if should_add_view && let Some(view) = update_active_view.view {
5883 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
5884 }
5885 }
5886 proto::update_followers::Variant::UpdateView(update_view) => {
5887 let variant = update_view.variant.context("missing update view variant")?;
5888 let id = update_view.id.context("missing update view id")?;
5889 let mut tasks = Vec::new();
5890 this.update_in(cx, |this, window, cx| {
5891 let project = this.project.clone();
5892 if let Some(state) = this.follower_states.get(&leader_id.into()) {
5893 let view_id = ViewId::from_proto(id.clone())?;
5894 if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
5895 tasks.push(item.view.apply_update_proto(
5896 &project,
5897 variant.clone(),
5898 window,
5899 cx,
5900 ));
5901 }
5902 }
5903 anyhow::Ok(())
5904 })??;
5905 try_join_all(tasks).await.log_err();
5906 }
5907 }
5908 this.update_in(cx, |this, window, cx| {
5909 this.leader_updated(leader_id, window, cx)
5910 })?;
5911 Ok(())
5912 }
5913
5914 async fn add_view_from_leader(
5915 this: WeakEntity<Self>,
5916 leader_id: PeerId,
5917 view: &proto::View,
5918 cx: &mut AsyncWindowContext,
5919 ) -> Result<()> {
5920 let this = this.upgrade().context("workspace dropped")?;
5921
5922 let Some(id) = view.id.clone() else {
5923 anyhow::bail!("no id for view");
5924 };
5925 let id = ViewId::from_proto(id)?;
5926 let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
5927
5928 let pane = this.update(cx, |this, _cx| {
5929 let state = this
5930 .follower_states
5931 .get(&leader_id.into())
5932 .context("stopped following")?;
5933 anyhow::Ok(state.pane().clone())
5934 })?;
5935 let existing_item = pane.update_in(cx, |pane, window, cx| {
5936 let client = this.read(cx).client().clone();
5937 pane.items().find_map(|item| {
5938 let item = item.to_followable_item_handle(cx)?;
5939 if item.remote_id(&client, window, cx) == Some(id) {
5940 Some(item)
5941 } else {
5942 None
5943 }
5944 })
5945 })?;
5946 let item = if let Some(existing_item) = existing_item {
5947 existing_item
5948 } else {
5949 let variant = view.variant.clone();
5950 anyhow::ensure!(variant.is_some(), "missing view variant");
5951
5952 let task = cx.update(|window, cx| {
5953 FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
5954 })?;
5955
5956 let Some(task) = task else {
5957 anyhow::bail!(
5958 "failed to construct view from leader (maybe from a different version of zed?)"
5959 );
5960 };
5961
5962 let mut new_item = task.await?;
5963 pane.update_in(cx, |pane, window, cx| {
5964 let mut item_to_remove = None;
5965 for (ix, item) in pane.items().enumerate() {
5966 if let Some(item) = item.to_followable_item_handle(cx) {
5967 match new_item.dedup(item.as_ref(), window, cx) {
5968 Some(item::Dedup::KeepExisting) => {
5969 new_item =
5970 item.boxed_clone().to_followable_item_handle(cx).unwrap();
5971 break;
5972 }
5973 Some(item::Dedup::ReplaceExisting) => {
5974 item_to_remove = Some((ix, item.item_id()));
5975 break;
5976 }
5977 None => {}
5978 }
5979 }
5980 }
5981
5982 if let Some((ix, id)) = item_to_remove {
5983 pane.remove_item(id, false, false, window, cx);
5984 pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
5985 }
5986 })?;
5987
5988 new_item
5989 };
5990
5991 this.update_in(cx, |this, window, cx| {
5992 let state = this.follower_states.get_mut(&leader_id.into())?;
5993 item.set_leader_id(Some(leader_id.into()), window, cx);
5994 state.items_by_leader_view_id.insert(
5995 id,
5996 FollowerView {
5997 view: item,
5998 location: panel_id,
5999 },
6000 );
6001
6002 Some(())
6003 })
6004 .context("no follower state")?;
6005
6006 Ok(())
6007 }
6008
6009 fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6010 let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
6011 return;
6012 };
6013
6014 if let Some(agent_location) = self.project.read(cx).agent_location() {
6015 let buffer_entity_id = agent_location.buffer.entity_id();
6016 let view_id = ViewId {
6017 creator: CollaboratorId::Agent,
6018 id: buffer_entity_id.as_u64(),
6019 };
6020 follower_state.active_view_id = Some(view_id);
6021
6022 let item = match follower_state.items_by_leader_view_id.entry(view_id) {
6023 hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
6024 hash_map::Entry::Vacant(entry) => {
6025 let existing_view =
6026 follower_state
6027 .center_pane
6028 .read(cx)
6029 .items()
6030 .find_map(|item| {
6031 let item = item.to_followable_item_handle(cx)?;
6032 if item.buffer_kind(cx) == ItemBufferKind::Singleton
6033 && item.project_item_model_ids(cx).as_slice()
6034 == [buffer_entity_id]
6035 {
6036 Some(item)
6037 } else {
6038 None
6039 }
6040 });
6041 let view = existing_view.or_else(|| {
6042 agent_location.buffer.upgrade().and_then(|buffer| {
6043 cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
6044 registry.build_item(buffer, self.project.clone(), None, window, cx)
6045 })?
6046 .to_followable_item_handle(cx)
6047 })
6048 });
6049
6050 view.map(|view| {
6051 entry.insert(FollowerView {
6052 view,
6053 location: None,
6054 })
6055 })
6056 }
6057 };
6058
6059 if let Some(item) = item {
6060 item.view
6061 .set_leader_id(Some(CollaboratorId::Agent), window, cx);
6062 item.view
6063 .update_agent_location(agent_location.position, window, cx);
6064 }
6065 } else {
6066 follower_state.active_view_id = None;
6067 }
6068
6069 self.leader_updated(CollaboratorId::Agent, window, cx);
6070 }
6071
6072 pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
6073 let mut is_project_item = true;
6074 let mut update = proto::UpdateActiveView::default();
6075 if window.is_window_active() {
6076 let (active_item, panel_id) = self.active_item_for_followers(window, cx);
6077
6078 if let Some(item) = active_item
6079 && item.item_focus_handle(cx).contains_focused(window, cx)
6080 {
6081 let leader_id = self
6082 .pane_for(&*item)
6083 .and_then(|pane| self.leader_for_pane(&pane));
6084 let leader_peer_id = match leader_id {
6085 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
6086 Some(CollaboratorId::Agent) | None => None,
6087 };
6088
6089 if let Some(item) = item.to_followable_item_handle(cx) {
6090 let id = item
6091 .remote_id(&self.app_state.client, window, cx)
6092 .map(|id| id.to_proto());
6093
6094 if let Some(id) = id
6095 && let Some(variant) = item.to_state_proto(window, cx)
6096 {
6097 let view = Some(proto::View {
6098 id,
6099 leader_id: leader_peer_id,
6100 variant: Some(variant),
6101 panel_id: panel_id.map(|id| id as i32),
6102 });
6103
6104 is_project_item = item.is_project_item(window, cx);
6105 update = proto::UpdateActiveView { view };
6106 };
6107 }
6108 }
6109 }
6110
6111 let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
6112 if active_view_id != self.last_active_view_id.as_ref() {
6113 self.last_active_view_id = active_view_id.cloned();
6114 self.update_followers(
6115 is_project_item,
6116 proto::update_followers::Variant::UpdateActiveView(update),
6117 window,
6118 cx,
6119 );
6120 }
6121 }
6122
6123 fn active_item_for_followers(
6124 &self,
6125 window: &mut Window,
6126 cx: &mut App,
6127 ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
6128 let mut active_item = None;
6129 let mut panel_id = None;
6130 for dock in self.all_docks() {
6131 if dock.focus_handle(cx).contains_focused(window, cx)
6132 && let Some(panel) = dock.read(cx).active_panel()
6133 && let Some(pane) = panel.pane(cx)
6134 && let Some(item) = pane.read(cx).active_item()
6135 {
6136 active_item = Some(item);
6137 panel_id = panel.remote_id();
6138 break;
6139 }
6140 }
6141
6142 if active_item.is_none() {
6143 active_item = self.active_pane().read(cx).active_item();
6144 }
6145 (active_item, panel_id)
6146 }
6147
6148 fn update_followers(
6149 &self,
6150 project_only: bool,
6151 update: proto::update_followers::Variant,
6152 _: &mut Window,
6153 cx: &mut App,
6154 ) -> Option<()> {
6155 // If this update only applies to for followers in the current project,
6156 // then skip it unless this project is shared. If it applies to all
6157 // followers, regardless of project, then set `project_id` to none,
6158 // indicating that it goes to all followers.
6159 let project_id = if project_only {
6160 Some(self.project.read(cx).remote_id()?)
6161 } else {
6162 None
6163 };
6164 self.app_state().workspace_store.update(cx, |store, cx| {
6165 store.update_followers(project_id, update, cx)
6166 })
6167 }
6168
6169 pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
6170 self.follower_states.iter().find_map(|(leader_id, state)| {
6171 if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
6172 Some(*leader_id)
6173 } else {
6174 None
6175 }
6176 })
6177 }
6178
6179 fn leader_updated(
6180 &mut self,
6181 leader_id: impl Into<CollaboratorId>,
6182 window: &mut Window,
6183 cx: &mut Context<Self>,
6184 ) -> Option<Box<dyn ItemHandle>> {
6185 cx.notify();
6186
6187 let leader_id = leader_id.into();
6188 let (panel_id, item) = match leader_id {
6189 CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
6190 CollaboratorId::Agent => (None, self.active_item_for_agent()?),
6191 };
6192
6193 let state = self.follower_states.get(&leader_id)?;
6194 let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
6195 let pane;
6196 if let Some(panel_id) = panel_id {
6197 pane = self
6198 .activate_panel_for_proto_id(panel_id, window, cx)?
6199 .pane(cx)?;
6200 let state = self.follower_states.get_mut(&leader_id)?;
6201 state.dock_pane = Some(pane.clone());
6202 } else {
6203 pane = state.center_pane.clone();
6204 let state = self.follower_states.get_mut(&leader_id)?;
6205 if let Some(dock_pane) = state.dock_pane.take() {
6206 transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
6207 }
6208 }
6209
6210 pane.update(cx, |pane, cx| {
6211 let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
6212 if let Some(index) = pane.index_for_item(item.as_ref()) {
6213 pane.activate_item(index, false, false, window, cx);
6214 } else {
6215 pane.add_item(item.boxed_clone(), false, false, None, window, cx)
6216 }
6217
6218 if focus_active_item {
6219 pane.focus_active_item(window, cx)
6220 }
6221 });
6222
6223 Some(item)
6224 }
6225
6226 fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
6227 let state = self.follower_states.get(&CollaboratorId::Agent)?;
6228 let active_view_id = state.active_view_id?;
6229 Some(
6230 state
6231 .items_by_leader_view_id
6232 .get(&active_view_id)?
6233 .view
6234 .boxed_clone(),
6235 )
6236 }
6237
6238 fn active_item_for_peer(
6239 &self,
6240 peer_id: PeerId,
6241 window: &mut Window,
6242 cx: &mut Context<Self>,
6243 ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
6244 let call = self.active_call()?;
6245 let participant = call.remote_participant_for_peer_id(peer_id, cx)?;
6246 let leader_in_this_app;
6247 let leader_in_this_project;
6248 match participant.location {
6249 ParticipantLocation::SharedProject { project_id } => {
6250 leader_in_this_app = true;
6251 leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
6252 }
6253 ParticipantLocation::UnsharedProject => {
6254 leader_in_this_app = true;
6255 leader_in_this_project = false;
6256 }
6257 ParticipantLocation::External => {
6258 leader_in_this_app = false;
6259 leader_in_this_project = false;
6260 }
6261 };
6262 let state = self.follower_states.get(&peer_id.into())?;
6263 let mut item_to_activate = None;
6264 if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
6265 if let Some(item) = state.items_by_leader_view_id.get(&active_view_id)
6266 && (leader_in_this_project || !item.view.is_project_item(window, cx))
6267 {
6268 item_to_activate = Some((item.location, item.view.boxed_clone()));
6269 }
6270 } else if let Some(shared_screen) =
6271 self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
6272 {
6273 item_to_activate = Some((None, Box::new(shared_screen)));
6274 }
6275 item_to_activate
6276 }
6277
6278 fn shared_screen_for_peer(
6279 &self,
6280 peer_id: PeerId,
6281 pane: &Entity<Pane>,
6282 window: &mut Window,
6283 cx: &mut App,
6284 ) -> Option<Entity<SharedScreen>> {
6285 self.active_call()?
6286 .create_shared_screen(peer_id, pane, window, cx)
6287 }
6288
6289 pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6290 if window.is_window_active() {
6291 self.update_active_view_for_followers(window, cx);
6292
6293 if let Some(database_id) = self.database_id {
6294 let db = WorkspaceDb::global(cx);
6295 cx.background_spawn(async move { db.update_timestamp(database_id).await })
6296 .detach();
6297 }
6298 } else {
6299 for pane in &self.panes {
6300 pane.update(cx, |pane, cx| {
6301 if let Some(item) = pane.active_item() {
6302 item.workspace_deactivated(window, cx);
6303 }
6304 for item in pane.items() {
6305 if matches!(
6306 item.workspace_settings(cx).autosave,
6307 AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
6308 ) {
6309 Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
6310 .detach_and_log_err(cx);
6311 }
6312 }
6313 });
6314 }
6315 }
6316 }
6317
6318 pub fn active_call(&self) -> Option<&dyn AnyActiveCall> {
6319 self.active_call.as_ref().map(|(call, _)| &*call.0)
6320 }
6321
6322 pub fn active_global_call(&self) -> Option<GlobalAnyActiveCall> {
6323 self.active_call.as_ref().map(|(call, _)| call.clone())
6324 }
6325
6326 fn on_active_call_event(
6327 &mut self,
6328 event: &ActiveCallEvent,
6329 window: &mut Window,
6330 cx: &mut Context<Self>,
6331 ) {
6332 match event {
6333 ActiveCallEvent::ParticipantLocationChanged { participant_id }
6334 | ActiveCallEvent::RemoteVideoTracksChanged { participant_id } => {
6335 self.leader_updated(participant_id, window, cx);
6336 }
6337 }
6338 }
6339
6340 pub fn database_id(&self) -> Option<WorkspaceId> {
6341 self.database_id
6342 }
6343
6344 #[cfg(any(test, feature = "test-support"))]
6345 pub(crate) fn set_database_id(&mut self, id: WorkspaceId) {
6346 self.database_id = Some(id);
6347 }
6348
6349 pub fn session_id(&self) -> Option<String> {
6350 self.session_id.clone()
6351 }
6352
6353 fn save_window_bounds(&self, window: &mut Window, cx: &mut App) -> Task<()> {
6354 let Some(display) = window.display(cx) else {
6355 return Task::ready(());
6356 };
6357 let Ok(display_uuid) = display.uuid() else {
6358 return Task::ready(());
6359 };
6360
6361 let window_bounds = window.inner_window_bounds();
6362 let database_id = self.database_id;
6363 let has_paths = !self.root_paths(cx).is_empty();
6364 let db = WorkspaceDb::global(cx);
6365 let kvp = db::kvp::KeyValueStore::global(cx);
6366
6367 cx.background_executor().spawn(async move {
6368 if !has_paths {
6369 persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
6370 .await
6371 .log_err();
6372 }
6373 if let Some(database_id) = database_id {
6374 db.set_window_open_status(
6375 database_id,
6376 SerializedWindowBounds(window_bounds),
6377 display_uuid,
6378 )
6379 .await
6380 .log_err();
6381 } else {
6382 persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
6383 .await
6384 .log_err();
6385 }
6386 })
6387 }
6388
6389 /// Bypass the 200ms serialization throttle and write workspace state to
6390 /// the DB immediately. Returns a task the caller can await to ensure the
6391 /// write completes. Used by the quit handler so the most recent state
6392 /// isn't lost to a pending throttle timer when the process exits.
6393 pub fn flush_serialization(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
6394 self._schedule_serialize_workspace.take();
6395 self._serialize_workspace_task.take();
6396 self.bounds_save_task_queued.take();
6397
6398 let bounds_task = self.save_window_bounds(window, cx);
6399 let serialize_task = self.serialize_workspace_internal(window, cx);
6400 cx.spawn(async move |_| {
6401 bounds_task.await;
6402 serialize_task.await;
6403 })
6404 }
6405
6406 pub fn root_paths(&self, cx: &App) -> Vec<Arc<Path>> {
6407 let project = self.project().read(cx);
6408 project
6409 .visible_worktrees(cx)
6410 .map(|worktree| worktree.read(cx).abs_path())
6411 .collect::<Vec<_>>()
6412 }
6413
6414 fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
6415 match member {
6416 Member::Axis(PaneAxis { members, .. }) => {
6417 for child in members.iter() {
6418 self.remove_panes(child.clone(), window, cx)
6419 }
6420 }
6421 Member::Pane(pane) => {
6422 self.force_remove_pane(&pane, &None, window, cx);
6423 }
6424 }
6425 }
6426
6427 fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
6428 self.session_id.take();
6429 self.serialize_workspace_internal(window, cx)
6430 }
6431
6432 fn force_remove_pane(
6433 &mut self,
6434 pane: &Entity<Pane>,
6435 focus_on: &Option<Entity<Pane>>,
6436 window: &mut Window,
6437 cx: &mut Context<Workspace>,
6438 ) {
6439 self.panes.retain(|p| p != pane);
6440 if let Some(focus_on) = focus_on {
6441 focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
6442 } else if self.active_pane() == pane {
6443 self.panes
6444 .last()
6445 .unwrap()
6446 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
6447 }
6448 if self.last_active_center_pane == Some(pane.downgrade()) {
6449 self.last_active_center_pane = None;
6450 }
6451 cx.notify();
6452 }
6453
6454 fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6455 if self._schedule_serialize_workspace.is_none() {
6456 self._schedule_serialize_workspace =
6457 Some(cx.spawn_in(window, async move |this, cx| {
6458 cx.background_executor()
6459 .timer(SERIALIZATION_THROTTLE_TIME)
6460 .await;
6461 this.update_in(cx, |this, window, cx| {
6462 this._serialize_workspace_task =
6463 Some(this.serialize_workspace_internal(window, cx));
6464 this._schedule_serialize_workspace.take();
6465 })
6466 .log_err();
6467 }));
6468 }
6469 }
6470
6471 fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
6472 let Some(database_id) = self.database_id() else {
6473 return Task::ready(());
6474 };
6475
6476 fn serialize_pane_handle(
6477 pane_handle: &Entity<Pane>,
6478 window: &mut Window,
6479 cx: &mut App,
6480 ) -> SerializedPane {
6481 let (items, active, pinned_count) = {
6482 let pane = pane_handle.read(cx);
6483 let active_item_id = pane.active_item().map(|item| item.item_id());
6484 (
6485 pane.items()
6486 .filter_map(|handle| {
6487 let handle = handle.to_serializable_item_handle(cx)?;
6488
6489 Some(SerializedItem {
6490 kind: Arc::from(handle.serialized_item_kind()),
6491 item_id: handle.item_id().as_u64(),
6492 active: Some(handle.item_id()) == active_item_id,
6493 preview: pane.is_active_preview_item(handle.item_id()),
6494 })
6495 })
6496 .collect::<Vec<_>>(),
6497 pane.has_focus(window, cx),
6498 pane.pinned_count(),
6499 )
6500 };
6501
6502 SerializedPane::new(items, active, pinned_count)
6503 }
6504
6505 fn build_serialized_pane_group(
6506 pane_group: &Member,
6507 window: &mut Window,
6508 cx: &mut App,
6509 ) -> SerializedPaneGroup {
6510 match pane_group {
6511 Member::Axis(PaneAxis {
6512 axis,
6513 members,
6514 flexes,
6515 bounding_boxes: _,
6516 }) => SerializedPaneGroup::Group {
6517 axis: SerializedAxis(*axis),
6518 children: members
6519 .iter()
6520 .map(|member| build_serialized_pane_group(member, window, cx))
6521 .collect::<Vec<_>>(),
6522 flexes: Some(flexes.lock().clone()),
6523 },
6524 Member::Pane(pane_handle) => {
6525 SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
6526 }
6527 }
6528 }
6529
6530 fn build_serialized_docks(
6531 this: &Workspace,
6532 window: &mut Window,
6533 cx: &mut App,
6534 ) -> DockStructure {
6535 this.capture_dock_state(window, cx)
6536 }
6537
6538 match self.workspace_location(cx) {
6539 WorkspaceLocation::Location(location, paths) => {
6540 let breakpoints = self.project.update(cx, |project, cx| {
6541 project
6542 .breakpoint_store()
6543 .read(cx)
6544 .all_source_breakpoints(cx)
6545 });
6546 let user_toolchains = self
6547 .project
6548 .read(cx)
6549 .user_toolchains(cx)
6550 .unwrap_or_default();
6551
6552 let center_group = build_serialized_pane_group(&self.center.root, window, cx);
6553 let docks = build_serialized_docks(self, window, cx);
6554 let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
6555
6556 let serialized_workspace = SerializedWorkspace {
6557 id: database_id,
6558 location,
6559 paths,
6560 center_group,
6561 window_bounds,
6562 display: Default::default(),
6563 docks,
6564 centered_layout: self.centered_layout,
6565 session_id: self.session_id.clone(),
6566 breakpoints,
6567 window_id: Some(window.window_handle().window_id().as_u64()),
6568 user_toolchains,
6569 };
6570
6571 let db = WorkspaceDb::global(cx);
6572 window.spawn(cx, async move |_| {
6573 db.save_workspace(serialized_workspace).await;
6574 })
6575 }
6576 WorkspaceLocation::DetachFromSession => {
6577 let window_bounds = SerializedWindowBounds(window.window_bounds());
6578 let display = window.display(cx).and_then(|d| d.uuid().ok());
6579 // Save dock state for empty local workspaces
6580 let docks = build_serialized_docks(self, window, cx);
6581 let db = WorkspaceDb::global(cx);
6582 let kvp = db::kvp::KeyValueStore::global(cx);
6583 window.spawn(cx, async move |_| {
6584 db.set_window_open_status(
6585 database_id,
6586 window_bounds,
6587 display.unwrap_or_default(),
6588 )
6589 .await
6590 .log_err();
6591 db.set_session_id(database_id, None).await.log_err();
6592 persistence::write_default_dock_state(&kvp, docks)
6593 .await
6594 .log_err();
6595 })
6596 }
6597 WorkspaceLocation::None => {
6598 // Save dock state for empty non-local workspaces
6599 let docks = build_serialized_docks(self, window, cx);
6600 let kvp = db::kvp::KeyValueStore::global(cx);
6601 window.spawn(cx, async move |_| {
6602 persistence::write_default_dock_state(&kvp, docks)
6603 .await
6604 .log_err();
6605 })
6606 }
6607 }
6608 }
6609
6610 fn has_any_items_open(&self, cx: &App) -> bool {
6611 self.panes.iter().any(|pane| pane.read(cx).items_len() > 0)
6612 }
6613
6614 fn workspace_location(&self, cx: &App) -> WorkspaceLocation {
6615 let paths = PathList::new(&self.root_paths(cx));
6616 if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {
6617 WorkspaceLocation::Location(SerializedWorkspaceLocation::Remote(connection), paths)
6618 } else if self.project.read(cx).is_local() {
6619 if !paths.is_empty() || self.has_any_items_open(cx) {
6620 WorkspaceLocation::Location(SerializedWorkspaceLocation::Local, paths)
6621 } else {
6622 WorkspaceLocation::DetachFromSession
6623 }
6624 } else {
6625 WorkspaceLocation::None
6626 }
6627 }
6628
6629 fn update_history(&self, cx: &mut App) {
6630 let Some(id) = self.database_id() else {
6631 return;
6632 };
6633 if !self.project.read(cx).is_local() {
6634 return;
6635 }
6636 if let Some(manager) = HistoryManager::global(cx) {
6637 let paths = PathList::new(&self.root_paths(cx));
6638 manager.update(cx, |this, cx| {
6639 this.update_history(id, HistoryManagerEntry::new(id, &paths), cx);
6640 });
6641 }
6642 }
6643
6644 async fn serialize_items(
6645 this: &WeakEntity<Self>,
6646 items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
6647 cx: &mut AsyncWindowContext,
6648 ) -> Result<()> {
6649 const CHUNK_SIZE: usize = 200;
6650
6651 let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
6652
6653 while let Some(items_received) = serializable_items.next().await {
6654 let unique_items =
6655 items_received
6656 .into_iter()
6657 .fold(HashMap::default(), |mut acc, item| {
6658 acc.entry(item.item_id()).or_insert(item);
6659 acc
6660 });
6661
6662 // We use into_iter() here so that the references to the items are moved into
6663 // the tasks and not kept alive while we're sleeping.
6664 for (_, item) in unique_items.into_iter() {
6665 if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
6666 item.serialize(workspace, false, window, cx)
6667 }) {
6668 cx.background_spawn(async move { task.await.log_err() })
6669 .detach();
6670 }
6671 }
6672
6673 cx.background_executor()
6674 .timer(SERIALIZATION_THROTTLE_TIME)
6675 .await;
6676 }
6677
6678 Ok(())
6679 }
6680
6681 pub(crate) fn enqueue_item_serialization(
6682 &mut self,
6683 item: Box<dyn SerializableItemHandle>,
6684 ) -> Result<()> {
6685 self.serializable_items_tx
6686 .unbounded_send(item)
6687 .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
6688 }
6689
6690 pub(crate) fn load_workspace(
6691 serialized_workspace: SerializedWorkspace,
6692 paths_to_open: Vec<Option<ProjectPath>>,
6693 window: &mut Window,
6694 cx: &mut Context<Workspace>,
6695 ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
6696 cx.spawn_in(window, async move |workspace, cx| {
6697 let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
6698
6699 let mut center_group = None;
6700 let mut center_items = None;
6701
6702 // Traverse the splits tree and add to things
6703 if let Some((group, active_pane, items)) = serialized_workspace
6704 .center_group
6705 .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
6706 .await
6707 {
6708 center_items = Some(items);
6709 center_group = Some((group, active_pane))
6710 }
6711
6712 let mut items_by_project_path = HashMap::default();
6713 let mut item_ids_by_kind = HashMap::default();
6714 let mut all_deserialized_items = Vec::default();
6715 cx.update(|_, cx| {
6716 for item in center_items.unwrap_or_default().into_iter().flatten() {
6717 if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
6718 item_ids_by_kind
6719 .entry(serializable_item_handle.serialized_item_kind())
6720 .or_insert(Vec::new())
6721 .push(item.item_id().as_u64() as ItemId);
6722 }
6723
6724 if let Some(project_path) = item.project_path(cx) {
6725 items_by_project_path.insert(project_path, item.clone());
6726 }
6727 all_deserialized_items.push(item);
6728 }
6729 })?;
6730
6731 let opened_items = paths_to_open
6732 .into_iter()
6733 .map(|path_to_open| {
6734 path_to_open
6735 .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
6736 })
6737 .collect::<Vec<_>>();
6738
6739 // Remove old panes from workspace panes list
6740 workspace.update_in(cx, |workspace, window, cx| {
6741 if let Some((center_group, active_pane)) = center_group {
6742 workspace.remove_panes(workspace.center.root.clone(), window, cx);
6743
6744 // Swap workspace center group
6745 workspace.center = PaneGroup::with_root(center_group);
6746 workspace.center.set_is_center(true);
6747 workspace.center.mark_positions(cx);
6748
6749 if let Some(active_pane) = active_pane {
6750 workspace.set_active_pane(&active_pane, window, cx);
6751 cx.focus_self(window);
6752 } else {
6753 workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
6754 }
6755 }
6756
6757 let docks = serialized_workspace.docks;
6758
6759 for (dock, serialized_dock) in [
6760 (&mut workspace.right_dock, docks.right),
6761 (&mut workspace.left_dock, docks.left),
6762 (&mut workspace.bottom_dock, docks.bottom),
6763 ]
6764 .iter_mut()
6765 {
6766 dock.update(cx, |dock, cx| {
6767 dock.serialized_dock = Some(serialized_dock.clone());
6768 dock.restore_state(window, cx);
6769 });
6770 }
6771
6772 cx.notify();
6773 })?;
6774
6775 let _ = project
6776 .update(cx, |project, cx| {
6777 project
6778 .breakpoint_store()
6779 .update(cx, |breakpoint_store, cx| {
6780 breakpoint_store
6781 .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
6782 })
6783 })
6784 .await;
6785
6786 // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
6787 // after loading the items, we might have different items and in order to avoid
6788 // the database filling up, we delete items that haven't been loaded now.
6789 //
6790 // The items that have been loaded, have been saved after they've been added to the workspace.
6791 let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
6792 item_ids_by_kind
6793 .into_iter()
6794 .map(|(item_kind, loaded_items)| {
6795 SerializableItemRegistry::cleanup(
6796 item_kind,
6797 serialized_workspace.id,
6798 loaded_items,
6799 window,
6800 cx,
6801 )
6802 .log_err()
6803 })
6804 .collect::<Vec<_>>()
6805 })?;
6806
6807 futures::future::join_all(clean_up_tasks).await;
6808
6809 workspace
6810 .update_in(cx, |workspace, window, cx| {
6811 // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
6812 workspace.serialize_workspace_internal(window, cx).detach();
6813
6814 // Ensure that we mark the window as edited if we did load dirty items
6815 workspace.update_window_edited(window, cx);
6816 })
6817 .ok();
6818
6819 Ok(opened_items)
6820 })
6821 }
6822
6823 pub fn key_context(&self, cx: &App) -> KeyContext {
6824 let mut context = KeyContext::new_with_defaults();
6825 context.add("Workspace");
6826 context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
6827 if let Some(status) = self
6828 .debugger_provider
6829 .as_ref()
6830 .and_then(|provider| provider.active_thread_state(cx))
6831 {
6832 match status {
6833 ThreadStatus::Running | ThreadStatus::Stepping => {
6834 context.add("debugger_running");
6835 }
6836 ThreadStatus::Stopped => context.add("debugger_stopped"),
6837 ThreadStatus::Exited | ThreadStatus::Ended => {}
6838 }
6839 }
6840
6841 if self.left_dock.read(cx).is_open() {
6842 if let Some(active_panel) = self.left_dock.read(cx).active_panel() {
6843 context.set("left_dock", active_panel.panel_key());
6844 }
6845 }
6846
6847 if self.right_dock.read(cx).is_open() {
6848 if let Some(active_panel) = self.right_dock.read(cx).active_panel() {
6849 context.set("right_dock", active_panel.panel_key());
6850 }
6851 }
6852
6853 if self.bottom_dock.read(cx).is_open() {
6854 if let Some(active_panel) = self.bottom_dock.read(cx).active_panel() {
6855 context.set("bottom_dock", active_panel.panel_key());
6856 }
6857 }
6858
6859 context
6860 }
6861
6862 /// Multiworkspace uses this to add workspace action handling to itself
6863 pub fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
6864 self.add_workspace_actions_listeners(div, window, cx)
6865 .on_action(cx.listener(
6866 |_workspace, action_sequence: &settings::ActionSequence, window, cx| {
6867 for action in &action_sequence.0 {
6868 window.dispatch_action(action.boxed_clone(), cx);
6869 }
6870 },
6871 ))
6872 .on_action(cx.listener(Self::close_inactive_items_and_panes))
6873 .on_action(cx.listener(Self::close_all_items_and_panes))
6874 .on_action(cx.listener(Self::close_item_in_all_panes))
6875 .on_action(cx.listener(Self::save_all))
6876 .on_action(cx.listener(Self::send_keystrokes))
6877 .on_action(cx.listener(Self::add_folder_to_project))
6878 .on_action(cx.listener(Self::follow_next_collaborator))
6879 .on_action(cx.listener(Self::activate_pane_at_index))
6880 .on_action(cx.listener(Self::move_item_to_pane_at_index))
6881 .on_action(cx.listener(Self::move_focused_panel_to_next_position))
6882 .on_action(cx.listener(Self::toggle_edit_predictions_all_files))
6883 .on_action(cx.listener(Self::toggle_theme_mode))
6884 .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
6885 let pane = workspace.active_pane().clone();
6886 workspace.unfollow_in_pane(&pane, window, cx);
6887 }))
6888 .on_action(cx.listener(|workspace, action: &Save, window, cx| {
6889 workspace
6890 .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
6891 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6892 }))
6893 .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
6894 workspace
6895 .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
6896 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6897 }))
6898 .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
6899 workspace
6900 .save_active_item(SaveIntent::SaveAs, window, cx)
6901 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6902 }))
6903 .on_action(
6904 cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
6905 workspace.activate_previous_pane(window, cx)
6906 }),
6907 )
6908 .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
6909 workspace.activate_next_pane(window, cx)
6910 }))
6911 .on_action(cx.listener(|workspace, _: &ActivateLastPane, window, cx| {
6912 workspace.activate_last_pane(window, cx)
6913 }))
6914 .on_action(
6915 cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
6916 workspace.activate_next_window(cx)
6917 }),
6918 )
6919 .on_action(
6920 cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
6921 workspace.activate_previous_window(cx)
6922 }),
6923 )
6924 .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
6925 workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
6926 }))
6927 .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
6928 workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
6929 }))
6930 .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
6931 workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
6932 }))
6933 .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
6934 workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
6935 }))
6936 .on_action(cx.listener(
6937 |workspace, action: &MoveItemToPaneInDirection, window, cx| {
6938 workspace.move_item_to_pane_in_direction(action, window, cx)
6939 },
6940 ))
6941 .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
6942 workspace.swap_pane_in_direction(SplitDirection::Left, cx)
6943 }))
6944 .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
6945 workspace.swap_pane_in_direction(SplitDirection::Right, cx)
6946 }))
6947 .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
6948 workspace.swap_pane_in_direction(SplitDirection::Up, cx)
6949 }))
6950 .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
6951 workspace.swap_pane_in_direction(SplitDirection::Down, cx)
6952 }))
6953 .on_action(cx.listener(|workspace, _: &SwapPaneAdjacent, window, cx| {
6954 const DIRECTION_PRIORITY: [SplitDirection; 4] = [
6955 SplitDirection::Down,
6956 SplitDirection::Up,
6957 SplitDirection::Right,
6958 SplitDirection::Left,
6959 ];
6960 for dir in DIRECTION_PRIORITY {
6961 if workspace.find_pane_in_direction(dir, cx).is_some() {
6962 workspace.swap_pane_in_direction(dir, cx);
6963 workspace.activate_pane_in_direction(dir.opposite(), window, cx);
6964 break;
6965 }
6966 }
6967 }))
6968 .on_action(cx.listener(|workspace, _: &MovePaneLeft, _, cx| {
6969 workspace.move_pane_to_border(SplitDirection::Left, cx)
6970 }))
6971 .on_action(cx.listener(|workspace, _: &MovePaneRight, _, cx| {
6972 workspace.move_pane_to_border(SplitDirection::Right, cx)
6973 }))
6974 .on_action(cx.listener(|workspace, _: &MovePaneUp, _, cx| {
6975 workspace.move_pane_to_border(SplitDirection::Up, cx)
6976 }))
6977 .on_action(cx.listener(|workspace, _: &MovePaneDown, _, cx| {
6978 workspace.move_pane_to_border(SplitDirection::Down, cx)
6979 }))
6980 .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
6981 this.toggle_dock(DockPosition::Left, window, cx);
6982 }))
6983 .on_action(cx.listener(
6984 |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
6985 workspace.toggle_dock(DockPosition::Right, window, cx);
6986 },
6987 ))
6988 .on_action(cx.listener(
6989 |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
6990 workspace.toggle_dock(DockPosition::Bottom, window, cx);
6991 },
6992 ))
6993 .on_action(cx.listener(
6994 |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
6995 if !workspace.close_active_dock(window, cx) {
6996 cx.propagate();
6997 }
6998 },
6999 ))
7000 .on_action(
7001 cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
7002 workspace.close_all_docks(window, cx);
7003 }),
7004 )
7005 .on_action(cx.listener(Self::toggle_all_docks))
7006 .on_action(cx.listener(
7007 |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
7008 workspace.clear_all_notifications(cx);
7009 },
7010 ))
7011 .on_action(cx.listener(
7012 |workspace: &mut Workspace, _: &ClearNavigationHistory, window, cx| {
7013 workspace.clear_navigation_history(window, cx);
7014 },
7015 ))
7016 .on_action(cx.listener(
7017 |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
7018 if let Some((notification_id, _)) = workspace.notifications.pop() {
7019 workspace.suppress_notification(¬ification_id, cx);
7020 }
7021 },
7022 ))
7023 .on_action(cx.listener(
7024 |workspace: &mut Workspace, _: &ToggleWorktreeSecurity, window, cx| {
7025 workspace.show_worktree_trust_security_modal(true, window, cx);
7026 },
7027 ))
7028 .on_action(
7029 cx.listener(|_: &mut Workspace, _: &ClearTrustedWorktrees, _, cx| {
7030 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
7031 trusted_worktrees.update(cx, |trusted_worktrees, _| {
7032 trusted_worktrees.clear_trusted_paths()
7033 });
7034 let db = WorkspaceDb::global(cx);
7035 cx.spawn(async move |_, cx| {
7036 if db.clear_trusted_worktrees().await.log_err().is_some() {
7037 cx.update(|cx| reload(cx));
7038 }
7039 })
7040 .detach();
7041 }
7042 }),
7043 )
7044 .on_action(cx.listener(
7045 |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
7046 workspace.reopen_closed_item(window, cx).detach();
7047 },
7048 ))
7049 .on_action(cx.listener(
7050 |workspace: &mut Workspace, _: &ResetActiveDockSize, window, cx| {
7051 for dock in workspace.all_docks() {
7052 if dock.focus_handle(cx).contains_focused(window, cx) {
7053 let panel = dock.read(cx).active_panel().cloned();
7054 if let Some(panel) = panel {
7055 dock.update(cx, |dock, cx| {
7056 dock.set_panel_size_state(
7057 panel.as_ref(),
7058 dock::PanelSizeState::default(),
7059 cx,
7060 );
7061 });
7062 }
7063 return;
7064 }
7065 }
7066 },
7067 ))
7068 .on_action(cx.listener(
7069 |workspace: &mut Workspace, _: &ResetOpenDocksSize, _window, cx| {
7070 for dock in workspace.all_docks() {
7071 let panel = dock.read(cx).visible_panel().cloned();
7072 if let Some(panel) = panel {
7073 dock.update(cx, |dock, cx| {
7074 dock.set_panel_size_state(
7075 panel.as_ref(),
7076 dock::PanelSizeState::default(),
7077 cx,
7078 );
7079 });
7080 }
7081 }
7082 },
7083 ))
7084 .on_action(cx.listener(
7085 |workspace: &mut Workspace, act: &IncreaseActiveDockSize, window, cx| {
7086 adjust_active_dock_size_by_px(
7087 px_with_ui_font_fallback(act.px, cx),
7088 workspace,
7089 window,
7090 cx,
7091 );
7092 },
7093 ))
7094 .on_action(cx.listener(
7095 |workspace: &mut Workspace, act: &DecreaseActiveDockSize, window, cx| {
7096 adjust_active_dock_size_by_px(
7097 px_with_ui_font_fallback(act.px, cx) * -1.,
7098 workspace,
7099 window,
7100 cx,
7101 );
7102 },
7103 ))
7104 .on_action(cx.listener(
7105 |workspace: &mut Workspace, act: &IncreaseOpenDocksSize, window, cx| {
7106 adjust_open_docks_size_by_px(
7107 px_with_ui_font_fallback(act.px, cx),
7108 workspace,
7109 window,
7110 cx,
7111 );
7112 },
7113 ))
7114 .on_action(cx.listener(
7115 |workspace: &mut Workspace, act: &DecreaseOpenDocksSize, window, cx| {
7116 adjust_open_docks_size_by_px(
7117 px_with_ui_font_fallback(act.px, cx) * -1.,
7118 workspace,
7119 window,
7120 cx,
7121 );
7122 },
7123 ))
7124 .on_action(cx.listener(Workspace::toggle_centered_layout))
7125 .on_action(cx.listener(
7126 |workspace: &mut Workspace, action: &pane::ActivateNextItem, window, cx| {
7127 if let Some(active_dock) = workspace.active_dock(window, cx) {
7128 let dock = active_dock.read(cx);
7129 if let Some(active_panel) = dock.active_panel() {
7130 if active_panel.pane(cx).is_none() {
7131 let mut recent_pane: Option<Entity<Pane>> = None;
7132 let mut recent_timestamp = 0;
7133 for pane_handle in workspace.panes() {
7134 let pane = pane_handle.read(cx);
7135 for entry in pane.activation_history() {
7136 if entry.timestamp > recent_timestamp {
7137 recent_timestamp = entry.timestamp;
7138 recent_pane = Some(pane_handle.clone());
7139 }
7140 }
7141 }
7142
7143 if let Some(pane) = recent_pane {
7144 let wrap_around = action.wrap_around;
7145 pane.update(cx, |pane, cx| {
7146 let current_index = pane.active_item_index();
7147 let items_len = pane.items_len();
7148 if items_len > 0 {
7149 let next_index = if current_index + 1 < items_len {
7150 current_index + 1
7151 } else if wrap_around {
7152 0
7153 } else {
7154 return;
7155 };
7156 pane.activate_item(
7157 next_index, false, false, window, cx,
7158 );
7159 }
7160 });
7161 return;
7162 }
7163 }
7164 }
7165 }
7166 cx.propagate();
7167 },
7168 ))
7169 .on_action(cx.listener(
7170 |workspace: &mut Workspace, action: &pane::ActivatePreviousItem, window, cx| {
7171 if let Some(active_dock) = workspace.active_dock(window, cx) {
7172 let dock = active_dock.read(cx);
7173 if let Some(active_panel) = dock.active_panel() {
7174 if active_panel.pane(cx).is_none() {
7175 let mut recent_pane: Option<Entity<Pane>> = None;
7176 let mut recent_timestamp = 0;
7177 for pane_handle in workspace.panes() {
7178 let pane = pane_handle.read(cx);
7179 for entry in pane.activation_history() {
7180 if entry.timestamp > recent_timestamp {
7181 recent_timestamp = entry.timestamp;
7182 recent_pane = Some(pane_handle.clone());
7183 }
7184 }
7185 }
7186
7187 if let Some(pane) = recent_pane {
7188 let wrap_around = action.wrap_around;
7189 pane.update(cx, |pane, cx| {
7190 let current_index = pane.active_item_index();
7191 let items_len = pane.items_len();
7192 if items_len > 0 {
7193 let prev_index = if current_index > 0 {
7194 current_index - 1
7195 } else if wrap_around {
7196 items_len.saturating_sub(1)
7197 } else {
7198 return;
7199 };
7200 pane.activate_item(
7201 prev_index, false, false, window, cx,
7202 );
7203 }
7204 });
7205 return;
7206 }
7207 }
7208 }
7209 }
7210 cx.propagate();
7211 },
7212 ))
7213 .on_action(cx.listener(
7214 |workspace: &mut Workspace, action: &pane::CloseActiveItem, window, cx| {
7215 if let Some(active_dock) = workspace.active_dock(window, cx) {
7216 let dock = active_dock.read(cx);
7217 if let Some(active_panel) = dock.active_panel() {
7218 if active_panel.pane(cx).is_none() {
7219 let active_pane = workspace.active_pane().clone();
7220 active_pane.update(cx, |pane, cx| {
7221 pane.close_active_item(action, window, cx)
7222 .detach_and_log_err(cx);
7223 });
7224 return;
7225 }
7226 }
7227 }
7228 cx.propagate();
7229 },
7230 ))
7231 .on_action(
7232 cx.listener(|workspace, _: &ToggleReadOnlyFile, window, cx| {
7233 let pane = workspace.active_pane().clone();
7234 if let Some(item) = pane.read(cx).active_item() {
7235 item.toggle_read_only(window, cx);
7236 }
7237 }),
7238 )
7239 .on_action(cx.listener(|workspace, _: &FocusCenterPane, window, cx| {
7240 workspace.focus_center_pane(window, cx);
7241 }))
7242 .on_action(cx.listener(Workspace::cancel))
7243 }
7244
7245 #[cfg(any(test, feature = "test-support"))]
7246 pub fn set_random_database_id(&mut self) {
7247 self.database_id = Some(WorkspaceId(Uuid::new_v4().as_u64_pair().0 as i64));
7248 }
7249
7250 #[cfg(any(test, feature = "test-support"))]
7251 pub(crate) fn test_new(
7252 project: Entity<Project>,
7253 window: &mut Window,
7254 cx: &mut Context<Self>,
7255 ) -> Self {
7256 use node_runtime::NodeRuntime;
7257 use session::Session;
7258
7259 let client = project.read(cx).client();
7260 let user_store = project.read(cx).user_store();
7261 let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
7262 let session = cx.new(|cx| AppSession::new(Session::test(), cx));
7263 window.activate_window();
7264 let app_state = Arc::new(AppState {
7265 languages: project.read(cx).languages().clone(),
7266 workspace_store,
7267 client,
7268 user_store,
7269 fs: project.read(cx).fs().clone(),
7270 build_window_options: |_, _| Default::default(),
7271 node_runtime: NodeRuntime::unavailable(),
7272 session,
7273 });
7274 let workspace = Self::new(Default::default(), project, app_state, window, cx);
7275 workspace
7276 .active_pane
7277 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
7278 workspace
7279 }
7280
7281 pub fn register_action<A: Action>(
7282 &mut self,
7283 callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
7284 ) -> &mut Self {
7285 let callback = Arc::new(callback);
7286
7287 self.workspace_actions.push(Box::new(move |div, _, _, cx| {
7288 let callback = callback.clone();
7289 div.on_action(cx.listener(move |workspace, event, window, cx| {
7290 (callback)(workspace, event, window, cx)
7291 }))
7292 }));
7293 self
7294 }
7295 pub fn register_action_renderer(
7296 &mut self,
7297 callback: impl Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div + 'static,
7298 ) -> &mut Self {
7299 self.workspace_actions.push(Box::new(callback));
7300 self
7301 }
7302
7303 fn add_workspace_actions_listeners(
7304 &self,
7305 mut div: Div,
7306 window: &mut Window,
7307 cx: &mut Context<Self>,
7308 ) -> Div {
7309 for action in self.workspace_actions.iter() {
7310 div = (action)(div, self, window, cx)
7311 }
7312 div
7313 }
7314
7315 pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
7316 self.modal_layer.read(cx).has_active_modal()
7317 }
7318
7319 pub fn is_active_modal_command_palette(&self, cx: &mut App) -> bool {
7320 self.modal_layer
7321 .read(cx)
7322 .is_active_modal_command_palette(cx)
7323 }
7324
7325 pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
7326 self.modal_layer.read(cx).active_modal()
7327 }
7328
7329 /// Toggles a modal of type `V`. If a modal of the same type is currently active,
7330 /// it will be hidden. If a different modal is active, it will be replaced with the new one.
7331 /// If no modal is active, the new modal will be shown.
7332 ///
7333 /// If closing the current modal fails (e.g., due to `on_before_dismiss` returning
7334 /// `DismissDecision::Dismiss(false)` or `DismissDecision::Pending`), the new modal
7335 /// will not be shown.
7336 pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
7337 where
7338 B: FnOnce(&mut Window, &mut Context<V>) -> V,
7339 {
7340 self.modal_layer.update(cx, |modal_layer, cx| {
7341 modal_layer.toggle_modal(window, cx, build)
7342 })
7343 }
7344
7345 pub fn hide_modal(&mut self, window: &mut Window, cx: &mut App) -> bool {
7346 self.modal_layer
7347 .update(cx, |modal_layer, cx| modal_layer.hide_modal(window, cx))
7348 }
7349
7350 pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
7351 self.toast_layer
7352 .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
7353 }
7354
7355 pub fn toggle_centered_layout(
7356 &mut self,
7357 _: &ToggleCenteredLayout,
7358 _: &mut Window,
7359 cx: &mut Context<Self>,
7360 ) {
7361 self.centered_layout = !self.centered_layout;
7362 if let Some(database_id) = self.database_id() {
7363 let db = WorkspaceDb::global(cx);
7364 let centered_layout = self.centered_layout;
7365 cx.background_spawn(async move {
7366 db.set_centered_layout(database_id, centered_layout).await
7367 })
7368 .detach_and_log_err(cx);
7369 }
7370 cx.notify();
7371 }
7372
7373 fn adjust_padding(padding: Option<f32>) -> f32 {
7374 padding
7375 .unwrap_or(CenteredPaddingSettings::default().0)
7376 .clamp(
7377 CenteredPaddingSettings::MIN_PADDING,
7378 CenteredPaddingSettings::MAX_PADDING,
7379 )
7380 }
7381
7382 fn render_dock(
7383 &self,
7384 position: DockPosition,
7385 dock: &Entity<Dock>,
7386 window: &mut Window,
7387 cx: &mut App,
7388 ) -> Option<Div> {
7389 if self.zoomed_position == Some(position) {
7390 return None;
7391 }
7392
7393 let leader_border = dock.read(cx).active_panel().and_then(|panel| {
7394 let pane = panel.pane(cx)?;
7395 let follower_states = &self.follower_states;
7396 leader_border_for_pane(follower_states, &pane, window, cx)
7397 });
7398
7399 let mut container = div()
7400 .flex()
7401 .overflow_hidden()
7402 .flex_none()
7403 .child(dock.clone())
7404 .children(leader_border);
7405
7406 // Apply sizing only when the dock is open. When closed the dock is still
7407 // included in the element tree so its focus handle remains mounted — without
7408 // this, toggle_panel_focus cannot focus the panel when the dock is closed.
7409 let dock = dock.read(cx);
7410 if let Some(panel) = dock.visible_panel() {
7411 let size_state = dock.stored_panel_size_state(panel.as_ref());
7412 if position.axis() == Axis::Horizontal {
7413 let use_flexible = panel.has_flexible_size(window, cx);
7414 let flex_grow = if use_flexible {
7415 size_state
7416 .and_then(|state| state.flex)
7417 .or_else(|| self.default_dock_flex(position))
7418 } else {
7419 None
7420 };
7421 if let Some(grow) = flex_grow {
7422 let grow = grow.max(0.001);
7423 let style = container.style();
7424 style.flex_grow = Some(grow);
7425 style.flex_shrink = Some(1.0);
7426 style.flex_basis = Some(relative(0.).into());
7427 } else {
7428 let size = size_state
7429 .and_then(|state| state.size)
7430 .unwrap_or_else(|| panel.default_size(window, cx));
7431 container = container.w(size);
7432 }
7433 } else {
7434 let size = size_state
7435 .and_then(|state| state.size)
7436 .unwrap_or_else(|| panel.default_size(window, cx));
7437 container = container.h(size);
7438 }
7439 }
7440
7441 Some(container)
7442 }
7443
7444 pub fn for_window(window: &Window, cx: &App) -> Option<Entity<Workspace>> {
7445 window
7446 .root::<MultiWorkspace>()
7447 .flatten()
7448 .map(|multi_workspace| multi_workspace.read(cx).workspace().clone())
7449 }
7450
7451 pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
7452 self.zoomed.as_ref()
7453 }
7454
7455 pub fn activate_next_window(&mut self, cx: &mut Context<Self>) {
7456 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
7457 return;
7458 };
7459 let windows = cx.windows();
7460 let next_window =
7461 SystemWindowTabController::get_next_tab_group_window(cx, current_window_id).or_else(
7462 || {
7463 windows
7464 .iter()
7465 .cycle()
7466 .skip_while(|window| window.window_id() != current_window_id)
7467 .nth(1)
7468 },
7469 );
7470
7471 if let Some(window) = next_window {
7472 window
7473 .update(cx, |_, window, _| window.activate_window())
7474 .ok();
7475 }
7476 }
7477
7478 pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
7479 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
7480 return;
7481 };
7482 let windows = cx.windows();
7483 let prev_window =
7484 SystemWindowTabController::get_prev_tab_group_window(cx, current_window_id).or_else(
7485 || {
7486 windows
7487 .iter()
7488 .rev()
7489 .cycle()
7490 .skip_while(|window| window.window_id() != current_window_id)
7491 .nth(1)
7492 },
7493 );
7494
7495 if let Some(window) = prev_window {
7496 window
7497 .update(cx, |_, window, _| window.activate_window())
7498 .ok();
7499 }
7500 }
7501
7502 pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
7503 if cx.stop_active_drag(window) {
7504 } else if let Some((notification_id, _)) = self.notifications.pop() {
7505 dismiss_app_notification(¬ification_id, cx);
7506 } else {
7507 cx.propagate();
7508 }
7509 }
7510
7511 fn resize_dock(
7512 &mut self,
7513 dock_pos: DockPosition,
7514 new_size: Pixels,
7515 window: &mut Window,
7516 cx: &mut Context<Self>,
7517 ) {
7518 match dock_pos {
7519 DockPosition::Left => self.resize_left_dock(new_size, window, cx),
7520 DockPosition::Right => self.resize_right_dock(new_size, window, cx),
7521 DockPosition::Bottom => self.resize_bottom_dock(new_size, window, cx),
7522 }
7523 }
7524
7525 fn resize_left_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7526 let workspace_width = self.bounds.size.width;
7527 let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
7528
7529 self.right_dock.read_with(cx, |right_dock, cx| {
7530 let right_dock_size = right_dock
7531 .stored_active_panel_size(window, cx)
7532 .unwrap_or(Pixels::ZERO);
7533 if right_dock_size + size > workspace_width {
7534 size = workspace_width - right_dock_size
7535 }
7536 });
7537
7538 let flex_grow = self.dock_flex_for_size(DockPosition::Left, size, window, cx);
7539 self.left_dock.update(cx, |left_dock, cx| {
7540 if WorkspaceSettings::get_global(cx)
7541 .resize_all_panels_in_dock
7542 .contains(&DockPosition::Left)
7543 {
7544 left_dock.resize_all_panels(Some(size), flex_grow, window, cx);
7545 } else {
7546 left_dock.resize_active_panel(Some(size), flex_grow, window, cx);
7547 }
7548 });
7549 }
7550
7551 fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7552 let workspace_width = self.bounds.size.width;
7553 let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
7554 self.left_dock.read_with(cx, |left_dock, cx| {
7555 let left_dock_size = left_dock
7556 .stored_active_panel_size(window, cx)
7557 .unwrap_or(Pixels::ZERO);
7558 if left_dock_size + size > workspace_width {
7559 size = workspace_width - left_dock_size
7560 }
7561 });
7562 let flex_grow = self.dock_flex_for_size(DockPosition::Right, size, window, cx);
7563 self.right_dock.update(cx, |right_dock, cx| {
7564 if WorkspaceSettings::get_global(cx)
7565 .resize_all_panels_in_dock
7566 .contains(&DockPosition::Right)
7567 {
7568 right_dock.resize_all_panels(Some(size), flex_grow, window, cx);
7569 } else {
7570 right_dock.resize_active_panel(Some(size), flex_grow, window, cx);
7571 }
7572 });
7573 }
7574
7575 fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7576 let size = new_size.min(self.bounds.bottom() - RESIZE_HANDLE_SIZE - self.bounds.top());
7577 self.bottom_dock.update(cx, |bottom_dock, cx| {
7578 if WorkspaceSettings::get_global(cx)
7579 .resize_all_panels_in_dock
7580 .contains(&DockPosition::Bottom)
7581 {
7582 bottom_dock.resize_all_panels(Some(size), None, window, cx);
7583 } else {
7584 bottom_dock.resize_active_panel(Some(size), None, window, cx);
7585 }
7586 });
7587 }
7588
7589 fn toggle_edit_predictions_all_files(
7590 &mut self,
7591 _: &ToggleEditPrediction,
7592 _window: &mut Window,
7593 cx: &mut Context<Self>,
7594 ) {
7595 let fs = self.project().read(cx).fs().clone();
7596 let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
7597 update_settings_file(fs, cx, move |file, _| {
7598 file.project.all_languages.defaults.show_edit_predictions = Some(!show_edit_predictions)
7599 });
7600 }
7601
7602 fn toggle_theme_mode(&mut self, _: &ToggleMode, _window: &mut Window, cx: &mut Context<Self>) {
7603 let current_mode = ThemeSettings::get_global(cx).theme.mode();
7604 let next_mode = match current_mode {
7605 Some(theme_settings::ThemeAppearanceMode::Light) => {
7606 theme_settings::ThemeAppearanceMode::Dark
7607 }
7608 Some(theme_settings::ThemeAppearanceMode::Dark) => {
7609 theme_settings::ThemeAppearanceMode::Light
7610 }
7611 Some(theme_settings::ThemeAppearanceMode::System) | None => {
7612 match cx.theme().appearance() {
7613 theme::Appearance::Light => theme_settings::ThemeAppearanceMode::Dark,
7614 theme::Appearance::Dark => theme_settings::ThemeAppearanceMode::Light,
7615 }
7616 }
7617 };
7618
7619 let fs = self.project().read(cx).fs().clone();
7620 settings::update_settings_file(fs, cx, move |settings, _cx| {
7621 theme_settings::set_mode(settings, next_mode);
7622 });
7623 }
7624
7625 pub fn show_worktree_trust_security_modal(
7626 &mut self,
7627 toggle: bool,
7628 window: &mut Window,
7629 cx: &mut Context<Self>,
7630 ) {
7631 if let Some(security_modal) = self.active_modal::<SecurityModal>(cx) {
7632 if toggle {
7633 security_modal.update(cx, |security_modal, cx| {
7634 security_modal.dismiss(cx);
7635 })
7636 } else {
7637 security_modal.update(cx, |security_modal, cx| {
7638 security_modal.refresh_restricted_paths(cx);
7639 });
7640 }
7641 } else {
7642 let has_restricted_worktrees = TrustedWorktrees::try_get_global(cx)
7643 .map(|trusted_worktrees| {
7644 trusted_worktrees
7645 .read(cx)
7646 .has_restricted_worktrees(&self.project().read(cx).worktree_store(), cx)
7647 })
7648 .unwrap_or(false);
7649 if has_restricted_worktrees {
7650 let project = self.project().read(cx);
7651 let remote_host = project
7652 .remote_connection_options(cx)
7653 .map(RemoteHostLocation::from);
7654 let worktree_store = project.worktree_store().downgrade();
7655 self.toggle_modal(window, cx, |_, cx| {
7656 SecurityModal::new(worktree_store, remote_host, cx)
7657 });
7658 }
7659 }
7660 }
7661}
7662
7663pub trait AnyActiveCall {
7664 fn entity(&self) -> AnyEntity;
7665 fn is_in_room(&self, _: &App) -> bool;
7666 fn room_id(&self, _: &App) -> Option<u64>;
7667 fn channel_id(&self, _: &App) -> Option<ChannelId>;
7668 fn hang_up(&self, _: &mut App) -> Task<Result<()>>;
7669 fn unshare_project(&self, _: Entity<Project>, _: &mut App) -> Result<()>;
7670 fn remote_participant_for_peer_id(&self, _: PeerId, _: &App) -> Option<RemoteCollaborator>;
7671 fn is_sharing_project(&self, _: &App) -> bool;
7672 fn has_remote_participants(&self, _: &App) -> bool;
7673 fn local_participant_is_guest(&self, _: &App) -> bool;
7674 fn client(&self, _: &App) -> Arc<Client>;
7675 fn share_on_join(&self, _: &App) -> bool;
7676 fn join_channel(&self, _: ChannelId, _: &mut App) -> Task<Result<bool>>;
7677 fn room_update_completed(&self, _: &mut App) -> Task<()>;
7678 fn most_active_project(&self, _: &App) -> Option<(u64, u64)>;
7679 fn share_project(&self, _: Entity<Project>, _: &mut App) -> Task<Result<u64>>;
7680 fn join_project(
7681 &self,
7682 _: u64,
7683 _: Arc<LanguageRegistry>,
7684 _: Arc<dyn Fs>,
7685 _: &mut App,
7686 ) -> Task<Result<Entity<Project>>>;
7687 fn peer_id_for_user_in_room(&self, _: u64, _: &App) -> Option<PeerId>;
7688 fn subscribe(
7689 &self,
7690 _: &mut Window,
7691 _: &mut Context<Workspace>,
7692 _: Box<dyn Fn(&mut Workspace, &ActiveCallEvent, &mut Window, &mut Context<Workspace>)>,
7693 ) -> Subscription;
7694 fn create_shared_screen(
7695 &self,
7696 _: PeerId,
7697 _: &Entity<Pane>,
7698 _: &mut Window,
7699 _: &mut App,
7700 ) -> Option<Entity<SharedScreen>>;
7701}
7702
7703#[derive(Clone)]
7704pub struct GlobalAnyActiveCall(pub Arc<dyn AnyActiveCall>);
7705impl Global for GlobalAnyActiveCall {}
7706
7707impl GlobalAnyActiveCall {
7708 pub(crate) fn try_global(cx: &App) -> Option<&Self> {
7709 cx.try_global()
7710 }
7711
7712 pub(crate) fn global(cx: &App) -> &Self {
7713 cx.global()
7714 }
7715}
7716
7717/// Workspace-local view of a remote participant's location.
7718#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7719pub enum ParticipantLocation {
7720 SharedProject { project_id: u64 },
7721 UnsharedProject,
7722 External,
7723}
7724
7725impl ParticipantLocation {
7726 pub fn from_proto(location: Option<proto::ParticipantLocation>) -> Result<Self> {
7727 match location
7728 .and_then(|l| l.variant)
7729 .context("participant location was not provided")?
7730 {
7731 proto::participant_location::Variant::SharedProject(project) => {
7732 Ok(Self::SharedProject {
7733 project_id: project.id,
7734 })
7735 }
7736 proto::participant_location::Variant::UnsharedProject(_) => Ok(Self::UnsharedProject),
7737 proto::participant_location::Variant::External(_) => Ok(Self::External),
7738 }
7739 }
7740}
7741/// Workspace-local view of a remote collaborator's state.
7742/// This is the subset of `call::RemoteParticipant` that workspace needs.
7743#[derive(Clone)]
7744pub struct RemoteCollaborator {
7745 pub user: Arc<User>,
7746 pub peer_id: PeerId,
7747 pub location: ParticipantLocation,
7748 pub participant_index: ParticipantIndex,
7749}
7750
7751pub enum ActiveCallEvent {
7752 ParticipantLocationChanged { participant_id: PeerId },
7753 RemoteVideoTracksChanged { participant_id: PeerId },
7754}
7755
7756fn leader_border_for_pane(
7757 follower_states: &HashMap<CollaboratorId, FollowerState>,
7758 pane: &Entity<Pane>,
7759 _: &Window,
7760 cx: &App,
7761) -> Option<Div> {
7762 let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
7763 if state.pane() == pane {
7764 Some((*leader_id, state))
7765 } else {
7766 None
7767 }
7768 })?;
7769
7770 let mut leader_color = match leader_id {
7771 CollaboratorId::PeerId(leader_peer_id) => {
7772 let leader = GlobalAnyActiveCall::try_global(cx)?
7773 .0
7774 .remote_participant_for_peer_id(leader_peer_id, cx)?;
7775
7776 cx.theme()
7777 .players()
7778 .color_for_participant(leader.participant_index.0)
7779 .cursor
7780 }
7781 CollaboratorId::Agent => cx.theme().players().agent().cursor,
7782 };
7783 leader_color.fade_out(0.3);
7784 Some(
7785 div()
7786 .absolute()
7787 .size_full()
7788 .left_0()
7789 .top_0()
7790 .border_2()
7791 .border_color(leader_color),
7792 )
7793}
7794
7795fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
7796 ZED_WINDOW_POSITION
7797 .zip(*ZED_WINDOW_SIZE)
7798 .map(|(position, size)| Bounds {
7799 origin: position,
7800 size,
7801 })
7802}
7803
7804fn open_items(
7805 serialized_workspace: Option<SerializedWorkspace>,
7806 mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
7807 window: &mut Window,
7808 cx: &mut Context<Workspace>,
7809) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
7810 let restored_items = serialized_workspace.map(|serialized_workspace| {
7811 Workspace::load_workspace(
7812 serialized_workspace,
7813 project_paths_to_open
7814 .iter()
7815 .map(|(_, project_path)| project_path)
7816 .cloned()
7817 .collect(),
7818 window,
7819 cx,
7820 )
7821 });
7822
7823 cx.spawn_in(window, async move |workspace, cx| {
7824 let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
7825
7826 if let Some(restored_items) = restored_items {
7827 let restored_items = restored_items.await?;
7828
7829 let restored_project_paths = restored_items
7830 .iter()
7831 .filter_map(|item| {
7832 cx.update(|_, cx| item.as_ref()?.project_path(cx))
7833 .ok()
7834 .flatten()
7835 })
7836 .collect::<HashSet<_>>();
7837
7838 for restored_item in restored_items {
7839 opened_items.push(restored_item.map(Ok));
7840 }
7841
7842 project_paths_to_open
7843 .iter_mut()
7844 .for_each(|(_, project_path)| {
7845 if let Some(project_path_to_open) = project_path
7846 && restored_project_paths.contains(project_path_to_open)
7847 {
7848 *project_path = None;
7849 }
7850 });
7851 } else {
7852 for _ in 0..project_paths_to_open.len() {
7853 opened_items.push(None);
7854 }
7855 }
7856 assert!(opened_items.len() == project_paths_to_open.len());
7857
7858 let tasks =
7859 project_paths_to_open
7860 .into_iter()
7861 .enumerate()
7862 .map(|(ix, (abs_path, project_path))| {
7863 let workspace = workspace.clone();
7864 cx.spawn(async move |cx| {
7865 let file_project_path = project_path?;
7866 let abs_path_task = workspace.update(cx, |workspace, cx| {
7867 workspace.project().update(cx, |project, cx| {
7868 project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
7869 })
7870 });
7871
7872 // We only want to open file paths here. If one of the items
7873 // here is a directory, it was already opened further above
7874 // with a `find_or_create_worktree`.
7875 if let Ok(task) = abs_path_task
7876 && task.await.is_none_or(|p| p.is_file())
7877 {
7878 return Some((
7879 ix,
7880 workspace
7881 .update_in(cx, |workspace, window, cx| {
7882 workspace.open_path(
7883 file_project_path,
7884 None,
7885 true,
7886 window,
7887 cx,
7888 )
7889 })
7890 .log_err()?
7891 .await,
7892 ));
7893 }
7894 None
7895 })
7896 });
7897
7898 let tasks = tasks.collect::<Vec<_>>();
7899
7900 let tasks = futures::future::join_all(tasks);
7901 for (ix, path_open_result) in tasks.await.into_iter().flatten() {
7902 opened_items[ix] = Some(path_open_result);
7903 }
7904
7905 Ok(opened_items)
7906 })
7907}
7908
7909#[derive(Clone)]
7910enum ActivateInDirectionTarget {
7911 Pane(Entity<Pane>),
7912 Dock(Entity<Dock>),
7913 Sidebar(FocusHandle),
7914}
7915
7916fn notify_if_database_failed(window: WindowHandle<MultiWorkspace>, cx: &mut AsyncApp) {
7917 window
7918 .update(cx, |multi_workspace, _, cx| {
7919 let workspace = multi_workspace.workspace().clone();
7920 workspace.update(cx, |workspace, cx| {
7921 if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
7922 struct DatabaseFailedNotification;
7923
7924 workspace.show_notification(
7925 NotificationId::unique::<DatabaseFailedNotification>(),
7926 cx,
7927 |cx| {
7928 cx.new(|cx| {
7929 MessageNotification::new("Failed to load the database file.", cx)
7930 .primary_message("File an Issue")
7931 .primary_icon(IconName::Plus)
7932 .primary_on_click(|window, cx| {
7933 window.dispatch_action(Box::new(FileBugReport), cx)
7934 })
7935 })
7936 },
7937 );
7938 }
7939 });
7940 })
7941 .log_err();
7942}
7943
7944fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
7945 if val == 0 {
7946 ThemeSettings::get_global(cx).ui_font_size(cx)
7947 } else {
7948 px(val as f32)
7949 }
7950}
7951
7952fn adjust_active_dock_size_by_px(
7953 px: Pixels,
7954 workspace: &mut Workspace,
7955 window: &mut Window,
7956 cx: &mut Context<Workspace>,
7957) {
7958 let Some(active_dock) = workspace
7959 .all_docks()
7960 .into_iter()
7961 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
7962 else {
7963 return;
7964 };
7965 let dock = active_dock.read(cx);
7966 let Some(panel_size) = workspace.dock_size(&dock, window, cx) else {
7967 return;
7968 };
7969 workspace.resize_dock(dock.position(), panel_size + px, window, cx);
7970}
7971
7972fn adjust_open_docks_size_by_px(
7973 px: Pixels,
7974 workspace: &mut Workspace,
7975 window: &mut Window,
7976 cx: &mut Context<Workspace>,
7977) {
7978 let docks = workspace
7979 .all_docks()
7980 .into_iter()
7981 .filter_map(|dock_entity| {
7982 let dock = dock_entity.read(cx);
7983 if dock.is_open() {
7984 let dock_pos = dock.position();
7985 let panel_size = workspace.dock_size(&dock, window, cx)?;
7986 Some((dock_pos, panel_size + px))
7987 } else {
7988 None
7989 }
7990 })
7991 .collect::<Vec<_>>();
7992
7993 for (position, new_size) in docks {
7994 workspace.resize_dock(position, new_size, window, cx);
7995 }
7996}
7997
7998impl Focusable for Workspace {
7999 fn focus_handle(&self, cx: &App) -> FocusHandle {
8000 self.active_pane.focus_handle(cx)
8001 }
8002}
8003
8004#[derive(Clone)]
8005struct DraggedDock(DockPosition);
8006
8007impl Render for DraggedDock {
8008 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
8009 gpui::Empty
8010 }
8011}
8012
8013impl Render for Workspace {
8014 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
8015 static FIRST_PAINT: AtomicBool = AtomicBool::new(true);
8016 if FIRST_PAINT.swap(false, std::sync::atomic::Ordering::Relaxed) {
8017 log::info!("Rendered first frame");
8018 }
8019
8020 let centered_layout = self.centered_layout
8021 && self.center.panes().len() == 1
8022 && self.active_item(cx).is_some();
8023 let render_padding = |size| {
8024 (size > 0.0).then(|| {
8025 div()
8026 .h_full()
8027 .w(relative(size))
8028 .bg(cx.theme().colors().editor_background)
8029 .border_color(cx.theme().colors().pane_group_border)
8030 })
8031 };
8032 let paddings = if centered_layout {
8033 let settings = WorkspaceSettings::get_global(cx).centered_layout;
8034 (
8035 render_padding(Self::adjust_padding(
8036 settings.left_padding.map(|padding| padding.0),
8037 )),
8038 render_padding(Self::adjust_padding(
8039 settings.right_padding.map(|padding| padding.0),
8040 )),
8041 )
8042 } else {
8043 (None, None)
8044 };
8045 let ui_font = theme_settings::setup_ui_font(window, cx);
8046
8047 let theme = cx.theme().clone();
8048 let colors = theme.colors();
8049 let notification_entities = self
8050 .notifications
8051 .iter()
8052 .map(|(_, notification)| notification.entity_id())
8053 .collect::<Vec<_>>();
8054 let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
8055
8056 div()
8057 .relative()
8058 .size_full()
8059 .flex()
8060 .flex_col()
8061 .font(ui_font)
8062 .gap_0()
8063 .justify_start()
8064 .items_start()
8065 .text_color(colors.text)
8066 .overflow_hidden()
8067 .children(self.titlebar_item.clone())
8068 .on_modifiers_changed(move |_, _, cx| {
8069 for &id in ¬ification_entities {
8070 cx.notify(id);
8071 }
8072 })
8073 .child(
8074 div()
8075 .size_full()
8076 .relative()
8077 .flex_1()
8078 .flex()
8079 .flex_col()
8080 .child(
8081 div()
8082 .id("workspace")
8083 .bg(colors.background)
8084 .relative()
8085 .flex_1()
8086 .w_full()
8087 .flex()
8088 .flex_col()
8089 .overflow_hidden()
8090 .border_t_1()
8091 .border_b_1()
8092 .border_color(colors.border)
8093 .child({
8094 let this = cx.entity();
8095 canvas(
8096 move |bounds, window, cx| {
8097 this.update(cx, |this, cx| {
8098 let bounds_changed = this.bounds != bounds;
8099 this.bounds = bounds;
8100
8101 if bounds_changed {
8102 this.left_dock.update(cx, |dock, cx| {
8103 dock.clamp_panel_size(
8104 bounds.size.width,
8105 window,
8106 cx,
8107 )
8108 });
8109
8110 this.right_dock.update(cx, |dock, cx| {
8111 dock.clamp_panel_size(
8112 bounds.size.width,
8113 window,
8114 cx,
8115 )
8116 });
8117
8118 this.bottom_dock.update(cx, |dock, cx| {
8119 dock.clamp_panel_size(
8120 bounds.size.height,
8121 window,
8122 cx,
8123 )
8124 });
8125 }
8126 })
8127 },
8128 |_, _, _, _| {},
8129 )
8130 .absolute()
8131 .size_full()
8132 })
8133 .when(self.zoomed.is_none(), |this| {
8134 this.on_drag_move(cx.listener(
8135 move |workspace,
8136 e: &DragMoveEvent<DraggedDock>,
8137 window,
8138 cx| {
8139 if workspace.previous_dock_drag_coordinates
8140 != Some(e.event.position)
8141 {
8142 workspace.previous_dock_drag_coordinates =
8143 Some(e.event.position);
8144
8145 match e.drag(cx).0 {
8146 DockPosition::Left => {
8147 workspace.resize_left_dock(
8148 e.event.position.x
8149 - workspace.bounds.left(),
8150 window,
8151 cx,
8152 );
8153 }
8154 DockPosition::Right => {
8155 workspace.resize_right_dock(
8156 workspace.bounds.right()
8157 - e.event.position.x,
8158 window,
8159 cx,
8160 );
8161 }
8162 DockPosition::Bottom => {
8163 workspace.resize_bottom_dock(
8164 workspace.bounds.bottom()
8165 - e.event.position.y,
8166 window,
8167 cx,
8168 );
8169 }
8170 };
8171 workspace.serialize_workspace(window, cx);
8172 }
8173 },
8174 ))
8175
8176 })
8177 .child({
8178 match bottom_dock_layout {
8179 BottomDockLayout::Full => div()
8180 .flex()
8181 .flex_col()
8182 .h_full()
8183 .child(
8184 div()
8185 .flex()
8186 .flex_row()
8187 .flex_1()
8188 .overflow_hidden()
8189 .children(self.render_dock(
8190 DockPosition::Left,
8191 &self.left_dock,
8192 window,
8193 cx,
8194 ))
8195
8196 .child(
8197 div()
8198 .flex()
8199 .flex_col()
8200 .flex_1()
8201 .overflow_hidden()
8202 .child(
8203 h_flex()
8204 .flex_1()
8205 .when_some(
8206 paddings.0,
8207 |this, p| {
8208 this.child(
8209 p.border_r_1(),
8210 )
8211 },
8212 )
8213 .child(self.center.render(
8214 self.zoomed.as_ref(),
8215 &PaneRenderContext {
8216 follower_states:
8217 &self.follower_states,
8218 active_call: self.active_call(),
8219 active_pane: &self.active_pane,
8220 app_state: &self.app_state,
8221 project: &self.project,
8222 workspace: &self.weak_self,
8223 },
8224 window,
8225 cx,
8226 ))
8227 .when_some(
8228 paddings.1,
8229 |this, p| {
8230 this.child(
8231 p.border_l_1(),
8232 )
8233 },
8234 ),
8235 ),
8236 )
8237
8238 .children(self.render_dock(
8239 DockPosition::Right,
8240 &self.right_dock,
8241 window,
8242 cx,
8243 )),
8244 )
8245 .child(div().w_full().children(self.render_dock(
8246 DockPosition::Bottom,
8247 &self.bottom_dock,
8248 window,
8249 cx
8250 ))),
8251
8252 BottomDockLayout::LeftAligned => div()
8253 .flex()
8254 .flex_row()
8255 .h_full()
8256 .child(
8257 div()
8258 .flex()
8259 .flex_col()
8260 .flex_1()
8261 .h_full()
8262 .child(
8263 div()
8264 .flex()
8265 .flex_row()
8266 .flex_1()
8267 .children(self.render_dock(DockPosition::Left, &self.left_dock, window, cx))
8268
8269 .child(
8270 div()
8271 .flex()
8272 .flex_col()
8273 .flex_1()
8274 .overflow_hidden()
8275 .child(
8276 h_flex()
8277 .flex_1()
8278 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
8279 .child(self.center.render(
8280 self.zoomed.as_ref(),
8281 &PaneRenderContext {
8282 follower_states:
8283 &self.follower_states,
8284 active_call: self.active_call(),
8285 active_pane: &self.active_pane,
8286 app_state: &self.app_state,
8287 project: &self.project,
8288 workspace: &self.weak_self,
8289 },
8290 window,
8291 cx,
8292 ))
8293 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
8294 )
8295 )
8296
8297 )
8298 .child(
8299 div()
8300 .w_full()
8301 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
8302 ),
8303 )
8304 .children(self.render_dock(
8305 DockPosition::Right,
8306 &self.right_dock,
8307 window,
8308 cx,
8309 )),
8310 BottomDockLayout::RightAligned => div()
8311 .flex()
8312 .flex_row()
8313 .h_full()
8314 .children(self.render_dock(
8315 DockPosition::Left,
8316 &self.left_dock,
8317 window,
8318 cx,
8319 ))
8320
8321 .child(
8322 div()
8323 .flex()
8324 .flex_col()
8325 .flex_1()
8326 .h_full()
8327 .child(
8328 div()
8329 .flex()
8330 .flex_row()
8331 .flex_1()
8332 .child(
8333 div()
8334 .flex()
8335 .flex_col()
8336 .flex_1()
8337 .overflow_hidden()
8338 .child(
8339 h_flex()
8340 .flex_1()
8341 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
8342 .child(self.center.render(
8343 self.zoomed.as_ref(),
8344 &PaneRenderContext {
8345 follower_states:
8346 &self.follower_states,
8347 active_call: self.active_call(),
8348 active_pane: &self.active_pane,
8349 app_state: &self.app_state,
8350 project: &self.project,
8351 workspace: &self.weak_self,
8352 },
8353 window,
8354 cx,
8355 ))
8356 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
8357 )
8358 )
8359
8360 .children(self.render_dock(DockPosition::Right, &self.right_dock, window, cx))
8361 )
8362 .child(
8363 div()
8364 .w_full()
8365 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
8366 ),
8367 ),
8368 BottomDockLayout::Contained => div()
8369 .flex()
8370 .flex_row()
8371 .h_full()
8372 .children(self.render_dock(
8373 DockPosition::Left,
8374 &self.left_dock,
8375 window,
8376 cx,
8377 ))
8378
8379 .child(
8380 div()
8381 .flex()
8382 .flex_col()
8383 .flex_1()
8384 .overflow_hidden()
8385 .child(
8386 h_flex()
8387 .flex_1()
8388 .when_some(paddings.0, |this, p| {
8389 this.child(p.border_r_1())
8390 })
8391 .child(self.center.render(
8392 self.zoomed.as_ref(),
8393 &PaneRenderContext {
8394 follower_states:
8395 &self.follower_states,
8396 active_call: self.active_call(),
8397 active_pane: &self.active_pane,
8398 app_state: &self.app_state,
8399 project: &self.project,
8400 workspace: &self.weak_self,
8401 },
8402 window,
8403 cx,
8404 ))
8405 .when_some(paddings.1, |this, p| {
8406 this.child(p.border_l_1())
8407 }),
8408 )
8409 .children(self.render_dock(
8410 DockPosition::Bottom,
8411 &self.bottom_dock,
8412 window,
8413 cx,
8414 )),
8415 )
8416
8417 .children(self.render_dock(
8418 DockPosition::Right,
8419 &self.right_dock,
8420 window,
8421 cx,
8422 )),
8423 }
8424 })
8425 .children(self.zoomed.as_ref().and_then(|view| {
8426 let zoomed_view = view.upgrade()?;
8427 let div = div()
8428 .occlude()
8429 .absolute()
8430 .overflow_hidden()
8431 .border_color(colors.border)
8432 .bg(colors.background)
8433 .child(zoomed_view)
8434 .inset_0()
8435 .shadow_lg();
8436
8437 if !WorkspaceSettings::get_global(cx).zoomed_padding {
8438 return Some(div);
8439 }
8440
8441 Some(match self.zoomed_position {
8442 Some(DockPosition::Left) => div.right_2().border_r_1(),
8443 Some(DockPosition::Right) => div.left_2().border_l_1(),
8444 Some(DockPosition::Bottom) => div.top_2().border_t_1(),
8445 None => {
8446 div.top_2().bottom_2().left_2().right_2().border_1()
8447 }
8448 })
8449 }))
8450 .children(self.render_notifications(window, cx)),
8451 )
8452 .when(self.status_bar_visible(cx), |parent| {
8453 parent.child(self.status_bar.clone())
8454 })
8455 .child(self.toast_layer.clone()),
8456 )
8457 }
8458}
8459
8460impl WorkspaceStore {
8461 pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
8462 Self {
8463 workspaces: Default::default(),
8464 _subscriptions: vec![
8465 client.add_request_handler(cx.weak_entity(), Self::handle_follow),
8466 client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
8467 ],
8468 client,
8469 }
8470 }
8471
8472 pub fn update_followers(
8473 &self,
8474 project_id: Option<u64>,
8475 update: proto::update_followers::Variant,
8476 cx: &App,
8477 ) -> Option<()> {
8478 let active_call = GlobalAnyActiveCall::try_global(cx)?;
8479 let room_id = active_call.0.room_id(cx)?;
8480 self.client
8481 .send(proto::UpdateFollowers {
8482 room_id,
8483 project_id,
8484 variant: Some(update),
8485 })
8486 .log_err()
8487 }
8488
8489 pub async fn handle_follow(
8490 this: Entity<Self>,
8491 envelope: TypedEnvelope<proto::Follow>,
8492 mut cx: AsyncApp,
8493 ) -> Result<proto::FollowResponse> {
8494 this.update(&mut cx, |this, cx| {
8495 let follower = Follower {
8496 project_id: envelope.payload.project_id,
8497 peer_id: envelope.original_sender_id()?,
8498 };
8499
8500 let mut response = proto::FollowResponse::default();
8501
8502 this.workspaces.retain(|(window_handle, weak_workspace)| {
8503 let Some(workspace) = weak_workspace.upgrade() else {
8504 return false;
8505 };
8506 window_handle
8507 .update(cx, |_, window, cx| {
8508 workspace.update(cx, |workspace, cx| {
8509 let handler_response =
8510 workspace.handle_follow(follower.project_id, window, cx);
8511 if let Some(active_view) = handler_response.active_view
8512 && workspace.project.read(cx).remote_id() == follower.project_id
8513 {
8514 response.active_view = Some(active_view)
8515 }
8516 });
8517 })
8518 .is_ok()
8519 });
8520
8521 Ok(response)
8522 })
8523 }
8524
8525 async fn handle_update_followers(
8526 this: Entity<Self>,
8527 envelope: TypedEnvelope<proto::UpdateFollowers>,
8528 mut cx: AsyncApp,
8529 ) -> Result<()> {
8530 let leader_id = envelope.original_sender_id()?;
8531 let update = envelope.payload;
8532
8533 this.update(&mut cx, |this, cx| {
8534 this.workspaces.retain(|(window_handle, weak_workspace)| {
8535 let Some(workspace) = weak_workspace.upgrade() else {
8536 return false;
8537 };
8538 window_handle
8539 .update(cx, |_, window, cx| {
8540 workspace.update(cx, |workspace, cx| {
8541 let project_id = workspace.project.read(cx).remote_id();
8542 if update.project_id != project_id && update.project_id.is_some() {
8543 return;
8544 }
8545 workspace.handle_update_followers(
8546 leader_id,
8547 update.clone(),
8548 window,
8549 cx,
8550 );
8551 });
8552 })
8553 .is_ok()
8554 });
8555 Ok(())
8556 })
8557 }
8558
8559 pub fn workspaces(&self) -> impl Iterator<Item = &WeakEntity<Workspace>> {
8560 self.workspaces.iter().map(|(_, weak)| weak)
8561 }
8562
8563 pub fn workspaces_with_windows(
8564 &self,
8565 ) -> impl Iterator<Item = (gpui::AnyWindowHandle, &WeakEntity<Workspace>)> {
8566 self.workspaces.iter().map(|(window, weak)| (*window, weak))
8567 }
8568}
8569
8570impl ViewId {
8571 pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
8572 Ok(Self {
8573 creator: message
8574 .creator
8575 .map(CollaboratorId::PeerId)
8576 .context("creator is missing")?,
8577 id: message.id,
8578 })
8579 }
8580
8581 pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
8582 if let CollaboratorId::PeerId(peer_id) = self.creator {
8583 Some(proto::ViewId {
8584 creator: Some(peer_id),
8585 id: self.id,
8586 })
8587 } else {
8588 None
8589 }
8590 }
8591}
8592
8593impl FollowerState {
8594 fn pane(&self) -> &Entity<Pane> {
8595 self.dock_pane.as_ref().unwrap_or(&self.center_pane)
8596 }
8597}
8598
8599pub trait WorkspaceHandle {
8600 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
8601}
8602
8603impl WorkspaceHandle for Entity<Workspace> {
8604 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
8605 self.read(cx)
8606 .worktrees(cx)
8607 .flat_map(|worktree| {
8608 let worktree_id = worktree.read(cx).id();
8609 worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
8610 worktree_id,
8611 path: f.path.clone(),
8612 })
8613 })
8614 .collect::<Vec<_>>()
8615 }
8616}
8617
8618pub async fn last_opened_workspace_location(
8619 db: &WorkspaceDb,
8620 fs: &dyn fs::Fs,
8621) -> Option<(WorkspaceId, SerializedWorkspaceLocation, PathList)> {
8622 db.last_workspace(fs)
8623 .await
8624 .log_err()
8625 .flatten()
8626 .map(|(id, location, paths, _timestamp)| (id, location, paths))
8627}
8628
8629pub async fn last_session_workspace_locations(
8630 db: &WorkspaceDb,
8631 last_session_id: &str,
8632 last_session_window_stack: Option<Vec<WindowId>>,
8633 fs: &dyn fs::Fs,
8634) -> Option<Vec<SessionWorkspace>> {
8635 db.last_session_workspace_locations(last_session_id, last_session_window_stack, fs)
8636 .await
8637 .log_err()
8638}
8639
8640pub async fn restore_multiworkspace(
8641 multi_workspace: SerializedMultiWorkspace,
8642 app_state: Arc<AppState>,
8643 cx: &mut AsyncApp,
8644) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
8645 let SerializedMultiWorkspace {
8646 active_workspace,
8647 state,
8648 } = multi_workspace;
8649 let MultiWorkspaceState {
8650 sidebar_open,
8651 project_group_keys,
8652 sidebar_state,
8653 ..
8654 } = state;
8655
8656 let window_handle = if active_workspace.paths.is_empty() {
8657 cx.update(|cx| {
8658 open_workspace_by_id(active_workspace.workspace_id, app_state.clone(), None, cx)
8659 })
8660 .await?
8661 } else {
8662 let OpenResult { window, .. } = cx
8663 .update(|cx| {
8664 Workspace::new_local(
8665 active_workspace.paths.paths().to_vec(),
8666 app_state.clone(),
8667 None,
8668 None,
8669 None,
8670 OpenMode::Activate,
8671 cx,
8672 )
8673 })
8674 .await?;
8675 window
8676 };
8677
8678 if !project_group_keys.is_empty() {
8679 let restored_keys: Vec<ProjectGroupKey> =
8680 project_group_keys.into_iter().map(Into::into).collect();
8681 window_handle
8682 .update(cx, |multi_workspace, _window, _cx| {
8683 multi_workspace.restore_project_group_keys(restored_keys);
8684 })
8685 .ok();
8686 }
8687
8688 if sidebar_open {
8689 window_handle
8690 .update(cx, |multi_workspace, _, cx| {
8691 multi_workspace.open_sidebar(cx);
8692 })
8693 .ok();
8694 }
8695
8696 if let Some(sidebar_state) = sidebar_state {
8697 window_handle
8698 .update(cx, |multi_workspace, window, cx| {
8699 if let Some(sidebar) = multi_workspace.sidebar() {
8700 sidebar.restore_serialized_state(&sidebar_state, window, cx);
8701 }
8702 multi_workspace.serialize(cx);
8703 })
8704 .ok();
8705 }
8706
8707 window_handle
8708 .update(cx, |_, window, _cx| {
8709 window.activate_window();
8710 })
8711 .ok();
8712
8713 Ok(window_handle)
8714}
8715
8716actions!(
8717 collab,
8718 [
8719 /// Opens the channel notes for the current call.
8720 ///
8721 /// Use `collab_panel::OpenSelectedChannelNotes` to open the channel notes for the selected
8722 /// channel in the collab panel.
8723 ///
8724 /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
8725 /// can be copied via "Copy link to section" in the context menu of the channel notes
8726 /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
8727 OpenChannelNotes,
8728 /// Mutes your microphone.
8729 Mute,
8730 /// Deafens yourself (mute both microphone and speakers).
8731 Deafen,
8732 /// Leaves the current call.
8733 LeaveCall,
8734 /// Shares the current project with collaborators.
8735 ShareProject,
8736 /// Shares your screen with collaborators.
8737 ScreenShare,
8738 /// Copies the current room name and session id for debugging purposes.
8739 CopyRoomId,
8740 ]
8741);
8742
8743/// Opens the channel notes for a specific channel by its ID.
8744#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
8745#[action(namespace = collab)]
8746#[serde(deny_unknown_fields)]
8747pub struct OpenChannelNotesById {
8748 pub channel_id: u64,
8749}
8750
8751actions!(
8752 zed,
8753 [
8754 /// Opens the Zed log file.
8755 OpenLog,
8756 /// Reveals the Zed log file in the system file manager.
8757 RevealLogInFileManager
8758 ]
8759);
8760
8761async fn join_channel_internal(
8762 channel_id: ChannelId,
8763 app_state: &Arc<AppState>,
8764 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8765 requesting_workspace: Option<WeakEntity<Workspace>>,
8766 active_call: &dyn AnyActiveCall,
8767 cx: &mut AsyncApp,
8768) -> Result<bool> {
8769 let (should_prompt, already_in_channel) = cx.update(|cx| {
8770 if !active_call.is_in_room(cx) {
8771 return (false, false);
8772 }
8773
8774 let already_in_channel = active_call.channel_id(cx) == Some(channel_id);
8775 let should_prompt = active_call.is_sharing_project(cx)
8776 && active_call.has_remote_participants(cx)
8777 && !already_in_channel;
8778 (should_prompt, already_in_channel)
8779 });
8780
8781 if already_in_channel {
8782 let task = cx.update(|cx| {
8783 if let Some((project, host)) = active_call.most_active_project(cx) {
8784 Some(join_in_room_project(project, host, app_state.clone(), cx))
8785 } else {
8786 None
8787 }
8788 });
8789 if let Some(task) = task {
8790 task.await?;
8791 }
8792 return anyhow::Ok(true);
8793 }
8794
8795 if should_prompt {
8796 if let Some(multi_workspace) = requesting_window {
8797 let answer = multi_workspace
8798 .update(cx, |_, window, cx| {
8799 window.prompt(
8800 PromptLevel::Warning,
8801 "Do you want to switch channels?",
8802 Some("Leaving this call will unshare your current project."),
8803 &["Yes, Join Channel", "Cancel"],
8804 cx,
8805 )
8806 })?
8807 .await;
8808
8809 if answer == Ok(1) {
8810 return Ok(false);
8811 }
8812 } else {
8813 return Ok(false);
8814 }
8815 }
8816
8817 let client = cx.update(|cx| active_call.client(cx));
8818
8819 let mut client_status = client.status();
8820
8821 // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
8822 'outer: loop {
8823 let Some(status) = client_status.recv().await else {
8824 anyhow::bail!("error connecting");
8825 };
8826
8827 match status {
8828 Status::Connecting
8829 | Status::Authenticating
8830 | Status::Authenticated
8831 | Status::Reconnecting
8832 | Status::Reauthenticating
8833 | Status::Reauthenticated => continue,
8834 Status::Connected { .. } => break 'outer,
8835 Status::SignedOut | Status::AuthenticationError => {
8836 return Err(ErrorCode::SignedOut.into());
8837 }
8838 Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
8839 Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
8840 return Err(ErrorCode::Disconnected.into());
8841 }
8842 }
8843 }
8844
8845 let joined = cx
8846 .update(|cx| active_call.join_channel(channel_id, cx))
8847 .await?;
8848
8849 if !joined {
8850 return anyhow::Ok(true);
8851 }
8852
8853 cx.update(|cx| active_call.room_update_completed(cx)).await;
8854
8855 let task = cx.update(|cx| {
8856 if let Some((project, host)) = active_call.most_active_project(cx) {
8857 return Some(join_in_room_project(project, host, app_state.clone(), cx));
8858 }
8859
8860 // If you are the first to join a channel, see if you should share your project.
8861 if !active_call.has_remote_participants(cx)
8862 && !active_call.local_participant_is_guest(cx)
8863 && let Some(workspace) = requesting_workspace.as_ref().and_then(|w| w.upgrade())
8864 {
8865 let project = workspace.update(cx, |workspace, cx| {
8866 let project = workspace.project.read(cx);
8867
8868 if !active_call.share_on_join(cx) {
8869 return None;
8870 }
8871
8872 if (project.is_local() || project.is_via_remote_server())
8873 && project.visible_worktrees(cx).any(|tree| {
8874 tree.read(cx)
8875 .root_entry()
8876 .is_some_and(|entry| entry.is_dir())
8877 })
8878 {
8879 Some(workspace.project.clone())
8880 } else {
8881 None
8882 }
8883 });
8884 if let Some(project) = project {
8885 let share_task = active_call.share_project(project, cx);
8886 return Some(cx.spawn(async move |_cx| -> Result<()> {
8887 share_task.await?;
8888 Ok(())
8889 }));
8890 }
8891 }
8892
8893 None
8894 });
8895 if let Some(task) = task {
8896 task.await?;
8897 return anyhow::Ok(true);
8898 }
8899 anyhow::Ok(false)
8900}
8901
8902pub fn join_channel(
8903 channel_id: ChannelId,
8904 app_state: Arc<AppState>,
8905 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8906 requesting_workspace: Option<WeakEntity<Workspace>>,
8907 cx: &mut App,
8908) -> Task<Result<()>> {
8909 let active_call = GlobalAnyActiveCall::global(cx).clone();
8910 cx.spawn(async move |cx| {
8911 let result = join_channel_internal(
8912 channel_id,
8913 &app_state,
8914 requesting_window,
8915 requesting_workspace,
8916 &*active_call.0,
8917 cx,
8918 )
8919 .await;
8920
8921 // join channel succeeded, and opened a window
8922 if matches!(result, Ok(true)) {
8923 return anyhow::Ok(());
8924 }
8925
8926 // find an existing workspace to focus and show call controls
8927 let mut active_window = requesting_window.or_else(|| activate_any_workspace_window(cx));
8928 if active_window.is_none() {
8929 // no open workspaces, make one to show the error in (blergh)
8930 let OpenResult {
8931 window: window_handle,
8932 ..
8933 } = cx
8934 .update(|cx| {
8935 Workspace::new_local(
8936 vec![],
8937 app_state.clone(),
8938 requesting_window,
8939 None,
8940 None,
8941 OpenMode::Activate,
8942 cx,
8943 )
8944 })
8945 .await?;
8946
8947 window_handle
8948 .update(cx, |_, window, _cx| {
8949 window.activate_window();
8950 })
8951 .ok();
8952
8953 if result.is_ok() {
8954 cx.update(|cx| {
8955 cx.dispatch_action(&OpenChannelNotes);
8956 });
8957 }
8958
8959 active_window = Some(window_handle);
8960 }
8961
8962 if let Err(err) = result {
8963 log::error!("failed to join channel: {}", err);
8964 if let Some(active_window) = active_window {
8965 active_window
8966 .update(cx, |_, window, cx| {
8967 let detail: SharedString = match err.error_code() {
8968 ErrorCode::SignedOut => "Please sign in to continue.".into(),
8969 ErrorCode::UpgradeRequired => concat!(
8970 "Your are running an unsupported version of Zed. ",
8971 "Please update to continue."
8972 )
8973 .into(),
8974 ErrorCode::NoSuchChannel => concat!(
8975 "No matching channel was found. ",
8976 "Please check the link and try again."
8977 )
8978 .into(),
8979 ErrorCode::Forbidden => concat!(
8980 "This channel is private, and you do not have access. ",
8981 "Please ask someone to add you and try again."
8982 )
8983 .into(),
8984 ErrorCode::Disconnected => {
8985 "Please check your internet connection and try again.".into()
8986 }
8987 _ => format!("{}\n\nPlease try again.", err).into(),
8988 };
8989 window.prompt(
8990 PromptLevel::Critical,
8991 "Failed to join channel",
8992 Some(&detail),
8993 &["Ok"],
8994 cx,
8995 )
8996 })?
8997 .await
8998 .ok();
8999 }
9000 }
9001
9002 // return ok, we showed the error to the user.
9003 anyhow::Ok(())
9004 })
9005}
9006
9007pub async fn get_any_active_multi_workspace(
9008 app_state: Arc<AppState>,
9009 mut cx: AsyncApp,
9010) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
9011 // find an existing workspace to focus and show call controls
9012 let active_window = activate_any_workspace_window(&mut cx);
9013 if active_window.is_none() {
9014 cx.update(|cx| {
9015 Workspace::new_local(
9016 vec![],
9017 app_state.clone(),
9018 None,
9019 None,
9020 None,
9021 OpenMode::Activate,
9022 cx,
9023 )
9024 })
9025 .await?;
9026 }
9027 activate_any_workspace_window(&mut cx).context("could not open zed")
9028}
9029
9030fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<MultiWorkspace>> {
9031 cx.update(|cx| {
9032 if let Some(workspace_window) = cx
9033 .active_window()
9034 .and_then(|window| window.downcast::<MultiWorkspace>())
9035 {
9036 return Some(workspace_window);
9037 }
9038
9039 for window in cx.windows() {
9040 if let Some(workspace_window) = window.downcast::<MultiWorkspace>() {
9041 workspace_window
9042 .update(cx, |_, window, _| window.activate_window())
9043 .ok();
9044 return Some(workspace_window);
9045 }
9046 }
9047 None
9048 })
9049}
9050
9051pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<MultiWorkspace>> {
9052 workspace_windows_for_location(&SerializedWorkspaceLocation::Local, cx)
9053}
9054
9055pub fn workspace_windows_for_location(
9056 serialized_location: &SerializedWorkspaceLocation,
9057 cx: &App,
9058) -> Vec<WindowHandle<MultiWorkspace>> {
9059 cx.windows()
9060 .into_iter()
9061 .filter_map(|window| window.downcast::<MultiWorkspace>())
9062 .filter(|multi_workspace| {
9063 let same_host = |left: &RemoteConnectionOptions, right: &RemoteConnectionOptions| match (left, right) {
9064 (RemoteConnectionOptions::Ssh(a), RemoteConnectionOptions::Ssh(b)) => {
9065 (&a.host, &a.username, &a.port) == (&b.host, &b.username, &b.port)
9066 }
9067 (RemoteConnectionOptions::Wsl(a), RemoteConnectionOptions::Wsl(b)) => {
9068 // The WSL username is not consistently populated in the workspace location, so ignore it for now.
9069 a.distro_name == b.distro_name
9070 }
9071 (RemoteConnectionOptions::Docker(a), RemoteConnectionOptions::Docker(b)) => {
9072 a.container_id == b.container_id
9073 }
9074 #[cfg(any(test, feature = "test-support"))]
9075 (RemoteConnectionOptions::Mock(a), RemoteConnectionOptions::Mock(b)) => {
9076 a.id == b.id
9077 }
9078 _ => false,
9079 };
9080
9081 multi_workspace.read(cx).is_ok_and(|multi_workspace| {
9082 multi_workspace.workspaces().any(|workspace| {
9083 match workspace.read(cx).workspace_location(cx) {
9084 WorkspaceLocation::Location(location, _) => {
9085 match (&location, serialized_location) {
9086 (
9087 SerializedWorkspaceLocation::Local,
9088 SerializedWorkspaceLocation::Local,
9089 ) => true,
9090 (
9091 SerializedWorkspaceLocation::Remote(a),
9092 SerializedWorkspaceLocation::Remote(b),
9093 ) => same_host(a, b),
9094 _ => false,
9095 }
9096 }
9097 _ => false,
9098 }
9099 })
9100 })
9101 })
9102 .collect()
9103}
9104
9105pub async fn find_existing_workspace(
9106 abs_paths: &[PathBuf],
9107 open_options: &OpenOptions,
9108 location: &SerializedWorkspaceLocation,
9109 cx: &mut AsyncApp,
9110) -> (
9111 Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)>,
9112 OpenVisible,
9113) {
9114 let mut existing: Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)> = None;
9115 let mut open_visible = OpenVisible::All;
9116 let mut best_match = None;
9117
9118 if open_options.open_new_workspace != Some(true) {
9119 cx.update(|cx| {
9120 for window in workspace_windows_for_location(location, cx) {
9121 if let Ok(multi_workspace) = window.read(cx) {
9122 for workspace in multi_workspace.workspaces() {
9123 let project = workspace.read(cx).project.read(cx);
9124 let m = project.visibility_for_paths(
9125 abs_paths,
9126 open_options.open_new_workspace == None,
9127 cx,
9128 );
9129 if m > best_match {
9130 existing = Some((window, workspace.clone()));
9131 best_match = m;
9132 } else if best_match.is_none()
9133 && open_options.open_new_workspace == Some(false)
9134 {
9135 existing = Some((window, workspace.clone()))
9136 }
9137 }
9138 }
9139 }
9140 });
9141
9142 let all_paths_are_files = existing
9143 .as_ref()
9144 .and_then(|(_, target_workspace)| {
9145 cx.update(|cx| {
9146 let workspace = target_workspace.read(cx);
9147 let project = workspace.project.read(cx);
9148 let path_style = workspace.path_style(cx);
9149 Some(!abs_paths.iter().any(|path| {
9150 let path = util::paths::SanitizedPath::new(path);
9151 project.worktrees(cx).any(|worktree| {
9152 let worktree = worktree.read(cx);
9153 let abs_path = worktree.abs_path();
9154 path_style
9155 .strip_prefix(path.as_ref(), abs_path.as_ref())
9156 .and_then(|rel| worktree.entry_for_path(&rel))
9157 .is_some_and(|e| e.is_dir())
9158 })
9159 }))
9160 })
9161 })
9162 .unwrap_or(false);
9163
9164 if open_options.open_new_workspace.is_none()
9165 && existing.is_some()
9166 && open_options.wait
9167 && all_paths_are_files
9168 {
9169 cx.update(|cx| {
9170 let windows = workspace_windows_for_location(location, cx);
9171 let window = cx
9172 .active_window()
9173 .and_then(|window| window.downcast::<MultiWorkspace>())
9174 .filter(|window| windows.contains(window))
9175 .or_else(|| windows.into_iter().next());
9176 if let Some(window) = window {
9177 if let Ok(multi_workspace) = window.read(cx) {
9178 let active_workspace = multi_workspace.workspace().clone();
9179 existing = Some((window, active_workspace));
9180 open_visible = OpenVisible::None;
9181 }
9182 }
9183 });
9184 }
9185 }
9186 (existing, open_visible)
9187}
9188
9189#[derive(Default, Clone)]
9190pub struct OpenOptions {
9191 pub visible: Option<OpenVisible>,
9192 pub focus: Option<bool>,
9193 pub open_new_workspace: Option<bool>,
9194 pub wait: bool,
9195 pub requesting_window: Option<WindowHandle<MultiWorkspace>>,
9196 pub open_mode: OpenMode,
9197 pub env: Option<HashMap<String, String>>,
9198 pub open_in_dev_container: bool,
9199}
9200
9201/// The result of opening a workspace via [`open_paths`], [`Workspace::new_local`],
9202/// or [`Workspace::open_workspace_for_paths`].
9203pub struct OpenResult {
9204 pub window: WindowHandle<MultiWorkspace>,
9205 pub workspace: Entity<Workspace>,
9206 pub opened_items: Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
9207}
9208
9209/// Opens a workspace by its database ID, used for restoring empty workspaces with unsaved content.
9210pub fn open_workspace_by_id(
9211 workspace_id: WorkspaceId,
9212 app_state: Arc<AppState>,
9213 requesting_window: Option<WindowHandle<MultiWorkspace>>,
9214 cx: &mut App,
9215) -> Task<anyhow::Result<WindowHandle<MultiWorkspace>>> {
9216 let project_handle = Project::local(
9217 app_state.client.clone(),
9218 app_state.node_runtime.clone(),
9219 app_state.user_store.clone(),
9220 app_state.languages.clone(),
9221 app_state.fs.clone(),
9222 None,
9223 project::LocalProjectFlags {
9224 init_worktree_trust: true,
9225 ..project::LocalProjectFlags::default()
9226 },
9227 cx,
9228 );
9229
9230 let db = WorkspaceDb::global(cx);
9231 let kvp = db::kvp::KeyValueStore::global(cx);
9232 cx.spawn(async move |cx| {
9233 let serialized_workspace = db
9234 .workspace_for_id(workspace_id)
9235 .with_context(|| format!("Workspace {workspace_id:?} not found"))?;
9236
9237 let centered_layout = serialized_workspace.centered_layout;
9238
9239 let (window, workspace) = if let Some(window) = requesting_window {
9240 let workspace = window.update(cx, |multi_workspace, window, cx| {
9241 let workspace = cx.new(|cx| {
9242 let mut workspace = Workspace::new(
9243 Some(workspace_id),
9244 project_handle.clone(),
9245 app_state.clone(),
9246 window,
9247 cx,
9248 );
9249 workspace.centered_layout = centered_layout;
9250 workspace
9251 });
9252 multi_workspace.add(workspace.clone(), &*window, cx);
9253 workspace
9254 })?;
9255 (window, workspace)
9256 } else {
9257 let window_bounds_override = window_bounds_env_override();
9258
9259 let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
9260 (Some(WindowBounds::Windowed(bounds)), None)
9261 } else if let Some(display) = serialized_workspace.display
9262 && let Some(bounds) = serialized_workspace.window_bounds.as_ref()
9263 {
9264 (Some(bounds.0), Some(display))
9265 } else if let Some((display, bounds)) = persistence::read_default_window_bounds(&kvp) {
9266 (Some(bounds), Some(display))
9267 } else {
9268 (None, None)
9269 };
9270
9271 let options = cx.update(|cx| {
9272 let mut options = (app_state.build_window_options)(display, cx);
9273 options.window_bounds = window_bounds;
9274 options
9275 });
9276
9277 let window = cx.open_window(options, {
9278 let app_state = app_state.clone();
9279 let project_handle = project_handle.clone();
9280 move |window, cx| {
9281 let workspace = cx.new(|cx| {
9282 let mut workspace = Workspace::new(
9283 Some(workspace_id),
9284 project_handle,
9285 app_state,
9286 window,
9287 cx,
9288 );
9289 workspace.centered_layout = centered_layout;
9290 workspace
9291 });
9292 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
9293 }
9294 })?;
9295
9296 let workspace = window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
9297 multi_workspace.workspace().clone()
9298 })?;
9299
9300 (window, workspace)
9301 };
9302
9303 notify_if_database_failed(window, cx);
9304
9305 // Restore items from the serialized workspace
9306 window
9307 .update(cx, |_, window, cx| {
9308 workspace.update(cx, |_workspace, cx| {
9309 open_items(Some(serialized_workspace), vec![], window, cx)
9310 })
9311 })?
9312 .await?;
9313
9314 window.update(cx, |_, window, cx| {
9315 workspace.update(cx, |workspace, cx| {
9316 workspace.serialize_workspace(window, cx);
9317 });
9318 })?;
9319
9320 Ok(window)
9321 })
9322}
9323
9324#[allow(clippy::type_complexity)]
9325pub fn open_paths(
9326 abs_paths: &[PathBuf],
9327 app_state: Arc<AppState>,
9328 mut open_options: OpenOptions,
9329 cx: &mut App,
9330) -> Task<anyhow::Result<OpenResult>> {
9331 let abs_paths = abs_paths.to_vec();
9332 #[cfg(target_os = "windows")]
9333 let wsl_path = abs_paths
9334 .iter()
9335 .find_map(|p| util::paths::WslPath::from_path(p));
9336
9337 cx.spawn(async move |cx| {
9338 let (mut existing, mut open_visible) = find_existing_workspace(
9339 &abs_paths,
9340 &open_options,
9341 &SerializedWorkspaceLocation::Local,
9342 cx,
9343 )
9344 .await;
9345
9346 // Fallback: if no workspace contains the paths and all paths are files,
9347 // prefer an existing local workspace window (active window first).
9348 if open_options.open_new_workspace.is_none() && existing.is_none() {
9349 let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
9350 let all_metadatas = futures::future::join_all(all_paths)
9351 .await
9352 .into_iter()
9353 .filter_map(|result| result.ok().flatten());
9354
9355 if all_metadatas.into_iter().all(|file| !file.is_dir) {
9356 cx.update(|cx| {
9357 let windows = workspace_windows_for_location(
9358 &SerializedWorkspaceLocation::Local,
9359 cx,
9360 );
9361 let window = cx
9362 .active_window()
9363 .and_then(|window| window.downcast::<MultiWorkspace>())
9364 .filter(|window| windows.contains(window))
9365 .or_else(|| windows.into_iter().next());
9366 if let Some(window) = window {
9367 if let Ok(multi_workspace) = window.read(cx) {
9368 let active_workspace = multi_workspace.workspace().clone();
9369 existing = Some((window, active_workspace));
9370 open_visible = OpenVisible::None;
9371 }
9372 }
9373 });
9374 }
9375 }
9376
9377 // Fallback for directories: when no flag is specified and no existing
9378 // workspace matched, add the directory as a new workspace in the
9379 // active window's MultiWorkspace (instead of opening a new window).
9380 if open_options.open_new_workspace.is_none() && existing.is_none() {
9381 let target_window = cx.update(|cx| {
9382 let windows = workspace_windows_for_location(
9383 &SerializedWorkspaceLocation::Local,
9384 cx,
9385 );
9386 let window = cx
9387 .active_window()
9388 .and_then(|window| window.downcast::<MultiWorkspace>())
9389 .filter(|window| windows.contains(window))
9390 .or_else(|| windows.into_iter().next());
9391 window.filter(|window| {
9392 window.read(cx).is_ok_and(|mw| mw.multi_workspace_enabled(cx))
9393 })
9394 });
9395
9396 if let Some(window) = target_window {
9397 open_options.requesting_window = Some(window);
9398 window
9399 .update(cx, |multi_workspace, _, cx| {
9400 multi_workspace.open_sidebar(cx);
9401 })
9402 .log_err();
9403 }
9404 }
9405
9406 let open_in_dev_container = open_options.open_in_dev_container;
9407
9408 let result = if let Some((existing, target_workspace)) = existing {
9409 let open_task = existing
9410 .update(cx, |multi_workspace, window, cx| {
9411 window.activate_window();
9412 multi_workspace.activate(target_workspace.clone(), window, cx);
9413 target_workspace.update(cx, |workspace, cx| {
9414 if open_in_dev_container {
9415 workspace.set_open_in_dev_container(true);
9416 }
9417 workspace.open_paths(
9418 abs_paths,
9419 OpenOptions {
9420 visible: Some(open_visible),
9421 ..Default::default()
9422 },
9423 None,
9424 window,
9425 cx,
9426 )
9427 })
9428 })?
9429 .await;
9430
9431 _ = existing.update(cx, |multi_workspace, _, cx| {
9432 let workspace = multi_workspace.workspace().clone();
9433 workspace.update(cx, |workspace, cx| {
9434 for item in open_task.iter().flatten() {
9435 if let Err(e) = item {
9436 workspace.show_error(&e, cx);
9437 }
9438 }
9439 });
9440 });
9441
9442 Ok(OpenResult { window: existing, workspace: target_workspace, opened_items: open_task })
9443 } else {
9444 let init = if open_in_dev_container {
9445 Some(Box::new(|workspace: &mut Workspace, _window: &mut Window, _cx: &mut Context<Workspace>| {
9446 workspace.set_open_in_dev_container(true);
9447 }) as Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>)
9448 } else {
9449 None
9450 };
9451 let result = cx
9452 .update(move |cx| {
9453 Workspace::new_local(
9454 abs_paths,
9455 app_state.clone(),
9456 open_options.requesting_window,
9457 open_options.env,
9458 init,
9459 open_options.open_mode,
9460 cx,
9461 )
9462 })
9463 .await;
9464
9465 if let Ok(ref result) = result {
9466 result.window
9467 .update(cx, |_, window, _cx| {
9468 window.activate_window();
9469 })
9470 .log_err();
9471 }
9472
9473 result
9474 };
9475
9476 #[cfg(target_os = "windows")]
9477 if let Some(util::paths::WslPath{distro, path}) = wsl_path
9478 && let Ok(ref result) = result
9479 {
9480 result.window
9481 .update(cx, move |multi_workspace, _window, cx| {
9482 struct OpenInWsl;
9483 let workspace = multi_workspace.workspace().clone();
9484 workspace.update(cx, |workspace, cx| {
9485 workspace.show_notification(NotificationId::unique::<OpenInWsl>(), cx, move |cx| {
9486 let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy());
9487 let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote");
9488 cx.new(move |cx| {
9489 MessageNotification::new(msg, cx)
9490 .primary_message("Open in WSL")
9491 .primary_icon(IconName::FolderOpen)
9492 .primary_on_click(move |window, cx| {
9493 window.dispatch_action(Box::new(remote::OpenWslPath {
9494 distro: remote::WslConnectionOptions {
9495 distro_name: distro.clone(),
9496 user: None,
9497 },
9498 paths: vec![path.clone().into()],
9499 }), cx)
9500 })
9501 })
9502 });
9503 });
9504 })
9505 .unwrap();
9506 };
9507 result
9508 })
9509}
9510
9511pub fn open_new(
9512 open_options: OpenOptions,
9513 app_state: Arc<AppState>,
9514 cx: &mut App,
9515 init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
9516) -> Task<anyhow::Result<()>> {
9517 let addition = open_options.open_mode;
9518 let task = Workspace::new_local(
9519 Vec::new(),
9520 app_state,
9521 open_options.requesting_window,
9522 open_options.env,
9523 Some(Box::new(init)),
9524 addition,
9525 cx,
9526 );
9527 cx.spawn(async move |cx| {
9528 let OpenResult { window, .. } = task.await?;
9529 window
9530 .update(cx, |_, window, _cx| {
9531 window.activate_window();
9532 })
9533 .ok();
9534 Ok(())
9535 })
9536}
9537
9538pub fn create_and_open_local_file(
9539 path: &'static Path,
9540 window: &mut Window,
9541 cx: &mut Context<Workspace>,
9542 default_content: impl 'static + Send + FnOnce() -> Rope,
9543) -> Task<Result<Box<dyn ItemHandle>>> {
9544 cx.spawn_in(window, async move |workspace, cx| {
9545 let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
9546 if !fs.is_file(path).await {
9547 fs.create_file(path, Default::default()).await?;
9548 fs.save(path, &default_content(), Default::default())
9549 .await?;
9550 }
9551
9552 workspace
9553 .update_in(cx, |workspace, window, cx| {
9554 workspace.with_local_or_wsl_workspace(window, cx, |workspace, window, cx| {
9555 let path = workspace
9556 .project
9557 .read_with(cx, |project, cx| project.try_windows_path_to_wsl(path, cx));
9558 cx.spawn_in(window, async move |workspace, cx| {
9559 let path = path.await?;
9560
9561 let path = fs.canonicalize(&path).await.unwrap_or(path);
9562
9563 let mut items = workspace
9564 .update_in(cx, |workspace, window, cx| {
9565 workspace.open_paths(
9566 vec![path.to_path_buf()],
9567 OpenOptions {
9568 visible: Some(OpenVisible::None),
9569 ..Default::default()
9570 },
9571 None,
9572 window,
9573 cx,
9574 )
9575 })?
9576 .await;
9577 let item = items.pop().flatten();
9578 item.with_context(|| format!("path {path:?} is not a file"))?
9579 })
9580 })
9581 })?
9582 .await?
9583 .await
9584 })
9585}
9586
9587pub fn open_remote_project_with_new_connection(
9588 window: WindowHandle<MultiWorkspace>,
9589 remote_connection: Arc<dyn RemoteConnection>,
9590 cancel_rx: oneshot::Receiver<()>,
9591 delegate: Arc<dyn RemoteClientDelegate>,
9592 app_state: Arc<AppState>,
9593 paths: Vec<PathBuf>,
9594 cx: &mut App,
9595) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
9596 cx.spawn(async move |cx| {
9597 let (workspace_id, serialized_workspace) =
9598 deserialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
9599 .await?;
9600
9601 let session = match cx
9602 .update(|cx| {
9603 remote::RemoteClient::new(
9604 ConnectionIdentifier::Workspace(workspace_id.0),
9605 remote_connection,
9606 cancel_rx,
9607 delegate,
9608 cx,
9609 )
9610 })
9611 .await?
9612 {
9613 Some(result) => result,
9614 None => return Ok(Vec::new()),
9615 };
9616
9617 let project = cx.update(|cx| {
9618 project::Project::remote(
9619 session,
9620 app_state.client.clone(),
9621 app_state.node_runtime.clone(),
9622 app_state.user_store.clone(),
9623 app_state.languages.clone(),
9624 app_state.fs.clone(),
9625 true,
9626 cx,
9627 )
9628 });
9629
9630 open_remote_project_inner(
9631 project,
9632 paths,
9633 workspace_id,
9634 serialized_workspace,
9635 app_state,
9636 window,
9637 cx,
9638 )
9639 .await
9640 })
9641}
9642
9643pub fn open_remote_project_with_existing_connection(
9644 connection_options: RemoteConnectionOptions,
9645 project: Entity<Project>,
9646 paths: Vec<PathBuf>,
9647 app_state: Arc<AppState>,
9648 window: WindowHandle<MultiWorkspace>,
9649 cx: &mut AsyncApp,
9650) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
9651 cx.spawn(async move |cx| {
9652 let (workspace_id, serialized_workspace) =
9653 deserialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
9654
9655 open_remote_project_inner(
9656 project,
9657 paths,
9658 workspace_id,
9659 serialized_workspace,
9660 app_state,
9661 window,
9662 cx,
9663 )
9664 .await
9665 })
9666}
9667
9668async fn open_remote_project_inner(
9669 project: Entity<Project>,
9670 paths: Vec<PathBuf>,
9671 workspace_id: WorkspaceId,
9672 serialized_workspace: Option<SerializedWorkspace>,
9673 app_state: Arc<AppState>,
9674 window: WindowHandle<MultiWorkspace>,
9675 cx: &mut AsyncApp,
9676) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
9677 let db = cx.update(|cx| WorkspaceDb::global(cx));
9678 let toolchains = db.toolchains(workspace_id).await?;
9679 for (toolchain, worktree_path, path) in toolchains {
9680 project
9681 .update(cx, |this, cx| {
9682 let Some(worktree_id) =
9683 this.find_worktree(&worktree_path, cx)
9684 .and_then(|(worktree, rel_path)| {
9685 if rel_path.is_empty() {
9686 Some(worktree.read(cx).id())
9687 } else {
9688 None
9689 }
9690 })
9691 else {
9692 return Task::ready(None);
9693 };
9694
9695 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
9696 })
9697 .await;
9698 }
9699 let mut project_paths_to_open = vec![];
9700 let mut project_path_errors = vec![];
9701
9702 for path in paths {
9703 let result = cx
9704 .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))
9705 .await;
9706 match result {
9707 Ok((_, project_path)) => {
9708 project_paths_to_open.push((path.clone(), Some(project_path)));
9709 }
9710 Err(error) => {
9711 project_path_errors.push(error);
9712 }
9713 };
9714 }
9715
9716 if project_paths_to_open.is_empty() {
9717 return Err(project_path_errors.pop().context("no paths given")?);
9718 }
9719
9720 let workspace = window.update(cx, |multi_workspace, window, cx| {
9721 telemetry::event!("SSH Project Opened");
9722
9723 let new_workspace = cx.new(|cx| {
9724 let mut workspace =
9725 Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
9726 workspace.update_history(cx);
9727
9728 if let Some(ref serialized) = serialized_workspace {
9729 workspace.centered_layout = serialized.centered_layout;
9730 }
9731
9732 workspace
9733 });
9734
9735 multi_workspace.activate(new_workspace.clone(), window, cx);
9736 new_workspace
9737 })?;
9738
9739 let items = window
9740 .update(cx, |_, window, cx| {
9741 window.activate_window();
9742 workspace.update(cx, |_workspace, cx| {
9743 open_items(serialized_workspace, project_paths_to_open, window, cx)
9744 })
9745 })?
9746 .await?;
9747
9748 workspace.update(cx, |workspace, cx| {
9749 for error in project_path_errors {
9750 if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
9751 if let Some(path) = error.error_tag("path") {
9752 workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
9753 }
9754 } else {
9755 workspace.show_error(&error, cx)
9756 }
9757 }
9758 });
9759
9760 Ok(items.into_iter().map(|item| item?.ok()).collect())
9761}
9762
9763fn deserialize_remote_project(
9764 connection_options: RemoteConnectionOptions,
9765 paths: Vec<PathBuf>,
9766 cx: &AsyncApp,
9767) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
9768 let db = cx.update(|cx| WorkspaceDb::global(cx));
9769 cx.background_spawn(async move {
9770 let remote_connection_id = db
9771 .get_or_create_remote_connection(connection_options)
9772 .await?;
9773
9774 let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
9775
9776 let workspace_id = if let Some(workspace_id) =
9777 serialized_workspace.as_ref().map(|workspace| workspace.id)
9778 {
9779 workspace_id
9780 } else {
9781 db.next_id().await?
9782 };
9783
9784 Ok((workspace_id, serialized_workspace))
9785 })
9786}
9787
9788pub fn join_in_room_project(
9789 project_id: u64,
9790 follow_user_id: u64,
9791 app_state: Arc<AppState>,
9792 cx: &mut App,
9793) -> Task<Result<()>> {
9794 let windows = cx.windows();
9795 cx.spawn(async move |cx| {
9796 let existing_window_and_workspace: Option<(
9797 WindowHandle<MultiWorkspace>,
9798 Entity<Workspace>,
9799 )> = windows.into_iter().find_map(|window_handle| {
9800 window_handle
9801 .downcast::<MultiWorkspace>()
9802 .and_then(|window_handle| {
9803 window_handle
9804 .update(cx, |multi_workspace, _window, cx| {
9805 for workspace in multi_workspace.workspaces() {
9806 if workspace.read(cx).project().read(cx).remote_id()
9807 == Some(project_id)
9808 {
9809 return Some((window_handle, workspace.clone()));
9810 }
9811 }
9812 None
9813 })
9814 .unwrap_or(None)
9815 })
9816 });
9817
9818 let multi_workspace_window = if let Some((existing_window, target_workspace)) =
9819 existing_window_and_workspace
9820 {
9821 existing_window
9822 .update(cx, |multi_workspace, window, cx| {
9823 multi_workspace.activate(target_workspace, window, cx);
9824 })
9825 .ok();
9826 existing_window
9827 } else {
9828 let active_call = cx.update(|cx| GlobalAnyActiveCall::global(cx).clone());
9829 let project = cx
9830 .update(|cx| {
9831 active_call.0.join_project(
9832 project_id,
9833 app_state.languages.clone(),
9834 app_state.fs.clone(),
9835 cx,
9836 )
9837 })
9838 .await?;
9839
9840 let window_bounds_override = window_bounds_env_override();
9841 cx.update(|cx| {
9842 let mut options = (app_state.build_window_options)(None, cx);
9843 options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
9844 cx.open_window(options, |window, cx| {
9845 let workspace = cx.new(|cx| {
9846 Workspace::new(Default::default(), project, app_state.clone(), window, cx)
9847 });
9848 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
9849 })
9850 })?
9851 };
9852
9853 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
9854 cx.activate(true);
9855 window.activate_window();
9856
9857 // We set the active workspace above, so this is the correct workspace.
9858 let workspace = multi_workspace.workspace().clone();
9859 workspace.update(cx, |workspace, cx| {
9860 let follow_peer_id = GlobalAnyActiveCall::try_global(cx)
9861 .and_then(|call| call.0.peer_id_for_user_in_room(follow_user_id, cx))
9862 .or_else(|| {
9863 // If we couldn't follow the given user, follow the host instead.
9864 let collaborator = workspace
9865 .project()
9866 .read(cx)
9867 .collaborators()
9868 .values()
9869 .find(|collaborator| collaborator.is_host)?;
9870 Some(collaborator.peer_id)
9871 });
9872
9873 if let Some(follow_peer_id) = follow_peer_id {
9874 workspace.follow(follow_peer_id, window, cx);
9875 }
9876 });
9877 })?;
9878
9879 anyhow::Ok(())
9880 })
9881}
9882
9883pub fn reload(cx: &mut App) {
9884 let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
9885 let mut workspace_windows = cx
9886 .windows()
9887 .into_iter()
9888 .filter_map(|window| window.downcast::<MultiWorkspace>())
9889 .collect::<Vec<_>>();
9890
9891 // If multiple windows have unsaved changes, and need a save prompt,
9892 // prompt in the active window before switching to a different window.
9893 workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
9894
9895 let mut prompt = None;
9896 if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
9897 prompt = window
9898 .update(cx, |_, window, cx| {
9899 window.prompt(
9900 PromptLevel::Info,
9901 "Are you sure you want to restart?",
9902 None,
9903 &["Restart", "Cancel"],
9904 cx,
9905 )
9906 })
9907 .ok();
9908 }
9909
9910 cx.spawn(async move |cx| {
9911 if let Some(prompt) = prompt {
9912 let answer = prompt.await?;
9913 if answer != 0 {
9914 return anyhow::Ok(());
9915 }
9916 }
9917
9918 // If the user cancels any save prompt, then keep the app open.
9919 for window in workspace_windows {
9920 if let Ok(should_close) = window.update(cx, |multi_workspace, window, cx| {
9921 let workspace = multi_workspace.workspace().clone();
9922 workspace.update(cx, |workspace, cx| {
9923 workspace.prepare_to_close(CloseIntent::Quit, window, cx)
9924 })
9925 }) && !should_close.await?
9926 {
9927 return anyhow::Ok(());
9928 }
9929 }
9930 cx.update(|cx| cx.restart());
9931 anyhow::Ok(())
9932 })
9933 .detach_and_log_err(cx);
9934}
9935
9936fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
9937 let mut parts = value.split(',');
9938 let x: usize = parts.next()?.parse().ok()?;
9939 let y: usize = parts.next()?.parse().ok()?;
9940 Some(point(px(x as f32), px(y as f32)))
9941}
9942
9943fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
9944 let mut parts = value.split(',');
9945 let width: usize = parts.next()?.parse().ok()?;
9946 let height: usize = parts.next()?.parse().ok()?;
9947 Some(size(px(width as f32), px(height as f32)))
9948}
9949
9950/// Add client-side decorations (rounded corners, shadows, resize handling) when
9951/// appropriate.
9952///
9953/// The `border_radius_tiling` parameter allows overriding which corners get
9954/// rounded, independently of the actual window tiling state. This is used
9955/// specifically for the workspace switcher sidebar: when the sidebar is open,
9956/// we want square corners on the left (so the sidebar appears flush with the
9957/// window edge) but we still need the shadow padding for proper visual
9958/// appearance. Unlike actual window tiling, this only affects border radius -
9959/// not padding or shadows.
9960pub fn client_side_decorations(
9961 element: impl IntoElement,
9962 window: &mut Window,
9963 cx: &mut App,
9964 border_radius_tiling: Tiling,
9965) -> Stateful<Div> {
9966 const BORDER_SIZE: Pixels = px(1.0);
9967 let decorations = window.window_decorations();
9968 let tiling = match decorations {
9969 Decorations::Server => Tiling::default(),
9970 Decorations::Client { tiling } => tiling,
9971 };
9972
9973 match decorations {
9974 Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
9975 Decorations::Server => window.set_client_inset(px(0.0)),
9976 }
9977
9978 struct GlobalResizeEdge(ResizeEdge);
9979 impl Global for GlobalResizeEdge {}
9980
9981 div()
9982 .id("window-backdrop")
9983 .bg(transparent_black())
9984 .map(|div| match decorations {
9985 Decorations::Server => div,
9986 Decorations::Client { .. } => div
9987 .when(
9988 !(tiling.top
9989 || tiling.right
9990 || border_radius_tiling.top
9991 || border_radius_tiling.right),
9992 |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9993 )
9994 .when(
9995 !(tiling.top
9996 || tiling.left
9997 || border_radius_tiling.top
9998 || border_radius_tiling.left),
9999 |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10000 )
10001 .when(
10002 !(tiling.bottom
10003 || tiling.right
10004 || border_radius_tiling.bottom
10005 || border_radius_tiling.right),
10006 |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10007 )
10008 .when(
10009 !(tiling.bottom
10010 || tiling.left
10011 || border_radius_tiling.bottom
10012 || border_radius_tiling.left),
10013 |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10014 )
10015 .when(!tiling.top, |div| {
10016 div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
10017 })
10018 .when(!tiling.bottom, |div| {
10019 div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
10020 })
10021 .when(!tiling.left, |div| {
10022 div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
10023 })
10024 .when(!tiling.right, |div| {
10025 div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
10026 })
10027 .on_mouse_move(move |e, window, cx| {
10028 let size = window.window_bounds().get_bounds().size;
10029 let pos = e.position;
10030
10031 let new_edge =
10032 resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
10033
10034 let edge = cx.try_global::<GlobalResizeEdge>();
10035 if new_edge != edge.map(|edge| edge.0) {
10036 window
10037 .window_handle()
10038 .update(cx, |workspace, _, cx| {
10039 cx.notify(workspace.entity_id());
10040 })
10041 .ok();
10042 }
10043 })
10044 .on_mouse_down(MouseButton::Left, move |e, window, _| {
10045 let size = window.window_bounds().get_bounds().size;
10046 let pos = e.position;
10047
10048 let edge = match resize_edge(
10049 pos,
10050 theme::CLIENT_SIDE_DECORATION_SHADOW,
10051 size,
10052 tiling,
10053 ) {
10054 Some(value) => value,
10055 None => return,
10056 };
10057
10058 window.start_window_resize(edge);
10059 }),
10060 })
10061 .size_full()
10062 .child(
10063 div()
10064 .cursor(CursorStyle::Arrow)
10065 .map(|div| match decorations {
10066 Decorations::Server => div,
10067 Decorations::Client { .. } => div
10068 .border_color(cx.theme().colors().border)
10069 .when(
10070 !(tiling.top
10071 || tiling.right
10072 || border_radius_tiling.top
10073 || border_radius_tiling.right),
10074 |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10075 )
10076 .when(
10077 !(tiling.top
10078 || tiling.left
10079 || border_radius_tiling.top
10080 || border_radius_tiling.left),
10081 |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10082 )
10083 .when(
10084 !(tiling.bottom
10085 || tiling.right
10086 || border_radius_tiling.bottom
10087 || border_radius_tiling.right),
10088 |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10089 )
10090 .when(
10091 !(tiling.bottom
10092 || tiling.left
10093 || border_radius_tiling.bottom
10094 || border_radius_tiling.left),
10095 |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10096 )
10097 .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
10098 .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
10099 .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
10100 .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
10101 .when(!tiling.is_tiled(), |div| {
10102 div.shadow(vec![gpui::BoxShadow {
10103 color: Hsla {
10104 h: 0.,
10105 s: 0.,
10106 l: 0.,
10107 a: 0.4,
10108 },
10109 blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
10110 spread_radius: px(0.),
10111 offset: point(px(0.0), px(0.0)),
10112 }])
10113 }),
10114 })
10115 .on_mouse_move(|_e, _, cx| {
10116 cx.stop_propagation();
10117 })
10118 .size_full()
10119 .child(element),
10120 )
10121 .map(|div| match decorations {
10122 Decorations::Server => div,
10123 Decorations::Client { tiling, .. } => div.child(
10124 canvas(
10125 |_bounds, window, _| {
10126 window.insert_hitbox(
10127 Bounds::new(
10128 point(px(0.0), px(0.0)),
10129 window.window_bounds().get_bounds().size,
10130 ),
10131 HitboxBehavior::Normal,
10132 )
10133 },
10134 move |_bounds, hitbox, window, cx| {
10135 let mouse = window.mouse_position();
10136 let size = window.window_bounds().get_bounds().size;
10137 let Some(edge) =
10138 resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
10139 else {
10140 return;
10141 };
10142 cx.set_global(GlobalResizeEdge(edge));
10143 window.set_cursor_style(
10144 match edge {
10145 ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
10146 ResizeEdge::Left | ResizeEdge::Right => {
10147 CursorStyle::ResizeLeftRight
10148 }
10149 ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
10150 CursorStyle::ResizeUpLeftDownRight
10151 }
10152 ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
10153 CursorStyle::ResizeUpRightDownLeft
10154 }
10155 },
10156 &hitbox,
10157 );
10158 },
10159 )
10160 .size_full()
10161 .absolute(),
10162 ),
10163 })
10164}
10165
10166fn resize_edge(
10167 pos: Point<Pixels>,
10168 shadow_size: Pixels,
10169 window_size: Size<Pixels>,
10170 tiling: Tiling,
10171) -> Option<ResizeEdge> {
10172 let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
10173 if bounds.contains(&pos) {
10174 return None;
10175 }
10176
10177 let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
10178 let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
10179 if !tiling.top && top_left_bounds.contains(&pos) {
10180 return Some(ResizeEdge::TopLeft);
10181 }
10182
10183 let top_right_bounds = Bounds::new(
10184 Point::new(window_size.width - corner_size.width, px(0.)),
10185 corner_size,
10186 );
10187 if !tiling.top && top_right_bounds.contains(&pos) {
10188 return Some(ResizeEdge::TopRight);
10189 }
10190
10191 let bottom_left_bounds = Bounds::new(
10192 Point::new(px(0.), window_size.height - corner_size.height),
10193 corner_size,
10194 );
10195 if !tiling.bottom && bottom_left_bounds.contains(&pos) {
10196 return Some(ResizeEdge::BottomLeft);
10197 }
10198
10199 let bottom_right_bounds = Bounds::new(
10200 Point::new(
10201 window_size.width - corner_size.width,
10202 window_size.height - corner_size.height,
10203 ),
10204 corner_size,
10205 );
10206 if !tiling.bottom && bottom_right_bounds.contains(&pos) {
10207 return Some(ResizeEdge::BottomRight);
10208 }
10209
10210 if !tiling.top && pos.y < shadow_size {
10211 Some(ResizeEdge::Top)
10212 } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
10213 Some(ResizeEdge::Bottom)
10214 } else if !tiling.left && pos.x < shadow_size {
10215 Some(ResizeEdge::Left)
10216 } else if !tiling.right && pos.x > window_size.width - shadow_size {
10217 Some(ResizeEdge::Right)
10218 } else {
10219 None
10220 }
10221}
10222
10223fn join_pane_into_active(
10224 active_pane: &Entity<Pane>,
10225 pane: &Entity<Pane>,
10226 window: &mut Window,
10227 cx: &mut App,
10228) {
10229 if pane == active_pane {
10230 } else if pane.read(cx).items_len() == 0 {
10231 pane.update(cx, |_, cx| {
10232 cx.emit(pane::Event::Remove {
10233 focus_on_pane: None,
10234 });
10235 })
10236 } else {
10237 move_all_items(pane, active_pane, window, cx);
10238 }
10239}
10240
10241fn move_all_items(
10242 from_pane: &Entity<Pane>,
10243 to_pane: &Entity<Pane>,
10244 window: &mut Window,
10245 cx: &mut App,
10246) {
10247 let destination_is_different = from_pane != to_pane;
10248 let mut moved_items = 0;
10249 for (item_ix, item_handle) in from_pane
10250 .read(cx)
10251 .items()
10252 .enumerate()
10253 .map(|(ix, item)| (ix, item.clone()))
10254 .collect::<Vec<_>>()
10255 {
10256 let ix = item_ix - moved_items;
10257 if destination_is_different {
10258 // Close item from previous pane
10259 from_pane.update(cx, |source, cx| {
10260 source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
10261 });
10262 moved_items += 1;
10263 }
10264
10265 // This automatically removes duplicate items in the pane
10266 to_pane.update(cx, |destination, cx| {
10267 destination.add_item(item_handle, true, true, None, window, cx);
10268 window.focus(&destination.focus_handle(cx), cx)
10269 });
10270 }
10271}
10272
10273pub fn move_item(
10274 source: &Entity<Pane>,
10275 destination: &Entity<Pane>,
10276 item_id_to_move: EntityId,
10277 destination_index: usize,
10278 activate: bool,
10279 window: &mut Window,
10280 cx: &mut App,
10281) {
10282 let Some((item_ix, item_handle)) = source
10283 .read(cx)
10284 .items()
10285 .enumerate()
10286 .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
10287 .map(|(ix, item)| (ix, item.clone()))
10288 else {
10289 // Tab was closed during drag
10290 return;
10291 };
10292
10293 if source != destination {
10294 // Close item from previous pane
10295 source.update(cx, |source, cx| {
10296 source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
10297 });
10298 }
10299
10300 // This automatically removes duplicate items in the pane
10301 destination.update(cx, |destination, cx| {
10302 destination.add_item_inner(
10303 item_handle,
10304 activate,
10305 activate,
10306 activate,
10307 Some(destination_index),
10308 window,
10309 cx,
10310 );
10311 if activate {
10312 window.focus(&destination.focus_handle(cx), cx)
10313 }
10314 });
10315}
10316
10317pub fn move_active_item(
10318 source: &Entity<Pane>,
10319 destination: &Entity<Pane>,
10320 focus_destination: bool,
10321 close_if_empty: bool,
10322 window: &mut Window,
10323 cx: &mut App,
10324) {
10325 if source == destination {
10326 return;
10327 }
10328 let Some(active_item) = source.read(cx).active_item() else {
10329 return;
10330 };
10331 source.update(cx, |source_pane, cx| {
10332 let item_id = active_item.item_id();
10333 source_pane.remove_item(item_id, false, close_if_empty, window, cx);
10334 destination.update(cx, |target_pane, cx| {
10335 target_pane.add_item(
10336 active_item,
10337 focus_destination,
10338 focus_destination,
10339 Some(target_pane.items_len()),
10340 window,
10341 cx,
10342 );
10343 });
10344 });
10345}
10346
10347pub fn clone_active_item(
10348 workspace_id: Option<WorkspaceId>,
10349 source: &Entity<Pane>,
10350 destination: &Entity<Pane>,
10351 focus_destination: bool,
10352 window: &mut Window,
10353 cx: &mut App,
10354) {
10355 if source == destination {
10356 return;
10357 }
10358 let Some(active_item) = source.read(cx).active_item() else {
10359 return;
10360 };
10361 if !active_item.can_split(cx) {
10362 return;
10363 }
10364 let destination = destination.downgrade();
10365 let task = active_item.clone_on_split(workspace_id, window, cx);
10366 window
10367 .spawn(cx, async move |cx| {
10368 let Some(clone) = task.await else {
10369 return;
10370 };
10371 destination
10372 .update_in(cx, |target_pane, window, cx| {
10373 target_pane.add_item(
10374 clone,
10375 focus_destination,
10376 focus_destination,
10377 Some(target_pane.items_len()),
10378 window,
10379 cx,
10380 );
10381 })
10382 .log_err();
10383 })
10384 .detach();
10385}
10386
10387#[derive(Debug)]
10388pub struct WorkspacePosition {
10389 pub window_bounds: Option<WindowBounds>,
10390 pub display: Option<Uuid>,
10391 pub centered_layout: bool,
10392}
10393
10394pub fn remote_workspace_position_from_db(
10395 connection_options: RemoteConnectionOptions,
10396 paths_to_open: &[PathBuf],
10397 cx: &App,
10398) -> Task<Result<WorkspacePosition>> {
10399 let paths = paths_to_open.to_vec();
10400 let db = WorkspaceDb::global(cx);
10401 let kvp = db::kvp::KeyValueStore::global(cx);
10402
10403 cx.background_spawn(async move {
10404 let remote_connection_id = db
10405 .get_or_create_remote_connection(connection_options)
10406 .await
10407 .context("fetching serialized ssh project")?;
10408 let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
10409
10410 let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
10411 (Some(WindowBounds::Windowed(bounds)), None)
10412 } else {
10413 let restorable_bounds = serialized_workspace
10414 .as_ref()
10415 .and_then(|workspace| {
10416 Some((workspace.display?, workspace.window_bounds.map(|b| b.0)?))
10417 })
10418 .or_else(|| persistence::read_default_window_bounds(&kvp));
10419
10420 if let Some((serialized_display, serialized_bounds)) = restorable_bounds {
10421 (Some(serialized_bounds), Some(serialized_display))
10422 } else {
10423 (None, None)
10424 }
10425 };
10426
10427 let centered_layout = serialized_workspace
10428 .as_ref()
10429 .map(|w| w.centered_layout)
10430 .unwrap_or(false);
10431
10432 Ok(WorkspacePosition {
10433 window_bounds,
10434 display,
10435 centered_layout,
10436 })
10437 })
10438}
10439
10440pub fn with_active_or_new_workspace(
10441 cx: &mut App,
10442 f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
10443) {
10444 match cx
10445 .active_window()
10446 .and_then(|w| w.downcast::<MultiWorkspace>())
10447 {
10448 Some(multi_workspace) => {
10449 cx.defer(move |cx| {
10450 multi_workspace
10451 .update(cx, |multi_workspace, window, cx| {
10452 let workspace = multi_workspace.workspace().clone();
10453 workspace.update(cx, |workspace, cx| f(workspace, window, cx));
10454 })
10455 .log_err();
10456 });
10457 }
10458 None => {
10459 let app_state = AppState::global(cx);
10460 open_new(
10461 OpenOptions::default(),
10462 app_state,
10463 cx,
10464 move |workspace, window, cx| f(workspace, window, cx),
10465 )
10466 .detach_and_log_err(cx);
10467 }
10468 }
10469}
10470
10471/// Reads a panel's pixel size from its legacy KVP format and deletes the legacy
10472/// key. This migration path only runs once per panel per workspace.
10473fn load_legacy_panel_size(
10474 panel_key: &str,
10475 dock_position: DockPosition,
10476 workspace: &Workspace,
10477 cx: &mut App,
10478) -> Option<Pixels> {
10479 #[derive(Deserialize)]
10480 struct LegacyPanelState {
10481 #[serde(default)]
10482 width: Option<Pixels>,
10483 #[serde(default)]
10484 height: Option<Pixels>,
10485 }
10486
10487 let workspace_id = workspace
10488 .database_id()
10489 .map(|id| i64::from(id).to_string())
10490 .or_else(|| workspace.session_id())?;
10491
10492 let legacy_key = match panel_key {
10493 "ProjectPanel" => {
10494 format!("{}-{:?}", "ProjectPanel", workspace_id)
10495 }
10496 "OutlinePanel" => {
10497 format!("{}-{:?}", "OutlinePanel", workspace_id)
10498 }
10499 "GitPanel" => {
10500 format!("{}-{:?}", "GitPanel", workspace_id)
10501 }
10502 "TerminalPanel" => {
10503 format!("{:?}-{:?}", "TerminalPanel", workspace_id)
10504 }
10505 _ => return None,
10506 };
10507
10508 let kvp = db::kvp::KeyValueStore::global(cx);
10509 let json = kvp.read_kvp(&legacy_key).log_err().flatten()?;
10510 let state = serde_json::from_str::<LegacyPanelState>(&json).log_err()?;
10511 let size = match dock_position {
10512 DockPosition::Bottom => state.height,
10513 DockPosition::Left | DockPosition::Right => state.width,
10514 }?;
10515
10516 cx.background_spawn(async move { kvp.delete_kvp(legacy_key).await })
10517 .detach_and_log_err(cx);
10518
10519 Some(size)
10520}
10521
10522#[cfg(test)]
10523mod tests {
10524 use std::{cell::RefCell, rc::Rc, sync::Arc, time::Duration};
10525
10526 use super::*;
10527 use crate::{
10528 dock::{PanelEvent, test::TestPanel},
10529 item::{
10530 ItemBufferKind, ItemEvent,
10531 test::{TestItem, TestProjectItem},
10532 },
10533 };
10534 use fs::FakeFs;
10535 use gpui::{
10536 DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
10537 UpdateGlobal, VisualTestContext, px,
10538 };
10539 use project::{Project, ProjectEntryId};
10540 use serde_json::json;
10541 use settings::SettingsStore;
10542 use util::path;
10543 use util::rel_path::rel_path;
10544
10545 #[gpui::test]
10546 async fn test_tab_disambiguation(cx: &mut TestAppContext) {
10547 init_test(cx);
10548
10549 let fs = FakeFs::new(cx.executor());
10550 let project = Project::test(fs, [], cx).await;
10551 let (workspace, cx) =
10552 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10553
10554 // Adding an item with no ambiguity renders the tab without detail.
10555 let item1 = cx.new(|cx| {
10556 let mut item = TestItem::new(cx);
10557 item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
10558 item
10559 });
10560 workspace.update_in(cx, |workspace, window, cx| {
10561 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10562 });
10563 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
10564
10565 // Adding an item that creates ambiguity increases the level of detail on
10566 // both tabs.
10567 let item2 = cx.new_window_entity(|_window, cx| {
10568 let mut item = TestItem::new(cx);
10569 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10570 item
10571 });
10572 workspace.update_in(cx, |workspace, window, cx| {
10573 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10574 });
10575 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10576 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10577
10578 // Adding an item that creates ambiguity increases the level of detail only
10579 // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
10580 // we stop at the highest detail available.
10581 let item3 = cx.new(|cx| {
10582 let mut item = TestItem::new(cx);
10583 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10584 item
10585 });
10586 workspace.update_in(cx, |workspace, window, cx| {
10587 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10588 });
10589 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10590 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10591 item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10592 }
10593
10594 #[gpui::test]
10595 async fn test_tracking_active_path(cx: &mut TestAppContext) {
10596 init_test(cx);
10597
10598 let fs = FakeFs::new(cx.executor());
10599 fs.insert_tree(
10600 "/root1",
10601 json!({
10602 "one.txt": "",
10603 "two.txt": "",
10604 }),
10605 )
10606 .await;
10607 fs.insert_tree(
10608 "/root2",
10609 json!({
10610 "three.txt": "",
10611 }),
10612 )
10613 .await;
10614
10615 let project = Project::test(fs, ["root1".as_ref()], cx).await;
10616 let (workspace, cx) =
10617 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10618 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10619 let worktree_id = project.update(cx, |project, cx| {
10620 project.worktrees(cx).next().unwrap().read(cx).id()
10621 });
10622
10623 let item1 = cx.new(|cx| {
10624 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
10625 });
10626 let item2 = cx.new(|cx| {
10627 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
10628 });
10629
10630 // Add an item to an empty pane
10631 workspace.update_in(cx, |workspace, window, cx| {
10632 workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
10633 });
10634 project.update(cx, |project, cx| {
10635 assert_eq!(
10636 project.active_entry(),
10637 project
10638 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10639 .map(|e| e.id)
10640 );
10641 });
10642 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10643
10644 // Add a second item to a non-empty pane
10645 workspace.update_in(cx, |workspace, window, cx| {
10646 workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
10647 });
10648 assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
10649 project.update(cx, |project, cx| {
10650 assert_eq!(
10651 project.active_entry(),
10652 project
10653 .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
10654 .map(|e| e.id)
10655 );
10656 });
10657
10658 // Close the active item
10659 pane.update_in(cx, |pane, window, cx| {
10660 pane.close_active_item(&Default::default(), window, cx)
10661 })
10662 .await
10663 .unwrap();
10664 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10665 project.update(cx, |project, cx| {
10666 assert_eq!(
10667 project.active_entry(),
10668 project
10669 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10670 .map(|e| e.id)
10671 );
10672 });
10673
10674 // Add a project folder
10675 project
10676 .update(cx, |project, cx| {
10677 project.find_or_create_worktree("root2", true, cx)
10678 })
10679 .await
10680 .unwrap();
10681 assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
10682
10683 // Remove a project folder
10684 project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
10685 assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
10686 }
10687
10688 #[gpui::test]
10689 async fn test_close_window(cx: &mut TestAppContext) {
10690 init_test(cx);
10691
10692 let fs = FakeFs::new(cx.executor());
10693 fs.insert_tree("/root", json!({ "one": "" })).await;
10694
10695 let project = Project::test(fs, ["root".as_ref()], cx).await;
10696 let (workspace, cx) =
10697 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10698
10699 // When there are no dirty items, there's nothing to do.
10700 let item1 = cx.new(TestItem::new);
10701 workspace.update_in(cx, |w, window, cx| {
10702 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
10703 });
10704 let task = workspace.update_in(cx, |w, window, cx| {
10705 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10706 });
10707 assert!(task.await.unwrap());
10708
10709 // When there are dirty untitled items, prompt to save each one. If the user
10710 // cancels any prompt, then abort.
10711 let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10712 let item3 = cx.new(|cx| {
10713 TestItem::new(cx)
10714 .with_dirty(true)
10715 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10716 });
10717 workspace.update_in(cx, |w, window, cx| {
10718 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10719 w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10720 });
10721 let task = workspace.update_in(cx, |w, window, cx| {
10722 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10723 });
10724 cx.executor().run_until_parked();
10725 cx.simulate_prompt_answer("Cancel"); // cancel save all
10726 cx.executor().run_until_parked();
10727 assert!(!cx.has_pending_prompt());
10728 assert!(!task.await.unwrap());
10729 }
10730
10731 #[gpui::test]
10732 async fn test_multi_workspace_close_window_multiple_workspaces_cancel(cx: &mut TestAppContext) {
10733 init_test(cx);
10734
10735 let fs = FakeFs::new(cx.executor());
10736 fs.insert_tree("/root", json!({ "one": "" })).await;
10737
10738 let project_a = Project::test(fs.clone(), ["root".as_ref()], cx).await;
10739 let project_b = Project::test(fs, ["root".as_ref()], cx).await;
10740 let multi_workspace_handle =
10741 cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
10742 cx.run_until_parked();
10743
10744 multi_workspace_handle
10745 .update(cx, |mw, _window, cx| {
10746 mw.open_sidebar(cx);
10747 })
10748 .unwrap();
10749
10750 let workspace_a = multi_workspace_handle
10751 .read_with(cx, |mw, _| mw.workspace().clone())
10752 .unwrap();
10753
10754 let workspace_b = multi_workspace_handle
10755 .update(cx, |mw, window, cx| {
10756 mw.test_add_workspace(project_b, window, cx)
10757 })
10758 .unwrap();
10759
10760 // Activate workspace A
10761 multi_workspace_handle
10762 .update(cx, |mw, window, cx| {
10763 let workspace = mw.workspaces().next().unwrap().clone();
10764 mw.activate(workspace, window, cx);
10765 })
10766 .unwrap();
10767
10768 let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
10769
10770 // Workspace A has a clean item
10771 let item_a = cx.new(TestItem::new);
10772 workspace_a.update_in(cx, |w, window, cx| {
10773 w.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
10774 });
10775
10776 // Workspace B has a dirty item
10777 let item_b = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10778 workspace_b.update_in(cx, |w, window, cx| {
10779 w.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx)
10780 });
10781
10782 // Verify workspace A is active
10783 multi_workspace_handle
10784 .read_with(cx, |mw, _| {
10785 assert_eq!(mw.workspace(), &workspace_a);
10786 })
10787 .unwrap();
10788
10789 // Dispatch CloseWindow — workspace A will pass, workspace B will prompt
10790 multi_workspace_handle
10791 .update(cx, |mw, window, cx| {
10792 mw.close_window(&CloseWindow, window, cx);
10793 })
10794 .unwrap();
10795 cx.run_until_parked();
10796
10797 // Workspace B should now be active since it has dirty items that need attention
10798 multi_workspace_handle
10799 .read_with(cx, |mw, _| {
10800 assert_eq!(
10801 mw.workspace(),
10802 &workspace_b,
10803 "workspace B should be activated when it prompts"
10804 );
10805 })
10806 .unwrap();
10807
10808 // User cancels the save prompt from workspace B
10809 cx.simulate_prompt_answer("Cancel");
10810 cx.run_until_parked();
10811
10812 // Window should still exist because workspace B's close was cancelled
10813 assert!(
10814 multi_workspace_handle.update(cx, |_, _, _| ()).is_ok(),
10815 "window should still exist after cancelling one workspace's close"
10816 );
10817 }
10818
10819 #[gpui::test]
10820 async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
10821 init_test(cx);
10822
10823 // Register TestItem as a serializable item
10824 cx.update(|cx| {
10825 register_serializable_item::<TestItem>(cx);
10826 });
10827
10828 let fs = FakeFs::new(cx.executor());
10829 fs.insert_tree("/root", json!({ "one": "" })).await;
10830
10831 let project = Project::test(fs, ["root".as_ref()], cx).await;
10832 let (workspace, cx) =
10833 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10834
10835 // When there are dirty untitled items, but they can serialize, then there is no prompt.
10836 let item1 = cx.new(|cx| {
10837 TestItem::new(cx)
10838 .with_dirty(true)
10839 .with_serialize(|| Some(Task::ready(Ok(()))))
10840 });
10841 let item2 = cx.new(|cx| {
10842 TestItem::new(cx)
10843 .with_dirty(true)
10844 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10845 .with_serialize(|| Some(Task::ready(Ok(()))))
10846 });
10847 workspace.update_in(cx, |w, window, cx| {
10848 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10849 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10850 });
10851 let task = workspace.update_in(cx, |w, window, cx| {
10852 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10853 });
10854 assert!(task.await.unwrap());
10855 }
10856
10857 #[gpui::test]
10858 async fn test_close_pane_items(cx: &mut TestAppContext) {
10859 init_test(cx);
10860
10861 let fs = FakeFs::new(cx.executor());
10862
10863 let project = Project::test(fs, None, cx).await;
10864 let (workspace, cx) =
10865 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10866
10867 let item1 = cx.new(|cx| {
10868 TestItem::new(cx)
10869 .with_dirty(true)
10870 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10871 });
10872 let item2 = cx.new(|cx| {
10873 TestItem::new(cx)
10874 .with_dirty(true)
10875 .with_conflict(true)
10876 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10877 });
10878 let item3 = cx.new(|cx| {
10879 TestItem::new(cx)
10880 .with_dirty(true)
10881 .with_conflict(true)
10882 .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
10883 });
10884 let item4 = cx.new(|cx| {
10885 TestItem::new(cx).with_dirty(true).with_project_items(&[{
10886 let project_item = TestProjectItem::new_untitled(cx);
10887 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10888 project_item
10889 }])
10890 });
10891 let pane = workspace.update_in(cx, |workspace, window, cx| {
10892 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10893 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10894 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10895 workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
10896 workspace.active_pane().clone()
10897 });
10898
10899 let close_items = pane.update_in(cx, |pane, window, cx| {
10900 pane.activate_item(1, true, true, window, cx);
10901 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10902 let item1_id = item1.item_id();
10903 let item3_id = item3.item_id();
10904 let item4_id = item4.item_id();
10905 pane.close_items(window, cx, SaveIntent::Close, &move |id| {
10906 [item1_id, item3_id, item4_id].contains(&id)
10907 })
10908 });
10909 cx.executor().run_until_parked();
10910
10911 assert!(cx.has_pending_prompt());
10912 cx.simulate_prompt_answer("Save all");
10913
10914 cx.executor().run_until_parked();
10915
10916 // Item 1 is saved. There's a prompt to save item 3.
10917 pane.update(cx, |pane, cx| {
10918 assert_eq!(item1.read(cx).save_count, 1);
10919 assert_eq!(item1.read(cx).save_as_count, 0);
10920 assert_eq!(item1.read(cx).reload_count, 0);
10921 assert_eq!(pane.items_len(), 3);
10922 assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
10923 });
10924 assert!(cx.has_pending_prompt());
10925
10926 // Cancel saving item 3.
10927 cx.simulate_prompt_answer("Discard");
10928 cx.executor().run_until_parked();
10929
10930 // Item 3 is reloaded. There's a prompt to save item 4.
10931 pane.update(cx, |pane, cx| {
10932 assert_eq!(item3.read(cx).save_count, 0);
10933 assert_eq!(item3.read(cx).save_as_count, 0);
10934 assert_eq!(item3.read(cx).reload_count, 1);
10935 assert_eq!(pane.items_len(), 2);
10936 assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
10937 });
10938
10939 // There's a prompt for a path for item 4.
10940 cx.simulate_new_path_selection(|_| Some(Default::default()));
10941 close_items.await.unwrap();
10942
10943 // The requested items are closed.
10944 pane.update(cx, |pane, cx| {
10945 assert_eq!(item4.read(cx).save_count, 0);
10946 assert_eq!(item4.read(cx).save_as_count, 1);
10947 assert_eq!(item4.read(cx).reload_count, 0);
10948 assert_eq!(pane.items_len(), 1);
10949 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10950 });
10951 }
10952
10953 #[gpui::test]
10954 async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
10955 init_test(cx);
10956
10957 let fs = FakeFs::new(cx.executor());
10958 let project = Project::test(fs, [], cx).await;
10959 let (workspace, cx) =
10960 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10961
10962 // Create several workspace items with single project entries, and two
10963 // workspace items with multiple project entries.
10964 let single_entry_items = (0..=4)
10965 .map(|project_entry_id| {
10966 cx.new(|cx| {
10967 TestItem::new(cx)
10968 .with_dirty(true)
10969 .with_project_items(&[dirty_project_item(
10970 project_entry_id,
10971 &format!("{project_entry_id}.txt"),
10972 cx,
10973 )])
10974 })
10975 })
10976 .collect::<Vec<_>>();
10977 let item_2_3 = cx.new(|cx| {
10978 TestItem::new(cx)
10979 .with_dirty(true)
10980 .with_buffer_kind(ItemBufferKind::Multibuffer)
10981 .with_project_items(&[
10982 single_entry_items[2].read(cx).project_items[0].clone(),
10983 single_entry_items[3].read(cx).project_items[0].clone(),
10984 ])
10985 });
10986 let item_3_4 = cx.new(|cx| {
10987 TestItem::new(cx)
10988 .with_dirty(true)
10989 .with_buffer_kind(ItemBufferKind::Multibuffer)
10990 .with_project_items(&[
10991 single_entry_items[3].read(cx).project_items[0].clone(),
10992 single_entry_items[4].read(cx).project_items[0].clone(),
10993 ])
10994 });
10995
10996 // Create two panes that contain the following project entries:
10997 // left pane:
10998 // multi-entry items: (2, 3)
10999 // single-entry items: 0, 2, 3, 4
11000 // right pane:
11001 // single-entry items: 4, 1
11002 // multi-entry items: (3, 4)
11003 let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
11004 let left_pane = workspace.active_pane().clone();
11005 workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
11006 workspace.add_item_to_active_pane(
11007 single_entry_items[0].boxed_clone(),
11008 None,
11009 true,
11010 window,
11011 cx,
11012 );
11013 workspace.add_item_to_active_pane(
11014 single_entry_items[2].boxed_clone(),
11015 None,
11016 true,
11017 window,
11018 cx,
11019 );
11020 workspace.add_item_to_active_pane(
11021 single_entry_items[3].boxed_clone(),
11022 None,
11023 true,
11024 window,
11025 cx,
11026 );
11027 workspace.add_item_to_active_pane(
11028 single_entry_items[4].boxed_clone(),
11029 None,
11030 true,
11031 window,
11032 cx,
11033 );
11034
11035 let right_pane =
11036 workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
11037
11038 let boxed_clone = single_entry_items[1].boxed_clone();
11039 let right_pane = window.spawn(cx, async move |cx| {
11040 right_pane.await.inspect(|right_pane| {
11041 right_pane
11042 .update_in(cx, |pane, window, cx| {
11043 pane.add_item(boxed_clone, true, true, None, window, cx);
11044 pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
11045 })
11046 .unwrap();
11047 })
11048 });
11049
11050 (left_pane, right_pane)
11051 });
11052 let right_pane = right_pane.await.unwrap();
11053 cx.focus(&right_pane);
11054
11055 let close = right_pane.update_in(cx, |pane, window, cx| {
11056 pane.close_all_items(&CloseAllItems::default(), window, cx)
11057 .unwrap()
11058 });
11059 cx.executor().run_until_parked();
11060
11061 let msg = cx.pending_prompt().unwrap().0;
11062 assert!(msg.contains("1.txt"));
11063 assert!(!msg.contains("2.txt"));
11064 assert!(!msg.contains("3.txt"));
11065 assert!(!msg.contains("4.txt"));
11066
11067 // With best-effort close, cancelling item 1 keeps it open but items 4
11068 // and (3,4) still close since their entries exist in left pane.
11069 cx.simulate_prompt_answer("Cancel");
11070 close.await;
11071
11072 right_pane.read_with(cx, |pane, _| {
11073 assert_eq!(pane.items_len(), 1);
11074 });
11075
11076 // Remove item 3 from left pane, making (2,3) the only item with entry 3.
11077 left_pane
11078 .update_in(cx, |left_pane, window, cx| {
11079 left_pane.close_item_by_id(
11080 single_entry_items[3].entity_id(),
11081 SaveIntent::Skip,
11082 window,
11083 cx,
11084 )
11085 })
11086 .await
11087 .unwrap();
11088
11089 let close = left_pane.update_in(cx, |pane, window, cx| {
11090 pane.close_all_items(&CloseAllItems::default(), window, cx)
11091 .unwrap()
11092 });
11093 cx.executor().run_until_parked();
11094
11095 let details = cx.pending_prompt().unwrap().1;
11096 assert!(details.contains("0.txt"));
11097 assert!(details.contains("3.txt"));
11098 assert!(details.contains("4.txt"));
11099 // Ideally 2.txt wouldn't appear since entry 2 still exists in item 2.
11100 // But we can only save whole items, so saving (2,3) for entry 3 includes 2.
11101 // assert!(!details.contains("2.txt"));
11102
11103 cx.simulate_prompt_answer("Save all");
11104 cx.executor().run_until_parked();
11105 close.await;
11106
11107 left_pane.read_with(cx, |pane, _| {
11108 assert_eq!(pane.items_len(), 0);
11109 });
11110 }
11111
11112 #[gpui::test]
11113 async fn test_autosave(cx: &mut gpui::TestAppContext) {
11114 init_test(cx);
11115
11116 let fs = FakeFs::new(cx.executor());
11117 let project = Project::test(fs, [], cx).await;
11118 let (workspace, cx) =
11119 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11120 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11121
11122 let item = cx.new(|cx| {
11123 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11124 });
11125 let item_id = item.entity_id();
11126 workspace.update_in(cx, |workspace, window, cx| {
11127 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11128 });
11129
11130 // Autosave on window change.
11131 item.update(cx, |item, cx| {
11132 SettingsStore::update_global(cx, |settings, cx| {
11133 settings.update_user_settings(cx, |settings| {
11134 settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
11135 })
11136 });
11137 item.is_dirty = true;
11138 });
11139
11140 // Deactivating the window saves the file.
11141 cx.deactivate_window();
11142 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11143
11144 // Re-activating the window doesn't save the file.
11145 cx.update(|window, _| window.activate_window());
11146 cx.executor().run_until_parked();
11147 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11148
11149 // Autosave on focus change.
11150 item.update_in(cx, |item, window, cx| {
11151 cx.focus_self(window);
11152 SettingsStore::update_global(cx, |settings, cx| {
11153 settings.update_user_settings(cx, |settings| {
11154 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11155 })
11156 });
11157 item.is_dirty = true;
11158 });
11159 // Blurring the item saves the file.
11160 item.update_in(cx, |_, window, _| window.blur());
11161 cx.executor().run_until_parked();
11162 item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
11163
11164 // Deactivating the window still saves the file.
11165 item.update_in(cx, |item, window, cx| {
11166 cx.focus_self(window);
11167 item.is_dirty = true;
11168 });
11169 cx.deactivate_window();
11170 item.update(cx, |item, _| assert_eq!(item.save_count, 3));
11171
11172 // Autosave after delay.
11173 item.update(cx, |item, cx| {
11174 SettingsStore::update_global(cx, |settings, cx| {
11175 settings.update_user_settings(cx, |settings| {
11176 settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
11177 milliseconds: 500.into(),
11178 });
11179 })
11180 });
11181 item.is_dirty = true;
11182 cx.emit(ItemEvent::Edit);
11183 });
11184
11185 // Delay hasn't fully expired, so the file is still dirty and unsaved.
11186 cx.executor().advance_clock(Duration::from_millis(250));
11187 item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
11188
11189 // After delay expires, the file is saved.
11190 cx.executor().advance_clock(Duration::from_millis(250));
11191 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
11192
11193 // Autosave after delay, should save earlier than delay if tab is closed
11194 item.update(cx, |item, cx| {
11195 item.is_dirty = true;
11196 cx.emit(ItemEvent::Edit);
11197 });
11198 cx.executor().advance_clock(Duration::from_millis(250));
11199 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
11200
11201 // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
11202 pane.update_in(cx, |pane, window, cx| {
11203 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11204 })
11205 .await
11206 .unwrap();
11207 assert!(!cx.has_pending_prompt());
11208 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
11209
11210 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11211 workspace.update_in(cx, |workspace, window, cx| {
11212 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11213 });
11214 item.update_in(cx, |item, _window, cx| {
11215 item.is_dirty = true;
11216 for project_item in &mut item.project_items {
11217 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11218 }
11219 });
11220 cx.run_until_parked();
11221 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
11222
11223 // Autosave on focus change, ensuring closing the tab counts as such.
11224 item.update(cx, |item, cx| {
11225 SettingsStore::update_global(cx, |settings, cx| {
11226 settings.update_user_settings(cx, |settings| {
11227 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11228 })
11229 });
11230 item.is_dirty = true;
11231 for project_item in &mut item.project_items {
11232 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11233 }
11234 });
11235
11236 pane.update_in(cx, |pane, window, cx| {
11237 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11238 })
11239 .await
11240 .unwrap();
11241 assert!(!cx.has_pending_prompt());
11242 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11243
11244 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11245 workspace.update_in(cx, |workspace, window, cx| {
11246 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11247 });
11248 item.update_in(cx, |item, window, cx| {
11249 item.project_items[0].update(cx, |item, _| {
11250 item.entry_id = None;
11251 });
11252 item.is_dirty = true;
11253 window.blur();
11254 });
11255 cx.run_until_parked();
11256 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11257
11258 // Ensure autosave is prevented for deleted files also when closing the buffer.
11259 let _close_items = pane.update_in(cx, |pane, window, cx| {
11260 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11261 });
11262 cx.run_until_parked();
11263 assert!(cx.has_pending_prompt());
11264 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11265 }
11266
11267 #[gpui::test]
11268 async fn test_autosave_on_focus_change_in_multibuffer(cx: &mut gpui::TestAppContext) {
11269 init_test(cx);
11270
11271 let fs = FakeFs::new(cx.executor());
11272 let project = Project::test(fs, [], cx).await;
11273 let (workspace, cx) =
11274 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11275
11276 // Create a multibuffer-like item with two child focus handles,
11277 // simulating individual buffer editors within a multibuffer.
11278 let item = cx.new(|cx| {
11279 TestItem::new(cx)
11280 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11281 .with_child_focus_handles(2, cx)
11282 });
11283 workspace.update_in(cx, |workspace, window, cx| {
11284 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11285 });
11286
11287 // Set autosave to OnFocusChange and focus the first child handle,
11288 // simulating the user's cursor being inside one of the multibuffer's excerpts.
11289 item.update_in(cx, |item, window, cx| {
11290 SettingsStore::update_global(cx, |settings, cx| {
11291 settings.update_user_settings(cx, |settings| {
11292 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11293 })
11294 });
11295 item.is_dirty = true;
11296 window.focus(&item.child_focus_handles[0], cx);
11297 });
11298 cx.executor().run_until_parked();
11299 item.read_with(cx, |item, _| assert_eq!(item.save_count, 0));
11300
11301 // Moving focus from one child to another within the same item should
11302 // NOT trigger autosave — focus is still within the item's focus hierarchy.
11303 item.update_in(cx, |item, window, cx| {
11304 window.focus(&item.child_focus_handles[1], cx);
11305 });
11306 cx.executor().run_until_parked();
11307 item.read_with(cx, |item, _| {
11308 assert_eq!(
11309 item.save_count, 0,
11310 "Switching focus between children within the same item should not autosave"
11311 );
11312 });
11313
11314 // Blurring the item saves the file. This is the core regression scenario:
11315 // with `on_blur`, this would NOT trigger because `on_blur` only fires when
11316 // the item's own focus handle is the leaf that lost focus. In a multibuffer,
11317 // the leaf is always a child focus handle, so `on_blur` never detected
11318 // focus leaving the item.
11319 item.update_in(cx, |_, window, _| window.blur());
11320 cx.executor().run_until_parked();
11321 item.read_with(cx, |item, _| {
11322 assert_eq!(
11323 item.save_count, 1,
11324 "Blurring should trigger autosave when focus was on a child of the item"
11325 );
11326 });
11327
11328 // Deactivating the window should also trigger autosave when a child of
11329 // the multibuffer item currently owns focus.
11330 item.update_in(cx, |item, window, cx| {
11331 item.is_dirty = true;
11332 window.focus(&item.child_focus_handles[0], cx);
11333 });
11334 cx.executor().run_until_parked();
11335 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11336
11337 cx.deactivate_window();
11338 item.read_with(cx, |item, _| {
11339 assert_eq!(
11340 item.save_count, 2,
11341 "Deactivating window should trigger autosave when focus was on a child"
11342 );
11343 });
11344 }
11345
11346 #[gpui::test]
11347 async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
11348 init_test(cx);
11349
11350 let fs = FakeFs::new(cx.executor());
11351
11352 let project = Project::test(fs, [], cx).await;
11353 let (workspace, cx) =
11354 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11355
11356 let item = cx.new(|cx| {
11357 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11358 });
11359 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11360 let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
11361 let toolbar_notify_count = Rc::new(RefCell::new(0));
11362
11363 workspace.update_in(cx, |workspace, window, cx| {
11364 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11365 let toolbar_notification_count = toolbar_notify_count.clone();
11366 cx.observe_in(&toolbar, window, move |_, _, _, _| {
11367 *toolbar_notification_count.borrow_mut() += 1
11368 })
11369 .detach();
11370 });
11371
11372 pane.read_with(cx, |pane, _| {
11373 assert!(!pane.can_navigate_backward());
11374 assert!(!pane.can_navigate_forward());
11375 });
11376
11377 item.update_in(cx, |item, _, cx| {
11378 item.set_state("one".to_string(), cx);
11379 });
11380
11381 // Toolbar must be notified to re-render the navigation buttons
11382 assert_eq!(*toolbar_notify_count.borrow(), 1);
11383
11384 pane.read_with(cx, |pane, _| {
11385 assert!(pane.can_navigate_backward());
11386 assert!(!pane.can_navigate_forward());
11387 });
11388
11389 workspace
11390 .update_in(cx, |workspace, window, cx| {
11391 workspace.go_back(pane.downgrade(), window, cx)
11392 })
11393 .await
11394 .unwrap();
11395
11396 assert_eq!(*toolbar_notify_count.borrow(), 2);
11397 pane.read_with(cx, |pane, _| {
11398 assert!(!pane.can_navigate_backward());
11399 assert!(pane.can_navigate_forward());
11400 });
11401 }
11402
11403 /// Tests that the navigation history deduplicates entries for the same item.
11404 ///
11405 /// When navigating back and forth between items (e.g., A -> B -> A -> B -> A -> B -> C),
11406 /// the navigation history deduplicates by keeping only the most recent visit to each item,
11407 /// resulting in [A, B, C] instead of [A, B, A, B, A, B, C]. This ensures that Go Back (Ctrl-O)
11408 /// navigates through unique items efficiently: C -> B -> A, rather than bouncing between
11409 /// repeated entries: C -> B -> A -> B -> A -> B -> A.
11410 ///
11411 /// This behavior prevents the navigation history from growing unnecessarily large and provides
11412 /// a better user experience by eliminating redundant navigation steps when jumping between files.
11413 #[gpui::test]
11414 async fn test_navigation_history_deduplication(cx: &mut gpui::TestAppContext) {
11415 init_test(cx);
11416
11417 let fs = FakeFs::new(cx.executor());
11418 let project = Project::test(fs, [], cx).await;
11419 let (workspace, cx) =
11420 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11421
11422 let item_a = cx.new(|cx| {
11423 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "a.txt", cx)])
11424 });
11425 let item_b = cx.new(|cx| {
11426 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "b.txt", cx)])
11427 });
11428 let item_c = cx.new(|cx| {
11429 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "c.txt", cx)])
11430 });
11431
11432 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11433
11434 workspace.update_in(cx, |workspace, window, cx| {
11435 workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx);
11436 workspace.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx);
11437 workspace.add_item_to_active_pane(Box::new(item_c.clone()), None, true, window, cx);
11438 });
11439
11440 workspace.update_in(cx, |workspace, window, cx| {
11441 workspace.activate_item(&item_a, false, false, window, cx);
11442 });
11443 cx.run_until_parked();
11444
11445 workspace.update_in(cx, |workspace, window, cx| {
11446 workspace.activate_item(&item_b, false, false, window, cx);
11447 });
11448 cx.run_until_parked();
11449
11450 workspace.update_in(cx, |workspace, window, cx| {
11451 workspace.activate_item(&item_a, false, false, window, cx);
11452 });
11453 cx.run_until_parked();
11454
11455 workspace.update_in(cx, |workspace, window, cx| {
11456 workspace.activate_item(&item_b, false, false, window, cx);
11457 });
11458 cx.run_until_parked();
11459
11460 workspace.update_in(cx, |workspace, window, cx| {
11461 workspace.activate_item(&item_a, false, false, window, cx);
11462 });
11463 cx.run_until_parked();
11464
11465 workspace.update_in(cx, |workspace, window, cx| {
11466 workspace.activate_item(&item_b, false, false, window, cx);
11467 });
11468 cx.run_until_parked();
11469
11470 workspace.update_in(cx, |workspace, window, cx| {
11471 workspace.activate_item(&item_c, false, false, window, cx);
11472 });
11473 cx.run_until_parked();
11474
11475 let backward_count = pane.read_with(cx, |pane, cx| {
11476 let mut count = 0;
11477 pane.nav_history().for_each_entry(cx, &mut |_, _| {
11478 count += 1;
11479 });
11480 count
11481 });
11482 assert!(
11483 backward_count <= 4,
11484 "Should have at most 4 entries, got {}",
11485 backward_count
11486 );
11487
11488 workspace
11489 .update_in(cx, |workspace, window, cx| {
11490 workspace.go_back(pane.downgrade(), window, cx)
11491 })
11492 .await
11493 .unwrap();
11494
11495 let active_item = workspace.read_with(cx, |workspace, cx| {
11496 workspace.active_item(cx).unwrap().item_id()
11497 });
11498 assert_eq!(
11499 active_item,
11500 item_b.entity_id(),
11501 "After first go_back, should be at item B"
11502 );
11503
11504 workspace
11505 .update_in(cx, |workspace, window, cx| {
11506 workspace.go_back(pane.downgrade(), window, cx)
11507 })
11508 .await
11509 .unwrap();
11510
11511 let active_item = workspace.read_with(cx, |workspace, cx| {
11512 workspace.active_item(cx).unwrap().item_id()
11513 });
11514 assert_eq!(
11515 active_item,
11516 item_a.entity_id(),
11517 "After second go_back, should be at item A"
11518 );
11519
11520 pane.read_with(cx, |pane, _| {
11521 assert!(pane.can_navigate_forward(), "Should be able to go forward");
11522 });
11523 }
11524
11525 #[gpui::test]
11526 async fn test_activate_last_pane(cx: &mut gpui::TestAppContext) {
11527 init_test(cx);
11528 let fs = FakeFs::new(cx.executor());
11529 let project = Project::test(fs, [], cx).await;
11530 let (multi_workspace, cx) =
11531 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11532 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11533
11534 workspace.update_in(cx, |workspace, window, cx| {
11535 let first_item = cx.new(|cx| {
11536 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11537 });
11538 workspace.add_item_to_active_pane(Box::new(first_item), None, true, window, cx);
11539 workspace.split_pane(
11540 workspace.active_pane().clone(),
11541 SplitDirection::Right,
11542 window,
11543 cx,
11544 );
11545 workspace.split_pane(
11546 workspace.active_pane().clone(),
11547 SplitDirection::Right,
11548 window,
11549 cx,
11550 );
11551 });
11552
11553 let (first_pane_id, target_last_pane_id) = workspace.update(cx, |workspace, _cx| {
11554 let panes = workspace.center.panes();
11555 assert!(panes.len() >= 2);
11556 (
11557 panes.first().expect("at least one pane").entity_id(),
11558 panes.last().expect("at least one pane").entity_id(),
11559 )
11560 });
11561
11562 workspace.update_in(cx, |workspace, window, cx| {
11563 workspace.activate_pane_at_index(&ActivatePane(0), window, cx);
11564 });
11565 workspace.update(cx, |workspace, _| {
11566 assert_eq!(workspace.active_pane().entity_id(), first_pane_id);
11567 assert_ne!(workspace.active_pane().entity_id(), target_last_pane_id);
11568 });
11569
11570 cx.dispatch_action(ActivateLastPane);
11571
11572 workspace.update(cx, |workspace, _| {
11573 assert_eq!(workspace.active_pane().entity_id(), target_last_pane_id);
11574 });
11575 }
11576
11577 #[gpui::test]
11578 async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
11579 init_test(cx);
11580 let fs = FakeFs::new(cx.executor());
11581
11582 let project = Project::test(fs, [], cx).await;
11583 let (workspace, cx) =
11584 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11585
11586 let panel = workspace.update_in(cx, |workspace, window, cx| {
11587 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11588 workspace.add_panel(panel.clone(), window, cx);
11589
11590 workspace
11591 .right_dock()
11592 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
11593
11594 panel
11595 });
11596
11597 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11598 pane.update_in(cx, |pane, window, cx| {
11599 let item = cx.new(TestItem::new);
11600 pane.add_item(Box::new(item), true, true, None, window, cx);
11601 });
11602
11603 // Transfer focus from center to panel
11604 workspace.update_in(cx, |workspace, window, cx| {
11605 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11606 });
11607
11608 workspace.update_in(cx, |workspace, window, cx| {
11609 assert!(workspace.right_dock().read(cx).is_open());
11610 assert!(!panel.is_zoomed(window, cx));
11611 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11612 });
11613
11614 // Transfer focus from panel to center
11615 workspace.update_in(cx, |workspace, window, cx| {
11616 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11617 });
11618
11619 workspace.update_in(cx, |workspace, window, cx| {
11620 assert!(workspace.right_dock().read(cx).is_open());
11621 assert!(!panel.is_zoomed(window, cx));
11622 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11623 assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11624 });
11625
11626 // Close the dock
11627 workspace.update_in(cx, |workspace, window, cx| {
11628 workspace.toggle_dock(DockPosition::Right, window, cx);
11629 });
11630
11631 workspace.update_in(cx, |workspace, window, cx| {
11632 assert!(!workspace.right_dock().read(cx).is_open());
11633 assert!(!panel.is_zoomed(window, cx));
11634 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11635 assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11636 });
11637
11638 // Open the dock
11639 workspace.update_in(cx, |workspace, window, cx| {
11640 workspace.toggle_dock(DockPosition::Right, window, cx);
11641 });
11642
11643 workspace.update_in(cx, |workspace, window, cx| {
11644 assert!(workspace.right_dock().read(cx).is_open());
11645 assert!(!panel.is_zoomed(window, cx));
11646 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11647 });
11648
11649 // Focus and zoom panel
11650 panel.update_in(cx, |panel, window, cx| {
11651 cx.focus_self(window);
11652 panel.set_zoomed(true, window, cx)
11653 });
11654
11655 workspace.update_in(cx, |workspace, window, cx| {
11656 assert!(workspace.right_dock().read(cx).is_open());
11657 assert!(panel.is_zoomed(window, cx));
11658 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11659 });
11660
11661 // Transfer focus to the center closes the dock
11662 workspace.update_in(cx, |workspace, window, cx| {
11663 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11664 });
11665
11666 workspace.update_in(cx, |workspace, window, cx| {
11667 assert!(!workspace.right_dock().read(cx).is_open());
11668 assert!(panel.is_zoomed(window, cx));
11669 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11670 });
11671
11672 // Transferring focus back to the panel keeps it zoomed
11673 workspace.update_in(cx, |workspace, window, cx| {
11674 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11675 });
11676
11677 workspace.update_in(cx, |workspace, window, cx| {
11678 assert!(workspace.right_dock().read(cx).is_open());
11679 assert!(panel.is_zoomed(window, cx));
11680 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11681 });
11682
11683 // Close the dock while it is zoomed
11684 workspace.update_in(cx, |workspace, window, cx| {
11685 workspace.toggle_dock(DockPosition::Right, window, cx)
11686 });
11687
11688 workspace.update_in(cx, |workspace, window, cx| {
11689 assert!(!workspace.right_dock().read(cx).is_open());
11690 assert!(panel.is_zoomed(window, cx));
11691 assert!(workspace.zoomed.is_none());
11692 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11693 });
11694
11695 // Opening the dock, when it's zoomed, retains focus
11696 workspace.update_in(cx, |workspace, window, cx| {
11697 workspace.toggle_dock(DockPosition::Right, window, cx)
11698 });
11699
11700 workspace.update_in(cx, |workspace, window, cx| {
11701 assert!(workspace.right_dock().read(cx).is_open());
11702 assert!(panel.is_zoomed(window, cx));
11703 assert!(workspace.zoomed.is_some());
11704 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11705 });
11706
11707 // Unzoom and close the panel, zoom the active pane.
11708 panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
11709 workspace.update_in(cx, |workspace, window, cx| {
11710 workspace.toggle_dock(DockPosition::Right, window, cx)
11711 });
11712 pane.update_in(cx, |pane, window, cx| {
11713 pane.toggle_zoom(&Default::default(), window, cx)
11714 });
11715
11716 // Opening a dock unzooms the pane.
11717 workspace.update_in(cx, |workspace, window, cx| {
11718 workspace.toggle_dock(DockPosition::Right, window, cx)
11719 });
11720 workspace.update_in(cx, |workspace, window, cx| {
11721 let pane = pane.read(cx);
11722 assert!(!pane.is_zoomed());
11723 assert!(!pane.focus_handle(cx).is_focused(window));
11724 assert!(workspace.right_dock().read(cx).is_open());
11725 assert!(workspace.zoomed.is_none());
11726 });
11727 }
11728
11729 #[gpui::test]
11730 async fn test_close_panel_on_toggle(cx: &mut gpui::TestAppContext) {
11731 init_test(cx);
11732 let fs = FakeFs::new(cx.executor());
11733
11734 let project = Project::test(fs, [], cx).await;
11735 let (workspace, cx) =
11736 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11737
11738 let panel = workspace.update_in(cx, |workspace, window, cx| {
11739 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11740 workspace.add_panel(panel.clone(), window, cx);
11741 panel
11742 });
11743
11744 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11745 pane.update_in(cx, |pane, window, cx| {
11746 let item = cx.new(TestItem::new);
11747 pane.add_item(Box::new(item), true, true, None, window, cx);
11748 });
11749
11750 // Enable close_panel_on_toggle
11751 cx.update_global(|store: &mut SettingsStore, cx| {
11752 store.update_user_settings(cx, |settings| {
11753 settings.workspace.close_panel_on_toggle = Some(true);
11754 });
11755 });
11756
11757 // Panel starts closed. Toggling should open and focus it.
11758 workspace.update_in(cx, |workspace, window, cx| {
11759 assert!(!workspace.right_dock().read(cx).is_open());
11760 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11761 });
11762
11763 workspace.update_in(cx, |workspace, window, cx| {
11764 assert!(
11765 workspace.right_dock().read(cx).is_open(),
11766 "Dock should be open after toggling from center"
11767 );
11768 assert!(
11769 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11770 "Panel should be focused after toggling from center"
11771 );
11772 });
11773
11774 // Panel is open and focused. Toggling should close the panel and
11775 // return focus to the center.
11776 workspace.update_in(cx, |workspace, window, cx| {
11777 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11778 });
11779
11780 workspace.update_in(cx, |workspace, window, cx| {
11781 assert!(
11782 !workspace.right_dock().read(cx).is_open(),
11783 "Dock should be closed after toggling from focused panel"
11784 );
11785 assert!(
11786 !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11787 "Panel should not be focused after toggling from focused panel"
11788 );
11789 });
11790
11791 // Open the dock and focus something else so the panel is open but not
11792 // focused. Toggling should focus the panel (not close it).
11793 workspace.update_in(cx, |workspace, window, cx| {
11794 workspace
11795 .right_dock()
11796 .update(cx, |dock, cx| dock.set_open(true, window, cx));
11797 window.focus(&pane.read(cx).focus_handle(cx), cx);
11798 });
11799
11800 workspace.update_in(cx, |workspace, window, cx| {
11801 assert!(workspace.right_dock().read(cx).is_open());
11802 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11803 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11804 });
11805
11806 workspace.update_in(cx, |workspace, window, cx| {
11807 assert!(
11808 workspace.right_dock().read(cx).is_open(),
11809 "Dock should remain open when toggling focuses an open-but-unfocused panel"
11810 );
11811 assert!(
11812 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11813 "Panel should be focused after toggling an open-but-unfocused panel"
11814 );
11815 });
11816
11817 // Now disable the setting and verify the original behavior: toggling
11818 // from a focused panel moves focus to center but leaves the dock open.
11819 cx.update_global(|store: &mut SettingsStore, cx| {
11820 store.update_user_settings(cx, |settings| {
11821 settings.workspace.close_panel_on_toggle = Some(false);
11822 });
11823 });
11824
11825 workspace.update_in(cx, |workspace, window, cx| {
11826 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11827 });
11828
11829 workspace.update_in(cx, |workspace, window, cx| {
11830 assert!(
11831 workspace.right_dock().read(cx).is_open(),
11832 "Dock should remain open when setting is disabled"
11833 );
11834 assert!(
11835 !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11836 "Panel should not be focused after toggling with setting disabled"
11837 );
11838 });
11839 }
11840
11841 #[gpui::test]
11842 async fn test_pane_zoom_in_out(cx: &mut TestAppContext) {
11843 init_test(cx);
11844 let fs = FakeFs::new(cx.executor());
11845
11846 let project = Project::test(fs, [], cx).await;
11847 let (workspace, cx) =
11848 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11849
11850 let pane = workspace.update_in(cx, |workspace, _window, _cx| {
11851 workspace.active_pane().clone()
11852 });
11853
11854 // Add an item to the pane so it can be zoomed
11855 workspace.update_in(cx, |workspace, window, cx| {
11856 let item = cx.new(TestItem::new);
11857 workspace.add_item(pane.clone(), Box::new(item), None, true, true, window, cx);
11858 });
11859
11860 // Initially not zoomed
11861 workspace.update_in(cx, |workspace, _window, cx| {
11862 assert!(!pane.read(cx).is_zoomed(), "Pane starts unzoomed");
11863 assert!(
11864 workspace.zoomed.is_none(),
11865 "Workspace should track no zoomed pane"
11866 );
11867 assert!(pane.read(cx).items_len() > 0, "Pane should have items");
11868 });
11869
11870 // Zoom In
11871 pane.update_in(cx, |pane, window, cx| {
11872 pane.zoom_in(&crate::ZoomIn, window, cx);
11873 });
11874
11875 workspace.update_in(cx, |workspace, window, cx| {
11876 assert!(
11877 pane.read(cx).is_zoomed(),
11878 "Pane should be zoomed after ZoomIn"
11879 );
11880 assert!(
11881 workspace.zoomed.is_some(),
11882 "Workspace should track the zoomed pane"
11883 );
11884 assert!(
11885 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11886 "ZoomIn should focus the pane"
11887 );
11888 });
11889
11890 // Zoom In again is a no-op
11891 pane.update_in(cx, |pane, window, cx| {
11892 pane.zoom_in(&crate::ZoomIn, window, cx);
11893 });
11894
11895 workspace.update_in(cx, |workspace, window, cx| {
11896 assert!(pane.read(cx).is_zoomed(), "Second ZoomIn keeps pane zoomed");
11897 assert!(
11898 workspace.zoomed.is_some(),
11899 "Workspace still tracks zoomed pane"
11900 );
11901 assert!(
11902 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11903 "Pane remains focused after repeated ZoomIn"
11904 );
11905 });
11906
11907 // Zoom Out
11908 pane.update_in(cx, |pane, window, cx| {
11909 pane.zoom_out(&crate::ZoomOut, window, cx);
11910 });
11911
11912 workspace.update_in(cx, |workspace, _window, cx| {
11913 assert!(
11914 !pane.read(cx).is_zoomed(),
11915 "Pane should unzoom after ZoomOut"
11916 );
11917 assert!(
11918 workspace.zoomed.is_none(),
11919 "Workspace clears zoom tracking after ZoomOut"
11920 );
11921 });
11922
11923 // Zoom Out again is a no-op
11924 pane.update_in(cx, |pane, window, cx| {
11925 pane.zoom_out(&crate::ZoomOut, window, cx);
11926 });
11927
11928 workspace.update_in(cx, |workspace, _window, cx| {
11929 assert!(
11930 !pane.read(cx).is_zoomed(),
11931 "Second ZoomOut keeps pane unzoomed"
11932 );
11933 assert!(
11934 workspace.zoomed.is_none(),
11935 "Workspace remains without zoomed pane"
11936 );
11937 });
11938 }
11939
11940 #[gpui::test]
11941 async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
11942 init_test(cx);
11943 let fs = FakeFs::new(cx.executor());
11944
11945 let project = Project::test(fs, [], cx).await;
11946 let (workspace, cx) =
11947 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11948 workspace.update_in(cx, |workspace, window, cx| {
11949 // Open two docks
11950 let left_dock = workspace.dock_at_position(DockPosition::Left);
11951 let right_dock = workspace.dock_at_position(DockPosition::Right);
11952
11953 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11954 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11955
11956 assert!(left_dock.read(cx).is_open());
11957 assert!(right_dock.read(cx).is_open());
11958 });
11959
11960 workspace.update_in(cx, |workspace, window, cx| {
11961 // Toggle all docks - should close both
11962 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11963
11964 let left_dock = workspace.dock_at_position(DockPosition::Left);
11965 let right_dock = workspace.dock_at_position(DockPosition::Right);
11966 assert!(!left_dock.read(cx).is_open());
11967 assert!(!right_dock.read(cx).is_open());
11968 });
11969
11970 workspace.update_in(cx, |workspace, window, cx| {
11971 // Toggle again - should reopen both
11972 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11973
11974 let left_dock = workspace.dock_at_position(DockPosition::Left);
11975 let right_dock = workspace.dock_at_position(DockPosition::Right);
11976 assert!(left_dock.read(cx).is_open());
11977 assert!(right_dock.read(cx).is_open());
11978 });
11979 }
11980
11981 #[gpui::test]
11982 async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
11983 init_test(cx);
11984 let fs = FakeFs::new(cx.executor());
11985
11986 let project = Project::test(fs, [], cx).await;
11987 let (workspace, cx) =
11988 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11989 workspace.update_in(cx, |workspace, window, cx| {
11990 // Open two docks
11991 let left_dock = workspace.dock_at_position(DockPosition::Left);
11992 let right_dock = workspace.dock_at_position(DockPosition::Right);
11993
11994 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11995 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11996
11997 assert!(left_dock.read(cx).is_open());
11998 assert!(right_dock.read(cx).is_open());
11999 });
12000
12001 workspace.update_in(cx, |workspace, window, cx| {
12002 // Close them manually
12003 workspace.toggle_dock(DockPosition::Left, window, cx);
12004 workspace.toggle_dock(DockPosition::Right, window, cx);
12005
12006 let left_dock = workspace.dock_at_position(DockPosition::Left);
12007 let right_dock = workspace.dock_at_position(DockPosition::Right);
12008 assert!(!left_dock.read(cx).is_open());
12009 assert!(!right_dock.read(cx).is_open());
12010 });
12011
12012 workspace.update_in(cx, |workspace, window, cx| {
12013 // Toggle all docks - only last closed (right dock) should reopen
12014 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12015
12016 let left_dock = workspace.dock_at_position(DockPosition::Left);
12017 let right_dock = workspace.dock_at_position(DockPosition::Right);
12018 assert!(!left_dock.read(cx).is_open());
12019 assert!(right_dock.read(cx).is_open());
12020 });
12021 }
12022
12023 #[gpui::test]
12024 async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
12025 init_test(cx);
12026 let fs = FakeFs::new(cx.executor());
12027 let project = Project::test(fs, [], cx).await;
12028 let (multi_workspace, cx) =
12029 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12030 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12031
12032 // Open two docks (left and right) with one panel each
12033 let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
12034 let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12035 workspace.add_panel(left_panel.clone(), window, cx);
12036
12037 let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
12038 workspace.add_panel(right_panel.clone(), window, cx);
12039
12040 workspace.toggle_dock(DockPosition::Left, window, cx);
12041 workspace.toggle_dock(DockPosition::Right, window, cx);
12042
12043 // Verify initial state
12044 assert!(
12045 workspace.left_dock().read(cx).is_open(),
12046 "Left dock should be open"
12047 );
12048 assert_eq!(
12049 workspace
12050 .left_dock()
12051 .read(cx)
12052 .visible_panel()
12053 .unwrap()
12054 .panel_id(),
12055 left_panel.panel_id(),
12056 "Left panel should be visible in left dock"
12057 );
12058 assert!(
12059 workspace.right_dock().read(cx).is_open(),
12060 "Right dock should be open"
12061 );
12062 assert_eq!(
12063 workspace
12064 .right_dock()
12065 .read(cx)
12066 .visible_panel()
12067 .unwrap()
12068 .panel_id(),
12069 right_panel.panel_id(),
12070 "Right panel should be visible in right dock"
12071 );
12072 assert!(
12073 !workspace.bottom_dock().read(cx).is_open(),
12074 "Bottom dock should be closed"
12075 );
12076
12077 (left_panel, right_panel)
12078 });
12079
12080 // Focus the left panel and move it to the next position (bottom dock)
12081 workspace.update_in(cx, |workspace, window, cx| {
12082 workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
12083 assert!(
12084 left_panel.read(cx).focus_handle(cx).is_focused(window),
12085 "Left panel should be focused"
12086 );
12087 });
12088
12089 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12090
12091 // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
12092 workspace.update(cx, |workspace, cx| {
12093 assert!(
12094 !workspace.left_dock().read(cx).is_open(),
12095 "Left dock should be closed"
12096 );
12097 assert!(
12098 workspace.bottom_dock().read(cx).is_open(),
12099 "Bottom dock should now be open"
12100 );
12101 assert_eq!(
12102 left_panel.read(cx).position,
12103 DockPosition::Bottom,
12104 "Left panel should now be in the bottom dock"
12105 );
12106 assert_eq!(
12107 workspace
12108 .bottom_dock()
12109 .read(cx)
12110 .visible_panel()
12111 .unwrap()
12112 .panel_id(),
12113 left_panel.panel_id(),
12114 "Left panel should be the visible panel in the bottom dock"
12115 );
12116 });
12117
12118 // Toggle all docks off
12119 workspace.update_in(cx, |workspace, window, cx| {
12120 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12121 assert!(
12122 !workspace.left_dock().read(cx).is_open(),
12123 "Left dock should be closed"
12124 );
12125 assert!(
12126 !workspace.right_dock().read(cx).is_open(),
12127 "Right dock should be closed"
12128 );
12129 assert!(
12130 !workspace.bottom_dock().read(cx).is_open(),
12131 "Bottom dock should be closed"
12132 );
12133 });
12134
12135 // Toggle all docks back on and verify positions are restored
12136 workspace.update_in(cx, |workspace, window, cx| {
12137 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12138 assert!(
12139 !workspace.left_dock().read(cx).is_open(),
12140 "Left dock should remain closed"
12141 );
12142 assert!(
12143 workspace.right_dock().read(cx).is_open(),
12144 "Right dock should remain open"
12145 );
12146 assert!(
12147 workspace.bottom_dock().read(cx).is_open(),
12148 "Bottom dock should remain open"
12149 );
12150 assert_eq!(
12151 left_panel.read(cx).position,
12152 DockPosition::Bottom,
12153 "Left panel should remain in the bottom dock"
12154 );
12155 assert_eq!(
12156 right_panel.read(cx).position,
12157 DockPosition::Right,
12158 "Right panel should remain in the right dock"
12159 );
12160 assert_eq!(
12161 workspace
12162 .bottom_dock()
12163 .read(cx)
12164 .visible_panel()
12165 .unwrap()
12166 .panel_id(),
12167 left_panel.panel_id(),
12168 "Left panel should be the visible panel in the right dock"
12169 );
12170 });
12171 }
12172
12173 #[gpui::test]
12174 async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
12175 init_test(cx);
12176
12177 let fs = FakeFs::new(cx.executor());
12178
12179 let project = Project::test(fs, None, cx).await;
12180 let (workspace, cx) =
12181 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12182
12183 // Let's arrange the panes like this:
12184 //
12185 // +-----------------------+
12186 // | top |
12187 // +------+--------+-------+
12188 // | left | center | right |
12189 // +------+--------+-------+
12190 // | bottom |
12191 // +-----------------------+
12192
12193 let top_item = cx.new(|cx| {
12194 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
12195 });
12196 let bottom_item = cx.new(|cx| {
12197 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
12198 });
12199 let left_item = cx.new(|cx| {
12200 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
12201 });
12202 let right_item = cx.new(|cx| {
12203 TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
12204 });
12205 let center_item = cx.new(|cx| {
12206 TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
12207 });
12208
12209 let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12210 let top_pane_id = workspace.active_pane().entity_id();
12211 workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
12212 workspace.split_pane(
12213 workspace.active_pane().clone(),
12214 SplitDirection::Down,
12215 window,
12216 cx,
12217 );
12218 top_pane_id
12219 });
12220 let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12221 let bottom_pane_id = workspace.active_pane().entity_id();
12222 workspace.add_item_to_active_pane(
12223 Box::new(bottom_item.clone()),
12224 None,
12225 false,
12226 window,
12227 cx,
12228 );
12229 workspace.split_pane(
12230 workspace.active_pane().clone(),
12231 SplitDirection::Up,
12232 window,
12233 cx,
12234 );
12235 bottom_pane_id
12236 });
12237 let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12238 let left_pane_id = workspace.active_pane().entity_id();
12239 workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
12240 workspace.split_pane(
12241 workspace.active_pane().clone(),
12242 SplitDirection::Right,
12243 window,
12244 cx,
12245 );
12246 left_pane_id
12247 });
12248 let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12249 let right_pane_id = workspace.active_pane().entity_id();
12250 workspace.add_item_to_active_pane(
12251 Box::new(right_item.clone()),
12252 None,
12253 false,
12254 window,
12255 cx,
12256 );
12257 workspace.split_pane(
12258 workspace.active_pane().clone(),
12259 SplitDirection::Left,
12260 window,
12261 cx,
12262 );
12263 right_pane_id
12264 });
12265 let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12266 let center_pane_id = workspace.active_pane().entity_id();
12267 workspace.add_item_to_active_pane(
12268 Box::new(center_item.clone()),
12269 None,
12270 false,
12271 window,
12272 cx,
12273 );
12274 center_pane_id
12275 });
12276 cx.executor().run_until_parked();
12277
12278 workspace.update_in(cx, |workspace, window, cx| {
12279 assert_eq!(center_pane_id, workspace.active_pane().entity_id());
12280
12281 // Join into next from center pane into right
12282 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12283 });
12284
12285 workspace.update_in(cx, |workspace, window, cx| {
12286 let active_pane = workspace.active_pane();
12287 assert_eq!(right_pane_id, active_pane.entity_id());
12288 assert_eq!(2, active_pane.read(cx).items_len());
12289 let item_ids_in_pane =
12290 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12291 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12292 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12293
12294 // Join into next from right pane into bottom
12295 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12296 });
12297
12298 workspace.update_in(cx, |workspace, window, cx| {
12299 let active_pane = workspace.active_pane();
12300 assert_eq!(bottom_pane_id, active_pane.entity_id());
12301 assert_eq!(3, active_pane.read(cx).items_len());
12302 let item_ids_in_pane =
12303 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12304 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12305 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12306 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12307
12308 // Join into next from bottom pane into left
12309 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12310 });
12311
12312 workspace.update_in(cx, |workspace, window, cx| {
12313 let active_pane = workspace.active_pane();
12314 assert_eq!(left_pane_id, active_pane.entity_id());
12315 assert_eq!(4, active_pane.read(cx).items_len());
12316 let item_ids_in_pane =
12317 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12318 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12319 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12320 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12321 assert!(item_ids_in_pane.contains(&left_item.item_id()));
12322
12323 // Join into next from left pane into top
12324 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12325 });
12326
12327 workspace.update_in(cx, |workspace, window, cx| {
12328 let active_pane = workspace.active_pane();
12329 assert_eq!(top_pane_id, active_pane.entity_id());
12330 assert_eq!(5, active_pane.read(cx).items_len());
12331 let item_ids_in_pane =
12332 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12333 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12334 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12335 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12336 assert!(item_ids_in_pane.contains(&left_item.item_id()));
12337 assert!(item_ids_in_pane.contains(&top_item.item_id()));
12338
12339 // Single pane left: no-op
12340 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
12341 });
12342
12343 workspace.update(cx, |workspace, _cx| {
12344 let active_pane = workspace.active_pane();
12345 assert_eq!(top_pane_id, active_pane.entity_id());
12346 });
12347 }
12348
12349 fn add_an_item_to_active_pane(
12350 cx: &mut VisualTestContext,
12351 workspace: &Entity<Workspace>,
12352 item_id: u64,
12353 ) -> Entity<TestItem> {
12354 let item = cx.new(|cx| {
12355 TestItem::new(cx).with_project_items(&[TestProjectItem::new(
12356 item_id,
12357 "item{item_id}.txt",
12358 cx,
12359 )])
12360 });
12361 workspace.update_in(cx, |workspace, window, cx| {
12362 workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
12363 });
12364 item
12365 }
12366
12367 fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
12368 workspace.update_in(cx, |workspace, window, cx| {
12369 workspace.split_pane(
12370 workspace.active_pane().clone(),
12371 SplitDirection::Right,
12372 window,
12373 cx,
12374 )
12375 })
12376 }
12377
12378 #[gpui::test]
12379 async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
12380 init_test(cx);
12381 let fs = FakeFs::new(cx.executor());
12382 let project = Project::test(fs, None, cx).await;
12383 let (workspace, cx) =
12384 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12385
12386 add_an_item_to_active_pane(cx, &workspace, 1);
12387 split_pane(cx, &workspace);
12388 add_an_item_to_active_pane(cx, &workspace, 2);
12389 split_pane(cx, &workspace); // empty pane
12390 split_pane(cx, &workspace);
12391 let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
12392
12393 cx.executor().run_until_parked();
12394
12395 workspace.update(cx, |workspace, cx| {
12396 let num_panes = workspace.panes().len();
12397 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12398 let active_item = workspace
12399 .active_pane()
12400 .read(cx)
12401 .active_item()
12402 .expect("item is in focus");
12403
12404 assert_eq!(num_panes, 4);
12405 assert_eq!(num_items_in_current_pane, 1);
12406 assert_eq!(active_item.item_id(), last_item.item_id());
12407 });
12408
12409 workspace.update_in(cx, |workspace, window, cx| {
12410 workspace.join_all_panes(window, cx);
12411 });
12412
12413 workspace.update(cx, |workspace, cx| {
12414 let num_panes = workspace.panes().len();
12415 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12416 let active_item = workspace
12417 .active_pane()
12418 .read(cx)
12419 .active_item()
12420 .expect("item is in focus");
12421
12422 assert_eq!(num_panes, 1);
12423 assert_eq!(num_items_in_current_pane, 3);
12424 assert_eq!(active_item.item_id(), last_item.item_id());
12425 });
12426 }
12427
12428 #[gpui::test]
12429 async fn test_flexible_dock_sizing(cx: &mut gpui::TestAppContext) {
12430 init_test(cx);
12431 let fs = FakeFs::new(cx.executor());
12432
12433 let project = Project::test(fs, [], cx).await;
12434 let (multi_workspace, cx) =
12435 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12436 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12437
12438 workspace.update(cx, |workspace, _cx| {
12439 workspace.bounds.size.width = px(800.);
12440 });
12441
12442 workspace.update_in(cx, |workspace, window, cx| {
12443 let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12444 workspace.add_panel(panel, window, cx);
12445 workspace.toggle_dock(DockPosition::Right, window, cx);
12446 });
12447
12448 let (panel, resized_width, ratio_basis_width) =
12449 workspace.update_in(cx, |workspace, window, cx| {
12450 let item = cx.new(|cx| {
12451 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12452 });
12453 workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12454
12455 let dock = workspace.right_dock().read(cx);
12456 let workspace_width = workspace.bounds.size.width;
12457 let initial_width = workspace
12458 .dock_size(&dock, window, cx)
12459 .expect("flexible dock should have an initial width");
12460
12461 assert_eq!(initial_width, workspace_width / 2.);
12462
12463 workspace.resize_right_dock(px(300.), window, cx);
12464
12465 let dock = workspace.right_dock().read(cx);
12466 let resized_width = workspace
12467 .dock_size(&dock, window, cx)
12468 .expect("flexible dock should keep its resized width");
12469
12470 assert_eq!(resized_width, px(300.));
12471
12472 let panel = workspace
12473 .right_dock()
12474 .read(cx)
12475 .visible_panel()
12476 .expect("flexible dock should have a visible panel")
12477 .panel_id();
12478
12479 (panel, resized_width, workspace_width)
12480 });
12481
12482 workspace.update_in(cx, |workspace, window, cx| {
12483 workspace.toggle_dock(DockPosition::Right, window, cx);
12484 workspace.toggle_dock(DockPosition::Right, window, cx);
12485
12486 let dock = workspace.right_dock().read(cx);
12487 let reopened_width = workspace
12488 .dock_size(&dock, window, cx)
12489 .expect("flexible dock should restore when reopened");
12490
12491 assert_eq!(reopened_width, resized_width);
12492
12493 let right_dock = workspace.right_dock().read(cx);
12494 let flexible_panel = right_dock
12495 .visible_panel()
12496 .expect("flexible dock should still have a visible panel");
12497 assert_eq!(flexible_panel.panel_id(), panel);
12498 assert_eq!(
12499 right_dock
12500 .stored_panel_size_state(flexible_panel.as_ref())
12501 .and_then(|size_state| size_state.flex),
12502 Some(
12503 resized_width.to_f64() as f32
12504 / (workspace.bounds.size.width - resized_width).to_f64() as f32
12505 )
12506 );
12507 });
12508
12509 workspace.update_in(cx, |workspace, window, cx| {
12510 workspace.split_pane(
12511 workspace.active_pane().clone(),
12512 SplitDirection::Right,
12513 window,
12514 cx,
12515 );
12516
12517 let dock = workspace.right_dock().read(cx);
12518 let split_width = workspace
12519 .dock_size(&dock, window, cx)
12520 .expect("flexible dock should keep its user-resized proportion");
12521
12522 assert_eq!(split_width, px(300.));
12523
12524 workspace.bounds.size.width = px(1600.);
12525
12526 let dock = workspace.right_dock().read(cx);
12527 let resized_window_width = workspace
12528 .dock_size(&dock, window, cx)
12529 .expect("flexible dock should preserve proportional size on window resize");
12530
12531 assert_eq!(
12532 resized_window_width,
12533 workspace.bounds.size.width
12534 * (resized_width.to_f64() as f32 / ratio_basis_width.to_f64() as f32)
12535 );
12536 });
12537 }
12538
12539 #[gpui::test]
12540 async fn test_panel_size_state_persistence(cx: &mut gpui::TestAppContext) {
12541 init_test(cx);
12542 let fs = FakeFs::new(cx.executor());
12543
12544 // Fixed-width panel: pixel size is persisted to KVP and restored on re-add.
12545 {
12546 let project = Project::test(fs.clone(), [], cx).await;
12547 let (multi_workspace, cx) =
12548 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12549 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12550
12551 workspace.update(cx, |workspace, _cx| {
12552 workspace.set_random_database_id();
12553 workspace.bounds.size.width = px(800.);
12554 });
12555
12556 let panel = workspace.update_in(cx, |workspace, window, cx| {
12557 let panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12558 workspace.add_panel(panel.clone(), window, cx);
12559 workspace.toggle_dock(DockPosition::Left, window, cx);
12560 panel
12561 });
12562
12563 workspace.update_in(cx, |workspace, window, cx| {
12564 workspace.resize_left_dock(px(350.), window, cx);
12565 });
12566
12567 cx.run_until_parked();
12568
12569 let persisted = workspace.read_with(cx, |workspace, cx| {
12570 workspace.persisted_panel_size_state(TestPanel::panel_key(), cx)
12571 });
12572 assert_eq!(
12573 persisted.and_then(|s| s.size),
12574 Some(px(350.)),
12575 "fixed-width panel size should be persisted to KVP"
12576 );
12577
12578 // Remove the panel and re-add a fresh instance with the same key.
12579 // The new instance should have its size state restored from KVP.
12580 workspace.update_in(cx, |workspace, window, cx| {
12581 workspace.remove_panel(&panel, window, cx);
12582 });
12583
12584 workspace.update_in(cx, |workspace, window, cx| {
12585 let new_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12586 workspace.add_panel(new_panel, window, cx);
12587
12588 let left_dock = workspace.left_dock().read(cx);
12589 let size_state = left_dock
12590 .panel::<TestPanel>()
12591 .and_then(|p| left_dock.stored_panel_size_state(&p));
12592 assert_eq!(
12593 size_state.and_then(|s| s.size),
12594 Some(px(350.)),
12595 "re-added fixed-width panel should restore persisted size from KVP"
12596 );
12597 });
12598 }
12599
12600 // Flexible panel: both pixel size and ratio are persisted and restored.
12601 {
12602 let project = Project::test(fs.clone(), [], cx).await;
12603 let (multi_workspace, cx) =
12604 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12605 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12606
12607 workspace.update(cx, |workspace, _cx| {
12608 workspace.set_random_database_id();
12609 workspace.bounds.size.width = px(800.);
12610 });
12611
12612 let panel = workspace.update_in(cx, |workspace, window, cx| {
12613 let item = cx.new(|cx| {
12614 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12615 });
12616 workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12617
12618 let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12619 workspace.add_panel(panel.clone(), window, cx);
12620 workspace.toggle_dock(DockPosition::Right, window, cx);
12621 panel
12622 });
12623
12624 workspace.update_in(cx, |workspace, window, cx| {
12625 workspace.resize_right_dock(px(300.), window, cx);
12626 });
12627
12628 cx.run_until_parked();
12629
12630 let persisted = workspace
12631 .read_with(cx, |workspace, cx| {
12632 workspace.persisted_panel_size_state(TestPanel::panel_key(), cx)
12633 })
12634 .expect("flexible panel state should be persisted to KVP");
12635 assert_eq!(
12636 persisted.size, None,
12637 "flexible panel should not persist a redundant pixel size"
12638 );
12639 let original_ratio = persisted.flex.expect("panel's flex should be persisted");
12640
12641 // Remove the panel and re-add: both size and ratio should be restored.
12642 workspace.update_in(cx, |workspace, window, cx| {
12643 workspace.remove_panel(&panel, window, cx);
12644 });
12645
12646 workspace.update_in(cx, |workspace, window, cx| {
12647 let new_panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12648 workspace.add_panel(new_panel, window, cx);
12649
12650 let right_dock = workspace.right_dock().read(cx);
12651 let size_state = right_dock
12652 .panel::<TestPanel>()
12653 .and_then(|p| right_dock.stored_panel_size_state(&p))
12654 .expect("re-added flexible panel should have restored size state from KVP");
12655 assert_eq!(
12656 size_state.size, None,
12657 "re-added flexible panel should not have a persisted pixel size"
12658 );
12659 assert_eq!(
12660 size_state.flex,
12661 Some(original_ratio),
12662 "re-added flexible panel should restore persisted flex"
12663 );
12664 });
12665 }
12666 }
12667
12668 #[gpui::test]
12669 async fn test_flexible_panel_left_dock_sizing(cx: &mut gpui::TestAppContext) {
12670 init_test(cx);
12671 let fs = FakeFs::new(cx.executor());
12672
12673 let project = Project::test(fs, [], cx).await;
12674 let (multi_workspace, cx) =
12675 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12676 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12677
12678 workspace.update(cx, |workspace, _cx| {
12679 workspace.bounds.size.width = px(900.);
12680 });
12681
12682 // Step 1: Add a tab to the center pane then open a flexible panel in the left
12683 // dock. With one full-width center pane the default ratio is 0.5, so the panel
12684 // and the center pane each take half the workspace width.
12685 workspace.update_in(cx, |workspace, window, cx| {
12686 let item = cx.new(|cx| {
12687 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12688 });
12689 workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12690
12691 let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Left, 100, cx));
12692 workspace.add_panel(panel, window, cx);
12693 workspace.toggle_dock(DockPosition::Left, window, cx);
12694
12695 let left_dock = workspace.left_dock().read(cx);
12696 let left_width = workspace
12697 .dock_size(&left_dock, window, cx)
12698 .expect("left dock should have an active panel");
12699
12700 assert_eq!(
12701 left_width,
12702 workspace.bounds.size.width / 2.,
12703 "flexible left panel should split evenly with the center pane"
12704 );
12705 });
12706
12707 // Step 2: Split the center pane vertically (top/bottom). Vertical splits do not
12708 // change horizontal width fractions, so the flexible panel stays at the same
12709 // width as each half of the split.
12710 workspace.update_in(cx, |workspace, window, cx| {
12711 workspace.split_pane(
12712 workspace.active_pane().clone(),
12713 SplitDirection::Down,
12714 window,
12715 cx,
12716 );
12717
12718 let left_dock = workspace.left_dock().read(cx);
12719 let left_width = workspace
12720 .dock_size(&left_dock, window, cx)
12721 .expect("left dock should still have an active panel after vertical split");
12722
12723 assert_eq!(
12724 left_width,
12725 workspace.bounds.size.width / 2.,
12726 "flexible left panel width should match each vertically-split pane"
12727 );
12728 });
12729
12730 // Step 3: Open a fixed-width panel in the right dock. The right dock's default
12731 // size reduces the available width, so the flexible left panel and the center
12732 // panes all shrink proportionally to accommodate it.
12733 workspace.update_in(cx, |workspace, window, cx| {
12734 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 200, cx));
12735 workspace.add_panel(panel, window, cx);
12736 workspace.toggle_dock(DockPosition::Right, window, cx);
12737
12738 let right_dock = workspace.right_dock().read(cx);
12739 let right_width = workspace
12740 .dock_size(&right_dock, window, cx)
12741 .expect("right dock should have an active panel");
12742
12743 let left_dock = workspace.left_dock().read(cx);
12744 let left_width = workspace
12745 .dock_size(&left_dock, window, cx)
12746 .expect("left dock should still have an active panel");
12747
12748 let available_width = workspace.bounds.size.width - right_width;
12749 assert_eq!(
12750 left_width,
12751 available_width / 2.,
12752 "flexible left panel should shrink proportionally as the right dock takes space"
12753 );
12754 });
12755
12756 // Step 4: Toggle the right dock's panel to flexible. Now both docks use
12757 // flex sizing and the workspace width is divided among left-flex, center
12758 // (implicit flex 1.0), and right-flex.
12759 workspace.update_in(cx, |workspace, window, cx| {
12760 let right_dock = workspace.right_dock().clone();
12761 let right_panel = right_dock
12762 .read(cx)
12763 .visible_panel()
12764 .expect("right dock should have a visible panel")
12765 .clone();
12766 workspace.toggle_dock_panel_flexible_size(
12767 &right_dock,
12768 right_panel.as_ref(),
12769 window,
12770 cx,
12771 );
12772
12773 let right_dock = right_dock.read(cx);
12774 let right_panel = right_dock
12775 .visible_panel()
12776 .expect("right dock should still have a visible panel");
12777 assert!(
12778 right_panel.has_flexible_size(window, cx),
12779 "right panel should now be flexible"
12780 );
12781
12782 let right_size_state = right_dock
12783 .stored_panel_size_state(right_panel.as_ref())
12784 .expect("right panel should have a stored size state after toggling");
12785 let right_flex = right_size_state
12786 .flex
12787 .expect("right panel should have a flex value after toggling");
12788
12789 let left_dock = workspace.left_dock().read(cx);
12790 let left_width = workspace
12791 .dock_size(&left_dock, window, cx)
12792 .expect("left dock should still have an active panel");
12793 let right_width = workspace
12794 .dock_size(&right_dock, window, cx)
12795 .expect("right dock should still have an active panel");
12796
12797 let left_flex = workspace
12798 .default_dock_flex(DockPosition::Left)
12799 .expect("left dock should have a default flex");
12800
12801 let total_flex = left_flex + 1.0 + right_flex;
12802 let expected_left = left_flex / total_flex * workspace.bounds.size.width;
12803 let expected_right = right_flex / total_flex * workspace.bounds.size.width;
12804 assert_eq!(
12805 left_width, expected_left,
12806 "flexible left panel should share workspace width via flex ratios"
12807 );
12808 assert_eq!(
12809 right_width, expected_right,
12810 "flexible right panel should share workspace width via flex ratios"
12811 );
12812 });
12813 }
12814
12815 struct TestModal(FocusHandle);
12816
12817 impl TestModal {
12818 fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
12819 Self(cx.focus_handle())
12820 }
12821 }
12822
12823 impl EventEmitter<DismissEvent> for TestModal {}
12824
12825 impl Focusable for TestModal {
12826 fn focus_handle(&self, _cx: &App) -> FocusHandle {
12827 self.0.clone()
12828 }
12829 }
12830
12831 impl ModalView for TestModal {}
12832
12833 impl Render for TestModal {
12834 fn render(
12835 &mut self,
12836 _window: &mut Window,
12837 _cx: &mut Context<TestModal>,
12838 ) -> impl IntoElement {
12839 div().track_focus(&self.0)
12840 }
12841 }
12842
12843 #[gpui::test]
12844 async fn test_panels(cx: &mut gpui::TestAppContext) {
12845 init_test(cx);
12846 let fs = FakeFs::new(cx.executor());
12847
12848 let project = Project::test(fs, [], cx).await;
12849 let (multi_workspace, cx) =
12850 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12851 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12852
12853 let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
12854 let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12855 workspace.add_panel(panel_1.clone(), window, cx);
12856 workspace.toggle_dock(DockPosition::Left, window, cx);
12857 let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
12858 workspace.add_panel(panel_2.clone(), window, cx);
12859 workspace.toggle_dock(DockPosition::Right, window, cx);
12860
12861 let left_dock = workspace.left_dock();
12862 assert_eq!(
12863 left_dock.read(cx).visible_panel().unwrap().panel_id(),
12864 panel_1.panel_id()
12865 );
12866 assert_eq!(
12867 workspace.dock_size(&left_dock.read(cx), window, cx),
12868 Some(px(300.))
12869 );
12870
12871 workspace.resize_left_dock(px(1337.), window, cx);
12872 assert_eq!(
12873 workspace
12874 .right_dock()
12875 .read(cx)
12876 .visible_panel()
12877 .unwrap()
12878 .panel_id(),
12879 panel_2.panel_id(),
12880 );
12881
12882 (panel_1, panel_2)
12883 });
12884
12885 // Move panel_1 to the right
12886 panel_1.update_in(cx, |panel_1, window, cx| {
12887 panel_1.set_position(DockPosition::Right, window, cx)
12888 });
12889
12890 workspace.update_in(cx, |workspace, window, cx| {
12891 // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
12892 // Since it was the only panel on the left, the left dock should now be closed.
12893 assert!(!workspace.left_dock().read(cx).is_open());
12894 assert!(workspace.left_dock().read(cx).visible_panel().is_none());
12895 let right_dock = workspace.right_dock();
12896 assert_eq!(
12897 right_dock.read(cx).visible_panel().unwrap().panel_id(),
12898 panel_1.panel_id()
12899 );
12900 assert_eq!(
12901 right_dock
12902 .read(cx)
12903 .active_panel_size()
12904 .unwrap()
12905 .size
12906 .unwrap(),
12907 px(1337.)
12908 );
12909
12910 // Now we move panel_2 to the left
12911 panel_2.set_position(DockPosition::Left, window, cx);
12912 });
12913
12914 workspace.update(cx, |workspace, cx| {
12915 // Since panel_2 was not visible on the right, we don't open the left dock.
12916 assert!(!workspace.left_dock().read(cx).is_open());
12917 // And the right dock is unaffected in its displaying of panel_1
12918 assert!(workspace.right_dock().read(cx).is_open());
12919 assert_eq!(
12920 workspace
12921 .right_dock()
12922 .read(cx)
12923 .visible_panel()
12924 .unwrap()
12925 .panel_id(),
12926 panel_1.panel_id(),
12927 );
12928 });
12929
12930 // Move panel_1 back to the left
12931 panel_1.update_in(cx, |panel_1, window, cx| {
12932 panel_1.set_position(DockPosition::Left, window, cx)
12933 });
12934
12935 workspace.update_in(cx, |workspace, window, cx| {
12936 // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
12937 let left_dock = workspace.left_dock();
12938 assert!(left_dock.read(cx).is_open());
12939 assert_eq!(
12940 left_dock.read(cx).visible_panel().unwrap().panel_id(),
12941 panel_1.panel_id()
12942 );
12943 assert_eq!(
12944 workspace.dock_size(&left_dock.read(cx), window, cx),
12945 Some(px(1337.))
12946 );
12947 // And the right dock should be closed as it no longer has any panels.
12948 assert!(!workspace.right_dock().read(cx).is_open());
12949
12950 // Now we move panel_1 to the bottom
12951 panel_1.set_position(DockPosition::Bottom, window, cx);
12952 });
12953
12954 workspace.update_in(cx, |workspace, window, cx| {
12955 // Since panel_1 was visible on the left, we close the left dock.
12956 assert!(!workspace.left_dock().read(cx).is_open());
12957 // The bottom dock is sized based on the panel's default size,
12958 // since the panel orientation changed from vertical to horizontal.
12959 let bottom_dock = workspace.bottom_dock();
12960 assert_eq!(
12961 workspace.dock_size(&bottom_dock.read(cx), window, cx),
12962 Some(px(300.))
12963 );
12964 // Close bottom dock and move panel_1 back to the left.
12965 bottom_dock.update(cx, |bottom_dock, cx| {
12966 bottom_dock.set_open(false, window, cx)
12967 });
12968 panel_1.set_position(DockPosition::Left, window, cx);
12969 });
12970
12971 // Emit activated event on panel 1
12972 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
12973
12974 // Now the left dock is open and panel_1 is active and focused.
12975 workspace.update_in(cx, |workspace, window, cx| {
12976 let left_dock = workspace.left_dock();
12977 assert!(left_dock.read(cx).is_open());
12978 assert_eq!(
12979 left_dock.read(cx).visible_panel().unwrap().panel_id(),
12980 panel_1.panel_id(),
12981 );
12982 assert!(panel_1.focus_handle(cx).is_focused(window));
12983 });
12984
12985 // Emit closed event on panel 2, which is not active
12986 panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
12987
12988 // Wo don't close the left dock, because panel_2 wasn't the active panel
12989 workspace.update(cx, |workspace, cx| {
12990 let left_dock = workspace.left_dock();
12991 assert!(left_dock.read(cx).is_open());
12992 assert_eq!(
12993 left_dock.read(cx).visible_panel().unwrap().panel_id(),
12994 panel_1.panel_id(),
12995 );
12996 });
12997
12998 // Emitting a ZoomIn event shows the panel as zoomed.
12999 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
13000 workspace.read_with(cx, |workspace, _| {
13001 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13002 assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
13003 });
13004
13005 // Move panel to another dock while it is zoomed
13006 panel_1.update_in(cx, |panel, window, cx| {
13007 panel.set_position(DockPosition::Right, window, cx)
13008 });
13009 workspace.read_with(cx, |workspace, _| {
13010 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13011
13012 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13013 });
13014
13015 // This is a helper for getting a:
13016 // - valid focus on an element,
13017 // - that isn't a part of the panes and panels system of the Workspace,
13018 // - and doesn't trigger the 'on_focus_lost' API.
13019 let focus_other_view = {
13020 let workspace = workspace.clone();
13021 move |cx: &mut VisualTestContext| {
13022 workspace.update_in(cx, |workspace, window, cx| {
13023 if workspace.active_modal::<TestModal>(cx).is_some() {
13024 workspace.toggle_modal(window, cx, TestModal::new);
13025 workspace.toggle_modal(window, cx, TestModal::new);
13026 } else {
13027 workspace.toggle_modal(window, cx, TestModal::new);
13028 }
13029 })
13030 }
13031 };
13032
13033 // If focus is transferred to another view that's not a panel or another pane, we still show
13034 // the panel as zoomed.
13035 focus_other_view(cx);
13036 workspace.read_with(cx, |workspace, _| {
13037 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13038 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13039 });
13040
13041 // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
13042 workspace.update_in(cx, |_workspace, window, cx| {
13043 cx.focus_self(window);
13044 });
13045 workspace.read_with(cx, |workspace, _| {
13046 assert_eq!(workspace.zoomed, None);
13047 assert_eq!(workspace.zoomed_position, None);
13048 });
13049
13050 // If focus is transferred again to another view that's not a panel or a pane, we won't
13051 // show the panel as zoomed because it wasn't zoomed before.
13052 focus_other_view(cx);
13053 workspace.read_with(cx, |workspace, _| {
13054 assert_eq!(workspace.zoomed, None);
13055 assert_eq!(workspace.zoomed_position, None);
13056 });
13057
13058 // When the panel is activated, it is zoomed again.
13059 cx.dispatch_action(ToggleRightDock);
13060 workspace.read_with(cx, |workspace, _| {
13061 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13062 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13063 });
13064
13065 // Emitting a ZoomOut event unzooms the panel.
13066 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
13067 workspace.read_with(cx, |workspace, _| {
13068 assert_eq!(workspace.zoomed, None);
13069 assert_eq!(workspace.zoomed_position, None);
13070 });
13071
13072 // Emit closed event on panel 1, which is active
13073 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
13074
13075 // Now the left dock is closed, because panel_1 was the active panel
13076 workspace.update(cx, |workspace, cx| {
13077 let right_dock = workspace.right_dock();
13078 assert!(!right_dock.read(cx).is_open());
13079 });
13080 }
13081
13082 #[gpui::test]
13083 async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
13084 init_test(cx);
13085
13086 let fs = FakeFs::new(cx.background_executor.clone());
13087 let project = Project::test(fs, [], cx).await;
13088 let (workspace, cx) =
13089 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13090 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13091
13092 let dirty_regular_buffer = cx.new(|cx| {
13093 TestItem::new(cx)
13094 .with_dirty(true)
13095 .with_label("1.txt")
13096 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13097 });
13098 let dirty_regular_buffer_2 = cx.new(|cx| {
13099 TestItem::new(cx)
13100 .with_dirty(true)
13101 .with_label("2.txt")
13102 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13103 });
13104 let dirty_multi_buffer_with_both = cx.new(|cx| {
13105 TestItem::new(cx)
13106 .with_dirty(true)
13107 .with_buffer_kind(ItemBufferKind::Multibuffer)
13108 .with_label("Fake Project Search")
13109 .with_project_items(&[
13110 dirty_regular_buffer.read(cx).project_items[0].clone(),
13111 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13112 ])
13113 });
13114 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
13115 workspace.update_in(cx, |workspace, window, cx| {
13116 workspace.add_item(
13117 pane.clone(),
13118 Box::new(dirty_regular_buffer.clone()),
13119 None,
13120 false,
13121 false,
13122 window,
13123 cx,
13124 );
13125 workspace.add_item(
13126 pane.clone(),
13127 Box::new(dirty_regular_buffer_2.clone()),
13128 None,
13129 false,
13130 false,
13131 window,
13132 cx,
13133 );
13134 workspace.add_item(
13135 pane.clone(),
13136 Box::new(dirty_multi_buffer_with_both.clone()),
13137 None,
13138 false,
13139 false,
13140 window,
13141 cx,
13142 );
13143 });
13144
13145 pane.update_in(cx, |pane, window, cx| {
13146 pane.activate_item(2, true, true, window, cx);
13147 assert_eq!(
13148 pane.active_item().unwrap().item_id(),
13149 multi_buffer_with_both_files_id,
13150 "Should select the multi buffer in the pane"
13151 );
13152 });
13153 let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13154 pane.close_other_items(
13155 &CloseOtherItems {
13156 save_intent: Some(SaveIntent::Save),
13157 close_pinned: true,
13158 },
13159 None,
13160 window,
13161 cx,
13162 )
13163 });
13164 cx.background_executor.run_until_parked();
13165 assert!(!cx.has_pending_prompt());
13166 close_all_but_multi_buffer_task
13167 .await
13168 .expect("Closing all buffers but the multi buffer failed");
13169 pane.update(cx, |pane, cx| {
13170 assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
13171 assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
13172 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
13173 assert_eq!(pane.items_len(), 1);
13174 assert_eq!(
13175 pane.active_item().unwrap().item_id(),
13176 multi_buffer_with_both_files_id,
13177 "Should have only the multi buffer left in the pane"
13178 );
13179 assert!(
13180 dirty_multi_buffer_with_both.read(cx).is_dirty,
13181 "The multi buffer containing the unsaved buffer should still be dirty"
13182 );
13183 });
13184
13185 dirty_regular_buffer.update(cx, |buffer, cx| {
13186 buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
13187 });
13188
13189 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13190 pane.close_active_item(
13191 &CloseActiveItem {
13192 save_intent: Some(SaveIntent::Close),
13193 close_pinned: false,
13194 },
13195 window,
13196 cx,
13197 )
13198 });
13199 cx.background_executor.run_until_parked();
13200 assert!(
13201 cx.has_pending_prompt(),
13202 "Dirty multi buffer should prompt a save dialog"
13203 );
13204 cx.simulate_prompt_answer("Save");
13205 cx.background_executor.run_until_parked();
13206 close_multi_buffer_task
13207 .await
13208 .expect("Closing the multi buffer failed");
13209 pane.update(cx, |pane, cx| {
13210 assert_eq!(
13211 dirty_multi_buffer_with_both.read(cx).save_count,
13212 1,
13213 "Multi buffer item should get be saved"
13214 );
13215 // Test impl does not save inner items, so we do not assert them
13216 assert_eq!(
13217 pane.items_len(),
13218 0,
13219 "No more items should be left in the pane"
13220 );
13221 assert!(pane.active_item().is_none());
13222 });
13223 }
13224
13225 #[gpui::test]
13226 async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
13227 cx: &mut TestAppContext,
13228 ) {
13229 init_test(cx);
13230
13231 let fs = FakeFs::new(cx.background_executor.clone());
13232 let project = Project::test(fs, [], cx).await;
13233 let (workspace, cx) =
13234 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13235 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13236
13237 let dirty_regular_buffer = cx.new(|cx| {
13238 TestItem::new(cx)
13239 .with_dirty(true)
13240 .with_label("1.txt")
13241 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13242 });
13243 let dirty_regular_buffer_2 = cx.new(|cx| {
13244 TestItem::new(cx)
13245 .with_dirty(true)
13246 .with_label("2.txt")
13247 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13248 });
13249 let clear_regular_buffer = cx.new(|cx| {
13250 TestItem::new(cx)
13251 .with_label("3.txt")
13252 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
13253 });
13254
13255 let dirty_multi_buffer_with_both = cx.new(|cx| {
13256 TestItem::new(cx)
13257 .with_dirty(true)
13258 .with_buffer_kind(ItemBufferKind::Multibuffer)
13259 .with_label("Fake Project Search")
13260 .with_project_items(&[
13261 dirty_regular_buffer.read(cx).project_items[0].clone(),
13262 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13263 clear_regular_buffer.read(cx).project_items[0].clone(),
13264 ])
13265 });
13266 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
13267 workspace.update_in(cx, |workspace, window, cx| {
13268 workspace.add_item(
13269 pane.clone(),
13270 Box::new(dirty_regular_buffer.clone()),
13271 None,
13272 false,
13273 false,
13274 window,
13275 cx,
13276 );
13277 workspace.add_item(
13278 pane.clone(),
13279 Box::new(dirty_multi_buffer_with_both.clone()),
13280 None,
13281 false,
13282 false,
13283 window,
13284 cx,
13285 );
13286 });
13287
13288 pane.update_in(cx, |pane, window, cx| {
13289 pane.activate_item(1, true, true, window, cx);
13290 assert_eq!(
13291 pane.active_item().unwrap().item_id(),
13292 multi_buffer_with_both_files_id,
13293 "Should select the multi buffer in the pane"
13294 );
13295 });
13296 let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13297 pane.close_active_item(
13298 &CloseActiveItem {
13299 save_intent: None,
13300 close_pinned: false,
13301 },
13302 window,
13303 cx,
13304 )
13305 });
13306 cx.background_executor.run_until_parked();
13307 assert!(
13308 cx.has_pending_prompt(),
13309 "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
13310 );
13311 }
13312
13313 /// Tests that when `close_on_file_delete` is enabled, files are automatically
13314 /// closed when they are deleted from disk.
13315 #[gpui::test]
13316 async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
13317 init_test(cx);
13318
13319 // Enable the close_on_disk_deletion setting
13320 cx.update_global(|store: &mut SettingsStore, cx| {
13321 store.update_user_settings(cx, |settings| {
13322 settings.workspace.close_on_file_delete = Some(true);
13323 });
13324 });
13325
13326 let fs = FakeFs::new(cx.background_executor.clone());
13327 let project = Project::test(fs, [], cx).await;
13328 let (workspace, cx) =
13329 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13330 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13331
13332 // Create a test item that simulates a file
13333 let item = cx.new(|cx| {
13334 TestItem::new(cx)
13335 .with_label("test.txt")
13336 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13337 });
13338
13339 // Add item to workspace
13340 workspace.update_in(cx, |workspace, window, cx| {
13341 workspace.add_item(
13342 pane.clone(),
13343 Box::new(item.clone()),
13344 None,
13345 false,
13346 false,
13347 window,
13348 cx,
13349 );
13350 });
13351
13352 // Verify the item is in the pane
13353 pane.read_with(cx, |pane, _| {
13354 assert_eq!(pane.items().count(), 1);
13355 });
13356
13357 // Simulate file deletion by setting the item's deleted state
13358 item.update(cx, |item, _| {
13359 item.set_has_deleted_file(true);
13360 });
13361
13362 // Emit UpdateTab event to trigger the close behavior
13363 cx.run_until_parked();
13364 item.update(cx, |_, cx| {
13365 cx.emit(ItemEvent::UpdateTab);
13366 });
13367
13368 // Allow the close operation to complete
13369 cx.run_until_parked();
13370
13371 // Verify the item was automatically closed
13372 pane.read_with(cx, |pane, _| {
13373 assert_eq!(
13374 pane.items().count(),
13375 0,
13376 "Item should be automatically closed when file is deleted"
13377 );
13378 });
13379 }
13380
13381 /// Tests that when `close_on_file_delete` is disabled (default), files remain
13382 /// open with a strikethrough when they are deleted from disk.
13383 #[gpui::test]
13384 async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
13385 init_test(cx);
13386
13387 // Ensure close_on_disk_deletion is disabled (default)
13388 cx.update_global(|store: &mut SettingsStore, cx| {
13389 store.update_user_settings(cx, |settings| {
13390 settings.workspace.close_on_file_delete = Some(false);
13391 });
13392 });
13393
13394 let fs = FakeFs::new(cx.background_executor.clone());
13395 let project = Project::test(fs, [], cx).await;
13396 let (workspace, cx) =
13397 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13398 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13399
13400 // Create a test item that simulates a file
13401 let item = cx.new(|cx| {
13402 TestItem::new(cx)
13403 .with_label("test.txt")
13404 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13405 });
13406
13407 // Add item to workspace
13408 workspace.update_in(cx, |workspace, window, cx| {
13409 workspace.add_item(
13410 pane.clone(),
13411 Box::new(item.clone()),
13412 None,
13413 false,
13414 false,
13415 window,
13416 cx,
13417 );
13418 });
13419
13420 // Verify the item is in the pane
13421 pane.read_with(cx, |pane, _| {
13422 assert_eq!(pane.items().count(), 1);
13423 });
13424
13425 // Simulate file deletion
13426 item.update(cx, |item, _| {
13427 item.set_has_deleted_file(true);
13428 });
13429
13430 // Emit UpdateTab event
13431 cx.run_until_parked();
13432 item.update(cx, |_, cx| {
13433 cx.emit(ItemEvent::UpdateTab);
13434 });
13435
13436 // Allow any potential close operation to complete
13437 cx.run_until_parked();
13438
13439 // Verify the item remains open (with strikethrough)
13440 pane.read_with(cx, |pane, _| {
13441 assert_eq!(
13442 pane.items().count(),
13443 1,
13444 "Item should remain open when close_on_disk_deletion is disabled"
13445 );
13446 });
13447
13448 // Verify the item shows as deleted
13449 item.read_with(cx, |item, _| {
13450 assert!(
13451 item.has_deleted_file,
13452 "Item should be marked as having deleted file"
13453 );
13454 });
13455 }
13456
13457 /// Tests that dirty files are not automatically closed when deleted from disk,
13458 /// even when `close_on_file_delete` is enabled. This ensures users don't lose
13459 /// unsaved changes without being prompted.
13460 #[gpui::test]
13461 async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
13462 init_test(cx);
13463
13464 // Enable the close_on_file_delete setting
13465 cx.update_global(|store: &mut SettingsStore, cx| {
13466 store.update_user_settings(cx, |settings| {
13467 settings.workspace.close_on_file_delete = Some(true);
13468 });
13469 });
13470
13471 let fs = FakeFs::new(cx.background_executor.clone());
13472 let project = Project::test(fs, [], cx).await;
13473 let (workspace, cx) =
13474 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13475 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13476
13477 // Create a dirty test item
13478 let item = cx.new(|cx| {
13479 TestItem::new(cx)
13480 .with_dirty(true)
13481 .with_label("test.txt")
13482 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13483 });
13484
13485 // Add item to workspace
13486 workspace.update_in(cx, |workspace, window, cx| {
13487 workspace.add_item(
13488 pane.clone(),
13489 Box::new(item.clone()),
13490 None,
13491 false,
13492 false,
13493 window,
13494 cx,
13495 );
13496 });
13497
13498 // Simulate file deletion
13499 item.update(cx, |item, _| {
13500 item.set_has_deleted_file(true);
13501 });
13502
13503 // Emit UpdateTab event to trigger the close behavior
13504 cx.run_until_parked();
13505 item.update(cx, |_, cx| {
13506 cx.emit(ItemEvent::UpdateTab);
13507 });
13508
13509 // Allow any potential close operation to complete
13510 cx.run_until_parked();
13511
13512 // Verify the item remains open (dirty files are not auto-closed)
13513 pane.read_with(cx, |pane, _| {
13514 assert_eq!(
13515 pane.items().count(),
13516 1,
13517 "Dirty items should not be automatically closed even when file is deleted"
13518 );
13519 });
13520
13521 // Verify the item is marked as deleted and still dirty
13522 item.read_with(cx, |item, _| {
13523 assert!(
13524 item.has_deleted_file,
13525 "Item should be marked as having deleted file"
13526 );
13527 assert!(item.is_dirty, "Item should still be dirty");
13528 });
13529 }
13530
13531 /// Tests that navigation history is cleaned up when files are auto-closed
13532 /// due to deletion from disk.
13533 #[gpui::test]
13534 async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
13535 init_test(cx);
13536
13537 // Enable the close_on_file_delete setting
13538 cx.update_global(|store: &mut SettingsStore, cx| {
13539 store.update_user_settings(cx, |settings| {
13540 settings.workspace.close_on_file_delete = Some(true);
13541 });
13542 });
13543
13544 let fs = FakeFs::new(cx.background_executor.clone());
13545 let project = Project::test(fs, [], cx).await;
13546 let (workspace, cx) =
13547 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13548 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13549
13550 // Create test items
13551 let item1 = cx.new(|cx| {
13552 TestItem::new(cx)
13553 .with_label("test1.txt")
13554 .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
13555 });
13556 let item1_id = item1.item_id();
13557
13558 let item2 = cx.new(|cx| {
13559 TestItem::new(cx)
13560 .with_label("test2.txt")
13561 .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
13562 });
13563
13564 // Add items to workspace
13565 workspace.update_in(cx, |workspace, window, cx| {
13566 workspace.add_item(
13567 pane.clone(),
13568 Box::new(item1.clone()),
13569 None,
13570 false,
13571 false,
13572 window,
13573 cx,
13574 );
13575 workspace.add_item(
13576 pane.clone(),
13577 Box::new(item2.clone()),
13578 None,
13579 false,
13580 false,
13581 window,
13582 cx,
13583 );
13584 });
13585
13586 // Activate item1 to ensure it gets navigation entries
13587 pane.update_in(cx, |pane, window, cx| {
13588 pane.activate_item(0, true, true, window, cx);
13589 });
13590
13591 // Switch to item2 and back to create navigation history
13592 pane.update_in(cx, |pane, window, cx| {
13593 pane.activate_item(1, true, true, window, cx);
13594 });
13595 cx.run_until_parked();
13596
13597 pane.update_in(cx, |pane, window, cx| {
13598 pane.activate_item(0, true, true, window, cx);
13599 });
13600 cx.run_until_parked();
13601
13602 // Simulate file deletion for item1
13603 item1.update(cx, |item, _| {
13604 item.set_has_deleted_file(true);
13605 });
13606
13607 // Emit UpdateTab event to trigger the close behavior
13608 item1.update(cx, |_, cx| {
13609 cx.emit(ItemEvent::UpdateTab);
13610 });
13611 cx.run_until_parked();
13612
13613 // Verify item1 was closed
13614 pane.read_with(cx, |pane, _| {
13615 assert_eq!(
13616 pane.items().count(),
13617 1,
13618 "Should have 1 item remaining after auto-close"
13619 );
13620 });
13621
13622 // Check navigation history after close
13623 let has_item = pane.read_with(cx, |pane, cx| {
13624 let mut has_item = false;
13625 pane.nav_history().for_each_entry(cx, &mut |entry, _| {
13626 if entry.item.id() == item1_id {
13627 has_item = true;
13628 }
13629 });
13630 has_item
13631 });
13632
13633 assert!(
13634 !has_item,
13635 "Navigation history should not contain closed item entries"
13636 );
13637 }
13638
13639 #[gpui::test]
13640 async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
13641 cx: &mut TestAppContext,
13642 ) {
13643 init_test(cx);
13644
13645 let fs = FakeFs::new(cx.background_executor.clone());
13646 let project = Project::test(fs, [], cx).await;
13647 let (workspace, cx) =
13648 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13649 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13650
13651 let dirty_regular_buffer = cx.new(|cx| {
13652 TestItem::new(cx)
13653 .with_dirty(true)
13654 .with_label("1.txt")
13655 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13656 });
13657 let dirty_regular_buffer_2 = cx.new(|cx| {
13658 TestItem::new(cx)
13659 .with_dirty(true)
13660 .with_label("2.txt")
13661 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13662 });
13663 let clear_regular_buffer = cx.new(|cx| {
13664 TestItem::new(cx)
13665 .with_label("3.txt")
13666 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
13667 });
13668
13669 let dirty_multi_buffer = cx.new(|cx| {
13670 TestItem::new(cx)
13671 .with_dirty(true)
13672 .with_buffer_kind(ItemBufferKind::Multibuffer)
13673 .with_label("Fake Project Search")
13674 .with_project_items(&[
13675 dirty_regular_buffer.read(cx).project_items[0].clone(),
13676 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13677 clear_regular_buffer.read(cx).project_items[0].clone(),
13678 ])
13679 });
13680 workspace.update_in(cx, |workspace, window, cx| {
13681 workspace.add_item(
13682 pane.clone(),
13683 Box::new(dirty_regular_buffer.clone()),
13684 None,
13685 false,
13686 false,
13687 window,
13688 cx,
13689 );
13690 workspace.add_item(
13691 pane.clone(),
13692 Box::new(dirty_regular_buffer_2.clone()),
13693 None,
13694 false,
13695 false,
13696 window,
13697 cx,
13698 );
13699 workspace.add_item(
13700 pane.clone(),
13701 Box::new(dirty_multi_buffer.clone()),
13702 None,
13703 false,
13704 false,
13705 window,
13706 cx,
13707 );
13708 });
13709
13710 pane.update_in(cx, |pane, window, cx| {
13711 pane.activate_item(2, true, true, window, cx);
13712 assert_eq!(
13713 pane.active_item().unwrap().item_id(),
13714 dirty_multi_buffer.item_id(),
13715 "Should select the multi buffer in the pane"
13716 );
13717 });
13718 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13719 pane.close_active_item(
13720 &CloseActiveItem {
13721 save_intent: None,
13722 close_pinned: false,
13723 },
13724 window,
13725 cx,
13726 )
13727 });
13728 cx.background_executor.run_until_parked();
13729 assert!(
13730 !cx.has_pending_prompt(),
13731 "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
13732 );
13733 close_multi_buffer_task
13734 .await
13735 .expect("Closing multi buffer failed");
13736 pane.update(cx, |pane, cx| {
13737 assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
13738 assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
13739 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
13740 assert_eq!(
13741 pane.items()
13742 .map(|item| item.item_id())
13743 .sorted()
13744 .collect::<Vec<_>>(),
13745 vec![
13746 dirty_regular_buffer.item_id(),
13747 dirty_regular_buffer_2.item_id(),
13748 ],
13749 "Should have no multi buffer left in the pane"
13750 );
13751 assert!(dirty_regular_buffer.read(cx).is_dirty);
13752 assert!(dirty_regular_buffer_2.read(cx).is_dirty);
13753 });
13754 }
13755
13756 #[gpui::test]
13757 async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
13758 init_test(cx);
13759 let fs = FakeFs::new(cx.executor());
13760 let project = Project::test(fs, [], cx).await;
13761 let (multi_workspace, cx) =
13762 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
13763 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
13764
13765 // Add a new panel to the right dock, opening the dock and setting the
13766 // focus to the new panel.
13767 let panel = workspace.update_in(cx, |workspace, window, cx| {
13768 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13769 workspace.add_panel(panel.clone(), window, cx);
13770
13771 workspace
13772 .right_dock()
13773 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
13774
13775 workspace.toggle_panel_focus::<TestPanel>(window, cx);
13776
13777 panel
13778 });
13779
13780 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
13781 // panel to the next valid position which, in this case, is the left
13782 // dock.
13783 cx.dispatch_action(MoveFocusedPanelToNextPosition);
13784 workspace.update(cx, |workspace, cx| {
13785 assert!(workspace.left_dock().read(cx).is_open());
13786 assert_eq!(panel.read(cx).position, DockPosition::Left);
13787 });
13788
13789 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
13790 // panel to the next valid position which, in this case, is the bottom
13791 // dock.
13792 cx.dispatch_action(MoveFocusedPanelToNextPosition);
13793 workspace.update(cx, |workspace, cx| {
13794 assert!(workspace.bottom_dock().read(cx).is_open());
13795 assert_eq!(panel.read(cx).position, DockPosition::Bottom);
13796 });
13797
13798 // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
13799 // around moving the panel to its initial position, the right dock.
13800 cx.dispatch_action(MoveFocusedPanelToNextPosition);
13801 workspace.update(cx, |workspace, cx| {
13802 assert!(workspace.right_dock().read(cx).is_open());
13803 assert_eq!(panel.read(cx).position, DockPosition::Right);
13804 });
13805
13806 // Remove focus from the panel, ensuring that, if the panel is not
13807 // focused, the `MoveFocusedPanelToNextPosition` action does not update
13808 // the panel's position, so the panel is still in the right dock.
13809 workspace.update_in(cx, |workspace, window, cx| {
13810 workspace.toggle_panel_focus::<TestPanel>(window, cx);
13811 });
13812
13813 cx.dispatch_action(MoveFocusedPanelToNextPosition);
13814 workspace.update(cx, |workspace, cx| {
13815 assert!(workspace.right_dock().read(cx).is_open());
13816 assert_eq!(panel.read(cx).position, DockPosition::Right);
13817 });
13818 }
13819
13820 #[gpui::test]
13821 async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
13822 init_test(cx);
13823
13824 let fs = FakeFs::new(cx.executor());
13825 let project = Project::test(fs, [], cx).await;
13826 let (workspace, cx) =
13827 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13828
13829 let item_1 = cx.new(|cx| {
13830 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
13831 });
13832 workspace.update_in(cx, |workspace, window, cx| {
13833 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
13834 workspace.move_item_to_pane_in_direction(
13835 &MoveItemToPaneInDirection {
13836 direction: SplitDirection::Right,
13837 focus: true,
13838 clone: false,
13839 },
13840 window,
13841 cx,
13842 );
13843 workspace.move_item_to_pane_at_index(
13844 &MoveItemToPane {
13845 destination: 3,
13846 focus: true,
13847 clone: false,
13848 },
13849 window,
13850 cx,
13851 );
13852
13853 assert_eq!(workspace.panes.len(), 1, "No new panes were created");
13854 assert_eq!(
13855 pane_items_paths(&workspace.active_pane, cx),
13856 vec!["first.txt".to_string()],
13857 "Single item was not moved anywhere"
13858 );
13859 });
13860
13861 let item_2 = cx.new(|cx| {
13862 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
13863 });
13864 workspace.update_in(cx, |workspace, window, cx| {
13865 workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
13866 assert_eq!(
13867 pane_items_paths(&workspace.panes[0], cx),
13868 vec!["first.txt".to_string(), "second.txt".to_string()],
13869 );
13870 workspace.move_item_to_pane_in_direction(
13871 &MoveItemToPaneInDirection {
13872 direction: SplitDirection::Right,
13873 focus: true,
13874 clone: false,
13875 },
13876 window,
13877 cx,
13878 );
13879
13880 assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
13881 assert_eq!(
13882 pane_items_paths(&workspace.panes[0], cx),
13883 vec!["first.txt".to_string()],
13884 "After moving, one item should be left in the original pane"
13885 );
13886 assert_eq!(
13887 pane_items_paths(&workspace.panes[1], cx),
13888 vec!["second.txt".to_string()],
13889 "New item should have been moved to the new pane"
13890 );
13891 });
13892
13893 let item_3 = cx.new(|cx| {
13894 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
13895 });
13896 workspace.update_in(cx, |workspace, window, cx| {
13897 let original_pane = workspace.panes[0].clone();
13898 workspace.set_active_pane(&original_pane, window, cx);
13899 workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
13900 assert_eq!(workspace.panes.len(), 2, "No new panes were created");
13901 assert_eq!(
13902 pane_items_paths(&workspace.active_pane, cx),
13903 vec!["first.txt".to_string(), "third.txt".to_string()],
13904 "New pane should be ready to move one item out"
13905 );
13906
13907 workspace.move_item_to_pane_at_index(
13908 &MoveItemToPane {
13909 destination: 3,
13910 focus: true,
13911 clone: false,
13912 },
13913 window,
13914 cx,
13915 );
13916 assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
13917 assert_eq!(
13918 pane_items_paths(&workspace.active_pane, cx),
13919 vec!["first.txt".to_string()],
13920 "After moving, one item should be left in the original pane"
13921 );
13922 assert_eq!(
13923 pane_items_paths(&workspace.panes[1], cx),
13924 vec!["second.txt".to_string()],
13925 "Previously created pane should be unchanged"
13926 );
13927 assert_eq!(
13928 pane_items_paths(&workspace.panes[2], cx),
13929 vec!["third.txt".to_string()],
13930 "New item should have been moved to the new pane"
13931 );
13932 });
13933 }
13934
13935 #[gpui::test]
13936 async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
13937 init_test(cx);
13938
13939 let fs = FakeFs::new(cx.executor());
13940 let project = Project::test(fs, [], cx).await;
13941 let (workspace, cx) =
13942 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13943
13944 let item_1 = cx.new(|cx| {
13945 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
13946 });
13947 workspace.update_in(cx, |workspace, window, cx| {
13948 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
13949 workspace.move_item_to_pane_in_direction(
13950 &MoveItemToPaneInDirection {
13951 direction: SplitDirection::Right,
13952 focus: true,
13953 clone: true,
13954 },
13955 window,
13956 cx,
13957 );
13958 });
13959 cx.run_until_parked();
13960 workspace.update_in(cx, |workspace, window, cx| {
13961 workspace.move_item_to_pane_at_index(
13962 &MoveItemToPane {
13963 destination: 3,
13964 focus: true,
13965 clone: true,
13966 },
13967 window,
13968 cx,
13969 );
13970 });
13971 cx.run_until_parked();
13972
13973 workspace.update(cx, |workspace, cx| {
13974 assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
13975 for pane in workspace.panes() {
13976 assert_eq!(
13977 pane_items_paths(pane, cx),
13978 vec!["first.txt".to_string()],
13979 "Single item exists in all panes"
13980 );
13981 }
13982 });
13983
13984 // verify that the active pane has been updated after waiting for the
13985 // pane focus event to fire and resolve
13986 workspace.read_with(cx, |workspace, _app| {
13987 assert_eq!(
13988 workspace.active_pane(),
13989 &workspace.panes[2],
13990 "The third pane should be the active one: {:?}",
13991 workspace.panes
13992 );
13993 })
13994 }
13995
13996 #[gpui::test]
13997 async fn test_close_item_in_all_panes(cx: &mut TestAppContext) {
13998 init_test(cx);
13999
14000 let fs = FakeFs::new(cx.executor());
14001 fs.insert_tree("/root", json!({ "test.txt": "" })).await;
14002
14003 let project = Project::test(fs, ["root".as_ref()], cx).await;
14004 let (workspace, cx) =
14005 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14006
14007 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14008 // Add item to pane A with project path
14009 let item_a = cx.new(|cx| {
14010 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
14011 });
14012 workspace.update_in(cx, |workspace, window, cx| {
14013 workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
14014 });
14015
14016 // Split to create pane B
14017 let pane_b = workspace.update_in(cx, |workspace, window, cx| {
14018 workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
14019 });
14020
14021 // Add item with SAME project path to pane B, and pin it
14022 let item_b = cx.new(|cx| {
14023 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
14024 });
14025 pane_b.update_in(cx, |pane, window, cx| {
14026 pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
14027 pane.set_pinned_count(1);
14028 });
14029
14030 assert_eq!(pane_a.read_with(cx, |pane, _| pane.items_len()), 1);
14031 assert_eq!(pane_b.read_with(cx, |pane, _| pane.items_len()), 1);
14032
14033 // close_pinned: false should only close the unpinned copy
14034 workspace.update_in(cx, |workspace, window, cx| {
14035 workspace.close_item_in_all_panes(
14036 &CloseItemInAllPanes {
14037 save_intent: Some(SaveIntent::Close),
14038 close_pinned: false,
14039 },
14040 window,
14041 cx,
14042 )
14043 });
14044 cx.executor().run_until_parked();
14045
14046 let item_count_a = pane_a.read_with(cx, |pane, _| pane.items_len());
14047 let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
14048 assert_eq!(item_count_a, 0, "Unpinned item in pane A should be closed");
14049 assert_eq!(item_count_b, 1, "Pinned item in pane B should remain");
14050
14051 // Split again, seeing as closing the previous item also closed its
14052 // pane, so only pane remains, which does not allow us to properly test
14053 // that both items close when `close_pinned: true`.
14054 let pane_c = workspace.update_in(cx, |workspace, window, cx| {
14055 workspace.split_pane(pane_b.clone(), SplitDirection::Right, window, cx)
14056 });
14057
14058 // Add an item with the same project path to pane C so that
14059 // close_item_in_all_panes can determine what to close across all panes
14060 // (it reads the active item from the active pane, and split_pane
14061 // creates an empty pane).
14062 let item_c = cx.new(|cx| {
14063 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
14064 });
14065 pane_c.update_in(cx, |pane, window, cx| {
14066 pane.add_item(Box::new(item_c.clone()), true, true, None, window, cx);
14067 });
14068
14069 // close_pinned: true should close the pinned copy too
14070 workspace.update_in(cx, |workspace, window, cx| {
14071 let panes_count = workspace.panes().len();
14072 assert_eq!(panes_count, 2, "Workspace should have two panes (B and C)");
14073
14074 workspace.close_item_in_all_panes(
14075 &CloseItemInAllPanes {
14076 save_intent: Some(SaveIntent::Close),
14077 close_pinned: true,
14078 },
14079 window,
14080 cx,
14081 )
14082 });
14083 cx.executor().run_until_parked();
14084
14085 let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
14086 let item_count_c = pane_c.read_with(cx, |pane, _| pane.items_len());
14087 assert_eq!(item_count_b, 0, "Pinned item in pane B should be closed");
14088 assert_eq!(item_count_c, 0, "Unpinned item in pane C should be closed");
14089 }
14090
14091 mod register_project_item_tests {
14092
14093 use super::*;
14094
14095 // View
14096 struct TestPngItemView {
14097 focus_handle: FocusHandle,
14098 }
14099 // Model
14100 struct TestPngItem {}
14101
14102 impl project::ProjectItem for TestPngItem {
14103 fn try_open(
14104 _project: &Entity<Project>,
14105 path: &ProjectPath,
14106 cx: &mut App,
14107 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
14108 if path.path.extension().unwrap() == "png" {
14109 Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestPngItem {}))))
14110 } else {
14111 None
14112 }
14113 }
14114
14115 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
14116 None
14117 }
14118
14119 fn project_path(&self, _: &App) -> Option<ProjectPath> {
14120 None
14121 }
14122
14123 fn is_dirty(&self) -> bool {
14124 false
14125 }
14126 }
14127
14128 impl Item for TestPngItemView {
14129 type Event = ();
14130 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14131 "".into()
14132 }
14133 }
14134 impl EventEmitter<()> for TestPngItemView {}
14135 impl Focusable for TestPngItemView {
14136 fn focus_handle(&self, _cx: &App) -> FocusHandle {
14137 self.focus_handle.clone()
14138 }
14139 }
14140
14141 impl Render for TestPngItemView {
14142 fn render(
14143 &mut self,
14144 _window: &mut Window,
14145 _cx: &mut Context<Self>,
14146 ) -> impl IntoElement {
14147 Empty
14148 }
14149 }
14150
14151 impl ProjectItem for TestPngItemView {
14152 type Item = TestPngItem;
14153
14154 fn for_project_item(
14155 _project: Entity<Project>,
14156 _pane: Option<&Pane>,
14157 _item: Entity<Self::Item>,
14158 _: &mut Window,
14159 cx: &mut Context<Self>,
14160 ) -> Self
14161 where
14162 Self: Sized,
14163 {
14164 Self {
14165 focus_handle: cx.focus_handle(),
14166 }
14167 }
14168 }
14169
14170 // View
14171 struct TestIpynbItemView {
14172 focus_handle: FocusHandle,
14173 }
14174 // Model
14175 struct TestIpynbItem {}
14176
14177 impl project::ProjectItem for TestIpynbItem {
14178 fn try_open(
14179 _project: &Entity<Project>,
14180 path: &ProjectPath,
14181 cx: &mut App,
14182 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
14183 if path.path.extension().unwrap() == "ipynb" {
14184 Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestIpynbItem {}))))
14185 } else {
14186 None
14187 }
14188 }
14189
14190 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
14191 None
14192 }
14193
14194 fn project_path(&self, _: &App) -> Option<ProjectPath> {
14195 None
14196 }
14197
14198 fn is_dirty(&self) -> bool {
14199 false
14200 }
14201 }
14202
14203 impl Item for TestIpynbItemView {
14204 type Event = ();
14205 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14206 "".into()
14207 }
14208 }
14209 impl EventEmitter<()> for TestIpynbItemView {}
14210 impl Focusable for TestIpynbItemView {
14211 fn focus_handle(&self, _cx: &App) -> FocusHandle {
14212 self.focus_handle.clone()
14213 }
14214 }
14215
14216 impl Render for TestIpynbItemView {
14217 fn render(
14218 &mut self,
14219 _window: &mut Window,
14220 _cx: &mut Context<Self>,
14221 ) -> impl IntoElement {
14222 Empty
14223 }
14224 }
14225
14226 impl ProjectItem for TestIpynbItemView {
14227 type Item = TestIpynbItem;
14228
14229 fn for_project_item(
14230 _project: Entity<Project>,
14231 _pane: Option<&Pane>,
14232 _item: Entity<Self::Item>,
14233 _: &mut Window,
14234 cx: &mut Context<Self>,
14235 ) -> Self
14236 where
14237 Self: Sized,
14238 {
14239 Self {
14240 focus_handle: cx.focus_handle(),
14241 }
14242 }
14243 }
14244
14245 struct TestAlternatePngItemView {
14246 focus_handle: FocusHandle,
14247 }
14248
14249 impl Item for TestAlternatePngItemView {
14250 type Event = ();
14251 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14252 "".into()
14253 }
14254 }
14255
14256 impl EventEmitter<()> for TestAlternatePngItemView {}
14257 impl Focusable for TestAlternatePngItemView {
14258 fn focus_handle(&self, _cx: &App) -> FocusHandle {
14259 self.focus_handle.clone()
14260 }
14261 }
14262
14263 impl Render for TestAlternatePngItemView {
14264 fn render(
14265 &mut self,
14266 _window: &mut Window,
14267 _cx: &mut Context<Self>,
14268 ) -> impl IntoElement {
14269 Empty
14270 }
14271 }
14272
14273 impl ProjectItem for TestAlternatePngItemView {
14274 type Item = TestPngItem;
14275
14276 fn for_project_item(
14277 _project: Entity<Project>,
14278 _pane: Option<&Pane>,
14279 _item: Entity<Self::Item>,
14280 _: &mut Window,
14281 cx: &mut Context<Self>,
14282 ) -> Self
14283 where
14284 Self: Sized,
14285 {
14286 Self {
14287 focus_handle: cx.focus_handle(),
14288 }
14289 }
14290 }
14291
14292 #[gpui::test]
14293 async fn test_register_project_item(cx: &mut TestAppContext) {
14294 init_test(cx);
14295
14296 cx.update(|cx| {
14297 register_project_item::<TestPngItemView>(cx);
14298 register_project_item::<TestIpynbItemView>(cx);
14299 });
14300
14301 let fs = FakeFs::new(cx.executor());
14302 fs.insert_tree(
14303 "/root1",
14304 json!({
14305 "one.png": "BINARYDATAHERE",
14306 "two.ipynb": "{ totally a notebook }",
14307 "three.txt": "editing text, sure why not?"
14308 }),
14309 )
14310 .await;
14311
14312 let project = Project::test(fs, ["root1".as_ref()], cx).await;
14313 let (workspace, cx) =
14314 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14315
14316 let worktree_id = project.update(cx, |project, cx| {
14317 project.worktrees(cx).next().unwrap().read(cx).id()
14318 });
14319
14320 let handle = workspace
14321 .update_in(cx, |workspace, window, cx| {
14322 let project_path = (worktree_id, rel_path("one.png"));
14323 workspace.open_path(project_path, None, true, window, cx)
14324 })
14325 .await
14326 .unwrap();
14327
14328 // Now we can check if the handle we got back errored or not
14329 assert_eq!(
14330 handle.to_any_view().entity_type(),
14331 TypeId::of::<TestPngItemView>()
14332 );
14333
14334 let handle = workspace
14335 .update_in(cx, |workspace, window, cx| {
14336 let project_path = (worktree_id, rel_path("two.ipynb"));
14337 workspace.open_path(project_path, None, true, window, cx)
14338 })
14339 .await
14340 .unwrap();
14341
14342 assert_eq!(
14343 handle.to_any_view().entity_type(),
14344 TypeId::of::<TestIpynbItemView>()
14345 );
14346
14347 let handle = workspace
14348 .update_in(cx, |workspace, window, cx| {
14349 let project_path = (worktree_id, rel_path("three.txt"));
14350 workspace.open_path(project_path, None, true, window, cx)
14351 })
14352 .await;
14353 assert!(handle.is_err());
14354 }
14355
14356 #[gpui::test]
14357 async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
14358 init_test(cx);
14359
14360 cx.update(|cx| {
14361 register_project_item::<TestPngItemView>(cx);
14362 register_project_item::<TestAlternatePngItemView>(cx);
14363 });
14364
14365 let fs = FakeFs::new(cx.executor());
14366 fs.insert_tree(
14367 "/root1",
14368 json!({
14369 "one.png": "BINARYDATAHERE",
14370 "two.ipynb": "{ totally a notebook }",
14371 "three.txt": "editing text, sure why not?"
14372 }),
14373 )
14374 .await;
14375 let project = Project::test(fs, ["root1".as_ref()], cx).await;
14376 let (workspace, cx) =
14377 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14378 let worktree_id = project.update(cx, |project, cx| {
14379 project.worktrees(cx).next().unwrap().read(cx).id()
14380 });
14381
14382 let handle = workspace
14383 .update_in(cx, |workspace, window, cx| {
14384 let project_path = (worktree_id, rel_path("one.png"));
14385 workspace.open_path(project_path, None, true, window, cx)
14386 })
14387 .await
14388 .unwrap();
14389
14390 // This _must_ be the second item registered
14391 assert_eq!(
14392 handle.to_any_view().entity_type(),
14393 TypeId::of::<TestAlternatePngItemView>()
14394 );
14395
14396 let handle = workspace
14397 .update_in(cx, |workspace, window, cx| {
14398 let project_path = (worktree_id, rel_path("three.txt"));
14399 workspace.open_path(project_path, None, true, window, cx)
14400 })
14401 .await;
14402 assert!(handle.is_err());
14403 }
14404 }
14405
14406 #[gpui::test]
14407 async fn test_status_bar_visibility(cx: &mut TestAppContext) {
14408 init_test(cx);
14409
14410 let fs = FakeFs::new(cx.executor());
14411 let project = Project::test(fs, [], cx).await;
14412 let (workspace, _cx) =
14413 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14414
14415 // Test with status bar shown (default)
14416 workspace.read_with(cx, |workspace, cx| {
14417 let visible = workspace.status_bar_visible(cx);
14418 assert!(visible, "Status bar should be visible by default");
14419 });
14420
14421 // Test with status bar hidden
14422 cx.update_global(|store: &mut SettingsStore, cx| {
14423 store.update_user_settings(cx, |settings| {
14424 settings.status_bar.get_or_insert_default().show = Some(false);
14425 });
14426 });
14427
14428 workspace.read_with(cx, |workspace, cx| {
14429 let visible = workspace.status_bar_visible(cx);
14430 assert!(!visible, "Status bar should be hidden when show is false");
14431 });
14432
14433 // Test with status bar shown explicitly
14434 cx.update_global(|store: &mut SettingsStore, cx| {
14435 store.update_user_settings(cx, |settings| {
14436 settings.status_bar.get_or_insert_default().show = Some(true);
14437 });
14438 });
14439
14440 workspace.read_with(cx, |workspace, cx| {
14441 let visible = workspace.status_bar_visible(cx);
14442 assert!(visible, "Status bar should be visible when show is true");
14443 });
14444 }
14445
14446 #[gpui::test]
14447 async fn test_pane_close_active_item(cx: &mut TestAppContext) {
14448 init_test(cx);
14449
14450 let fs = FakeFs::new(cx.executor());
14451 let project = Project::test(fs, [], cx).await;
14452 let (multi_workspace, cx) =
14453 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
14454 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
14455 let panel = workspace.update_in(cx, |workspace, window, cx| {
14456 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14457 workspace.add_panel(panel.clone(), window, cx);
14458
14459 workspace
14460 .right_dock()
14461 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
14462
14463 panel
14464 });
14465
14466 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14467 let item_a = cx.new(TestItem::new);
14468 let item_b = cx.new(TestItem::new);
14469 let item_a_id = item_a.entity_id();
14470 let item_b_id = item_b.entity_id();
14471
14472 pane.update_in(cx, |pane, window, cx| {
14473 pane.add_item(Box::new(item_a.clone()), true, true, None, window, cx);
14474 pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
14475 });
14476
14477 pane.read_with(cx, |pane, _| {
14478 assert_eq!(pane.items_len(), 2);
14479 assert_eq!(pane.active_item().unwrap().item_id(), item_b_id);
14480 });
14481
14482 workspace.update_in(cx, |workspace, window, cx| {
14483 workspace.toggle_panel_focus::<TestPanel>(window, cx);
14484 });
14485
14486 workspace.update_in(cx, |_, window, cx| {
14487 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14488 });
14489
14490 // Assert that the `pane::CloseActiveItem` action is handled at the
14491 // workspace level when one of the dock panels is focused and, in that
14492 // case, the center pane's active item is closed but the focus is not
14493 // moved.
14494 cx.dispatch_action(pane::CloseActiveItem::default());
14495 cx.run_until_parked();
14496
14497 pane.read_with(cx, |pane, _| {
14498 assert_eq!(pane.items_len(), 1);
14499 assert_eq!(pane.active_item().unwrap().item_id(), item_a_id);
14500 });
14501
14502 workspace.update_in(cx, |workspace, window, cx| {
14503 assert!(workspace.right_dock().read(cx).is_open());
14504 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14505 });
14506 }
14507
14508 #[gpui::test]
14509 async fn test_panel_zoom_preserved_across_workspace_switch(cx: &mut TestAppContext) {
14510 init_test(cx);
14511 let fs = FakeFs::new(cx.executor());
14512
14513 let project_a = Project::test(fs.clone(), [], cx).await;
14514 let project_b = Project::test(fs, [], cx).await;
14515
14516 let multi_workspace_handle =
14517 cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
14518 cx.run_until_parked();
14519
14520 multi_workspace_handle
14521 .update(cx, |mw, _window, cx| {
14522 mw.open_sidebar(cx);
14523 })
14524 .unwrap();
14525
14526 let workspace_a = multi_workspace_handle
14527 .read_with(cx, |mw, _| mw.workspace().clone())
14528 .unwrap();
14529
14530 let _workspace_b = multi_workspace_handle
14531 .update(cx, |mw, window, cx| {
14532 mw.test_add_workspace(project_b, window, cx)
14533 })
14534 .unwrap();
14535
14536 // Switch to workspace A
14537 multi_workspace_handle
14538 .update(cx, |mw, window, cx| {
14539 let workspace = mw.workspaces().next().unwrap().clone();
14540 mw.activate(workspace, window, cx);
14541 })
14542 .unwrap();
14543
14544 let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
14545
14546 // Add a panel to workspace A's right dock and open the dock
14547 let panel = workspace_a.update_in(cx, |workspace, window, cx| {
14548 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14549 workspace.add_panel(panel.clone(), window, cx);
14550 workspace
14551 .right_dock()
14552 .update(cx, |dock, cx| dock.set_open(true, window, cx));
14553 panel
14554 });
14555
14556 // Focus the panel through the workspace (matching existing test pattern)
14557 workspace_a.update_in(cx, |workspace, window, cx| {
14558 workspace.toggle_panel_focus::<TestPanel>(window, cx);
14559 });
14560
14561 // Zoom the panel
14562 panel.update_in(cx, |panel, window, cx| {
14563 panel.set_zoomed(true, window, cx);
14564 });
14565
14566 // Verify the panel is zoomed and the dock is open
14567 workspace_a.update_in(cx, |workspace, window, cx| {
14568 assert!(
14569 workspace.right_dock().read(cx).is_open(),
14570 "dock should be open before switch"
14571 );
14572 assert!(
14573 panel.is_zoomed(window, cx),
14574 "panel should be zoomed before switch"
14575 );
14576 assert!(
14577 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
14578 "panel should be focused before switch"
14579 );
14580 });
14581
14582 // Switch to workspace B
14583 multi_workspace_handle
14584 .update(cx, |mw, window, cx| {
14585 let workspace = mw.workspaces().nth(1).unwrap().clone();
14586 mw.activate(workspace, window, cx);
14587 })
14588 .unwrap();
14589 cx.run_until_parked();
14590
14591 // Switch back to workspace A
14592 multi_workspace_handle
14593 .update(cx, |mw, window, cx| {
14594 let workspace = mw.workspaces().next().unwrap().clone();
14595 mw.activate(workspace, window, cx);
14596 })
14597 .unwrap();
14598 cx.run_until_parked();
14599
14600 // Verify the panel is still zoomed and the dock is still open
14601 workspace_a.update_in(cx, |workspace, window, cx| {
14602 assert!(
14603 workspace.right_dock().read(cx).is_open(),
14604 "dock should still be open after switching back"
14605 );
14606 assert!(
14607 panel.is_zoomed(window, cx),
14608 "panel should still be zoomed after switching back"
14609 );
14610 });
14611 }
14612
14613 fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
14614 pane.read(cx)
14615 .items()
14616 .flat_map(|item| {
14617 item.project_paths(cx)
14618 .into_iter()
14619 .map(|path| path.path.display(PathStyle::local()).into_owned())
14620 })
14621 .collect()
14622 }
14623
14624 pub fn init_test(cx: &mut TestAppContext) {
14625 cx.update(|cx| {
14626 let settings_store = SettingsStore::test(cx);
14627 cx.set_global(settings_store);
14628 cx.set_global(db::AppDatabase::test_new());
14629 theme_settings::init(theme::LoadThemes::JustBase, cx);
14630 });
14631 }
14632
14633 #[gpui::test]
14634 async fn test_toggle_theme_mode_persists_and_updates_active_theme(cx: &mut TestAppContext) {
14635 use settings::{ThemeName, ThemeSelection};
14636 use theme::SystemAppearance;
14637 use zed_actions::theme::ToggleMode;
14638
14639 init_test(cx);
14640
14641 let fs = FakeFs::new(cx.executor());
14642 let settings_fs: Arc<dyn fs::Fs> = fs.clone();
14643
14644 fs.insert_tree(path!("/root"), json!({ "file.rs": "fn main() {}\n" }))
14645 .await;
14646
14647 // Build a test project and workspace view so the test can invoke
14648 // the workspace action handler the same way the UI would.
14649 let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
14650 let (workspace, cx) =
14651 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14652
14653 // Seed the settings file with a plain static light theme so the
14654 // first toggle always starts from a known persisted state.
14655 workspace.update_in(cx, |_workspace, _window, cx| {
14656 *SystemAppearance::global_mut(cx) = SystemAppearance(theme::Appearance::Light);
14657 settings::update_settings_file(settings_fs.clone(), cx, |settings, _cx| {
14658 settings.theme.theme = Some(ThemeSelection::Static(ThemeName("One Light".into())));
14659 });
14660 });
14661 cx.executor().advance_clock(Duration::from_millis(200));
14662 cx.run_until_parked();
14663
14664 // Confirm the initial persisted settings contain the static theme
14665 // we just wrote before any toggling happens.
14666 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14667 assert!(settings_text.contains(r#""theme": "One Light""#));
14668
14669 // Toggle once. This should migrate the persisted theme settings
14670 // into light/dark slots and enable system mode.
14671 workspace.update_in(cx, |workspace, window, cx| {
14672 workspace.toggle_theme_mode(&ToggleMode, window, cx);
14673 });
14674 cx.executor().advance_clock(Duration::from_millis(200));
14675 cx.run_until_parked();
14676
14677 // 1. Static -> Dynamic
14678 // this assertion checks theme changed from static to dynamic.
14679 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14680 let parsed: serde_json::Value = settings::parse_json_with_comments(&settings_text).unwrap();
14681 assert_eq!(
14682 parsed["theme"],
14683 serde_json::json!({
14684 "mode": "system",
14685 "light": "One Light",
14686 "dark": "One Dark"
14687 })
14688 );
14689
14690 // 2. Toggle again, suppose it will change the mode to light
14691 workspace.update_in(cx, |workspace, window, cx| {
14692 workspace.toggle_theme_mode(&ToggleMode, window, cx);
14693 });
14694 cx.executor().advance_clock(Duration::from_millis(200));
14695 cx.run_until_parked();
14696
14697 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14698 assert!(settings_text.contains(r#""mode": "light""#));
14699 }
14700
14701 fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
14702 let item = TestProjectItem::new(id, path, cx);
14703 item.update(cx, |item, _| {
14704 item.is_dirty = true;
14705 });
14706 item
14707 }
14708
14709 #[gpui::test]
14710 async fn test_zoomed_panel_without_pane_preserved_on_center_focus(
14711 cx: &mut gpui::TestAppContext,
14712 ) {
14713 init_test(cx);
14714 let fs = FakeFs::new(cx.executor());
14715
14716 let project = Project::test(fs, [], cx).await;
14717 let (workspace, cx) =
14718 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
14719
14720 let panel = workspace.update_in(cx, |workspace, window, cx| {
14721 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14722 workspace.add_panel(panel.clone(), window, cx);
14723 workspace
14724 .right_dock()
14725 .update(cx, |dock, cx| dock.set_open(true, window, cx));
14726 panel
14727 });
14728
14729 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14730 pane.update_in(cx, |pane, window, cx| {
14731 let item = cx.new(TestItem::new);
14732 pane.add_item(Box::new(item), true, true, None, window, cx);
14733 });
14734
14735 // Transfer focus to the panel, then zoom it. Using toggle_panel_focus
14736 // mirrors the real-world flow and avoids side effects from directly
14737 // focusing the panel while the center pane is active.
14738 workspace.update_in(cx, |workspace, window, cx| {
14739 workspace.toggle_panel_focus::<TestPanel>(window, cx);
14740 });
14741
14742 panel.update_in(cx, |panel, window, cx| {
14743 panel.set_zoomed(true, window, cx);
14744 });
14745
14746 workspace.update_in(cx, |workspace, window, cx| {
14747 assert!(workspace.right_dock().read(cx).is_open());
14748 assert!(panel.is_zoomed(window, cx));
14749 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14750 });
14751
14752 // Simulate a spurious pane::Event::Focus on the center pane while the
14753 // panel still has focus. This mirrors what happens during macOS window
14754 // activation: the center pane fires a focus event even though actual
14755 // focus remains on the dock panel.
14756 pane.update_in(cx, |_, _, cx| {
14757 cx.emit(pane::Event::Focus);
14758 });
14759
14760 // The dock must remain open because the panel had focus at the time the
14761 // event was processed. Before the fix, dock_to_preserve was None for
14762 // panels that don't implement pane(), causing the dock to close.
14763 workspace.update_in(cx, |workspace, window, cx| {
14764 assert!(
14765 workspace.right_dock().read(cx).is_open(),
14766 "Dock should stay open when its zoomed panel (without pane()) still has focus"
14767 );
14768 assert!(panel.is_zoomed(window, cx));
14769 });
14770 }
14771
14772 #[gpui::test]
14773 async fn test_panels_stay_open_after_position_change_and_settings_update(
14774 cx: &mut gpui::TestAppContext,
14775 ) {
14776 init_test(cx);
14777 let fs = FakeFs::new(cx.executor());
14778 let project = Project::test(fs, [], cx).await;
14779 let (workspace, cx) =
14780 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
14781
14782 // Add two panels to the left dock and open it.
14783 let (panel_a, panel_b) = workspace.update_in(cx, |workspace, window, cx| {
14784 let panel_a = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
14785 let panel_b = cx.new(|cx| TestPanel::new(DockPosition::Left, 101, cx));
14786 workspace.add_panel(panel_a.clone(), window, cx);
14787 workspace.add_panel(panel_b.clone(), window, cx);
14788 workspace.left_dock().update(cx, |dock, cx| {
14789 dock.set_open(true, window, cx);
14790 dock.activate_panel(0, window, cx);
14791 });
14792 (panel_a, panel_b)
14793 });
14794
14795 workspace.update_in(cx, |workspace, _, cx| {
14796 assert!(workspace.left_dock().read(cx).is_open());
14797 });
14798
14799 // Simulate a feature flag changing default dock positions: both panels
14800 // move from Left to Right.
14801 workspace.update_in(cx, |_workspace, _window, cx| {
14802 panel_a.update(cx, |p, _cx| p.position = DockPosition::Right);
14803 panel_b.update(cx, |p, _cx| p.position = DockPosition::Right);
14804 cx.update_global::<SettingsStore, _>(|_, _| {});
14805 });
14806
14807 // Both panels should now be in the right dock.
14808 workspace.update_in(cx, |workspace, _, cx| {
14809 let right_dock = workspace.right_dock().read(cx);
14810 assert_eq!(right_dock.panels_len(), 2);
14811 });
14812
14813 // Open the right dock and activate panel_b (simulating the user
14814 // opening the panel after it moved).
14815 workspace.update_in(cx, |workspace, window, cx| {
14816 workspace.right_dock().update(cx, |dock, cx| {
14817 dock.set_open(true, window, cx);
14818 dock.activate_panel(1, window, cx);
14819 });
14820 });
14821
14822 // Now trigger another SettingsStore change
14823 workspace.update_in(cx, |_workspace, _window, cx| {
14824 cx.update_global::<SettingsStore, _>(|_, _| {});
14825 });
14826
14827 workspace.update_in(cx, |workspace, _, cx| {
14828 assert!(
14829 workspace.right_dock().read(cx).is_open(),
14830 "Right dock should still be open after a settings change"
14831 );
14832 assert_eq!(
14833 workspace.right_dock().read(cx).panels_len(),
14834 2,
14835 "Both panels should still be in the right dock"
14836 );
14837 });
14838 }
14839}